{"text":"\n#include \n\n#include \"component.h\"\n#include \"entity.h\"\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include \"manager.h\"\n\nusing ::testing::NiceMock;\nusing ::testing::Return;\n\n\/\/ TODO move to shared testing file\nclass TestRenderer : public aronnax::Renderer {\n public:\n TestRenderer() { };\n ~TestRenderer() { };\n void render() { };\n void beforeRender() { };\n void afterRender() { };\n};\n\n\/\/ TODO move to shared testing file\nclass MockComponent : public aronnax::Component {\n public:\n MOCK_METHOD2(update, void(aronnax::Entity &entity, const uint32_t dt));\n MOCK_METHOD1(render, void(aronnax::Entity &entity));\n MOCK_METHOD0(getType, std::string());\n};\n\n\nclass ManagerTest: public testing::Test {\n protected:\n virtual void SetUp() {\n std::shared_ptr tr = std::make_shared();\n testManager_ = new aronnax::Manager(tr, testEntities_);\n }\n\n virtual void TearDown() {\n delete testManager_;\n }\n\n aronnax::Manager* testManager_;\n aronnax::Entities testEntities_;\n aronnax::Components testComponentList_;\n};\n\nTEST(manager, Constructor) {\n std::shared_ptr testRenderer = std::make_shared();\n aronnax::Manager testManager(testRenderer);\n}\n\nTEST_F(ManagerTest, add) {\n NiceMock testComponent;\n testComponentList_.push_back(&testComponent);\n\n ON_CALL(testComponent, getType())\n .WillByDefault(Return(\"TestComponentA\"));\n\n auto actual = testManager_->add(testComponentList_);\n EXPECT_EQ(1, testManager_->getEntities().size());\n EXPECT_EQ(1, testManager_->getEntities().count(actual));\n\n auto actualComponent = actual.get()->getComponent(\"TestComponentA\");\n EXPECT_EQ(actualComponent, &testComponent);\n\n actual = testManager_->add(testComponentList_);\n EXPECT_EQ(2, testManager_->getEntities().size());\n EXPECT_EQ(1, testManager_->getEntities().count(actual));\n}\n\nTEST_F(ManagerTest, getEntities) {\n aronnax::EntityPtr testEntity = std::make_shared(\n testComponentList_);\n testEntities_.insert(testEntity);\n\n std::shared_ptr tr = std::make_shared();\n auto testManager = new aronnax::Manager(tr, testEntities_);\n\n auto actual = testManager_->getEntities().size();\n \/\/EXPECT_EQ(1, actual);\n}\nManager render test\n#include \n\n#include \"component.h\"\n#include \"entity.h\"\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include \"manager.h\"\n\nusing ::testing::Mock;\nusing ::testing::NiceMock;\nusing ::testing::Return;\n\n\/\/ TODO move to shared testing file\nclass TestRenderer : public aronnax::Renderer {\n public:\n TestRenderer() { };\n ~TestRenderer() { };\n void render() { };\n void beforeRender() { };\n void afterRender() { };\n};\n\nclass MockRenderer: public TestRenderer {\n public:\n MOCK_METHOD0(render, void());\n MOCK_METHOD0(beforeRender, void());\n MOCK_METHOD0(afterRender, void());\n};\n\n\/\/ TODO move to shared testing file\nclass MockComponent : public aronnax::Component {\n public:\n MOCK_METHOD2(update, void(aronnax::Entity &entity, const uint32_t dt));\n MOCK_METHOD1(render, void(aronnax::Entity &entity));\n MOCK_METHOD0(getType, std::string());\n};\n\n\nclass ManagerTest: public testing::Test {\n protected:\n virtual void SetUp() {\n std::shared_ptr tr = std::make_shared();\n testManager_ = new aronnax::Manager(tr, testEntities_);\n }\n\n virtual void TearDown() {\n delete testManager_;\n }\n\n aronnax::Manager* testManager_;\n aronnax::Entities testEntities_;\n aronnax::Components testComponentList_;\n};\n\nTEST(manager, Constructor) {\n std::shared_ptr testRenderer = std::make_shared();\n aronnax::Manager testManager(testRenderer);\n}\n\nTEST_F(ManagerTest, add) {\n NiceMock testComponent;\n testComponentList_.push_back(&testComponent);\n\n ON_CALL(testComponent, getType())\n .WillByDefault(Return(\"TestComponentA\"));\n\n auto actual = testManager_->add(testComponentList_);\n EXPECT_EQ(1, testManager_->getEntities().size());\n EXPECT_EQ(1, testManager_->getEntities().count(actual));\n\n auto actualComponent = actual.get()->getComponent(\"TestComponentA\");\n EXPECT_EQ(actualComponent, &testComponent);\n\n actual = testManager_->add(testComponentList_);\n EXPECT_EQ(2, testManager_->getEntities().size());\n EXPECT_EQ(1, testManager_->getEntities().count(actual));\n}\n\nTEST_F(ManagerTest, getEntities) {\n aronnax::EntityPtr testEntity = std::make_shared(\n testComponentList_);\n testEntities_.insert(testEntity);\n\n std::shared_ptr tr = std::make_shared();\n auto testManager = new aronnax::Manager(tr, testEntities_);\n\n auto actual = testManager_->getEntities().size();\n \/\/EXPECT_EQ(1, actual);\n}\n\nTEST_F(ManagerTest, render) {\n std::shared_ptr mockRenderer = std::make_shared();\n auto* testManager = new aronnax::Manager(mockRenderer, testEntities_);\n\n EXPECT_CALL(*mockRenderer, beforeRender()).Times(1);\n EXPECT_CALL(*mockRenderer, afterRender()).Times(1);\n\n testManager->render();\n Mock::AllowLeak(mockRenderer.get());\n Mock::VerifyAndClearExpectations(mockRenderer.get());\n}\n<|endoftext|>"} {"text":"#include \"client.h\"\n#include \"controller\/taskcontroller.h\"\n#include \"controller\/reportcontroller.h\"\n#include \"controller\/logincontroller.h\"\n#include \"controller\/configcontroller.h\"\n#include \"controller\/crashcontroller.h\"\n#include \"network\/networkmanager.h\"\n#include \"task\/taskexecutor.h\"\n#include \"scheduler\/schedulerstorage.h\"\n#include \"report\/reportstorage.h\"\n#include \"scheduler\/scheduler.h\"\n#include \"settings.h\"\n#include \"log\/logger.h\"\n\n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_UNIX\n#include \n#include \n#include \n#include \n#endif \/\/ Q_OS_UNIX\n\n#ifdef Q_OS_WIN\n#include \n#include \n#endif \/\/ Q_OS_WIN\n\n\/\/ TEST INCLUDES\n#include \"timing\/immediatetiming.h\"\n#include \"timing\/timing.h\"\n#include \"task\/task.h\"\n#include \"measurement\/btc\/btc_definition.h\"\n#include \"measurement\/http\/httpdownload_definition.h\"\n#include \"measurement\/ping\/ping_definition.h\"\n#include \"measurement\/dnslookup\/dnslookup_definition.h\"\n#include \"measurement\/reverse_dnslookup\/reverseDnslookup_definition.h\"\n#include \"measurement\/packettrains\/packettrainsdefinition.h\"\n#include \"measurement\/udpping\/udpping_definition.h\"\n#include \"measurement\/traceroute\/traceroute_definition.h\"\n\nLOGGER(Client);\n\nQ_GLOBAL_STATIC(Ntp, ntp)\n\nclass Client::Private : public QObject\n{\n Q_OBJECT\n\npublic:\n Private(Client *q)\n : q(q)\n , status(Client::Unregistered)\n , networkAccessManager(new QNetworkAccessManager(q))\n , schedulerStorage(&scheduler)\n , reportStorage(&reportScheduler)\n {\n executor.setNetworkManager(&networkManager);\n scheduler.setExecutor(&executor);\n\n connect(&executor, SIGNAL(finished(TestDefinition, Result)), this, SLOT(taskFinished(TestDefinition,\n Result)));\n connect(&loginController, SIGNAL(finished()), this, SLOT(loginStatusChanged()));\n }\n\n Client *q;\n\n \/\/ Properties\n Client::Status status;\n QNetworkAccessManager *networkAccessManager;\n\n TaskExecutor executor;\n\n Scheduler scheduler;\n SchedulerStorage schedulerStorage;\n\n ReportScheduler reportScheduler;\n ReportStorage reportStorage;\n\n Settings settings;\n NetworkManager networkManager;\n\n TaskController taskController;\n ReportController reportController;\n LoginController loginController;\n ConfigController configController;\n CrashController crashController;\n\n#ifdef Q_OS_UNIX\n static int sigintFd[2];\n static int sighupFd[2];\n static int sigtermFd[2];\n\n QSocketNotifier *snInt;\n QSocketNotifier *snHup;\n QSocketNotifier *snTerm;\n\n \/\/ Unix signal handlers.\n static void intSignalHandler(int unused);\n static void hupSignalHandler(int unused);\n static void termSignalHandler(int unused);\n#endif \/\/ Q_OS_UNIX\n\n \/\/ Functions\n void setupUnixSignalHandlers();\n\n#ifdef Q_OS_WIN\n static BOOL CtrlHandler(DWORD ctrlType);\n#endif \/\/ Q_OS_WIN\n\npublic slots:\n#ifdef Q_OS_UNIX\n void handleSigInt();\n void handleSigHup();\n void handleSigTerm();\n#endif \/\/ Q_OS_UNIX\n void taskFinished(const TestDefinition &test, const Result &result);\n void loginStatusChanged();\n};\n\n#ifdef Q_OS_UNIX\nint Client::Private::sigintFd[2];\nint Client::Private::sighupFd[2];\nint Client::Private::sigtermFd[2];\n\nvoid Client::Private::intSignalHandler(int)\n{\n char a = 1;\n ::write(sigintFd[0], &a, sizeof(a));\n}\n\nvoid Client::Private::hupSignalHandler(int)\n{\n char a = 1;\n ::write(sighupFd[0], &a, sizeof(a));\n}\n\nvoid Client::Private::termSignalHandler(int)\n{\n char a = 1;\n ::write(sigtermFd[0], &a, sizeof(a));\n}\n#endif \/\/ Q_OS_UNIX\n\nvoid Client::Private::setupUnixSignalHandlers()\n{\n#ifdef Q_OS_UNIX\n struct sigaction Int, hup, term;\n\n Int.sa_handler = Client::Private::intSignalHandler;\n sigemptyset(&Int.sa_mask);\n Int.sa_flags = 0;\n Int.sa_flags |= SA_RESTART;\n\n if (sigaction(SIGINT, &Int, 0) > 0)\n {\n return;\n }\n\n hup.sa_handler = Client::Private::hupSignalHandler;\n sigemptyset(&hup.sa_mask);\n hup.sa_flags = 0;\n hup.sa_flags |= SA_RESTART;\n\n if (sigaction(SIGHUP, &hup, 0) > 0)\n {\n return;\n }\n\n term.sa_handler = Client::Private::termSignalHandler;\n sigemptyset(&term.sa_mask);\n term.sa_flags = 0;\n term.sa_flags |= SA_RESTART;\n\n if (sigaction(SIGTERM, &term, 0) > 0)\n {\n return;\n }\n\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))\n {\n qFatal(\"Couldn't create INT socketpair\");\n }\n\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))\n {\n qFatal(\"Couldn't create HUP socketpair\");\n }\n\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))\n {\n qFatal(\"Couldn't create TERM socketpair\");\n }\n\n snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);\n connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));\n\n snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);\n connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));\n\n snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);\n connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));\n#elif defined(Q_OS_WIN)\n SetConsoleCtrlHandler((PHANDLER_ROUTINE)Private::CtrlHandler, TRUE);\n#endif\n}\n\n#ifdef Q_OS_WIN\nBOOL Client::Private::CtrlHandler(DWORD ctrlType)\n{\n switch (ctrlType)\n {\n case CTRL_C_EVENT:\n case CTRL_CLOSE_EVENT:\n LOG_INFO(\"Close requested, quitting.\");\n qApp->quit();\n return TRUE;\n\n case CTRL_LOGOFF_EVENT:\n case CTRL_SHUTDOWN_EVENT:\n LOG_INFO(\"System shutdown or user logout, quitting.\");\n qApp->quit();\n return FALSE;\n\n default:\n return FALSE;\n }\n}\n#endif \/\/ Q_OS_WIN\n\n#ifdef Q_OS_UNIX\nvoid Client::Private::handleSigInt()\n{\n snInt->setEnabled(false);\n char tmp;\n ::read(sigintFd[1], &tmp, sizeof(tmp));\n\n LOG_INFO(\"Interrupt requested, quitting.\");\n qApp->quit();\n\n snInt->setEnabled(true);\n}\n\nvoid Client::Private::handleSigTerm()\n{\n snTerm->setEnabled(false);\n char tmp;\n ::read(sigtermFd[1], &tmp, sizeof(tmp));\n\n LOG_INFO(\"Termination requested, quitting.\");\n qApp->quit();\n\n snTerm->setEnabled(true);\n}\n\nvoid Client::Private::handleSigHup()\n{\n snHup->setEnabled(false);\n char tmp;\n ::read(sighupFd[1], &tmp, sizeof(tmp));\n\n LOG_INFO(\"Hangup detected, quitting.\");\n qApp->quit();\n\n snHup->setEnabled(true);\n}\n#endif \/\/ Q_OS_UNIX\n\nvoid Client::Private::taskFinished(const TestDefinition &test, const Result &result)\n{\n Report report = reportScheduler.reportByTaskId(test.id());\n\n ResultList results = report.isNull() ? ResultList() : report.results();\n results.append(result);\n\n if (report.isNull())\n {\n report = Report(test.id(), QDateTime::currentDateTime(), Client::version(), results);\n reportScheduler.addReport(report);\n }\n else\n {\n report.setResults(results);\n reportScheduler.modifyReport(report);\n }\n}\n\nvoid Client::Private::loginStatusChanged()\n{\n if (!settings.isPassive() && loginController.registeredDevice())\n {\n taskController.fetchTasks();\n }\n}\n\nClient::Client(QObject *parent)\n: QObject(parent)\n, d(new Private(this))\n{\n}\n\nClient::~Client()\n{\n d->schedulerStorage.storeData();\n d->reportStorage.storeData();\n delete d;\n}\n\nClient *Client::instance()\n{\n static Client *ins = NULL;\n\n if (!ins)\n {\n ins = new Client();\n }\n\n return ins;\n}\n\nbool Client::init()\n{\n qRegisterMetaType();\n qRegisterMetaType();\n\n \/\/ Get network time from ntp server\n QHostInfo hostInfo = QHostInfo::fromName(\"ptbtime1.ptb.de\");\n\n if (!hostInfo.addresses().isEmpty())\n {\n QHostAddress ntpServer = hostInfo.addresses().first();\n ntp->sync(ntpServer);\n }\n else\n {\n LOG_WARNING(\"could not resolve ntp server\");\n }\n\n d->setupUnixSignalHandlers();\n d->settings.init();\n\n \/\/ Initialize storages\n d->schedulerStorage.loadData();\n d->reportStorage.loadData();\n\n \/\/ Initialize controllers\n d->networkManager.init(&d->scheduler, &d->settings);\n d->configController.init(&d->networkManager, &d->settings);\n d->reportController.init(&d->reportScheduler, &d->settings);\n d->loginController.init(&d->networkManager, &d->settings);\n d->crashController.init(&d->networkManager, &d->settings);\n\n if (!d->settings.isPassive())\n {\n d->taskController.init(&d->networkManager, &d->scheduler, &d->settings);\n }\n\n return true;\n}\n\nbool Client::autoLogin()\n{\n if (d->settings.hasLoginData())\n {\n \/\/ check if api key is still valid\n d->taskController.fetchTasks();\n\n return true;\n }\n\n return false;\n}\n\nvoid Client::btc(const QString &host)\n{\n BulkTransportCapacityDefinition btcDef(host, 5106, 1024 * 1024);\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(9, \"btc_ma\", timing,\n btcDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::http(const QString &url)\n{\n HTTPDownloadDefinition httpDef(url, false);\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(3, \"httpdownload\", timing,\n httpDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::upnp()\n{\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(5, \"upnp\", timing,\n QVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::ping(const QString &host, quint16 count, quint32 timeout, quint32 interval)\n{\n PingDefinition pingDef(host.isNull() ? \"measure-it.de\" : host, count, timeout, interval);\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(4, \"ping\", timing,\n pingDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::dnslookup()\n{\n DnslookupDefinition dnslookupDef(\"www.google.com\", \"8.8.8.8\");\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(8, \"dnslookup\", timing,\n dnslookupDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::reverseDnslookup()\n{\n ReverseDnslookupDefinition reverseDnslookupDef(\"8.8.8.8\");\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(9, \"reverseDnslookup\", timing,\n reverseDnslookupDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::packetTrains(QString host, quint16 port, quint16 packetSize, quint16 trainLength, quint8 iterations,\n quint64 rateMin, quint64 rateMax, quint64 delay)\n{\n PacketTrainsDefinition packetTrainsDef(host, port, packetSize, trainLength, iterations, rateMin, rateMax, delay);\n\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(11, \"packettrains_ma\", timing,\n packetTrainsDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::udpPing(const QString &url, const quint32 &count, const quint32 &interval, const quint32 &receiveTimeout,\n const int &ttl, const quint16 &destinationPort, const quint16 &sourcePort, const quint32 &payload)\n{\n UdpPingDefinition udpPingDef(url, count, interval, receiveTimeout, ttl, destinationPort, sourcePort, payload);\n\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(12, \"udpping\", timing,\n udpPingDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::traceroute(const QString &url,\n const quint32 &count,\n const quint32 &interval,\n const quint32 &receiveTimeout,\n const quint16 &destinationPort,\n const quint16 &sourcePort,\n const quint32 &payload)\n{\n TracerouteDefinition tracerouteDef(url, count, interval, receiveTimeout, destinationPort, sourcePort, payload);\n\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(13, \"traceroute\", timing,\n tracerouteDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::measureIt()\n{\n \/\/ Ping\n d->scheduler.executeOnDemandTest(1);\n\n \/\/ BTC\n d->scheduler.executeOnDemandTest(2);\n\n \/\/ HTTP download\n d->scheduler.executeOnDemandTest(3);\n\n \/\/ PacketTrains\n d->scheduler.executeOnDemandTest(4);\n\n \/\/ UdpPing\n d->scheduler.executeOnDemandTest(5);\n\n \/\/ Traceroute\n d->scheduler.executeOnDemandTest(6);\n}\n\nvoid Client::setStatus(Client::Status status)\n{\n if (d->status == status)\n {\n return;\n }\n\n d->status = status;\n emit statusChanged();\n}\n\nClient::Status Client::status() const\n{\n return d->status;\n}\n\nQString Client::version()\n{\n return QString(\"%1.%2.%3\").arg(Client::versionMajor).arg(Client::versionMinor).arg(Client::versionPatch);\n}\n\nQNetworkAccessManager *Client::networkAccessManager() const\n{\n return d->networkAccessManager;\n}\n\nScheduler *Client::scheduler() const\n{\n return &d->scheduler;\n}\n\nReportScheduler *Client::reportScheduler() const\n{\n return &d->reportScheduler;\n}\n\nNetworkManager *Client::networkManager() const\n{\n return &d->networkManager;\n}\n\nTaskExecutor *Client::taskExecutor() const\n{\n return &d->executor;\n}\n\nConfigController *Client::configController() const\n{\n return &d->configController;\n}\n\nLoginController *Client::loginController() const\n{\n return &d->loginController;\n}\n\nReportController *Client::reportController() const\n{\n return &d->reportController;\n}\n\nTaskController *Client::taskController() const\n{\n return &d->taskController;\n}\n\nCrashController *Client::crashController() const\n{\n return &d->crashController;\n}\n\nSettings *Client::settings() const\n{\n return &d->settings;\n}\n\n#include \"client.moc\"\nFixed an evil bug which ignored results of each task on the first run.#include \"client.h\"\n#include \"controller\/taskcontroller.h\"\n#include \"controller\/reportcontroller.h\"\n#include \"controller\/logincontroller.h\"\n#include \"controller\/configcontroller.h\"\n#include \"controller\/crashcontroller.h\"\n#include \"network\/networkmanager.h\"\n#include \"task\/taskexecutor.h\"\n#include \"scheduler\/schedulerstorage.h\"\n#include \"report\/reportstorage.h\"\n#include \"scheduler\/scheduler.h\"\n#include \"settings.h\"\n#include \"log\/logger.h\"\n\n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_UNIX\n#include \n#include \n#include \n#include \n#endif \/\/ Q_OS_UNIX\n\n#ifdef Q_OS_WIN\n#include \n#include \n#endif \/\/ Q_OS_WIN\n\n\/\/ TEST INCLUDES\n#include \"timing\/immediatetiming.h\"\n#include \"timing\/timing.h\"\n#include \"task\/task.h\"\n#include \"measurement\/btc\/btc_definition.h\"\n#include \"measurement\/http\/httpdownload_definition.h\"\n#include \"measurement\/ping\/ping_definition.h\"\n#include \"measurement\/dnslookup\/dnslookup_definition.h\"\n#include \"measurement\/reverse_dnslookup\/reverseDnslookup_definition.h\"\n#include \"measurement\/packettrains\/packettrainsdefinition.h\"\n#include \"measurement\/udpping\/udpping_definition.h\"\n#include \"measurement\/traceroute\/traceroute_definition.h\"\n\nLOGGER(Client);\n\nQ_GLOBAL_STATIC(Ntp, ntp)\n\nclass Client::Private : public QObject\n{\n Q_OBJECT\n\npublic:\n Private(Client *q)\n : q(q)\n , status(Client::Unregistered)\n , networkAccessManager(new QNetworkAccessManager(q))\n , schedulerStorage(&scheduler)\n , reportStorage(&reportScheduler)\n {\n executor.setNetworkManager(&networkManager);\n scheduler.setExecutor(&executor);\n\n connect(&executor, SIGNAL(finished(TestDefinition, Result)), this, SLOT(taskFinished(TestDefinition,\n Result)));\n connect(&loginController, SIGNAL(finished()), this, SLOT(loginStatusChanged()));\n }\n\n Client *q;\n\n \/\/ Properties\n Client::Status status;\n QNetworkAccessManager *networkAccessManager;\n\n TaskExecutor executor;\n\n Scheduler scheduler;\n SchedulerStorage schedulerStorage;\n\n ReportScheduler reportScheduler;\n ReportStorage reportStorage;\n\n Settings settings;\n NetworkManager networkManager;\n\n TaskController taskController;\n ReportController reportController;\n LoginController loginController;\n ConfigController configController;\n CrashController crashController;\n\n#ifdef Q_OS_UNIX\n static int sigintFd[2];\n static int sighupFd[2];\n static int sigtermFd[2];\n\n QSocketNotifier *snInt;\n QSocketNotifier *snHup;\n QSocketNotifier *snTerm;\n\n \/\/ Unix signal handlers.\n static void intSignalHandler(int unused);\n static void hupSignalHandler(int unused);\n static void termSignalHandler(int unused);\n#endif \/\/ Q_OS_UNIX\n\n \/\/ Functions\n void setupUnixSignalHandlers();\n\n#ifdef Q_OS_WIN\n static BOOL CtrlHandler(DWORD ctrlType);\n#endif \/\/ Q_OS_WIN\n\npublic slots:\n#ifdef Q_OS_UNIX\n void handleSigInt();\n void handleSigHup();\n void handleSigTerm();\n#endif \/\/ Q_OS_UNIX\n void taskFinished(const TestDefinition &test, const Result &result);\n void loginStatusChanged();\n};\n\n#ifdef Q_OS_UNIX\nint Client::Private::sigintFd[2];\nint Client::Private::sighupFd[2];\nint Client::Private::sigtermFd[2];\n\nvoid Client::Private::intSignalHandler(int)\n{\n char a = 1;\n ::write(sigintFd[0], &a, sizeof(a));\n}\n\nvoid Client::Private::hupSignalHandler(int)\n{\n char a = 1;\n ::write(sighupFd[0], &a, sizeof(a));\n}\n\nvoid Client::Private::termSignalHandler(int)\n{\n char a = 1;\n ::write(sigtermFd[0], &a, sizeof(a));\n}\n#endif \/\/ Q_OS_UNIX\n\nvoid Client::Private::setupUnixSignalHandlers()\n{\n#ifdef Q_OS_UNIX\n struct sigaction Int, hup, term;\n\n Int.sa_handler = Client::Private::intSignalHandler;\n sigemptyset(&Int.sa_mask);\n Int.sa_flags = 0;\n Int.sa_flags |= SA_RESTART;\n\n if (sigaction(SIGINT, &Int, 0) > 0)\n {\n return;\n }\n\n hup.sa_handler = Client::Private::hupSignalHandler;\n sigemptyset(&hup.sa_mask);\n hup.sa_flags = 0;\n hup.sa_flags |= SA_RESTART;\n\n if (sigaction(SIGHUP, &hup, 0) > 0)\n {\n return;\n }\n\n term.sa_handler = Client::Private::termSignalHandler;\n sigemptyset(&term.sa_mask);\n term.sa_flags = 0;\n term.sa_flags |= SA_RESTART;\n\n if (sigaction(SIGTERM, &term, 0) > 0)\n {\n return;\n }\n\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))\n {\n qFatal(\"Couldn't create INT socketpair\");\n }\n\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))\n {\n qFatal(\"Couldn't create HUP socketpair\");\n }\n\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))\n {\n qFatal(\"Couldn't create TERM socketpair\");\n }\n\n snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);\n connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));\n\n snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);\n connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));\n\n snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);\n connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));\n#elif defined(Q_OS_WIN)\n SetConsoleCtrlHandler((PHANDLER_ROUTINE)Private::CtrlHandler, TRUE);\n#endif\n}\n\n#ifdef Q_OS_WIN\nBOOL Client::Private::CtrlHandler(DWORD ctrlType)\n{\n switch (ctrlType)\n {\n case CTRL_C_EVENT:\n case CTRL_CLOSE_EVENT:\n LOG_INFO(\"Close requested, quitting.\");\n qApp->quit();\n return TRUE;\n\n case CTRL_LOGOFF_EVENT:\n case CTRL_SHUTDOWN_EVENT:\n LOG_INFO(\"System shutdown or user logout, quitting.\");\n qApp->quit();\n return FALSE;\n\n default:\n return FALSE;\n }\n}\n#endif \/\/ Q_OS_WIN\n\n#ifdef Q_OS_UNIX\nvoid Client::Private::handleSigInt()\n{\n snInt->setEnabled(false);\n char tmp;\n ::read(sigintFd[1], &tmp, sizeof(tmp));\n\n LOG_INFO(\"Interrupt requested, quitting.\");\n qApp->quit();\n\n snInt->setEnabled(true);\n}\n\nvoid Client::Private::handleSigTerm()\n{\n snTerm->setEnabled(false);\n char tmp;\n ::read(sigtermFd[1], &tmp, sizeof(tmp));\n\n LOG_INFO(\"Termination requested, quitting.\");\n qApp->quit();\n\n snTerm->setEnabled(true);\n}\n\nvoid Client::Private::handleSigHup()\n{\n snHup->setEnabled(false);\n char tmp;\n ::read(sighupFd[1], &tmp, sizeof(tmp));\n\n LOG_INFO(\"Hangup detected, quitting.\");\n qApp->quit();\n\n snHup->setEnabled(true);\n}\n#endif \/\/ Q_OS_UNIX\n\nvoid Client::Private::taskFinished(const TestDefinition &test, const Result &result)\n{\n Report report = reportScheduler.reportByTaskId(test.id());\n\n ResultList results = report.isNull() ? ResultList() : report.results();\n results.append(result);\n\n if (report.isNull() || results.size() == 1)\n {\n report = Report(test.id(), QDateTime::currentDateTime(), Client::version(), results);\n reportScheduler.addReport(report);\n }\n else\n {\n report.setResults(results);\n reportScheduler.modifyReport(report);\n }\n}\n\nvoid Client::Private::loginStatusChanged()\n{\n if (!settings.isPassive() && loginController.registeredDevice())\n {\n taskController.fetchTasks();\n }\n}\n\nClient::Client(QObject *parent)\n: QObject(parent)\n, d(new Private(this))\n{\n}\n\nClient::~Client()\n{\n d->schedulerStorage.storeData();\n d->reportStorage.storeData();\n delete d;\n}\n\nClient *Client::instance()\n{\n static Client *ins = NULL;\n\n if (!ins)\n {\n ins = new Client();\n }\n\n return ins;\n}\n\nbool Client::init()\n{\n qRegisterMetaType();\n qRegisterMetaType();\n\n \/\/ Get network time from ntp server\n QHostInfo hostInfo = QHostInfo::fromName(\"ptbtime1.ptb.de\");\n\n if (!hostInfo.addresses().isEmpty())\n {\n QHostAddress ntpServer = hostInfo.addresses().first();\n ntp->sync(ntpServer);\n }\n else\n {\n LOG_WARNING(\"could not resolve ntp server\");\n }\n\n d->setupUnixSignalHandlers();\n d->settings.init();\n\n \/\/ Initialize storages\n d->schedulerStorage.loadData();\n d->reportStorage.loadData();\n\n \/\/ Initialize controllers\n d->networkManager.init(&d->scheduler, &d->settings);\n d->configController.init(&d->networkManager, &d->settings);\n d->reportController.init(&d->reportScheduler, &d->settings);\n d->loginController.init(&d->networkManager, &d->settings);\n d->crashController.init(&d->networkManager, &d->settings);\n\n if (!d->settings.isPassive())\n {\n d->taskController.init(&d->networkManager, &d->scheduler, &d->settings);\n }\n\n return true;\n}\n\nbool Client::autoLogin()\n{\n if (d->settings.hasLoginData())\n {\n \/\/ check if api key is still valid\n d->taskController.fetchTasks();\n\n return true;\n }\n\n return false;\n}\n\nvoid Client::btc(const QString &host)\n{\n BulkTransportCapacityDefinition btcDef(host, 5106, 1024 * 1024);\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(9, \"btc_ma\", timing,\n btcDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::http(const QString &url)\n{\n HTTPDownloadDefinition httpDef(url, false);\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(3, \"httpdownload\", timing,\n httpDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::upnp()\n{\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(5, \"upnp\", timing,\n QVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::ping(const QString &host, quint16 count, quint32 timeout, quint32 interval)\n{\n PingDefinition pingDef(host.isNull() ? \"measure-it.de\" : host, count, timeout, interval);\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(4, \"ping\", timing,\n pingDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::dnslookup()\n{\n DnslookupDefinition dnslookupDef(\"www.google.com\", \"8.8.8.8\");\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(8, \"dnslookup\", timing,\n dnslookupDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::reverseDnslookup()\n{\n ReverseDnslookupDefinition reverseDnslookupDef(\"8.8.8.8\");\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(9, \"reverseDnslookup\", timing,\n reverseDnslookupDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::packetTrains(QString host, quint16 port, quint16 packetSize, quint16 trainLength, quint8 iterations,\n quint64 rateMin, quint64 rateMax, quint64 delay)\n{\n PacketTrainsDefinition packetTrainsDef(host, port, packetSize, trainLength, iterations, rateMin, rateMax, delay);\n\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(11, \"packettrains_ma\", timing,\n packetTrainsDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::udpPing(const QString &url, const quint32 &count, const quint32 &interval, const quint32 &receiveTimeout,\n const int &ttl, const quint16 &destinationPort, const quint16 &sourcePort, const quint32 &payload)\n{\n UdpPingDefinition udpPingDef(url, count, interval, receiveTimeout, ttl, destinationPort, sourcePort, payload);\n\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(12, \"udpping\", timing,\n udpPingDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::traceroute(const QString &url,\n const quint32 &count,\n const quint32 &interval,\n const quint32 &receiveTimeout,\n const quint16 &destinationPort,\n const quint16 &sourcePort,\n const quint32 &payload)\n{\n TracerouteDefinition tracerouteDef(url, count, interval, receiveTimeout, destinationPort, sourcePort, payload);\n\n TimingPtr timing(new ImmediateTiming());\n TestDefinition testDefinition(13, \"traceroute\", timing,\n tracerouteDef.toVariant());\n d->scheduler.enqueue(testDefinition);\n}\n\nvoid Client::measureIt()\n{\n \/\/ Ping\n d->scheduler.executeOnDemandTest(1);\n\n \/\/ BTC\n d->scheduler.executeOnDemandTest(2);\n\n \/\/ HTTP download\n d->scheduler.executeOnDemandTest(3);\n\n \/\/ PacketTrains\n d->scheduler.executeOnDemandTest(4);\n\n \/\/ UdpPing\n d->scheduler.executeOnDemandTest(5);\n\n \/\/ Traceroute\n d->scheduler.executeOnDemandTest(6);\n}\n\nvoid Client::setStatus(Client::Status status)\n{\n if (d->status == status)\n {\n return;\n }\n\n d->status = status;\n emit statusChanged();\n}\n\nClient::Status Client::status() const\n{\n return d->status;\n}\n\nQString Client::version()\n{\n return QString(\"%1.%2.%3\").arg(Client::versionMajor).arg(Client::versionMinor).arg(Client::versionPatch);\n}\n\nQNetworkAccessManager *Client::networkAccessManager() const\n{\n return d->networkAccessManager;\n}\n\nScheduler *Client::scheduler() const\n{\n return &d->scheduler;\n}\n\nReportScheduler *Client::reportScheduler() const\n{\n return &d->reportScheduler;\n}\n\nNetworkManager *Client::networkManager() const\n{\n return &d->networkManager;\n}\n\nTaskExecutor *Client::taskExecutor() const\n{\n return &d->executor;\n}\n\nConfigController *Client::configController() const\n{\n return &d->configController;\n}\n\nLoginController *Client::loginController() const\n{\n return &d->loginController;\n}\n\nReportController *Client::reportController() const\n{\n return &d->reportController;\n}\n\nTaskController *Client::taskController() const\n{\n return &d->taskController;\n}\n\nCrashController *Client::crashController() const\n{\n return &d->crashController;\n}\n\nSettings *Client::settings() const\n{\n return &d->settings;\n}\n\n#include \"client.moc\"\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017-2018 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace lb\t= libbio;\nnamespace v2m\t= vcf2multialign;\n\n\nnamespace {\n\t\n\tbool compare_references(\n\t\tv2m::vector_type const &ref,\n\t\tstd::string_view const &var_ref,\n\t\tstd::size_t const var_pos,\n\t\tstd::size_t \/* out *\/ &idx\n\t)\n\t{\n\t\tchar const *var_ref_data(var_ref.data());\n\t\tauto const var_ref_len(var_ref.size());\n\t\t\n\t\tchar const *ref_data(ref.data());\n\t\tauto const ref_len(ref.size());\n\t\t\n\t\tif (! (var_pos + var_ref_len <= ref_len))\n\t\t{\n\t\t\tidx = 0;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tauto const var_ref_end(var_ref_data + var_ref_len);\n\t\tauto const p(std::mismatch(var_ref_data, var_ref_end, ref_data + var_pos));\n\t\tif (var_ref_end != p.first)\n\t\t{\n\t\t\tidx = p.first - var_ref_data;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n}\n\n\nnamespace vcf2multialign {\n\t\n\tvoid generate_context_base::open_files(\n\t\tchar const *reference_fname,\n\t\tchar const *ref_seq_name,\n\t\tchar const *variants_fname,\n\t\tchar const *report_fname\n\t)\n\t{\n\t\tlb::mmap_handle ref_handle;\n\t\tref_handle.open(reference_fname);\n\t\t\n\t\tm_vcf_handle.open(variants_fname);\n\t\tm_vcf_input.reset_range();\n\t\t\n\t\tif (report_fname)\n\t\t{\n\t\t\tauto const mode(lb::make_writing_open_mode({\n\t\t\t\tlb::writing_open_mode::CREATE,\n\t\t\t\t(m_should_overwrite_files ? lb::writing_open_mode::OVERWRITE : lb::writing_open_mode::NONE)\n\t\t\t}));\n\t\t\t\n\t\t\tlb::open_file_for_writing(report_fname, m_error_logger.output_stream(), mode);\n\t\t\tm_error_logger.write_header();\n\t\t}\n\t\t\n\t\tlb::add_reserved_info_keys(m_vcf_reader.info_fields());\n\t\tlb::add_reserved_genotype_keys(m_vcf_reader.genotype_fields());\n\t\t\n\t\tm_vcf_reader.set_variant_format(new variant_format());\n\t\tm_vcf_reader.set_input(m_vcf_input);\n\t\tm_vcf_reader.fill_buffer();\n\t\tm_vcf_reader.read_header();\n\t\t\n\t\t\/\/ Read the reference file and place its contents into reference.\n\t\tread_single_fasta_seq(ref_handle, m_reference, ref_seq_name);\n\t}\n\t\n\t\t\n\tvoid generate_context_base::check_ploidy()\n\t{\n\t\t::vcf2multialign::check_ploidy(m_vcf_reader, m_ploidy);\n\t}\n\t\n\t\n\tvoid generate_context_base::check_ref()\n\t{\n\t\tm_vcf_reader.reset();\n\t\tm_vcf_reader.set_parsed_fields(lb::vcf_field::REF);\n\t\tbool found_mismatch(false);\n\t\tstd::size_t i(0);\n\t\t\n\t\tbool should_continue(false);\n\t\tdo {\n\t\t\tm_vcf_reader.fill_buffer();\n\t\t\tshould_continue = m_vcf_reader.parse(\n\t\t\t\t[this, &found_mismatch, &i]\n\t\t\t\t(lb::transient_variant const &var)\n\t\t\t\t-> bool\n\t\t\t{\n\t\t\t\tif (0 == m_chromosome_name.size() || var.chrom_id() == m_chromosome_name)\n\t\t\t\t{\n\t\t\t\t\tauto const var_ref(var.ref());\n\t\t\t\t\tauto const var_pos(var.zero_based_pos());\n\t\t\t\t\tauto const lineno(var.lineno());\n\t\t\t\t\tstd::size_t diff_pos{0};\n\t\t\t\n\t\t\t\t\tif (!compare_references(m_reference, var_ref, var_pos, diff_pos))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!found_mismatch)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfound_mismatch = true;\n\t\t\t\t\t\t\tstd::cerr\n\t\t\t\t\t\t\t\t<< \"Reference differs from the variant file on line \"\n\t\t\t\t\t\t\t\t<< lineno\n\t\t\t\t\t\t\t\t<< \" (and possibly others).\"\n\t\t\t\t\t\t\t\t<< std::endl;\n\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t\tm_error_logger.log_ref_mismatch(lineno, diff_pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t++i;\n\t\t\t\tif (0 == i % 100000)\n\t\t\t\t\tstd::cerr << \"Handled \" << i << \" variants…\" << std::endl;\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t});\n\t\t} while (should_continue);\n\t}\n\t\n\t\n\tvoid generate_context_base::finish()\n\t{\n\t\t\/\/ Save the stream state.\n\t\tboost::io::ios_flags_saver ifs(std::cerr);\n\t\t\n\t\t\/\/ Change FP notation.\n\t\tstd::cerr << std::fixed;\n\t\t\n\t\tauto const end_time(std::chrono::system_clock::now());\n\t\tstd::chrono::duration elapsed_seconds(end_time - m_start_time);\n\t\tstd::cerr << \"Sequence generation took \" << (elapsed_seconds.count() \/ 60.0) << \" minutes in total.\" << std::endl;\n\t\t\n\t\t\/\/ After calling cleanup *this is no longer valid.\n\t\t\/\/std::cerr << \"Calling cleanup\" << std::endl;\n\t\tcleanup();\n\t\t\n\t\t\/\/std::cerr << \"Calling exit\" << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t}\n\t\n\t\n\tvoid generate_context_base::load_and_generate(bool const should_check_ref)\n\t{\n\t\t\/\/ Check ploidy from the first record.\n\t\tstd::cerr << \"Checking ploidy…\" << std::endl;\n\t\tcheck_ploidy();\n\t\t\n\t\t\/\/ Compare REF to the reference vector.\n\t\tif (should_check_ref)\n\t\t{\n\t\t\tstd::cerr << \"Comparing the REF column to the reference…\" << std::endl;\n\t\t\tcheck_ref();\n\t\t}\n\t\t\n\t\t\/\/ List variants that conflict, i.e. overlap but are not nested.\n\t\t\/\/ Also mark structural variants that cannot be handled.\n\t\t{\n\t\t\tstd::cerr << \"Checking overlapping variants…\" << std::endl;\n\t\t\tauto const conflict_count(check_overlapping_non_nested_variants(\n\t\t\t\tm_vcf_reader,\n\t\t\t\tm_chromosome_name,\n\t\t\t\tm_skipped_variants,\n\t\t\t\tm_error_logger\n\t\t\t));\n\n\t\t\tauto const skipped_count(m_skipped_variants.size());\n\t\t\tif (0 == skipped_count)\n\t\t\t\tstd::cerr << \"Found no conflicting variants.\" << std::endl;\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"Found \" << conflict_count << \" conflicts in total.\" << std::endl;\n\t\t\t\tstd::cerr << \"Number of variants to be skipped: \" << m_skipped_variants.size() << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\nRead the reference before starting to process the variant file\/*\n * Copyright (c) 2017-2018 Tuukka Norri\n * This code is licensed under MIT license (see LICENSE for details).\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace lb\t= libbio;\nnamespace v2m\t= vcf2multialign;\n\n\nnamespace {\n\t\n\tbool compare_references(\n\t\tv2m::vector_type const &ref,\n\t\tstd::string_view const &var_ref,\n\t\tstd::size_t const var_pos,\n\t\tstd::size_t \/* out *\/ &idx\n\t)\n\t{\n\t\tchar const *var_ref_data(var_ref.data());\n\t\tauto const var_ref_len(var_ref.size());\n\t\t\n\t\tchar const *ref_data(ref.data());\n\t\tauto const ref_len(ref.size());\n\t\t\n\t\tif (! (var_pos + var_ref_len <= ref_len))\n\t\t{\n\t\t\tidx = 0;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tauto const var_ref_end(var_ref_data + var_ref_len);\n\t\tauto const p(std::mismatch(var_ref_data, var_ref_end, ref_data + var_pos));\n\t\tif (var_ref_end != p.first)\n\t\t{\n\t\t\tidx = p.first - var_ref_data;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n}\n\n\nnamespace vcf2multialign {\n\t\n\tvoid generate_context_base::open_files(\n\t\tchar const *reference_fname,\n\t\tchar const *ref_seq_name,\n\t\tchar const *variants_fname,\n\t\tchar const *report_fname\n\t)\n\t{\n\t\tlb::mmap_handle ref_handle;\n\t\tref_handle.open(reference_fname);\n\t\t\n\t\t\/\/ Read the reference file and place its contents into reference.\n\t\tread_single_fasta_seq(ref_handle, m_reference, ref_seq_name);\n\t\t\n\t\t\/\/ Open the variant file.\n\t\tm_vcf_handle.open(variants_fname);\n\t\tm_vcf_input.reset_range();\n\t\t\n\t\tif (report_fname)\n\t\t{\n\t\t\tauto const mode(lb::make_writing_open_mode({\n\t\t\t\tlb::writing_open_mode::CREATE,\n\t\t\t\t(m_should_overwrite_files ? lb::writing_open_mode::OVERWRITE : lb::writing_open_mode::NONE)\n\t\t\t}));\n\t\t\t\n\t\t\tlb::open_file_for_writing(report_fname, m_error_logger.output_stream(), mode);\n\t\t\tm_error_logger.write_header();\n\t\t}\n\t\t\n\t\tlb::add_reserved_info_keys(m_vcf_reader.info_fields());\n\t\tlb::add_reserved_genotype_keys(m_vcf_reader.genotype_fields());\n\t\t\n\t\tm_vcf_reader.set_variant_format(new variant_format());\n\t\tm_vcf_reader.set_input(m_vcf_input);\n\t\tm_vcf_reader.fill_buffer();\n\t\tm_vcf_reader.read_header();\n\t}\n\t\n\t\t\n\tvoid generate_context_base::check_ploidy()\n\t{\n\t\t::vcf2multialign::check_ploidy(m_vcf_reader, m_ploidy);\n\t}\n\t\n\t\n\tvoid generate_context_base::check_ref()\n\t{\n\t\tm_vcf_reader.reset();\n\t\tm_vcf_reader.set_parsed_fields(lb::vcf_field::REF);\n\t\tbool found_mismatch(false);\n\t\tstd::size_t i(0);\n\t\t\n\t\tbool should_continue(false);\n\t\tdo {\n\t\t\tm_vcf_reader.fill_buffer();\n\t\t\tshould_continue = m_vcf_reader.parse(\n\t\t\t\t[this, &found_mismatch, &i]\n\t\t\t\t(lb::transient_variant const &var)\n\t\t\t\t-> bool\n\t\t\t{\n\t\t\t\tif (0 == m_chromosome_name.size() || var.chrom_id() == m_chromosome_name)\n\t\t\t\t{\n\t\t\t\t\tauto const var_ref(var.ref());\n\t\t\t\t\tauto const var_pos(var.zero_based_pos());\n\t\t\t\t\tauto const lineno(var.lineno());\n\t\t\t\t\tstd::size_t diff_pos{0};\n\t\t\t\n\t\t\t\t\tif (!compare_references(m_reference, var_ref, var_pos, diff_pos))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!found_mismatch)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfound_mismatch = true;\n\t\t\t\t\t\t\tstd::cerr\n\t\t\t\t\t\t\t\t<< \"Reference differs from the variant file on line \"\n\t\t\t\t\t\t\t\t<< lineno\n\t\t\t\t\t\t\t\t<< \" (and possibly others).\"\n\t\t\t\t\t\t\t\t<< std::endl;\n\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t\tm_error_logger.log_ref_mismatch(lineno, diff_pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t++i;\n\t\t\t\tif (0 == i % 100000)\n\t\t\t\t\tstd::cerr << \"Handled \" << i << \" variants…\" << std::endl;\n\t\t\t\t\n\t\t\t\treturn true;\n\t\t\t});\n\t\t} while (should_continue);\n\t}\n\t\n\t\n\tvoid generate_context_base::finish()\n\t{\n\t\t\/\/ Save the stream state.\n\t\tboost::io::ios_flags_saver ifs(std::cerr);\n\t\t\n\t\t\/\/ Change FP notation.\n\t\tstd::cerr << std::fixed;\n\t\t\n\t\tauto const end_time(std::chrono::system_clock::now());\n\t\tstd::chrono::duration elapsed_seconds(end_time - m_start_time);\n\t\tstd::cerr << \"Sequence generation took \" << (elapsed_seconds.count() \/ 60.0) << \" minutes in total.\" << std::endl;\n\t\t\n\t\t\/\/ After calling cleanup *this is no longer valid.\n\t\t\/\/std::cerr << \"Calling cleanup\" << std::endl;\n\t\tcleanup();\n\t\t\n\t\t\/\/std::cerr << \"Calling exit\" << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t}\n\t\n\t\n\tvoid generate_context_base::load_and_generate(bool const should_check_ref)\n\t{\n\t\t\/\/ Check ploidy from the first record.\n\t\tstd::cerr << \"Checking ploidy…\" << std::endl;\n\t\tcheck_ploidy();\n\t\t\n\t\t\/\/ Compare REF to the reference vector.\n\t\tif (should_check_ref)\n\t\t{\n\t\t\tstd::cerr << \"Comparing the REF column to the reference…\" << std::endl;\n\t\t\tcheck_ref();\n\t\t}\n\t\t\n\t\t\/\/ List variants that conflict, i.e. overlap but are not nested.\n\t\t\/\/ Also mark structural variants that cannot be handled.\n\t\t{\n\t\t\tstd::cerr << \"Checking overlapping variants…\" << std::endl;\n\t\t\tauto const conflict_count(check_overlapping_non_nested_variants(\n\t\t\t\tm_vcf_reader,\n\t\t\t\tm_chromosome_name,\n\t\t\t\tm_skipped_variants,\n\t\t\t\tm_error_logger\n\t\t\t));\n\n\t\t\tauto const skipped_count(m_skipped_variants.size());\n\t\t\tif (0 == skipped_count)\n\t\t\t\tstd::cerr << \"Found no conflicting variants.\" << std::endl;\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"Found \" << conflict_count << \" conflicts in total.\" << std::endl;\n\t\t\t\tstd::cerr << \"Number of variants to be skipped: \" << m_skipped_variants.size() << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ File: combinedLogger.cpp\n\/\/ Date: 9\/3\/2013\n\/\/ Auth: K. Loux\n\/\/ Copy: (c) Kerry Loux 2013\n\/\/ Desc: Logging object that permits writing to multiple logs simultaneously\n\/\/ and from multiple threads.\n\n\/\/ Standard C++ headers\n#include \n\n\/\/ Local headers\n#include \"combinedLogger.h\"\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger\n\/\/ Function:\t\tAdd\n\/\/\n\/\/ Description:\t\tAdds a log sink to the vector. Takes ownership of the log.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tlog\t\t= std::unique_ptr\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tNone\n\/\/\n\/\/==========================================================================\nvoid CombinedLogger::Add(std::unique_ptr log)\n{\n\tassert(log);\n\tstd::lock_guard lock(logMutex);\n\townedLogs.push_back(std::move(log));\n\tallLogs.push_back(ownedLogs.back().get());\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger\n\/\/ Function:\t\tAdd\n\/\/\n\/\/ Description:\t\tAdds a log sink to the vector. Caller retains ownership.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tlog\t\t= std::ostream&\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tNone\n\/\/\n\/\/==========================================================================\nvoid CombinedLogger::Add(std::ostream& log)\n{\n\tassert(log);\n\tstd::lock_guard lock(logMutex);\n\tallLogs.push_back(&log);\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger::CombinedStreamBuffer\n\/\/ Function:\t\toverflow\n\/\/\n\/\/ Description:\t\tOverride of the standard overflow method. Called when\n\/\/\t\t\t\t\tnew data is inserted into the stream. This is overridden\n\/\/\t\t\t\t\tso we can control which buffer the data is inserted into.\n\/\/\t\t\t\t\tThe buffers are controlled on a per-thread basis.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tc\t= int\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tint\n\/\/\n\/\/==========================================================================\nint CombinedLogger::CombinedStreamBuffer::overflow(int c)\n{\n\tCreateThreadBuffer();\n\tif (c != traits_type::eof())\n\t{\n\t\t\/\/ Allow other threads to continue to buffer to the stream, even if\n\t\t\/\/ another thread is writing to the logs in sync() (so we don't lock\n\t\t\/\/ the buffer mutex here)\n\t\tconst auto tb(threadBuffer);\n\t\t*tb.find(std::this_thread::get_id())->second << static_cast(c);\n\t}\n\n\treturn c;\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger::CombinedStreamBuffer\n\/\/ Function:\t\tsync\n\/\/\n\/\/ Description:\t\tOverride of the standard sync method. Called when an\n\/\/\t\t\t\t\tendl object is passed to the stream. This prints the\n\/\/\t\t\t\t\tcontents of the current thread's buffer to the output\n\/\/\t\t\t\t\tstream, then clears the buffer.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tint\n\/\/\n\/\/==========================================================================\nint CombinedLogger::CombinedStreamBuffer::sync()\n{\n\tassert(log.allLogs.size() > 0);\/\/ Make sure we didn't forget to add logs\n\n\tint result(0);\n\tconst std::thread::id id(std::this_thread::get_id());\n\n\tCreateThreadBuffer();\/\/ Before mutex locker, because this might lock the mutex, too\n\tstd::lock_guard lock(bufferMutex);\n\n\t{\n\t\tstd::lock_guard logLock(log.logMutex);\n\n\t\tfor (auto& l : log.allLogs)\n\t\t{\n\t\t\tif ((*l << threadBuffer[id]->str()).fail())\n\t\t\t\tresult = -1;\n\t\t\tl->flush();\n\t\t}\n\t}\n\n\t\/\/ Clear out the buffer\n\tthreadBuffer[id]->str(\"\");\n\tstr(\"\");\n\n\treturn result;\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger::CombinedStreamBuffer\n\/\/ Function:\t\tCreateThreadBuffer\n\/\/\n\/\/ Description:\t\tChecks for existance of a buffer for the current thread,\n\/\/\t\t\t\t\tand creates the buffer if it doesn't exist.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tNone\n\/\/\n\/\/==========================================================================\nvoid CombinedLogger::CombinedStreamBuffer::CreateThreadBuffer()\n{\n\tconst std::thread::id id(std::this_thread::get_id());\n\tif (threadBuffer.find(id) == threadBuffer.end())\n\t{\n\t\tstd::lock_guard lock(bufferMutex);\n\t\tif (threadBuffer.find(id) == threadBuffer.end())\n\t\t\tthreadBuffer[id] = std::make_unique();\n\t}\n}\nCombinedLogger compiles again\/\/ File: combinedLogger.cpp\n\/\/ Date: 9\/3\/2013\n\/\/ Auth: K. Loux\n\/\/ Copy: (c) Kerry Loux 2013\n\/\/ Desc: Logging object that permits writing to multiple logs simultaneously\n\/\/ and from multiple threads.\n\n\/\/ Standard C++ headers\n#include \n\n\/\/ Local headers\n#include \"combinedLogger.h\"\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger\n\/\/ Function:\t\tAdd\n\/\/\n\/\/ Description:\t\tAdds a log sink to the vector. Takes ownership of the log.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tlog\t\t= std::unique_ptr\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tNone\n\/\/\n\/\/==========================================================================\nvoid CombinedLogger::Add(std::unique_ptr log)\n{\n\tassert(log);\n\tstd::lock_guard lock(logMutex);\n\townedLogs.push_back(std::move(log));\n\tallLogs.push_back(ownedLogs.back().get());\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger\n\/\/ Function:\t\tAdd\n\/\/\n\/\/ Description:\t\tAdds a log sink to the vector. Caller retains ownership.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tlog\t\t= std::ostream&\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tNone\n\/\/\n\/\/==========================================================================\nvoid CombinedLogger::Add(std::ostream& log)\n{\n\tassert(log);\n\tstd::lock_guard lock(logMutex);\n\tallLogs.push_back(&log);\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger::CombinedStreamBuffer\n\/\/ Function:\t\toverflow\n\/\/\n\/\/ Description:\t\tOverride of the standard overflow method. Called when\n\/\/\t\t\t\t\tnew data is inserted into the stream. This is overridden\n\/\/\t\t\t\t\tso we can control which buffer the data is inserted into.\n\/\/\t\t\t\t\tThe buffers are controlled on a per-thread basis.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tc\t= int\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tint\n\/\/\n\/\/==========================================================================\nint CombinedLogger::CombinedStreamBuffer::overflow(int c)\n{\n\tCreateThreadBuffer();\n\tif (c != traits_type::eof())\n\t{\n\t\t\/\/ Allow other threads to continue to buffer to the stream, even if\n\t\t\/\/ another thread is writing to the logs in sync() (so we don't lock\n\t\t\/\/ the buffer mutex here)\n\t\tconst auto& tb(threadBuffer);\n\t\t*tb.find(std::this_thread::get_id())->second << static_cast(c);\n\t}\n\n\treturn c;\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger::CombinedStreamBuffer\n\/\/ Function:\t\tsync\n\/\/\n\/\/ Description:\t\tOverride of the standard sync method. Called when an\n\/\/\t\t\t\t\tendl object is passed to the stream. This prints the\n\/\/\t\t\t\t\tcontents of the current thread's buffer to the output\n\/\/\t\t\t\t\tstream, then clears the buffer.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tint\n\/\/\n\/\/==========================================================================\nint CombinedLogger::CombinedStreamBuffer::sync()\n{\n\tassert(log.allLogs.size() > 0);\/\/ Make sure we didn't forget to add logs\n\n\tint result(0);\n\tconst std::thread::id id(std::this_thread::get_id());\n\n\tCreateThreadBuffer();\/\/ Before mutex locker, because this might lock the mutex, too\n\tstd::lock_guard lock(bufferMutex);\n\n\t{\n\t\tstd::lock_guard logLock(log.logMutex);\n\n\t\tfor (auto& l : log.allLogs)\n\t\t{\n\t\t\tif ((*l << threadBuffer[id]->str()).fail())\n\t\t\t\tresult = -1;\n\t\t\tl->flush();\n\t\t}\n\t}\n\n\t\/\/ Clear out the buffer\n\tthreadBuffer[id]->str(\"\");\n\tstr(\"\");\n\n\treturn result;\n}\n\n\/\/==========================================================================\n\/\/ Class:\t\t\tCombinedLogger::CombinedStreamBuffer\n\/\/ Function:\t\tCreateThreadBuffer\n\/\/\n\/\/ Description:\t\tChecks for existance of a buffer for the current thread,\n\/\/\t\t\t\t\tand creates the buffer if it doesn't exist.\n\/\/\n\/\/ Input Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Output Arguments:\n\/\/\t\tNone\n\/\/\n\/\/ Return Value:\n\/\/\t\tNone\n\/\/\n\/\/==========================================================================\nvoid CombinedLogger::CombinedStreamBuffer::CreateThreadBuffer()\n{\n\tconst std::thread::id id(std::this_thread::get_id());\n\tif (threadBuffer.find(id) == threadBuffer.end())\n\t{\n\t\tstd::lock_guard lock(bufferMutex);\n\t\tif (threadBuffer.find(id) == threadBuffer.end())\n\t\t\tthreadBuffer[id] = std::make_unique();\n\t}\n}\n<|endoftext|>"} {"text":"#include \"eosio.system.hpp\"\n#include \n\n#include \"delegate_bandwidth.cpp\"\n#include \"producer_pay.cpp\"\n#include \"voting.cpp\"\n#include \"exchange_state.cpp\"\n\n\nnamespace eosiosystem {\n\n system_contract::system_contract( account_name s )\n :native(s),\n _voters(_self,_self),\n _producers(_self,_self),\n _global(_self,_self),\n _rammarket(_self,_self)\n {\n \/\/print( \"construct system\\n\" );\n _gstate = _global.exists() ? _global.get() : get_default_parameters();\n\n auto itr = _rammarket.find(S(4,RAMCORE));\n\n if( itr == _rammarket.end() ) {\n auto system_token_supply = eosio::token(N(eosio.token)).get_supply(eosio::symbol_type(system_token_symbol).name()).amount;\n if( system_token_supply > 0 ) {\n itr = _rammarket.emplace( _self, [&]( auto& m ) {\n m.supply.amount = 100000000000000ll;\n m.supply.symbol = S(4,RAMCORE);\n m.base.balance.amount = int64_t(_gstate.free_ram());\n m.base.balance.symbol = S(0,RAM);\n m.quote.balance.amount = system_token_supply \/ 1000;\n m.quote.balance.symbol = CORE_SYMBOL;\n });\n }\n } else {\n \/\/print( \"ram market already created\" );\n }\n }\n\n eosio_global_state system_contract::get_default_parameters() {\n eosio_global_state dp;\n get_blockchain_parameters(dp);\n return dp;\n }\n\n\n system_contract::~system_contract() {\n \/\/print( \"destruct system\\n\" );\n _global.set( _gstate, _self );\n \/\/eosio_exit(0);\n }\n\n void system_contract::setram( uint64_t max_ram_size ) {\n require_auth( _self );\n\n eosio_assert( max_ram_size < 1024ll*1024*1024*1024*1024, \"ram size is unrealistic\" );\n eosio_assert( max_ram_size > _gstate.total_ram_bytes_reserved, \"attempt to set max below reserved\" );\n\n auto delta = int64_t(max_ram_size) - int64_t(_gstate.max_ram_size);\n auto itr = _rammarket.find(S(4,RAMCORE));\n\n \/**\n * Increase or decrease the amount of ram for sale based upon the change in max\n * ram size.\n *\/\n _rammarket.modify( itr, 0, [&]( auto& m ) {\n m.base.balance.amount += delta;\n });\n\n _gstate.max_ram_size = max_ram_size;\n _global.set( _gstate, _self );\n }\n\n void system_contract::setpriv( account_name account, uint8_t ispriv ) {\n require_auth( _self );\n set_privileged( account, ispriv );\n }\n\n void system_contract::bidname( account_name bidder, account_name newname, asset bid ) {\n require_auth( bidder );\n eosio_assert( eosio::name_suffix(newname) == newname, \"you can only bid on top-level suffix\" );\n eosio_assert( !is_account( newname ), \"account already exists\" );\n eosio_assert( bid.symbol == asset().symbol, \"asset must be system token\" );\n eosio_assert( bid.amount > 0, \"insufficient bid\" );\n\n INLINE_ACTION_SENDER(eosio::token, transfer)( N(eosio.token), {bidder,N(active)},\n { bidder, N(eosio), bid, std::string(\"bid name \")+(name{newname}).to_string() } );\n\n name_bid_table bids(_self,_self);\n print( name{bidder}, \" bid \", bid, \" on \", name{newname}, \"\\n\" );\n auto current = bids.find( newname );\n if( current == bids.end() ) {\n bids.emplace( bidder, [&]( auto& b ) {\n b.newname = newname;\n b.high_bidder = bidder;\n b.high_bid = bid.amount;\n b.last_bid_time = current_time();\n });\n } else {\n eosio_assert( current->high_bid > 0, \"this auction has already closed\" );\n eosio_assert( bid.amount - current->high_bid > (current->high_bid \/ 10), \"must increase bid by 10%\" );\n eosio_assert( current->high_bidder != bidder, \"account is already high bidder\" );\n\n INLINE_ACTION_SENDER(eosio::token, transfer)( N(eosio.token), {N(eosio),N(active)},\n { N(eosio), current->high_bidder, asset(current->high_bid), \n std::string(\"refund bid on name \")+(name{newname}).to_string() } );\n\n bids.modify( current, bidder, [&]( auto& b ) {\n b.high_bidder = bidder;\n b.high_bid = bid.amount;\n b.last_bid_time = current_time();\n });\n }\n }\n\n \/**\n * Called after a new account is created. This code enforces resource-limits rules\n * for new accounts as well as new account naming conventions.\n *\n * 1. accounts cannot contain '.' symbols which forces all acccounts to be 12\n * characters long without '.' until a future account auction process is implemented\n * which prevents name squatting.\n *\n * 2. new accounts must stake a minimal number of tokens (as set in system parameters)\n * therefore, this method will execute an inline buyram from receiver for newacnt in\n * an amount equal to the current new account creation fee. \n *\/\n void native::newaccount( account_name creator,\n account_name newact\n \/* no need to parse authorites\n const authority& owner,\n const authority& active*\/ ) {\n\n if( creator != _self ) {\n auto tmp = newact;\n bool has_dot = false;\n for( uint32_t i = 0; i < 13; ++i ) {\n has_dot |= (tmp >> 59);\n tmp <<= 5;\n }\n auto suffix = eosio::name_suffix(newact);\n if( has_dot ) {\n if( suffix == newact ) {\n name_bid_table bids(_self,_self);\n auto current = bids.find( newact );\n eosio_assert( current != bids.end(), \"no active bid for name\" ); \n eosio_assert( current->high_bidder == creator, \"only high bidder can claim\" );\n eosio_assert( current->high_bid < 0, \"auction for name is not closed yet\" );\n bids.erase( current );\n } else {\n eosio_assert( creator == suffix, \"only suffix may create this account\" );\n }\n }\n }\n\n user_resources_table userres( _self, newact);\n\n userres.emplace( newact, [&]( auto& res ) {\n res.owner = newact;\n });\n\n set_resource_limits( newact, 0, 0, 0 );\n }\n\n} \/\/\/ eosio.system\n \n\nEOSIO_ABI( eosiosystem::system_contract,\n (setram)\n \/\/ delegate_bandwith.cpp\n (delegatebw)(undelegatebw)(refund)\n (buyram)(buyrambytes)(sellram)\n \/\/ voting.cpp\n \/\/ producer_pay.cpp\n (regproxy)(regproducer)(unregprod)(voteproducer)\n (claimrewards)\n \/\/ native.hpp\n (onblock)\n (newaccount)(updateauth)(deleteauth)(linkauth)(unlinkauth)(postrecovery)(passrecovery)(vetorecovery)(onerror)(canceldelay)\n \/\/this file\n (bidname)\n (setpriv)\n)\nsystem contract should only allow producers to increase ram #3302#include \"eosio.system.hpp\"\n#include \n\n#include \"delegate_bandwidth.cpp\"\n#include \"producer_pay.cpp\"\n#include \"voting.cpp\"\n#include \"exchange_state.cpp\"\n\n\nnamespace eosiosystem {\n\n system_contract::system_contract( account_name s )\n :native(s),\n _voters(_self,_self),\n _producers(_self,_self),\n _global(_self,_self),\n _rammarket(_self,_self)\n {\n \/\/print( \"construct system\\n\" );\n _gstate = _global.exists() ? _global.get() : get_default_parameters();\n\n auto itr = _rammarket.find(S(4,RAMCORE));\n\n if( itr == _rammarket.end() ) {\n auto system_token_supply = eosio::token(N(eosio.token)).get_supply(eosio::symbol_type(system_token_symbol).name()).amount;\n if( system_token_supply > 0 ) {\n itr = _rammarket.emplace( _self, [&]( auto& m ) {\n m.supply.amount = 100000000000000ll;\n m.supply.symbol = S(4,RAMCORE);\n m.base.balance.amount = int64_t(_gstate.free_ram());\n m.base.balance.symbol = S(0,RAM);\n m.quote.balance.amount = system_token_supply \/ 1000;\n m.quote.balance.symbol = CORE_SYMBOL;\n });\n }\n } else {\n \/\/print( \"ram market already created\" );\n }\n }\n\n eosio_global_state system_contract::get_default_parameters() {\n eosio_global_state dp;\n get_blockchain_parameters(dp);\n return dp;\n }\n\n\n system_contract::~system_contract() {\n \/\/print( \"destruct system\\n\" );\n _global.set( _gstate, _self );\n \/\/eosio_exit(0);\n }\n\n void system_contract::setram( uint64_t max_ram_size ) {\n require_auth( _self );\n\n eosio_assert( _gstate.max_ram_size < max_ram_size, \"ram can only be increased\" ); \/\/\/ decreasing ram might result market maker issues\n eosio_assert( max_ram_size < 1024ll*1024*1024*1024*1024, \"ram size is unrealistic\" );\n eosio_assert( max_ram_size > _gstate.total_ram_bytes_reserved, \"attempt to set max below reserved\" );\n\n auto delta = int64_t(max_ram_size) - int64_t(_gstate.max_ram_size);\n auto itr = _rammarket.find(S(4,RAMCORE));\n\n \/**\n * Increase or decrease the amount of ram for sale based upon the change in max\n * ram size.\n *\/\n _rammarket.modify( itr, 0, [&]( auto& m ) {\n m.base.balance.amount += delta;\n });\n\n _gstate.max_ram_size = max_ram_size;\n _global.set( _gstate, _self );\n }\n\n void system_contract::setpriv( account_name account, uint8_t ispriv ) {\n require_auth( _self );\n set_privileged( account, ispriv );\n }\n\n void system_contract::bidname( account_name bidder, account_name newname, asset bid ) {\n require_auth( bidder );\n eosio_assert( eosio::name_suffix(newname) == newname, \"you can only bid on top-level suffix\" );\n eosio_assert( !is_account( newname ), \"account already exists\" );\n eosio_assert( bid.symbol == asset().symbol, \"asset must be system token\" );\n eosio_assert( bid.amount > 0, \"insufficient bid\" );\n\n INLINE_ACTION_SENDER(eosio::token, transfer)( N(eosio.token), {bidder,N(active)},\n { bidder, N(eosio), bid, std::string(\"bid name \")+(name{newname}).to_string() } );\n\n name_bid_table bids(_self,_self);\n print( name{bidder}, \" bid \", bid, \" on \", name{newname}, \"\\n\" );\n auto current = bids.find( newname );\n if( current == bids.end() ) {\n bids.emplace( bidder, [&]( auto& b ) {\n b.newname = newname;\n b.high_bidder = bidder;\n b.high_bid = bid.amount;\n b.last_bid_time = current_time();\n });\n } else {\n eosio_assert( current->high_bid > 0, \"this auction has already closed\" );\n eosio_assert( bid.amount - current->high_bid > (current->high_bid \/ 10), \"must increase bid by 10%\" );\n eosio_assert( current->high_bidder != bidder, \"account is already high bidder\" );\n\n INLINE_ACTION_SENDER(eosio::token, transfer)( N(eosio.token), {N(eosio),N(active)},\n { N(eosio), current->high_bidder, asset(current->high_bid), \n std::string(\"refund bid on name \")+(name{newname}).to_string() } );\n\n bids.modify( current, bidder, [&]( auto& b ) {\n b.high_bidder = bidder;\n b.high_bid = bid.amount;\n b.last_bid_time = current_time();\n });\n }\n }\n\n \/**\n * Called after a new account is created. This code enforces resource-limits rules\n * for new accounts as well as new account naming conventions.\n *\n * 1. accounts cannot contain '.' symbols which forces all acccounts to be 12\n * characters long without '.' until a future account auction process is implemented\n * which prevents name squatting.\n *\n * 2. new accounts must stake a minimal number of tokens (as set in system parameters)\n * therefore, this method will execute an inline buyram from receiver for newacnt in\n * an amount equal to the current new account creation fee. \n *\/\n void native::newaccount( account_name creator,\n account_name newact\n \/* no need to parse authorites\n const authority& owner,\n const authority& active*\/ ) {\n\n if( creator != _self ) {\n auto tmp = newact;\n bool has_dot = false;\n for( uint32_t i = 0; i < 13; ++i ) {\n has_dot |= (tmp >> 59);\n tmp <<= 5;\n }\n auto suffix = eosio::name_suffix(newact);\n if( has_dot ) {\n if( suffix == newact ) {\n name_bid_table bids(_self,_self);\n auto current = bids.find( newact );\n eosio_assert( current != bids.end(), \"no active bid for name\" ); \n eosio_assert( current->high_bidder == creator, \"only high bidder can claim\" );\n eosio_assert( current->high_bid < 0, \"auction for name is not closed yet\" );\n bids.erase( current );\n } else {\n eosio_assert( creator == suffix, \"only suffix may create this account\" );\n }\n }\n }\n\n user_resources_table userres( _self, newact);\n\n userres.emplace( newact, [&]( auto& res ) {\n res.owner = newact;\n });\n\n set_resource_limits( newact, 0, 0, 0 );\n }\n\n} \/\/\/ eosio.system\n \n\nEOSIO_ABI( eosiosystem::system_contract,\n (setram)\n \/\/ delegate_bandwith.cpp\n (delegatebw)(undelegatebw)(refund)\n (buyram)(buyrambytes)(sellram)\n \/\/ voting.cpp\n \/\/ producer_pay.cpp\n (regproxy)(regproducer)(unregprod)(voteproducer)\n (claimrewards)\n \/\/ native.hpp\n (onblock)\n (newaccount)(updateauth)(deleteauth)(linkauth)(unlinkauth)(postrecovery)(passrecovery)(vetorecovery)(onerror)(canceldelay)\n \/\/this file\n (bidname)\n (setpriv)\n)\n<|endoftext|>"} {"text":"\/*\nThis file is part of cphVB and copyright (c) 2012 the cphVB team:\nhttp:\/\/cphvb.bitbucket.org\n\ncphVB is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 \nof the License, or (at your option) any later version.\n\ncphVB is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the \nGNU Lesser General Public License along with cphVB. \n\nIf not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"cphvb_vem_cluster.h\"\n#include \"dispatch.h\"\n#include \"pgrid.h\"\n#include \"exec.h\"\n#include \"darray_extension.h\"\n\n\n\/\/Local array information and storage\nstatic std::map map_dary2ary;\nstatic std::map map_ary2dary;\nstatic StaticStore ary_store(512);\n\n \nint main()\n{\n dispatch_msg *msg;\n cphvb_error e;\n \n \/\/Initiate the process grid\n if((e = pgrid_init()) != CPHVB_SUCCESS)\n return e;\n\n while(1)\n {\n if((e = dispatch_reset()) != CPHVB_SUCCESS)\n return e;\n\n if((e = dispatch_recv(&msg)) != CPHVB_SUCCESS)\n return e;\n\n switch(msg->type) \n {\n case CPHVB_CLUSTER_DISPATCH_INIT:\n {\n char *name = msg->payload;\n printf(\"Slave (rank %d) received INIT. name: %s\\n\", pgrid_myrank, name);\n if((e = exec_init(name)) != CPHVB_SUCCESS)\n return e;\n break;\n }\n case CPHVB_CLUSTER_DISPATCH_SHUTDOWN:\n {\n printf(\"Slave (rank %d) received SHUTDOWN\\n\",pgrid_myrank);\n return exec_shutdown(); \n }\n case CPHVB_CLUSTER_DISPATCH_UFUNC:\n {\n cphvb_intp *id = (cphvb_intp *)msg->payload;\n char *fun = msg->payload+sizeof(cphvb_intp);\n printf(\"Slave (rank %d) received UFUNC. fun: %s, id: %ld\\n\",pgrid_myrank, fun, *id);\n if((e = exec_reg_func(fun, id)) != CPHVB_SUCCESS)\n return e;\n break;\n }\n case CPHVB_CLUSTER_DISPATCH_EXEC:\n {\n \/\/The number of instructions\n cphvb_intp *noi = (cphvb_intp *)msg->payload; \n \/\/The master-instruction list\n cphvb_instruction *master_list = (cphvb_instruction *)(noi+1);\n \/\/The number of new arrays\n cphvb_intp *noa = (cphvb_intp *)(master_list + *noi);\n \/\/The list of new arrays\n darray *darys = (darray*)(noa+1); \/\/number of new arrays\n \/\/The number of user-defined functions\n cphvb_intp *nou = (cphvb_intp *)(darys + *noa);\n \/\/The list of user-defined functions\n cphvb_userfunc *ufunc = (cphvb_userfunc*)(nou+1); \/\/number of new arrays\n\n\n printf(\"Slave (rank %d) received EXEC. noi: %ld, noa: %ld, nou: %ld\\n\",pgrid_myrank, *noi, *noa, *nou);\n \n \/\/Insert the new array into the array store and the array maps\n std::set base_darys;\n for(cphvb_intp i=0; i < *noa; ++i)\n {\n darray *dary = ary_store.c_next();\n *dary = darys[i];\n assert(map_dary2ary.count(dary->id) == 0);\n assert(map_ary2dary.count(&dary->global_ary) == 0);\n map_dary2ary[dary->id] = &dary->global_ary;\n map_ary2dary[&dary->global_ary] = dary;\n if(dary->global_ary.base == NULL)\/\/This is a base array.\n base_darys.insert(dary);\n } \n\n \/\/Update the base-array-pointers\n for(cphvb_intp i=0; i < *noa; ++i)\n {\n cphvb_array *ary = map_dary2ary[darys[i].id];\n if(ary->base != NULL)\/\/This is NOT a base array\n {\n assert(map_dary2ary.count((cphvb_intp)ary->base) == 1);\n ary->base = map_dary2ary[(cphvb_intp)ary->base];\n }\n }\n\n \/\/Receive the dispatched array-data from the master-process\n if((e = dispatch_array_data(base_darys)) != CPHVB_SUCCESS)\n return e;\n \n \/\/Allocate the local instruction list that should reference local arrays\n cphvb_instruction *local_list = (cphvb_instruction *)malloc(*noi*sizeof(cphvb_instruction));\n if(local_list == NULL)\n return CPHVB_OUT_OF_MEMORY;\n memcpy(local_list, master_list, (*noi)*sizeof(cphvb_instruction));\n \n \/\/De-serialize all user-defined function pointers.\n for(cphvb_intp i=0; i < *noi; ++i)\n {\n cphvb_instruction *inst = &local_list[i];\n if(inst->opcode == CPHVB_USERFUNC)\n { \n inst->userfunc = (cphvb_userfunc*) malloc(ufunc->struct_size);\n if(inst->userfunc == NULL)\n return CPHVB_OUT_OF_MEMORY;\n \/\/Save a local copy of the user-defined function\n memcpy(inst->userfunc, ufunc, ufunc->struct_size);\n \/\/Iterate to the next user-defined function\n ufunc = (cphvb_userfunc*)(((char*)ufunc) + ufunc->struct_size);\n }\n }\n\n \/\/Update all instruction to reference local arrays \n for(cphvb_intp i=0; i < *noi; ++i)\n {\n cphvb_instruction *inst = &local_list[i];\n int nop = cphvb_operands_in_instruction(inst);\n cphvb_array **ops;\n if(inst->opcode == CPHVB_USERFUNC)\n ops = inst->userfunc->operand;\n else\n ops = inst->operand;\n\n \/\/Convert all instructon operands\n for(cphvb_intp j=0; jImplemented error checking by the slave process\/*\nThis file is part of cphVB and copyright (c) 2012 the cphVB team:\nhttp:\/\/cphvb.bitbucket.org\n\ncphVB is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 \nof the License, or (at your option) any later version.\n\ncphVB is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the \nGNU Lesser General Public License along with cphVB. \n\nIf not, see .\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"cphvb_vem_cluster.h\"\n#include \"dispatch.h\"\n#include \"pgrid.h\"\n#include \"exec.h\"\n#include \"darray_extension.h\"\n\n\n\/\/Local array information and storage\nstatic std::map map_dary2ary;\nstatic std::map map_ary2dary;\nstatic StaticStore ary_store(512);\n \n\/\/Check for error. Will exit on error.\nstatic void check_error(cphvb_error err, const char *file, int line)\n{\n if(err != CPHVB_SUCCESS)\n {\n fprintf(stderr, \"[VEM-CLUSTER] Slave (rank %d) encountered the error %s at %s:%d\\n\",\n pgrid_myrank, cphvb_error_text(err), file, line);\n MPI_Abort(MPI_COMM_WORLD,-1);\n }\n}\n\n\/\/Check for execution error. Will exit on error.\nstatic void check_exec_error(cphvb_error err, const char *file, int line, \n cphvb_intp count, cphvb_instruction inst_list[])\n{\n if(err == CPHVB_PARTIAL_SUCCESS)\/\/Only partial success\n {\n char msg[count+4096];\n sprintf(msg, \"[VEM-CLUSTER] Slave (rank %d) encountered error in instruction batch: %s\\n\",\n pgrid_myrank, cphvb_error_text(err));\n for(cphvb_intp i=0; iopcode));\n if(ist->opcode == CPHVB_USERFUNC)\n {\n sprintf(msg+strlen(msg),\", Operand types:\");\n for(cphvb_intp j=0; jstatus));\n }\n fprintf(stderr,\"%s\", msg);\n MPI_Abort(MPI_COMM_WORLD,-1);\n }\n check_error(err, file, line);\n} \n\nint main()\n{\n dispatch_msg *msg;\n \n \/\/Initiate the process grid\n check_error(pgrid_init(),__FILE__,__LINE__);\n\n while(1)\n {\n \/\/Receive the dispatch message from the master-process\n check_error(dispatch_reset(),__FILE__,__LINE__);\n check_error(dispatch_recv(&msg),__FILE__,__LINE__);\n\n \/\/Handle the message\n switch(msg->type) \n {\n case CPHVB_CLUSTER_DISPATCH_INIT:\n {\n char *name = msg->payload;\n printf(\"Slave (rank %d) received INIT. name: %s\\n\", pgrid_myrank, name);\n check_error(exec_init(name),__FILE__,__LINE__);\n break;\n }\n case CPHVB_CLUSTER_DISPATCH_SHUTDOWN:\n {\n printf(\"Slave (rank %d) received SHUTDOWN\\n\",pgrid_myrank);\n return exec_shutdown(); \n }\n case CPHVB_CLUSTER_DISPATCH_UFUNC:\n {\n cphvb_intp *id = (cphvb_intp *)msg->payload;\n char *fun = msg->payload+sizeof(cphvb_intp);\n printf(\"Slave (rank %d) received UFUNC. fun: %s, id: %ld\\n\",pgrid_myrank, fun, *id);\n check_error(exec_reg_func(fun, id),__FILE__,__LINE__);\n break;\n }\n case CPHVB_CLUSTER_DISPATCH_EXEC:\n {\n \/\/The number of instructions\n cphvb_intp *noi = (cphvb_intp *)msg->payload; \n \/\/The master-instruction list\n cphvb_instruction *master_list = (cphvb_instruction *)(noi+1);\n \/\/The number of new arrays\n cphvb_intp *noa = (cphvb_intp *)(master_list + *noi);\n \/\/The list of new arrays\n darray *darys = (darray*)(noa+1); \/\/number of new arrays\n \/\/The number of user-defined functions\n cphvb_intp *nou = (cphvb_intp *)(darys + *noa);\n \/\/The list of user-defined functions\n cphvb_userfunc *ufunc = (cphvb_userfunc*)(nou+1); \/\/number of new arrays\n\n\n printf(\"Slave (rank %d) received EXEC. noi: %ld, noa: %ld, nou: %ld\\n\",pgrid_myrank, *noi, *noa, *nou);\n \n \/\/Insert the new array into the array store and the array maps\n std::set base_darys;\n for(cphvb_intp i=0; i < *noa; ++i)\n {\n darray *dary = ary_store.c_next();\n *dary = darys[i];\n assert(map_dary2ary.count(dary->id) == 0);\n assert(map_ary2dary.count(&dary->global_ary) == 0);\n map_dary2ary[dary->id] = &dary->global_ary;\n map_ary2dary[&dary->global_ary] = dary;\n if(dary->global_ary.base == NULL)\/\/This is a base array.\n base_darys.insert(dary);\n } \n\n \/\/Update the base-array-pointers\n for(cphvb_intp i=0; i < *noa; ++i)\n {\n cphvb_array *ary = map_dary2ary[darys[i].id];\n if(ary->base != NULL)\/\/This is NOT a base array\n {\n assert(map_dary2ary.count((cphvb_intp)ary->base) == 1);\n ary->base = map_dary2ary[(cphvb_intp)ary->base];\n }\n }\n\n \/\/Receive the dispatched array-data from the master-process\n check_error(dispatch_array_data(base_darys),__FILE__,__LINE__);\n \n \n \/\/Allocate the local instruction list that should reference local arrays\n cphvb_instruction *local_list = (cphvb_instruction *)malloc(*noi*sizeof(cphvb_instruction));\n if(local_list == NULL)\n return CPHVB_OUT_OF_MEMORY;\n memcpy(local_list, master_list, (*noi)*sizeof(cphvb_instruction));\n \n \/\/De-serialize all user-defined function pointers.\n for(cphvb_intp i=0; i < *noi; ++i)\n {\n cphvb_instruction *inst = &local_list[i];\n if(inst->opcode == CPHVB_USERFUNC)\n { \n inst->userfunc = (cphvb_userfunc*) malloc(ufunc->struct_size);\n if(inst->userfunc == NULL)\n return CPHVB_OUT_OF_MEMORY;\n \/\/Save a local copy of the user-defined function\n memcpy(inst->userfunc, ufunc, ufunc->struct_size);\n \/\/Iterate to the next user-defined function\n ufunc = (cphvb_userfunc*)(((char*)ufunc) + ufunc->struct_size);\n }\n }\n\n \/\/Update all instruction to reference local arrays \n for(cphvb_intp i=0; i < *noi; ++i)\n {\n cphvb_instruction *inst = &local_list[i];\n int nop = cphvb_operands_in_instruction(inst);\n cphvb_array **ops;\n if(inst->opcode == CPHVB_USERFUNC)\n ops = inst->userfunc->operand;\n else\n ops = inst->operand;\n\n \/\/Convert all instructon operands\n for(cphvb_intp j=0; j"} {"text":"#pragma once\n\n#include \n#include \n#include \n\nnamespace nix {\n\n\/* A simple least-recently used cache. Not thread-safe. *\/\ntemplate\nclass LRUCache\n{\nprivate:\n\n size_t capacity;\n\n \/\/ Stupid wrapper to get around circular dependency between Data\n \/\/ and LRU.\n struct LRUIterator;\n\n using Data = std::map>;\n using LRU = std::list;\n\n struct LRUIterator { typename LRU::iterator it; };\n\n Data data;\n LRU lru;\n\npublic:\n\n LRUCache(size_t capacity) : capacity(capacity) { }\n\n \/* Insert or upsert an item in the cache. *\/\n void upsert(const Key & key, const Value & value)\n {\n if (capacity == 0) return;\n\n erase(key);\n\n if (data.size() >= capacity) {\n \/* Retire the oldest item. *\/\n auto oldest = lru.begin();\n data.erase(*oldest);\n lru.erase(oldest);\n }\n\n auto res = data.emplace(key, std::make_pair(LRUIterator(), value));\n assert(res.second);\n auto & i(res.first);\n\n auto j = lru.insert(lru.end(), i);\n\n i->second.first.it = j;\n }\n\n bool erase(const Key & key)\n {\n auto i = data.find(key);\n if (i == data.end()) return false;\n lru.erase(i->second.first.it);\n data.erase(i);\n return true;\n }\n\n \/* Look up an item in the cache. If it exists, it becomes the most\n recently used item. *\/\n std::optional get(const Key & key)\n {\n auto i = data.find(key);\n if (i == data.end()) return {};\n\n \/* Move this item to the back of the LRU list. *\/\n lru.erase(i->second.first.it);\n auto j = lru.insert(lru.end(), i);\n i->second.first.it = j;\n\n return i->second.second;\n }\n\n size_t size()\n {\n return data.size();\n }\n\n void clear()\n {\n data.clear();\n lru.clear();\n }\n};\n\n}\nMissing `#include ` in `lru-cache.hh` (#3654)#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace nix {\n\n\/* A simple least-recently used cache. Not thread-safe. *\/\ntemplate\nclass LRUCache\n{\nprivate:\n\n size_t capacity;\n\n \/\/ Stupid wrapper to get around circular dependency between Data\n \/\/ and LRU.\n struct LRUIterator;\n\n using Data = std::map>;\n using LRU = std::list;\n\n struct LRUIterator { typename LRU::iterator it; };\n\n Data data;\n LRU lru;\n\npublic:\n\n LRUCache(size_t capacity) : capacity(capacity) { }\n\n \/* Insert or upsert an item in the cache. *\/\n void upsert(const Key & key, const Value & value)\n {\n if (capacity == 0) return;\n\n erase(key);\n\n if (data.size() >= capacity) {\n \/* Retire the oldest item. *\/\n auto oldest = lru.begin();\n data.erase(*oldest);\n lru.erase(oldest);\n }\n\n auto res = data.emplace(key, std::make_pair(LRUIterator(), value));\n assert(res.second);\n auto & i(res.first);\n\n auto j = lru.insert(lru.end(), i);\n\n i->second.first.it = j;\n }\n\n bool erase(const Key & key)\n {\n auto i = data.find(key);\n if (i == data.end()) return false;\n lru.erase(i->second.first.it);\n data.erase(i);\n return true;\n }\n\n \/* Look up an item in the cache. If it exists, it becomes the most\n recently used item. *\/\n std::optional get(const Key & key)\n {\n auto i = data.find(key);\n if (i == data.end()) return {};\n\n \/* Move this item to the back of the LRU list. *\/\n lru.erase(i->second.first.it);\n auto j = lru.insert(lru.end(), i);\n i->second.first.it = j;\n\n return i->second.second;\n }\n\n size_t size()\n {\n return data.size();\n }\n\n void clear()\n {\n data.clear();\n lru.clear();\n }\n};\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sprite.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 08:15:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_SPRITE_HXX\n#define _CPPCANVAS_SPRITE_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n\n#ifndef BOOST_SHARED_PTR_HPP_INCLUDED\n#include \n#endif\n\nnamespace basegfx\n{\n class B2DHomMatrix;\n class B2DPolyPolygon;\n class B2DPoint;\n}\n\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n class XSprite;\n} } } }\n\n\n\/* Definition of Sprite class *\/\n\nnamespace cppcanvas\n{\n\n class Sprite\n {\n public:\n virtual ~Sprite() {}\n\n virtual void setAlpha( const double& rAlpha ) = 0;\n\n \/** Set the sprite position on screen\n\n This method differs from the XSprite::move() insofar, as\n no viewstate\/renderstate transformations are applied to\n the specified position. The given position is interpreted\n in device coordinates (i.e. screen pixel)\n *\/\n virtual void movePixel( const ::basegfx::B2DPoint& rNewPos ) = 0;\n\n \/** Set the sprite position on screen\n\n This method sets the sprite position in the view\n coordinate system of the parent canvas\n *\/\n virtual void move( const ::basegfx::B2DPoint& rNewPos ) = 0;\n\n virtual void transform( const ::basegfx::B2DHomMatrix& rMatrix ) = 0;\n\n \/** Set output clipping\n\n This method differs from the XSprite::clip() insofar, as\n no viewstate\/renderstate transformations are applied to\n the specified clip polygon. The given polygon is\n interpreted in device coordinates (i.e. screen pixel)\n *\/\n virtual void setClipPixel( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0;\n\n \/** Set output clipping\n\n This method applies the clip poly-polygon interpreted in\n the view coordinate system of the parent canvas.\n *\/\n virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0;\n\n virtual void show() = 0;\n virtual void hide() = 0;\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XSprite > getUNOSprite() const = 0;\n };\n\n typedef ::boost::shared_ptr< ::cppcanvas::Sprite > SpriteSharedPtr;\n}\n\n#endif \/* _CPPCANVAS_SPRITE_HXX *\/\nINTEGRATION: CWS canvas02 (1.6.4); FILE MERGED 2005\/10\/24 16:27:46 thb 1.6.4.1: #i48939# Providing the sprite priority also on the cppcanvas wrapper\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sprite.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2005-11-02 13:38:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_SPRITE_HXX\n#define _CPPCANVAS_SPRITE_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n\n#ifndef BOOST_SHARED_PTR_HPP_INCLUDED\n#include \n#endif\n\nnamespace basegfx\n{\n class B2DHomMatrix;\n class B2DPolyPolygon;\n class B2DPoint;\n}\n\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n class XSprite;\n} } } }\n\n\n\/* Definition of Sprite class *\/\n\nnamespace cppcanvas\n{\n\n class Sprite\n {\n public:\n virtual ~Sprite() {}\n\n virtual void setAlpha( const double& rAlpha ) = 0;\n\n \/** Set the sprite position on screen\n\n This method differs from the XSprite::move() insofar, as\n no viewstate\/renderstate transformations are applied to\n the specified position. The given position is interpreted\n in device coordinates (i.e. screen pixel)\n *\/\n virtual void movePixel( const ::basegfx::B2DPoint& rNewPos ) = 0;\n\n \/** Set the sprite position on screen\n\n This method sets the sprite position in the view\n coordinate system of the parent canvas\n *\/\n virtual void move( const ::basegfx::B2DPoint& rNewPos ) = 0;\n\n virtual void transform( const ::basegfx::B2DHomMatrix& rMatrix ) = 0;\n\n \/** Set output clipping\n\n This method differs from the XSprite::clip() insofar, as\n no viewstate\/renderstate transformations are applied to\n the specified clip polygon. The given polygon is\n interpreted in device coordinates (i.e. screen pixel)\n *\/\n virtual void setClipPixel( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0;\n\n \/** Set output clipping\n\n This method applies the clip poly-polygon interpreted in\n the view coordinate system of the parent canvas.\n *\/\n virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly ) = 0;\n\n virtual void show() = 0;\n virtual void hide() = 0;\n\n \/** Change the sprite priority\n\n @param fPriority\n New sprite priority. The higher the priority, the further\n towards the viewer the sprite appears. That is, sprites\n with higher priority appear before ones with lower\n priority.\n *\/\n virtual void setPriority( double fPriority ) = 0;\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XSprite > getUNOSprite() const = 0;\n };\n\n typedef ::boost::shared_ptr< ::cppcanvas::Sprite > SpriteSharedPtr;\n}\n\n#endif \/* _CPPCANVAS_SPRITE_HXX *\/\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/scene_update_context.h\"\n\n#include \"flutter\/flow\/layers\/layer.h\"\n#include \"flutter\/flow\/matrix_decomposition.h\"\n#include \"flutter\/fml\/trace_event.h\"\n\nnamespace flutter {\n\n\/\/ Helper function to generate clip planes for a scenic::EntityNode.\nstatic void SetEntityNodeClipPlanes(scenic::EntityNode* entity_node,\n const SkRect& bounds) {\n const float top = bounds.top();\n const float bottom = bounds.bottom();\n const float left = bounds.left();\n const float right = bounds.right();\n\n \/\/ We will generate 4 oriented planes, one for each edge of the bounding rect.\n std::vector clip_planes;\n clip_planes.resize(4);\n\n \/\/ Top plane.\n clip_planes[0].dist = top;\n clip_planes[0].dir.x = 0.f;\n clip_planes[0].dir.y = 1.f;\n clip_planes[0].dir.z = 0.f;\n\n \/\/ Bottom plane.\n clip_planes[1].dist = -bottom;\n clip_planes[1].dir.x = 0.f;\n clip_planes[1].dir.y = -1.f;\n clip_planes[1].dir.z = 0.f;\n\n \/\/ Left plane.\n clip_planes[2].dist = left;\n clip_planes[2].dir.x = 1.f;\n clip_planes[2].dir.y = 0.f;\n clip_planes[2].dir.z = 0.f;\n\n \/\/ Right plane.\n clip_planes[3].dist = -right;\n clip_planes[3].dir.x = -1.f;\n clip_planes[3].dir.y = 0.f;\n clip_planes[3].dir.z = 0.f;\n\n entity_node->SetClipPlanes(std::move(clip_planes));\n}\n\nSceneUpdateContext::SceneUpdateContext(scenic::Session* session,\n SurfaceProducer* surface_producer)\n : session_(session), surface_producer_(surface_producer) {\n FML_DCHECK(surface_producer_ != nullptr);\n}\n\nvoid SceneUpdateContext::CreateFrame(\n std::unique_ptr entity_node,\n std::unique_ptr shape_node,\n const SkRRect& rrect,\n SkColor color,\n const SkRect& paint_bounds,\n std::vector paint_layers,\n Layer* layer) {\n \/\/ Frames always clip their children.\n SetEntityNodeClipPlanes(entity_node.get(), rrect.getBounds());\n \/\/ TODO(SCN-1274): AddPart() and SetClip() will be deleted.\n entity_node->SetClip(0u, true \/* clip to self *\/);\n\n \/\/ We don't need a shape if the frame is zero size.\n if (rrect.isEmpty())\n return;\n\n \/\/ Add a part which represents the frame's geometry for clipping purposes\n \/\/ and possibly for its texture.\n \/\/ TODO(SCN-137): Need to be able to express the radii as vectors.\n SkRect shape_bounds = rrect.getBounds();\n scenic::RoundedRectangle shape(\n session_, \/\/ session\n rrect.width(), \/\/ width\n rrect.height(), \/\/ height\n rrect.radii(SkRRect::kUpperLeft_Corner).x(), \/\/ top_left_radius\n rrect.radii(SkRRect::kUpperRight_Corner).x(), \/\/ top_right_radius\n rrect.radii(SkRRect::kLowerRight_Corner).x(), \/\/ bottom_right_radius\n rrect.radii(SkRRect::kLowerLeft_Corner).x() \/\/ bottom_left_radius\n );\n shape_node->SetShape(shape);\n shape_node->SetTranslation(shape_bounds.width() * 0.5f + shape_bounds.left(),\n shape_bounds.height() * 0.5f + shape_bounds.top(),\n 0.f);\n\n \/\/ Check whether the painted layers will be visible.\n if (paint_bounds.isEmpty() || !paint_bounds.intersects(shape_bounds))\n paint_layers.clear();\n\n \/\/ Check whether a solid color will suffice.\n if (paint_layers.empty()) {\n SetShapeColor(*shape_node, color);\n return;\n }\n\n \/\/ Apply current metrics and transformation scale factors.\n const float scale_x = ScaleX();\n const float scale_y = ScaleY();\n\n \/\/ Apply a texture to the whole shape.\n SetShapeTextureOrColor(*shape_node, color, scale_x, scale_y, shape_bounds,\n std::move(paint_layers), layer,\n std::move(entity_node));\n}\n\nvoid SceneUpdateContext::SetShapeTextureOrColor(\n scenic::ShapeNode& shape_node,\n SkColor color,\n SkScalar scale_x,\n SkScalar scale_y,\n const SkRect& paint_bounds,\n std::vector paint_layers,\n Layer* layer,\n std::unique_ptr entity_node) {\n scenic::Image* image = GenerateImageIfNeeded(\n color, scale_x, scale_y, paint_bounds, std::move(paint_layers), layer,\n std::move(entity_node));\n if (image != nullptr) {\n scenic::Material material(session_);\n material.SetTexture(*image);\n shape_node.SetMaterial(material);\n return;\n }\n\n SetShapeColor(shape_node, color);\n}\n\nvoid SceneUpdateContext::SetShapeColor(scenic::ShapeNode& shape_node,\n SkColor color) {\n if (SkColorGetA(color) == 0)\n return;\n\n scenic::Material material(session_);\n material.SetColor(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color),\n SkColorGetA(color));\n shape_node.SetMaterial(material);\n}\n\nscenic::Image* SceneUpdateContext::GenerateImageIfNeeded(\n SkColor color,\n SkScalar scale_x,\n SkScalar scale_y,\n const SkRect& paint_bounds,\n std::vector paint_layers,\n Layer* layer,\n std::unique_ptr entity_node) {\n \/\/ Bail if there's nothing to paint.\n if (paint_layers.empty())\n return nullptr;\n\n \/\/ Bail if the physical bounds are empty after rounding.\n SkISize physical_size = SkISize::Make(paint_bounds.width() * scale_x,\n paint_bounds.height() * scale_y);\n if (physical_size.isEmpty())\n return nullptr;\n\n \/\/ Acquire a surface from the surface producer and register the paint tasks.\n std::unique_ptr surface =\n surface_producer_->ProduceSurface(\n physical_size,\n LayerRasterCacheKey(\n \/\/ Root frame has a nullptr layer\n layer ? layer->unique_id() : 0, Matrix()),\n std::move(entity_node));\n\n if (!surface) {\n FML_LOG(ERROR) << \"Could not acquire a surface from the surface producer \"\n \"of size: \"\n << physical_size.width() << \"x\" << physical_size.height();\n return nullptr;\n }\n\n auto image = surface->GetImage();\n\n \/\/ Enqueue the paint task.\n paint_tasks_.push_back({.surface = std::move(surface),\n .left = paint_bounds.left(),\n .top = paint_bounds.top(),\n .scale_x = scale_x,\n .scale_y = scale_y,\n .background_color = color,\n .layers = std::move(paint_layers)});\n return image;\n}\n\nstd::vector<\n std::unique_ptr>\nSceneUpdateContext::ExecutePaintTasks(CompositorContext::ScopedFrame& frame) {\n TRACE_EVENT0(\"flutter\", \"SceneUpdateContext::ExecutePaintTasks\");\n std::vector> surfaces_to_submit;\n for (auto& task : paint_tasks_) {\n FML_DCHECK(task.surface);\n SkCanvas* canvas = task.surface->GetSkiaSurface()->getCanvas();\n Layer::PaintContext context = {canvas,\n canvas,\n frame.gr_context(),\n nullptr,\n frame.context().raster_time(),\n frame.context().ui_time(),\n frame.context().texture_registry(),\n &frame.context().raster_cache(),\n false};\n canvas->restoreToCount(1);\n canvas->save();\n canvas->clear(task.background_color);\n canvas->scale(task.scale_x, task.scale_y);\n canvas->translate(-task.left, -task.top);\n for (Layer* layer : task.layers) {\n layer->Paint(context);\n }\n surfaces_to_submit.emplace_back(std::move(task.surface));\n }\n paint_tasks_.clear();\n return surfaces_to_submit;\n}\n\nSceneUpdateContext::Entity::Entity(SceneUpdateContext& context)\n : context_(context), previous_entity_(context.top_entity_) {\n entity_node_ptr_ = std::make_unique(context.session());\n shape_node_ptr_ = std::make_unique(context.session());\n \/\/ TODO(SCN-1274): AddPart() and SetClip() will be deleted.\n entity_node_ptr_->AddPart(*shape_node_ptr_);\n if (previous_entity_)\n previous_entity_->entity_node_ptr_->AddChild(*entity_node_ptr_);\n context.top_entity_ = this;\n}\n\nSceneUpdateContext::Entity::~Entity() {\n FML_DCHECK(context_.top_entity_ == this);\n context_.top_entity_ = previous_entity_;\n}\n\nSceneUpdateContext::Transform::Transform(SceneUpdateContext& context,\n const SkMatrix& transform)\n : Entity(context),\n previous_scale_x_(context.top_scale_x_),\n previous_scale_y_(context.top_scale_y_) {\n if (!transform.isIdentity()) {\n \/\/ TODO(SCN-192): The perspective and shear components in the matrix\n \/\/ are not handled correctly.\n MatrixDecomposition decomposition(transform);\n if (decomposition.IsValid()) {\n entity_node().SetTranslation(decomposition.translation().x(), \/\/\n decomposition.translation().y(), \/\/\n -decomposition.translation().z() \/\/\n );\n\n entity_node().SetScale(decomposition.scale().x(), \/\/\n decomposition.scale().y(), \/\/\n decomposition.scale().z() \/\/\n );\n context.top_scale_x_ *= decomposition.scale().x();\n context.top_scale_y_ *= decomposition.scale().y();\n\n entity_node().SetRotation(decomposition.rotation().fData[0], \/\/\n decomposition.rotation().fData[1], \/\/\n decomposition.rotation().fData[2], \/\/\n decomposition.rotation().fData[3] \/\/\n );\n }\n }\n}\n\nSceneUpdateContext::Transform::Transform(SceneUpdateContext& context,\n float scale_x,\n float scale_y,\n float scale_z)\n : Entity(context),\n previous_scale_x_(context.top_scale_x_),\n previous_scale_y_(context.top_scale_y_) {\n if (scale_x != 1.f || scale_y != 1.f || scale_z != 1.f) {\n entity_node().SetScale(scale_x, scale_y, scale_z);\n context.top_scale_x_ *= scale_x;\n context.top_scale_y_ *= scale_y;\n }\n}\n\nSceneUpdateContext::Transform::~Transform() {\n context().top_scale_x_ = previous_scale_x_;\n context().top_scale_y_ = previous_scale_y_;\n}\n\nSceneUpdateContext::Frame::Frame(SceneUpdateContext& context,\n const SkRRect& rrect,\n SkColor color,\n float local_elevation,\n float world_elevation,\n float depth,\n Layer* layer)\n : Entity(context),\n rrect_(rrect),\n color_(color),\n paint_bounds_(SkRect::MakeEmpty()),\n layer_(layer) {\n if (local_elevation != 0.0) {\n if (depth > -1 && world_elevation >= depth) {\n \/\/ TODO(mklim): Deal with bounds overflow correctly.\n FML_LOG(ERROR) << \"Elevation \" << world_elevation << \" is outside of \"\n << depth;\n }\n entity_node().SetTranslation(0.f, 0.f, -local_elevation);\n }\n}\n\nSceneUpdateContext::Frame::~Frame() {\n context().CreateFrame(std::move(entity_node_ptr()),\n std::move(shape_node_ptr()), rrect_, color_,\n paint_bounds_, std::move(paint_layers_), layer_);\n}\n\nvoid SceneUpdateContext::Frame::AddPaintLayer(Layer* layer) {\n FML_DCHECK(layer->needs_painting());\n paint_layers_.push_back(layer);\n paint_bounds_.join(layer->paint_bounds());\n}\n\nSceneUpdateContext::Clip::Clip(SceneUpdateContext& context,\n scenic::Shape& shape,\n const SkRect& shape_bounds)\n : Entity(context) {\n shape_node().SetShape(shape);\n shape_node().SetTranslation(shape_bounds.width() * 0.5f + shape_bounds.left(),\n shape_bounds.height() * 0.5f + shape_bounds.top(),\n 0.f);\n entity_node().SetClip(0u, true \/* clip to self *\/);\n\n SetEntityNodeClipPlanes(&entity_node(), shape_bounds);\n}\n\n} \/\/ namespace flutter\nClamp when overflowing z bounds (#9402)\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/scene_update_context.h\"\n\n#include \"flutter\/flow\/layers\/layer.h\"\n#include \"flutter\/flow\/matrix_decomposition.h\"\n#include \"flutter\/fml\/trace_event.h\"\n\nnamespace flutter {\n\n\/\/ Helper function to generate clip planes for a scenic::EntityNode.\nstatic void SetEntityNodeClipPlanes(scenic::EntityNode* entity_node,\n const SkRect& bounds) {\n const float top = bounds.top();\n const float bottom = bounds.bottom();\n const float left = bounds.left();\n const float right = bounds.right();\n\n \/\/ We will generate 4 oriented planes, one for each edge of the bounding rect.\n std::vector clip_planes;\n clip_planes.resize(4);\n\n \/\/ Top plane.\n clip_planes[0].dist = top;\n clip_planes[0].dir.x = 0.f;\n clip_planes[0].dir.y = 1.f;\n clip_planes[0].dir.z = 0.f;\n\n \/\/ Bottom plane.\n clip_planes[1].dist = -bottom;\n clip_planes[1].dir.x = 0.f;\n clip_planes[1].dir.y = -1.f;\n clip_planes[1].dir.z = 0.f;\n\n \/\/ Left plane.\n clip_planes[2].dist = left;\n clip_planes[2].dir.x = 1.f;\n clip_planes[2].dir.y = 0.f;\n clip_planes[2].dir.z = 0.f;\n\n \/\/ Right plane.\n clip_planes[3].dist = -right;\n clip_planes[3].dir.x = -1.f;\n clip_planes[3].dir.y = 0.f;\n clip_planes[3].dir.z = 0.f;\n\n entity_node->SetClipPlanes(std::move(clip_planes));\n}\n\nSceneUpdateContext::SceneUpdateContext(scenic::Session* session,\n SurfaceProducer* surface_producer)\n : session_(session), surface_producer_(surface_producer) {\n FML_DCHECK(surface_producer_ != nullptr);\n}\n\nvoid SceneUpdateContext::CreateFrame(\n std::unique_ptr entity_node,\n std::unique_ptr shape_node,\n const SkRRect& rrect,\n SkColor color,\n const SkRect& paint_bounds,\n std::vector paint_layers,\n Layer* layer) {\n \/\/ Frames always clip their children.\n SetEntityNodeClipPlanes(entity_node.get(), rrect.getBounds());\n \/\/ TODO(SCN-1274): AddPart() and SetClip() will be deleted.\n entity_node->SetClip(0u, true \/* clip to self *\/);\n\n \/\/ We don't need a shape if the frame is zero size.\n if (rrect.isEmpty())\n return;\n\n \/\/ Add a part which represents the frame's geometry for clipping purposes\n \/\/ and possibly for its texture.\n \/\/ TODO(SCN-137): Need to be able to express the radii as vectors.\n SkRect shape_bounds = rrect.getBounds();\n scenic::RoundedRectangle shape(\n session_, \/\/ session\n rrect.width(), \/\/ width\n rrect.height(), \/\/ height\n rrect.radii(SkRRect::kUpperLeft_Corner).x(), \/\/ top_left_radius\n rrect.radii(SkRRect::kUpperRight_Corner).x(), \/\/ top_right_radius\n rrect.radii(SkRRect::kLowerRight_Corner).x(), \/\/ bottom_right_radius\n rrect.radii(SkRRect::kLowerLeft_Corner).x() \/\/ bottom_left_radius\n );\n shape_node->SetShape(shape);\n shape_node->SetTranslation(shape_bounds.width() * 0.5f + shape_bounds.left(),\n shape_bounds.height() * 0.5f + shape_bounds.top(),\n 0.f);\n\n \/\/ Check whether the painted layers will be visible.\n if (paint_bounds.isEmpty() || !paint_bounds.intersects(shape_bounds))\n paint_layers.clear();\n\n \/\/ Check whether a solid color will suffice.\n if (paint_layers.empty()) {\n SetShapeColor(*shape_node, color);\n return;\n }\n\n \/\/ Apply current metrics and transformation scale factors.\n const float scale_x = ScaleX();\n const float scale_y = ScaleY();\n\n \/\/ Apply a texture to the whole shape.\n SetShapeTextureOrColor(*shape_node, color, scale_x, scale_y, shape_bounds,\n std::move(paint_layers), layer,\n std::move(entity_node));\n}\n\nvoid SceneUpdateContext::SetShapeTextureOrColor(\n scenic::ShapeNode& shape_node,\n SkColor color,\n SkScalar scale_x,\n SkScalar scale_y,\n const SkRect& paint_bounds,\n std::vector paint_layers,\n Layer* layer,\n std::unique_ptr entity_node) {\n scenic::Image* image = GenerateImageIfNeeded(\n color, scale_x, scale_y, paint_bounds, std::move(paint_layers), layer,\n std::move(entity_node));\n if (image != nullptr) {\n scenic::Material material(session_);\n material.SetTexture(*image);\n shape_node.SetMaterial(material);\n return;\n }\n\n SetShapeColor(shape_node, color);\n}\n\nvoid SceneUpdateContext::SetShapeColor(scenic::ShapeNode& shape_node,\n SkColor color) {\n if (SkColorGetA(color) == 0)\n return;\n\n scenic::Material material(session_);\n material.SetColor(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color),\n SkColorGetA(color));\n shape_node.SetMaterial(material);\n}\n\nscenic::Image* SceneUpdateContext::GenerateImageIfNeeded(\n SkColor color,\n SkScalar scale_x,\n SkScalar scale_y,\n const SkRect& paint_bounds,\n std::vector paint_layers,\n Layer* layer,\n std::unique_ptr entity_node) {\n \/\/ Bail if there's nothing to paint.\n if (paint_layers.empty())\n return nullptr;\n\n \/\/ Bail if the physical bounds are empty after rounding.\n SkISize physical_size = SkISize::Make(paint_bounds.width() * scale_x,\n paint_bounds.height() * scale_y);\n if (physical_size.isEmpty())\n return nullptr;\n\n \/\/ Acquire a surface from the surface producer and register the paint tasks.\n std::unique_ptr surface =\n surface_producer_->ProduceSurface(\n physical_size,\n LayerRasterCacheKey(\n \/\/ Root frame has a nullptr layer\n layer ? layer->unique_id() : 0, Matrix()),\n std::move(entity_node));\n\n if (!surface) {\n FML_LOG(ERROR) << \"Could not acquire a surface from the surface producer \"\n \"of size: \"\n << physical_size.width() << \"x\" << physical_size.height();\n return nullptr;\n }\n\n auto image = surface->GetImage();\n\n \/\/ Enqueue the paint task.\n paint_tasks_.push_back({.surface = std::move(surface),\n .left = paint_bounds.left(),\n .top = paint_bounds.top(),\n .scale_x = scale_x,\n .scale_y = scale_y,\n .background_color = color,\n .layers = std::move(paint_layers)});\n return image;\n}\n\nstd::vector<\n std::unique_ptr>\nSceneUpdateContext::ExecutePaintTasks(CompositorContext::ScopedFrame& frame) {\n TRACE_EVENT0(\"flutter\", \"SceneUpdateContext::ExecutePaintTasks\");\n std::vector> surfaces_to_submit;\n for (auto& task : paint_tasks_) {\n FML_DCHECK(task.surface);\n SkCanvas* canvas = task.surface->GetSkiaSurface()->getCanvas();\n Layer::PaintContext context = {canvas,\n canvas,\n frame.gr_context(),\n nullptr,\n frame.context().raster_time(),\n frame.context().ui_time(),\n frame.context().texture_registry(),\n &frame.context().raster_cache(),\n false};\n canvas->restoreToCount(1);\n canvas->save();\n canvas->clear(task.background_color);\n canvas->scale(task.scale_x, task.scale_y);\n canvas->translate(-task.left, -task.top);\n for (Layer* layer : task.layers) {\n layer->Paint(context);\n }\n surfaces_to_submit.emplace_back(std::move(task.surface));\n }\n paint_tasks_.clear();\n return surfaces_to_submit;\n}\n\nSceneUpdateContext::Entity::Entity(SceneUpdateContext& context)\n : context_(context), previous_entity_(context.top_entity_) {\n entity_node_ptr_ = std::make_unique(context.session());\n shape_node_ptr_ = std::make_unique(context.session());\n \/\/ TODO(SCN-1274): AddPart() and SetClip() will be deleted.\n entity_node_ptr_->AddPart(*shape_node_ptr_);\n if (previous_entity_)\n previous_entity_->entity_node_ptr_->AddChild(*entity_node_ptr_);\n context.top_entity_ = this;\n}\n\nSceneUpdateContext::Entity::~Entity() {\n FML_DCHECK(context_.top_entity_ == this);\n context_.top_entity_ = previous_entity_;\n}\n\nSceneUpdateContext::Transform::Transform(SceneUpdateContext& context,\n const SkMatrix& transform)\n : Entity(context),\n previous_scale_x_(context.top_scale_x_),\n previous_scale_y_(context.top_scale_y_) {\n if (!transform.isIdentity()) {\n \/\/ TODO(SCN-192): The perspective and shear components in the matrix\n \/\/ are not handled correctly.\n MatrixDecomposition decomposition(transform);\n if (decomposition.IsValid()) {\n entity_node().SetTranslation(decomposition.translation().x(), \/\/\n decomposition.translation().y(), \/\/\n -decomposition.translation().z() \/\/\n );\n\n entity_node().SetScale(decomposition.scale().x(), \/\/\n decomposition.scale().y(), \/\/\n decomposition.scale().z() \/\/\n );\n context.top_scale_x_ *= decomposition.scale().x();\n context.top_scale_y_ *= decomposition.scale().y();\n\n entity_node().SetRotation(decomposition.rotation().fData[0], \/\/\n decomposition.rotation().fData[1], \/\/\n decomposition.rotation().fData[2], \/\/\n decomposition.rotation().fData[3] \/\/\n );\n }\n }\n}\n\nSceneUpdateContext::Transform::Transform(SceneUpdateContext& context,\n float scale_x,\n float scale_y,\n float scale_z)\n : Entity(context),\n previous_scale_x_(context.top_scale_x_),\n previous_scale_y_(context.top_scale_y_) {\n if (scale_x != 1.f || scale_y != 1.f || scale_z != 1.f) {\n entity_node().SetScale(scale_x, scale_y, scale_z);\n context.top_scale_x_ *= scale_x;\n context.top_scale_y_ *= scale_y;\n }\n}\n\nSceneUpdateContext::Transform::~Transform() {\n context().top_scale_x_ = previous_scale_x_;\n context().top_scale_y_ = previous_scale_y_;\n}\n\nSceneUpdateContext::Frame::Frame(SceneUpdateContext& context,\n const SkRRect& rrect,\n SkColor color,\n float local_elevation,\n float world_elevation,\n float depth,\n Layer* layer)\n : Entity(context),\n rrect_(rrect),\n color_(color),\n paint_bounds_(SkRect::MakeEmpty()),\n layer_(layer) {\n if (depth > -1 && world_elevation > depth) {\n \/\/ TODO(mklim): Deal with bounds overflow more elegantly. We'd like to be\n \/\/ able to have developers specify the behavior here to alternatives besides\n \/\/ clamping, like normalization on some arbitrary curve.\n\n \/\/ Clamp the local z coordinate at our max bound. Take into account the\n \/\/ parent z position here to fix clamping in cases where the child is\n \/\/ overflowing because of its parents.\n const float parent_elevation = world_elevation - local_elevation;\n local_elevation = depth - parent_elevation;\n }\n if (local_elevation != 0.0) {\n entity_node().SetTranslation(0.f, 0.f, -local_elevation);\n }\n}\n\nSceneUpdateContext::Frame::~Frame() {\n context().CreateFrame(std::move(entity_node_ptr()),\n std::move(shape_node_ptr()), rrect_, color_,\n paint_bounds_, std::move(paint_layers_), layer_);\n}\n\nvoid SceneUpdateContext::Frame::AddPaintLayer(Layer* layer) {\n FML_DCHECK(layer->needs_painting());\n paint_layers_.push_back(layer);\n paint_bounds_.join(layer->paint_bounds());\n}\n\nSceneUpdateContext::Clip::Clip(SceneUpdateContext& context,\n scenic::Shape& shape,\n const SkRect& shape_bounds)\n : Entity(context) {\n shape_node().SetShape(shape);\n shape_node().SetTranslation(shape_bounds.width() * 0.5f + shape_bounds.left(),\n shape_bounds.height() * 0.5f + shape_bounds.top(),\n 0.f);\n entity_node().SetClip(0u, true \/* clip to self *\/);\n\n SetEntityNodeClipPlanes(&entity_node(), shape_bounds);\n}\n\n} \/\/ namespace flutter\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2000-2001 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csgeom\/math3d.h\"\n#include \"csgeom\/box.h\"\n#include \"nullmesh.h\"\n#include \"iengine\/movable.h\"\n#include \"iengine\/rview.h\"\n#include \"ivideo\/graph3d.h\"\n#include \"ivideo\/graph2d.h\"\n#include \"ivideo\/material.h\"\n#include \"ivideo\/vbufmgr.h\"\n#include \"iengine\/material.h\"\n#include \"iengine\/camera.h\"\n#include \"igeom\/clip2d.h\"\n#include \"iengine\/engine.h\"\n#include \"iengine\/light.h\"\n#include \"iutil\/objreg.h\"\n#include \"qsqrt.h\"\n\nCS_IMPLEMENT_PLUGIN\n\nSCF_IMPLEMENT_IBASE (csNullmeshMeshObject)\n SCF_IMPLEMENTS_INTERFACE (iMeshObject)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iMeshObjectFactory)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iObjectModel)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iNullMeshState)\nSCF_IMPLEMENT_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObject::MeshObjectFactory)\n SCF_IMPLEMENTS_INTERFACE (iMeshObjectFactory)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObject::ObjectModel)\n SCF_IMPLEMENTS_INTERFACE (iObjectModel)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObject::NullMeshState)\n SCF_IMPLEMENTS_INTERFACE (iNullMeshState)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\n\ncsNullmeshMeshObject::csNullmeshMeshObject (iMeshObjectFactory* factory)\n{\n SCF_CONSTRUCT_IBASE (0);\n SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMeshObjectFactory);\n SCF_CONSTRUCT_EMBEDDED_IBASE (scfiObjectModel);\n SCF_CONSTRUCT_EMBEDDED_IBASE (scfiNullMeshState);\n csNullmeshMeshObject::factory = factory;\n logparent = 0;\n vis_cb = 0;\n radius = .1;\n}\n\ncsNullmeshMeshObject::~csNullmeshMeshObject ()\n{\n if (vis_cb) vis_cb->DecRef ();\n}\n\nbool csNullmeshMeshObject::DrawTest (iRenderView* rview, iMovable* movable)\n{\n iCamera* camera = rview->GetCamera ();\n\n \/\/ First create the transformation from object to camera space directly:\n \/\/ W = Mow * O - Vow;\n \/\/ C = Mwc * (W - Vwc)\n \/\/ ->\n \/\/ C = Mwc * (Mow * O - Vow - Vwc)\n \/\/ C = Mwc * Mow * O - Mwc * (Vow + Vwc)\n csReversibleTransform tr_o2c = camera->GetTransform ();\n if (!movable->IsFullTransformIdentity ())\n tr_o2c \/= movable->GetFullTransform ();\n\n csSphere sphere;\n sphere.SetCenter (csVector3 (0, 0, 0));\n sphere.SetRadius (radius);\n int clip_portal, clip_plane, clip_z_plane;\n if (rview->ClipBSphere (tr_o2c, sphere, clip_portal, clip_plane,\n \tclip_z_plane) == false)\n return false;\n return true;\n}\n\nvoid csNullmeshMeshObject::SetRadius (float radius)\n{\n csNullmeshMeshObject::radius = radius;\n box.Set (-radius, -radius, -radius, radius, radius, radius);\n scfiObjectModel.ShapeChanged ();\n}\n\nvoid csNullmeshMeshObject::SetBoundingBox (const csBox3& box)\n{\n csNullmeshMeshObject::box = box;\n radius = qsqrt (csSquaredDist::PointPoint (box.Max (), box.Min ())) \/ 2.0;\n scfiObjectModel.ShapeChanged ();\n}\n\nvoid csNullmeshMeshObject::UpdateLighting (iLight**, int, iMovable*)\n{\n return;\n}\n\nbool csNullmeshMeshObject::Draw (iRenderView* rview, iMovable* \/*movable*\/,\n\tcsZBufMode \/*mode*\/)\n{\n if (vis_cb) if (!vis_cb->BeforeDrawing (this, rview)) return false;\n return true;\n}\n\nvoid csNullmeshMeshObject::GetObjectBoundingBox (csBox3& bbox, int \/*type*\/)\n{\n bbox = box;\n}\n\nbool csNullmeshMeshObject::HitBeamOutline (const csVector3& \/*start*\/,\n const csVector3& \/*end*\/, csVector3& \/*isect*\/, float* \/*pr*\/)\n{\n \/\/ @@@ TODO\n return false;\n}\n\nbool csNullmeshMeshObject::HitBeamObject (const csVector3& \/*start*\/,\n const csVector3& \/*end*\/, csVector3& \/*isect*\/, float* \/*pr*\/)\n{\n \/\/ @@@ TODO\n return false;\n}\n\nvoid csNullmeshMeshObject::GetRadius (csVector3& rad, csVector3& cent)\n{\n rad.Set (radius);\n cent.Set (box.GetCenter ());\n}\n\ncsPtr csNullmeshMeshObject::MeshObjectFactory::NewInstance ()\n{\n csNullmeshMeshObject* cm = new csNullmeshMeshObject (\n \t(iMeshObjectFactory*)this);\n csRef im (SCF_QUERY_INTERFACE (cm, iMeshObject));\n cm->DecRef ();\n return csPtr (im);\n}\n\n\/\/----------------------------------------------------------------------\n\nSCF_IMPLEMENT_IBASE (csNullmeshMeshObjectType)\n SCF_IMPLEMENTS_INTERFACE (iMeshObjectType)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iComponent)\nSCF_IMPLEMENT_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObjectType::eiComponent)\n SCF_IMPLEMENTS_INTERFACE (iComponent)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_FACTORY (csNullmeshMeshObjectType)\n\n\ncsNullmeshMeshObjectType::csNullmeshMeshObjectType (iBase* pParent)\n{\n SCF_CONSTRUCT_IBASE (pParent);\n SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);\n}\n\ncsNullmeshMeshObjectType::~csNullmeshMeshObjectType ()\n{\n}\n\ncsPtr csNullmeshMeshObjectType::NewFactory ()\n{\n csNullmeshMeshObject* cm = new csNullmeshMeshObject (0);\n csRef ifact (\n \tSCF_QUERY_INTERFACE (cm, iMeshObjectFactory));\n cm->DecRef ();\n return csPtr (ifact);\n}\n\nNullmesh is now initialized with a legal (albeit very small) bounding box.\/*\n Copyright (C) 2000-2001 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"csgeom\/math3d.h\"\n#include \"csgeom\/box.h\"\n#include \"nullmesh.h\"\n#include \"iengine\/movable.h\"\n#include \"iengine\/rview.h\"\n#include \"ivideo\/graph3d.h\"\n#include \"ivideo\/graph2d.h\"\n#include \"ivideo\/material.h\"\n#include \"ivideo\/vbufmgr.h\"\n#include \"iengine\/material.h\"\n#include \"iengine\/camera.h\"\n#include \"igeom\/clip2d.h\"\n#include \"iengine\/engine.h\"\n#include \"iengine\/light.h\"\n#include \"iutil\/objreg.h\"\n#include \"qsqrt.h\"\n\nCS_IMPLEMENT_PLUGIN\n\nSCF_IMPLEMENT_IBASE (csNullmeshMeshObject)\n SCF_IMPLEMENTS_INTERFACE (iMeshObject)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iMeshObjectFactory)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iObjectModel)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iNullMeshState)\nSCF_IMPLEMENT_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObject::MeshObjectFactory)\n SCF_IMPLEMENTS_INTERFACE (iMeshObjectFactory)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObject::ObjectModel)\n SCF_IMPLEMENTS_INTERFACE (iObjectModel)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObject::NullMeshState)\n SCF_IMPLEMENTS_INTERFACE (iNullMeshState)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\n\ncsNullmeshMeshObject::csNullmeshMeshObject (iMeshObjectFactory* factory)\n{\n SCF_CONSTRUCT_IBASE (0);\n SCF_CONSTRUCT_EMBEDDED_IBASE (scfiMeshObjectFactory);\n SCF_CONSTRUCT_EMBEDDED_IBASE (scfiObjectModel);\n SCF_CONSTRUCT_EMBEDDED_IBASE (scfiNullMeshState);\n csNullmeshMeshObject::factory = factory;\n logparent = 0;\n vis_cb = 0;\n radius = .0001;\n box.Set (-radius, -radius, -radius, radius, radius, radius);\n}\n\ncsNullmeshMeshObject::~csNullmeshMeshObject ()\n{\n if (vis_cb) vis_cb->DecRef ();\n}\n\nbool csNullmeshMeshObject::DrawTest (iRenderView* rview, iMovable* movable)\n{\n iCamera* camera = rview->GetCamera ();\n\n \/\/ First create the transformation from object to camera space directly:\n \/\/ W = Mow * O - Vow;\n \/\/ C = Mwc * (W - Vwc)\n \/\/ ->\n \/\/ C = Mwc * (Mow * O - Vow - Vwc)\n \/\/ C = Mwc * Mow * O - Mwc * (Vow + Vwc)\n csReversibleTransform tr_o2c = camera->GetTransform ();\n if (!movable->IsFullTransformIdentity ())\n tr_o2c \/= movable->GetFullTransform ();\n\n csSphere sphere;\n sphere.SetCenter (csVector3 (0, 0, 0));\n sphere.SetRadius (radius);\n int clip_portal, clip_plane, clip_z_plane;\n if (rview->ClipBSphere (tr_o2c, sphere, clip_portal, clip_plane,\n \tclip_z_plane) == false)\n return false;\n return true;\n}\n\nvoid csNullmeshMeshObject::SetRadius (float radius)\n{\n csNullmeshMeshObject::radius = radius;\n box.Set (-radius, -radius, -radius, radius, radius, radius);\n scfiObjectModel.ShapeChanged ();\n}\n\nvoid csNullmeshMeshObject::SetBoundingBox (const csBox3& box)\n{\n csNullmeshMeshObject::box = box;\n radius = qsqrt (csSquaredDist::PointPoint (box.Max (), box.Min ())) \/ 2.0;\n scfiObjectModel.ShapeChanged ();\n}\n\nvoid csNullmeshMeshObject::UpdateLighting (iLight**, int, iMovable*)\n{\n return;\n}\n\nbool csNullmeshMeshObject::Draw (iRenderView* rview, iMovable* \/*movable*\/,\n\tcsZBufMode \/*mode*\/)\n{\n if (vis_cb) if (!vis_cb->BeforeDrawing (this, rview)) return false;\n return true;\n}\n\nvoid csNullmeshMeshObject::GetObjectBoundingBox (csBox3& bbox, int \/*type*\/)\n{\n bbox = box;\n}\n\nbool csNullmeshMeshObject::HitBeamOutline (const csVector3& \/*start*\/,\n const csVector3& \/*end*\/, csVector3& \/*isect*\/, float* \/*pr*\/)\n{\n \/\/ @@@ TODO\n return false;\n}\n\nbool csNullmeshMeshObject::HitBeamObject (const csVector3& \/*start*\/,\n const csVector3& \/*end*\/, csVector3& \/*isect*\/, float* \/*pr*\/)\n{\n \/\/ @@@ TODO\n return false;\n}\n\nvoid csNullmeshMeshObject::GetRadius (csVector3& rad, csVector3& cent)\n{\n rad.Set (radius);\n cent.Set (box.GetCenter ());\n}\n\ncsPtr csNullmeshMeshObject::MeshObjectFactory::NewInstance ()\n{\n csNullmeshMeshObject* cm = new csNullmeshMeshObject (\n \t(iMeshObjectFactory*)this);\n csRef im (SCF_QUERY_INTERFACE (cm, iMeshObject));\n cm->DecRef ();\n return csPtr (im);\n}\n\n\/\/----------------------------------------------------------------------\n\nSCF_IMPLEMENT_IBASE (csNullmeshMeshObjectType)\n SCF_IMPLEMENTS_INTERFACE (iMeshObjectType)\n SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iComponent)\nSCF_IMPLEMENT_IBASE_END\n\nSCF_IMPLEMENT_EMBEDDED_IBASE (csNullmeshMeshObjectType::eiComponent)\n SCF_IMPLEMENTS_INTERFACE (iComponent)\nSCF_IMPLEMENT_EMBEDDED_IBASE_END\n\nSCF_IMPLEMENT_FACTORY (csNullmeshMeshObjectType)\n\n\ncsNullmeshMeshObjectType::csNullmeshMeshObjectType (iBase* pParent)\n{\n SCF_CONSTRUCT_IBASE (pParent);\n SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);\n}\n\ncsNullmeshMeshObjectType::~csNullmeshMeshObjectType ()\n{\n}\n\ncsPtr csNullmeshMeshObjectType::NewFactory ()\n{\n csNullmeshMeshObject* cm = new csNullmeshMeshObject (0);\n csRef ifact (\n \tSCF_QUERY_INTERFACE (cm, iMeshObjectFactory));\n cm->DecRef ();\n return csPtr (ifact);\n}\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by kerail on 10.07.16.\n\/\/\n\n#ifndef DAISU_SO3_HPP\n#define DAISU_SO3_HPP\n\n#include \n#include \n#include \n#include \n\ntemplate\nclass SO3 {\n public:\n typedef Eigen::Matrix Vector3;\n typedef Eigen::Matrix Matrix33;\n typedef Eigen::Quaternion Quaternion;\n\n SO3(const T &x, const T &y, const T &z) {\n m_coeffs = Eigen::Vector3d(x, y, z);\n }\n\n SO3(const Vector3 &v) {\n m_coeffs = v;\n }\n\n SO3(T angle, const Vector3 &v) {\n m_coeffs = v * angle;\n }\n\n SO3(const Quaternion &q_) {\n const Quaternion &q = q_.w() >= T(0) ? q_ : Quaternion(-q_.coeffs());\n\n const Vector3 &qv = q.vec();\n T sinha = qv.norm();\n if (sinha > T(0)) {\n T angle = T(2) * atan2(sinha, q.w()); \/\/NOTE: signed\n m_coeffs = qv * (angle \/ sinha);\n } else {\n \/\/ if l is too small, its norm can be equal 0 but norm_inf greater 0\n \/\/ probably w is much bigger that vec, use it as length\n m_coeffs = qv * (T(2) \/ q.w()); \/\/\/\/NOTE: signed\n }\n }\n\n Vector3 rotateVector(const Vector3 &v) const {\n T a = getAngle();\n Vector3 axis = getAxis();\n T c_a = cos(a);\n T s_a = sin(a);\n return v * c_a + (axis.cross(v)) * s_a + axis * (axis.dot(v)) * (1 - c_a);\n }\n\n Matrix33 getMatrix() const {\n Matrix33 m;\n const Vector3 &cfs = m_coeffs;\n\n T l2 = cfs.squaredNorm();\n T l = sqrt(l2);\n\n T sn_l, cs1_ll, cs;\n if (l == T(0)) {\n \/\/ if l is 0 sin(x)\/x = 1\n sn_l = T(1);\n } else {\n sn_l = sin(l) \/ l;\n }\n\n cs = cos(l);\n static const T c_pi64 = cos(M_PI \/ T(64));\n if (cs > c_pi64) {\/\/fabs(l) < M_PI\/T(64)\n \/\/ when l is near nezo, we need to switch to more precise formula\n if (l2 == T(0)) {\n \/\/ when l2 is zero, we can precisely calculate limit\n cs1_ll = 1 \/ T(2);\n } else {\n \/\/ 1 - cos(x) = 2 * sin(x\/2)^2\n T sn = sin(l \/ T(2));\n cs1_ll = T(2) * sn * sn \/ l2;\n }\n } else {\n \/\/ here l2 > 0 because abs(l) > pi\/64\n cs1_ll = (T(1) - cs) \/ l2;\n }\n\n Vector3 sn_ax = sn_l * m_coeffs;\n Vector3 cs1_l_ax = cs1_ll * m_coeffs;\n\n T tmp;\n tmp = cs1_l_ax.x() * m_coeffs.y();\n m.coeffRef(0, 1) = tmp - sn_ax.z();\n m.coeffRef(1, 0) = tmp + sn_ax.z();\n\n tmp = cs1_l_ax.x() * m_coeffs.z();\n m.coeffRef(0, 2) = tmp + sn_ax.y();\n m.coeffRef(2, 0) = tmp - sn_ax.y();\n\n tmp = cs1_l_ax.y() * m_coeffs.z();\n m.coeffRef(1, 2) = tmp - sn_ax.x();\n m.coeffRef(2, 1) = tmp + sn_ax.x();\n\n\/\/ m.diagonal() = (cs1_l_ax.cwiseProduct(m_coeffs)).array() + cs;\n\n Vector3 sq = cs1_l_ax.cwiseProduct(m_coeffs);\n m.coeffRef(0, 0) = 1 + (-sq.y() - sq.z());\n m.coeffRef(1, 1) = 1 + (-sq.x() - sq.z());\n m.coeffRef(2, 2) = 1 + (-sq.x() - sq.y());\n\n \/\/ Rotation matrix checks\n assert((m * m.transpose() - Matrix33::Identity()).norm() < 1e-10);\n assert(fabs(fabs(m.determinant()) - 1) < 1e-10);\n return m;\n }\n\n Quaternion getQuaternion() const {\n T a = getAngle();\n Vector3 axis = getAxis();\n T c_a2 = cos(a \/ 2.0);\n T s_a2 = sin(a \/ 2.0);\n Vector3 im = axis * s_a2;\n T real = c_a2;\n\n return Quaternion(real, im.x(), im.y(), im.z());\n }\n\n Vector3 coeffs() const {\n return m_coeffs;\n }\n\n T getAngle() const {\n return m_coeffs.norm();\n }\n\n Vector3 getAxis() const {\n T a = getAngle();\n return a > 0 ? (Vector3) (m_coeffs \/ a) : m_coeffs;\n }\n\n SO3 inverted() const {\n return SO3(-m_coeffs);\n }\n\n private:\n Vector3 m_coeffs;\n\n Matrix33 antiSymmMatrix() const {\n Vector3 axis = getAxis();\n Matrix33 m = Matrix33::Zero();\n m(0, 1) = -axis(2);\n m(1, 0) = axis(2);\n\n m(0, 2) = axis(1);\n m(2, 0) = -axis(1);\n\n m(2, 1) = axis(0);\n m(1, 2) = -axis(0);\n return m;\n }\n\n};\n\ntypedef SO3 SO3d;\ntypedef SO3 SO3f;\n\n#endif \/\/DAISU_SO3_HPP\nMore precise quaternion calculation\/\/\n\/\/ Created by kerail on 10.07.16.\n\/\/\n\n#ifndef DAISU_SO3_HPP\n#define DAISU_SO3_HPP\n\n#include \n#include \n#include \n#include \n\ntemplate\nclass SO3 {\n public:\n typedef Eigen::Matrix Vector3;\n typedef Eigen::Matrix Matrix33;\n typedef Eigen::Quaternion Quaternion;\n\n SO3(const T &x, const T &y, const T &z) {\n m_coeffs = Eigen::Vector3d(x, y, z);\n }\n\n SO3(const Vector3 &v) {\n m_coeffs = v;\n }\n\n SO3(T angle, const Vector3 &v) {\n m_coeffs = v * angle;\n }\n\n SO3(const Quaternion &q_) {\n const Quaternion &q = q_.w() >= T(0) ? q_ : Quaternion(-q_.coeffs());\n\n const Vector3 &qv = q.vec();\n T sinha = qv.norm();\n if (sinha > T(0)) {\n T angle = T(2) * atan2(sinha, q.w()); \/\/NOTE: signed\n m_coeffs = qv * (angle \/ sinha);\n } else {\n \/\/ if l is too small, its norm can be equal 0 but norm_inf greater 0\n \/\/ probably w is much bigger that vec, use it as length\n m_coeffs = qv * (T(2) \/ q.w()); \/\/\/\/NOTE: signed\n }\n }\n\n Vector3 rotateVector(const Vector3 &v) const {\n T a = getAngle();\n Vector3 axis = getAxis();\n T c_a = cos(a);\n T s_a = sin(a);\n return v * c_a + (axis.cross(v)) * s_a + axis * (axis.dot(v)) * (1 - c_a);\n }\n\n Matrix33 getMatrix() const {\n Matrix33 m;\n const Vector3 &cfs = m_coeffs;\n\n T l2 = cfs.squaredNorm();\n T l = sqrt(l2);\n\n T sn_l, cs1_ll, cs;\n if (l == T(0)) {\n \/\/ if l is 0 sin(x)\/x = 1\n sn_l = T(1);\n } else {\n sn_l = sin(l) \/ l;\n }\n\n cs = cos(l);\n static const T c_pi64 = cos(M_PI \/ T(64));\n if (cs > c_pi64) {\/\/fabs(l) < M_PI\/T(64)\n \/\/ when l is near nezo, we need to switch to more precise formula\n if (l2 == T(0)) {\n \/\/ when l2 is zero, we can precisely calculate limit\n cs1_ll = 1 \/ T(2);\n } else {\n \/\/ 1 - cos(x) = 2 * sin(x\/2)^2\n T sn = sin(l \/ T(2));\n cs1_ll = T(2) * sn * sn \/ l2;\n }\n } else {\n \/\/ here l2 > 0 because abs(l) > pi\/64\n cs1_ll = (T(1) - cs) \/ l2;\n }\n\n Vector3 sn_ax = sn_l * m_coeffs;\n Vector3 cs1_l_ax = cs1_ll * m_coeffs;\n\n T tmp;\n tmp = cs1_l_ax.x() * m_coeffs.y();\n m.coeffRef(0, 1) = tmp - sn_ax.z();\n m.coeffRef(1, 0) = tmp + sn_ax.z();\n\n tmp = cs1_l_ax.x() * m_coeffs.z();\n m.coeffRef(0, 2) = tmp + sn_ax.y();\n m.coeffRef(2, 0) = tmp - sn_ax.y();\n\n tmp = cs1_l_ax.y() * m_coeffs.z();\n m.coeffRef(1, 2) = tmp - sn_ax.x();\n m.coeffRef(2, 1) = tmp + sn_ax.x();\n\n\/\/ m.diagonal() = (cs1_l_ax.cwiseProduct(m_coeffs)).array() + cs;\n\n Vector3 sq = cs1_l_ax.cwiseProduct(m_coeffs);\n m.coeffRef(0, 0) = 1 + (-sq.y() - sq.z());\n m.coeffRef(1, 1) = 1 + (-sq.x() - sq.z());\n m.coeffRef(2, 2) = 1 + (-sq.x() - sq.y());\n\n \/\/ Rotation matrix checks\n assert((m * m.transpose() - Matrix33::Identity()).norm() < 1e-10);\n assert(fabs(fabs(m.determinant()) - 1) < 1e-10);\n return m;\n }\n\n Quaternion getQuaternion() const {\n const Vector3 cf2 = m_coeffs \/ T(2);\n T a = cf2.norm();\n if (a > T(0)) {\n T sn = sin(a) \/ a;\n return Quaternion(cos(a), cf2.x() * sn, cf2.y() * sn, cf2.z() * sn);\n } else {\n return Quaternion(T(1), cf2.x(), cf2.y(), cf2.z());\n }\n }\n\n Vector3 coeffs() const {\n return m_coeffs;\n }\n\n T getAngle() const {\n return m_coeffs.norm();\n }\n\n Vector3 getAxis() const {\n T a = getAngle();\n return a > 0 ? (Vector3) (m_coeffs \/ a) : m_coeffs;\n }\n\n SO3 inverted() const {\n return SO3(-m_coeffs);\n }\n\n private:\n Vector3 m_coeffs;\n\n Matrix33 antiSymmMatrix() const {\n Vector3 axis = getAxis();\n Matrix33 m = Matrix33::Zero();\n m(0, 1) = -axis(2);\n m(1, 0) = axis(2);\n\n m(0, 2) = axis(1);\n m(2, 0) = -axis(1);\n\n m(2, 1) = axis(0);\n m(1, 2) = -axis(0);\n return m;\n }\n\n};\n\ntypedef SO3 SO3d;\ntypedef SO3 SO3f;\n\n#endif \/\/DAISU_SO3_HPP\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace folly { namespace detail {\n\nAtomicStruct\nMemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));\n\nvoid MemoryIdler::flushLocalMallocCaches() {\n if (!usingJEMalloc()) {\n return;\n }\n if (!mallctl || !mallctlnametomib || !mallctlbymib) {\n FB_LOG_EVERY_MS(ERROR, 10000) << \"mallctl* weak link failed\";\n return;\n }\n\n try {\n \/\/ Not using mallctlCall as this will fail if tcache is disabled.\n mallctl(\"thread.tcache.flush\", nullptr, nullptr, nullptr, 0);\n\n \/\/ By default jemalloc has 4 arenas per cpu, and then assigns each\n \/\/ thread to one of those arenas. This means that in any service\n \/\/ that doesn't perform a lot of context switching, the chances that\n \/\/ another thread will be using the current thread's arena (and hence\n \/\/ doing the appropriate dirty-page purging) are low. Some good\n \/\/ tuned configurations (such as that used by hhvm) use fewer arenas\n \/\/ and then pin threads to avoid contended access. In that case,\n \/\/ purging the arenas is counter-productive. We use the heuristic\n \/\/ that if narenas <= 2 * num_cpus then we shouldn't do anything here,\n \/\/ which detects when the narenas has been reduced from the default\n unsigned narenas;\n unsigned arenaForCurrent;\n size_t mib[3];\n size_t miblen = 3;\n\n mallctlRead(\"opt.narenas\", &narenas);\n mallctlRead(\"thread.arena\", &arenaForCurrent);\n if (narenas > 2 * CacheLocality::system().numCpus &&\n mallctlnametomib(\"arena.0.purge\", mib, &miblen) == 0) {\n mib[1] = static_cast(arenaForCurrent);\n mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);\n }\n } catch (const std::runtime_error& ex) {\n FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();\n }\n}\n\n\n\/\/ Stack madvise isn't Linux or glibc specific, but the system calls\n\/\/ and arithmetic (and bug compatibility) are not portable. The set of\n\/\/ platforms could be increased if it was useful.\n#if (FOLLY_X64 || FOLLY_PPC64) && defined(_GNU_SOURCE) && \\\n defined(__linux__) && !FOLLY_MOBILE && !FOLLY_SANITIZE_ADDRESS\n\nstatic FOLLY_TLS uintptr_t tls_stackLimit;\nstatic FOLLY_TLS size_t tls_stackSize;\n\nstatic size_t pageSize() {\n static const size_t s_pageSize = sysconf(_SC_PAGESIZE);\n return s_pageSize;\n}\n\nstatic void fetchStackLimits() {\n pthread_attr_t attr;\n pthread_getattr_np(pthread_self(), &attr);\n SCOPE_EXIT { pthread_attr_destroy(&attr); };\n\n void* addr;\n size_t rawSize;\n int err;\n if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {\n \/\/ unexpected, but it is better to continue in prod than do nothing\n FB_LOG_EVERY_MS(ERROR, 10000) << \"pthread_attr_getstack error \" << err;\n assert(false);\n tls_stackSize = 1;\n return;\n }\n assert(addr != nullptr);\n assert(rawSize >= PTHREAD_STACK_MIN);\n\n \/\/ glibc subtracts guard page from stack size, even though pthread docs\n \/\/ seem to imply the opposite\n size_t guardSize;\n if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {\n guardSize = 0;\n }\n assert(rawSize > guardSize);\n\n \/\/ stack goes down, so guard page adds to the base addr\n tls_stackLimit = reinterpret_cast(addr) + guardSize;\n tls_stackSize = rawSize - guardSize;\n\n assert((tls_stackLimit & (pageSize() - 1)) == 0);\n}\n\nFOLLY_NOINLINE static uintptr_t getStackPtr() {\n char marker;\n auto rv = reinterpret_cast(&marker);\n return rv;\n}\n\nvoid MemoryIdler::unmapUnusedStack(size_t retain) {\n if (tls_stackSize == 0) {\n fetchStackLimits();\n }\n if (tls_stackSize <= std::max(static_cast(1), retain)) {\n \/\/ covers both missing stack info, and impossibly large retain\n return;\n }\n\n auto sp = getStackPtr();\n assert(sp >= tls_stackLimit);\n assert(sp - tls_stackLimit < tls_stackSize);\n\n auto end = (sp - retain) & ~(pageSize() - 1);\n if (end <= tls_stackLimit) {\n \/\/ no pages are eligible for unmapping\n return;\n }\n\n size_t len = end - tls_stackLimit;\n assert((len & (pageSize() - 1)) == 0);\n if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {\n \/\/ It is likely that the stack vma hasn't been fully grown. In this\n \/\/ case madvise will apply dontneed to the present vmas, then return\n \/\/ errno of ENOMEM. We can also get an EAGAIN, theoretically.\n \/\/ EINVAL means either an invalid alignment or length, or that some\n \/\/ of the pages are locked or shared. Neither should occur.\n assert(errno == EAGAIN || errno == ENOMEM);\n }\n}\n\n#else\n\nvoid MemoryIdler::unmapUnusedStack(size_t \/* retain *\/) {}\n\n#endif\n\n} \/\/ namespace detail\n} \/\/ namespace folly\nbetter error handling in MemoryIdler for inside jails\/*\n * Copyright 2017 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace folly { namespace detail {\n\nAtomicStruct\nMemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));\n\nvoid MemoryIdler::flushLocalMallocCaches() {\n if (!usingJEMalloc()) {\n return;\n }\n if (!mallctl || !mallctlnametomib || !mallctlbymib) {\n FB_LOG_EVERY_MS(ERROR, 10000) << \"mallctl* weak link failed\";\n return;\n }\n\n try {\n \/\/ Not using mallctlCall as this will fail if tcache is disabled.\n mallctl(\"thread.tcache.flush\", nullptr, nullptr, nullptr, 0);\n\n \/\/ By default jemalloc has 4 arenas per cpu, and then assigns each\n \/\/ thread to one of those arenas. This means that in any service\n \/\/ that doesn't perform a lot of context switching, the chances that\n \/\/ another thread will be using the current thread's arena (and hence\n \/\/ doing the appropriate dirty-page purging) are low. Some good\n \/\/ tuned configurations (such as that used by hhvm) use fewer arenas\n \/\/ and then pin threads to avoid contended access. In that case,\n \/\/ purging the arenas is counter-productive. We use the heuristic\n \/\/ that if narenas <= 2 * num_cpus then we shouldn't do anything here,\n \/\/ which detects when the narenas has been reduced from the default\n unsigned narenas;\n unsigned arenaForCurrent;\n size_t mib[3];\n size_t miblen = 3;\n\n mallctlRead(\"opt.narenas\", &narenas);\n mallctlRead(\"thread.arena\", &arenaForCurrent);\n if (narenas > 2 * CacheLocality::system().numCpus &&\n mallctlnametomib(\"arena.0.purge\", mib, &miblen) == 0) {\n mib[1] = static_cast(arenaForCurrent);\n mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);\n }\n } catch (const std::runtime_error& ex) {\n FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();\n }\n}\n\n\n\/\/ Stack madvise isn't Linux or glibc specific, but the system calls\n\/\/ and arithmetic (and bug compatibility) are not portable. The set of\n\/\/ platforms could be increased if it was useful.\n#if (FOLLY_X64 || FOLLY_PPC64) && defined(_GNU_SOURCE) && \\\n defined(__linux__) && !FOLLY_MOBILE && !FOLLY_SANITIZE_ADDRESS\n\nstatic FOLLY_TLS uintptr_t tls_stackLimit;\nstatic FOLLY_TLS size_t tls_stackSize;\n\nstatic size_t pageSize() {\n static const size_t s_pageSize = sysconf(_SC_PAGESIZE);\n return s_pageSize;\n}\n\nstatic void fetchStackLimits() {\n int err;\n pthread_attr_t attr;\n if ((err = pthread_getattr_np(pthread_self(), &attr))) {\n \/\/ some restricted environments can't access \/proc\n static folly::once_flag flag;\n folly::call_once(flag, [err]() {\n LOG(WARNING) << \"pthread_getaddr_np failed errno=\" << err;\n });\n\n tls_stackSize = 1;\n return;\n }\n SCOPE_EXIT { pthread_attr_destroy(&attr); };\n\n void* addr;\n size_t rawSize;\n if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {\n \/\/ unexpected, but it is better to continue in prod than do nothing\n FB_LOG_EVERY_MS(ERROR, 10000) << \"pthread_attr_getstack error \" << err;\n assert(false);\n tls_stackSize = 1;\n return;\n }\n assert(addr != nullptr);\n assert(rawSize >= PTHREAD_STACK_MIN);\n\n \/\/ glibc subtracts guard page from stack size, even though pthread docs\n \/\/ seem to imply the opposite\n size_t guardSize;\n if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {\n guardSize = 0;\n }\n assert(rawSize > guardSize);\n\n \/\/ stack goes down, so guard page adds to the base addr\n tls_stackLimit = reinterpret_cast(addr) + guardSize;\n tls_stackSize = rawSize - guardSize;\n\n assert((tls_stackLimit & (pageSize() - 1)) == 0);\n}\n\nFOLLY_NOINLINE static uintptr_t getStackPtr() {\n char marker;\n auto rv = reinterpret_cast(&marker);\n return rv;\n}\n\nvoid MemoryIdler::unmapUnusedStack(size_t retain) {\n if (tls_stackSize == 0) {\n fetchStackLimits();\n }\n if (tls_stackSize <= std::max(static_cast(1), retain)) {\n \/\/ covers both missing stack info, and impossibly large retain\n return;\n }\n\n auto sp = getStackPtr();\n assert(sp >= tls_stackLimit);\n assert(sp - tls_stackLimit < tls_stackSize);\n\n auto end = (sp - retain) & ~(pageSize() - 1);\n if (end <= tls_stackLimit) {\n \/\/ no pages are eligible for unmapping\n return;\n }\n\n size_t len = end - tls_stackLimit;\n assert((len & (pageSize() - 1)) == 0);\n if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {\n \/\/ It is likely that the stack vma hasn't been fully grown. In this\n \/\/ case madvise will apply dontneed to the present vmas, then return\n \/\/ errno of ENOMEM. We can also get an EAGAIN, theoretically.\n \/\/ EINVAL means either an invalid alignment or length, or that some\n \/\/ of the pages are locked or shared. Neither should occur.\n assert(errno == EAGAIN || errno == ENOMEM);\n }\n}\n\n#else\n\nvoid MemoryIdler::unmapUnusedStack(size_t \/* retain *\/) {}\n\n#endif\n\n} \/\/ namespace detail\n} \/\/ namespace folly\n<|endoftext|>"} {"text":"#include \n#include \"mathematic_utils.hpp\"\n\nusing namespace Eigen;\n\ndouble distance2(const Vector3d& P1, const Vector3d& P2)\n{\n Vector3d dP = P2 - P1;\n return dP.dot(dP);\n}\n\nVector3d normalize(const Vector3d& X)\n{\n Vector3d N = X;\n if (N == Vector3d(0.,0.,0.)) return N;\n N.normalize();\n return N;\n}\n\nVector3d rotate(const Vector3d& X, const Vector3d& a, const double p)\n{\n Vector3d n = normalize(a);\n return X * cos(p) + n * (1.-cos(p)) * X.dot(n) + n.cross(X*sin(p));\n}\n\nbool inner_elipsoid(const Vector3d& P, const Vector3d& O, const Vector3d& R)\n{\n Vector3d Ps = (P - O).array() \/ R.array();\n return (Ps.array() * Ps.array()).sum() <= 1.;\n}\n\nVector3dSet neighoring(const Vector3d& O, const Vector3dSet& P)\n{\n Vector3dSet Q;\n double d;\n\n if ( P.size() == 0 ) return Q;\n\n Q.push_back(P[0]);\n d = distance2(P[0],O);\n for (size_t p = 1; p < P.size(); p++ ) {\n double d2 = distance2(P[p],O);\n if (d2 == d) {\n Q.push_back(P[p]);\n } else if (d2 < d) {\n Q.clear();\n Q.push_back(P[p]);\n d = d2;\n }\n }\n\n return Q;\n}\n\nVector3d reflect(const Vector3d& X, const Vector3d& n)\n{\n Vector3d Y;\n if (X.dot(n) == 0.) {\n \/\/ 特異点: Xとnが直交する\n Y = X;\n } else if ((X.cross(n).array() == 0.).all()) {\n \/\/ 特異点: Xとnが平行している\n Y = -X;\n } else {\n double lx = sqrt(X.dot(X));\n double ln = sqrt(n.dot(n));\n double p = acos(X.dot(n)\/(lx*ln));\n Vector3d a = X.cross(n);\n Y = -rotate(X,a,2.*p);\n }\n\n return Y;\n}\n\nVector3dSet intersection(const Vector3d& P, const Vector3d& v,\n const Vector3d& O, const Vector3d& R)\n{\n Vector3dSet Q;\n Vector3d P0 = P - O;\n\n \/\/ Q = P + v.t として\n \/\/ (Qx\/a)**2 + (Qy\/b)**2 + (Qz\/c)**2 = 1\n \/\/ となる方程式 A.t**2 + B.t + C = 0 を t について解く\n double A = ((v.array() \/ R.array()) * (v.array() \/ R.array())).sum();\n double B = ( P0.array() * v.array() * 2. \/ (R.array() * R.array())).sum();\n double C = ((P.array() \/ R.array()) * (P0.array() \/ R.array())).sum() - 1.;\n\n \/\/ 解の判定\n double D = B*B - 4.*A*C;\n if ( D >= 0. ) {\n \/\/ 実数解になる\n double t1 = (-B + sqrt(D)) \/ (2. * A);\n double t2 = (-B - sqrt(D)) \/ (2. * A);\n\n \/\/ tをLの方程式に当てて交点Qとする\n Vector3d Q1 = P + v*t1;\n Vector3d Q2 = P + v*t2;\n\n if ( D == 0. ) {\n \/\/ 解はひとつ\n Q.push_back(Q1);\n } else {\n \/\/ 解は2つ\n Q.push_back(Q1);\n Q.push_back(Q2);\n }\n }\n\n return Q;\n}\n\n式の実装記述ミスを修正#include \n#include \"mathematic_utils.hpp\"\n\nusing namespace Eigen;\n\ndouble distance2(const Vector3d& P1, const Vector3d& P2)\n{\n Vector3d dP = P2 - P1;\n return dP.dot(dP);\n}\n\nVector3d normalize(const Vector3d& X)\n{\n Vector3d N = X;\n if (N == Vector3d(0.,0.,0.)) return N;\n N.normalize();\n return N;\n}\n\nVector3d rotate(const Vector3d& X, const Vector3d& a, const double p)\n{\n Vector3d n = normalize(a);\n return X * cos(p) + n * (1.-cos(p)) * X.dot(n) + n.cross(X*sin(p));\n}\n\nbool inner_elipsoid(const Vector3d& P, const Vector3d& O, const Vector3d& R)\n{\n Vector3d Ps = (P - O).array() \/ R.array();\n return (Ps.array() * Ps.array()).sum() <= 1.;\n}\n\nVector3dSet neighoring(const Vector3d& O, const Vector3dSet& P)\n{\n Vector3dSet Q;\n double d;\n\n if ( P.size() == 0 ) return Q;\n\n Q.push_back(P[0]);\n d = distance2(P[0],O);\n for (size_t p = 1; p < P.size(); p++ ) {\n double d2 = distance2(P[p],O);\n if (d2 == d) {\n Q.push_back(P[p]);\n } else if (d2 < d) {\n Q.clear();\n Q.push_back(P[p]);\n d = d2;\n }\n }\n\n return Q;\n}\n\nVector3d reflect(const Vector3d& X, const Vector3d& n)\n{\n Vector3d Y;\n if (X.dot(n) == 0.) {\n \/\/ 特異点: Xとnが直交する\n Y = X;\n } else if ((X.cross(n).array() == 0.).all()) {\n \/\/ 特異点: Xとnが平行している\n Y = -X;\n } else {\n double lx = sqrt(X.dot(X));\n double ln = sqrt(n.dot(n));\n double p = acos(X.dot(n)\/(lx*ln));\n Vector3d a = X.cross(n);\n Y = -rotate(X,a,2.*p);\n }\n\n return Y;\n}\n\nVector3dSet intersection(const Vector3d& P, const Vector3d& v,\n const Vector3d& O, const Vector3d& R)\n{\n Vector3dSet Q;\n Vector3d P0 = P - O;\n\n \/\/ Q = P + v.t として\n \/\/ (Qx\/a)**2 + (Qy\/b)**2 + (Qz\/c)**2 = 1\n \/\/ となる方程式 A.t**2 + B.t + C = 0 を t について解く\n double A = ((v.array() \/ R.array()) * (v.array() \/ R.array())).sum();\n double B = ( P0.array() * v.array() * 2. \/ (R.array() * R.array())).sum();\n double C = ((P0.array() \/ R.array()) * (P0.array() \/ R.array())).sum() - 1.;\n\n \/\/ 解の判定\n double D = B*B - 4.*A*C;\n if ( D >= 0. ) {\n \/\/ 実数解になる\n double t1 = (-B + sqrt(D)) \/ (2. * A);\n double t2 = (-B - sqrt(D)) \/ (2. * A);\n\n \/\/ tをLの方程式に当てて交点Qとする\n Vector3d Q1 = P + v*t1;\n Vector3d Q2 = P + v*t2;\n\n if ( D == 0. ) {\n \/\/ 解はひとつ\n Q.push_back(Q1);\n } else {\n \/\/ 解は2つ\n Q.push_back(Q1);\n Q.push_back(Q2);\n }\n }\n\n return Q;\n}\n\n<|endoftext|>"} {"text":"#include \"menu\/option_menu.h\"\n#include \"menu\/menu.h\"\n#include \"menu\/tab_menu.h\"\n#include \"util\/token.h\"\n#include \"return_exception.h\"\n#include \"util\/token_exception.h\"\n#include \"util\/funcs.h\"\n\nOptionMenu::OptionMenu(Token *token) throw (LoadException): MenuOption(token, Event), _menu(0)\n{\n \/\/ Check whether we have a menu or tabmenu\n if ( *token == \"menu\" )\n {\n\t_menu = new Menu();\n } else if (*token == \"tabmenu\"){\n\t_menu = new TabMenu();\n } else {\n\tthrow LoadException(\"Not a menu\");\n }\n \/\/ Set this menu as an option\n _menu->setAsOption(true);\n \n \/\/ Lets try loading from a file\n std::string temp;\n \/\/ Filename\n *token >> temp;\n if(temp==\"name\")\n {\n\t token->resetToken();\n\t _menu->load(token);\n }\n else _menu->load(Util::getDataPath() + temp);\n this->setText(_menu->getName());\n \n \/\/ Lets check if this menu is going bye bye\n if ( _menu->checkRemoval() ) setForRemoval(true);\n}\n\nOptionMenu::~OptionMenu()\n{\n\t\/\/ Delete our menu\n\tif(_menu)delete _menu;\n}\n\nvoid OptionMenu::logic()\n{\n\t\/\/ Nothing\n}\n\nvoid OptionMenu::run(bool &endGame)\n{\n\t\/\/ Do our new menu\n\t_menu->run();\n}\n\ndont assume first token is \"name\"#include \"menu\/option_menu.h\"\n#include \"menu\/menu.h\"\n#include \"menu\/tab_menu.h\"\n#include \"util\/token.h\"\n#include \"return_exception.h\"\n#include \"util\/token_exception.h\"\n#include \"util\/funcs.h\"\n#include \"globals.h\"\n\nOptionMenu::OptionMenu(Token *token) throw (LoadException):\nMenuOption(token, Event),\n_menu(0){\n \/\/ Check whether we have a menu or tabmenu\n if ( *token == \"menu\" ){\n\t_menu = new Menu();\n } else if (*token == \"tabmenu\"){\n\t_menu = new TabMenu();\n } else {\n\tthrow LoadException(\"Not a menu\");\n }\n \/\/ Set this menu as an option\n _menu->setAsOption(true);\n \n \/*\n \/\/ Lets try loading from a file\n std::string temp;\n \/\/ Filename\n *token >> temp;\n *\/\n\n if (token->numTokens() == 1){\n std::string temp;\n *token >> temp;\n _menu->load(Util::getDataPath() + temp);\n } else {\n _menu->load(token);\n }\n\n this->setText(_menu->getName());\n \n \/\/ Lets check if this menu is going bye bye\n if ( _menu->checkRemoval() ) setForRemoval(true);\n}\n\nOptionMenu::~OptionMenu()\n{\n\t\/\/ Delete our menu\n\tif(_menu)delete _menu;\n}\n\nvoid OptionMenu::logic()\n{\n\t\/\/ Nothing\n}\n\nvoid OptionMenu::run(bool &endGame)\n{\n\t\/\/ Do our new menu\n\t_menu->run();\n}\n\n<|endoftext|>"} {"text":"\/* Copyright 2019 Google LLC. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n\n#include \"test.h\"\n\nnamespace ruy {\n\nusing LhsScalar = RUY_TEST_LHSSCALAR;\nusing RhsScalar = RUY_TEST_RHSSCALAR;\nusing AccumScalar = RUY_TEST_ACCUMSCALAR;\nusing DstScalar = RUY_TEST_DSTSCALAR;\nusing TestSetType =\n TestSet>;\n\nstruct BenchmarkShape {\n int rows;\n int depth;\n int cols;\n int symm_lhs;\n int symm_rhs;\n};\n\ntemplate \nstd::vector>> BenchmarkRCC(\n const BenchmarkShape& shape) {\n TestSetType test_set;\n test_set.rows = shape.rows;\n test_set.depth = shape.depth;\n test_set.cols = shape.cols;\n test_set.lhs_order = Order::kRowMajor;\n test_set.rhs_order = Order::kColMajor;\n test_set.dst_order = Order::kColMajor;\n test_set.layout_style = LayoutStyle::kPackedLinear;\n test_set.benchmark = true;\n const int asymmetry_lhs = shape.symm_lhs ? 0 : 1;\n const int asymmetry_rhs = shape.symm_rhs ? 0 : 1;\n test_set.lhs_zero_point = SymmetricZeroPoint() + asymmetry_lhs;\n test_set.rhs_zero_point = SymmetricZeroPoint() + asymmetry_rhs;\n test_set.use_specified_zero_points = true;\n test_set.perchannel = GetBoolEnvVarOrFalse(\"PERCHANNEL\");\n test_set.benchmark_prepack_lhs = GetBoolEnvVarOrFalse(\"PREPACK_LHS\");\n test_set.benchmark_prepack_rhs = GetBoolEnvVarOrFalse(\"PREPACK_RHS\");\n test_set.Run();\n return std::move(test_set.results);\n}\n\nstd::vector ParseCommaSeparatedInts(\n const std::string& comma_separated_ints) {\n std::vector result;\n for (std::size_t pos = 0; pos < comma_separated_ints.size();) {\n std::size_t delim_pos = comma_separated_ints.find(',', pos);\n if (delim_pos == std::string::npos) {\n delim_pos = comma_separated_ints.size();\n }\n result.push_back(\n std::stoi(comma_separated_ints.substr(pos, delim_pos - pos)));\n pos = delim_pos + 1;\n }\n return result;\n}\n\nvoid Benchmark() {\n const bool symm_lhs = std::is_floating_point::value ||\n GetBoolEnvVarOrFalse(\"SYMM_LHS\");\n const bool symm_rhs = std::is_floating_point::value ||\n GetBoolEnvVarOrFalse(\"SYMM_RHS\");\n const bool benchmark_cubic = GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_CUBIC\") ||\n GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_CUBIC_LIST\");\n const int explicit_rows = GetIntEnvVarOrZero(\"ROWS\");\n const int explicit_cols = GetIntEnvVarOrZero(\"COLS\");\n const int explicit_depth = GetIntEnvVarOrZero(\"DEPTH\");\n\n std::vector shapes;\n\n if (benchmark_cubic) {\n std::vector sizes;\n const char* benchmark_cubic_list_env = getenv(\"RUY_BENCHMARK_CUBIC_LIST\");\n if (benchmark_cubic_list_env) {\n sizes = ParseCommaSeparatedInts(benchmark_cubic_list_env);\n } else {\n \/\/ Often 8 is used for this multiplier, but to check teeny sizes one can\n \/\/ use 1.\n static constexpr int cubic_size_multiplier = 8;\n for (int i = 2 * cubic_size_multiplier;\n i <= (512 * cubic_size_multiplier); i *= 2) {\n sizes.push_back(i);\n if (i < (512 * cubic_size_multiplier)) {\n sizes.push_back(i * 3 \/ 2);\n }\n }\n }\n for (int i : sizes) {\n BenchmarkShape shape;\n \/\/ Even in cubic mode, one may still override an individual dimension\n \/\/ to allow testing a batch of rectangular sizes.\n shape.rows = explicit_rows ? explicit_rows : i;\n shape.cols = explicit_cols ? explicit_cols : i;\n shape.depth = explicit_depth ? explicit_depth : i;\n shape.symm_lhs = symm_lhs;\n shape.symm_rhs = symm_rhs;\n shapes.push_back(shape);\n }\n } else {\n BenchmarkShape shape;\n shape.rows = explicit_rows;\n shape.cols = explicit_cols;\n shape.depth = explicit_depth;\n if (!shape.rows || !shape.depth || !shape.cols) {\n fprintf(stderr,\n \"Please specify positive sizes with these env vars: ROWS, DEPTH, \"\n \"COLS.\\n\");\n exit(1);\n }\n shape.symm_lhs = symm_lhs;\n shape.symm_rhs = symm_rhs;\n shapes.push_back(shape);\n }\n\n for (int i = 0; i < shapes.size(); i++) {\n const auto& shape = shapes[i];\n const auto& results = BenchmarkRCC(shape);\n if (i == 0) {\n if (benchmark_cubic) {\n printf(\"size\");\n for (const auto& result : results) {\n printf(\",%s\", PathName(*result).c_str());\n }\n printf(\"\\n\");\n } else {\n printf(\"path,shape,Gop\/s\\n\");\n }\n fflush(stdout);\n }\n if (benchmark_cubic) {\n printf(\"%d\", shape.rows);\n for (const auto& result : results) {\n printf(\",%.4g\", 2.0e-9 * shape.rows * shape.cols * shape.depth \/\n result->latency);\n if (GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_PMU\")) {\n printf(\",%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g\",\n result->l1_refill_rate, result->l2_refill_rate,\n result->l3_refill_rate, result->l1tlb_refill_rate,\n result->l2tlb_refill_rate, result->mispred_rate,\n result->frontend_stall_rate, result->backend_stall_rate);\n }\n }\n printf(\"\\n\");\n fflush(stdout);\n } else {\n for (const auto& result : results) {\n printf(\n \"%s,%dx%dx%d,%.4g\", PathName(*result).c_str(), shape.rows,\n shape.depth, shape.cols,\n 2.0e-9 * shape.rows * shape.cols * shape.depth \/ result->latency);\n if (GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_PMU\")) {\n printf(\",%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g\",\n result->l1_refill_rate, result->l2_refill_rate,\n result->l3_refill_rate, result->l1tlb_refill_rate,\n result->l2tlb_refill_rate, result->mispred_rate,\n result->frontend_stall_rate, result->backend_stall_rate);\n }\n printf(\"\\n\");\n }\n fflush(stdout);\n }\n }\n}\n\n} \/\/ namespace ruy\n\nint main() { ruy::Benchmark(); }\nbetter column headers in the benchmark output.\/* Copyright 2019 Google LLC. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n\n#include \"test.h\"\n\nnamespace ruy {\n\nusing LhsScalar = RUY_TEST_LHSSCALAR;\nusing RhsScalar = RUY_TEST_RHSSCALAR;\nusing AccumScalar = RUY_TEST_ACCUMSCALAR;\nusing DstScalar = RUY_TEST_DSTSCALAR;\nusing TestSetType =\n TestSet>;\n\nstruct BenchmarkShape {\n int rows;\n int depth;\n int cols;\n int symm_lhs;\n int symm_rhs;\n};\n\ntemplate \nstd::vector>> BenchmarkRCC(\n const BenchmarkShape& shape) {\n TestSetType test_set;\n test_set.rows = shape.rows;\n test_set.depth = shape.depth;\n test_set.cols = shape.cols;\n test_set.lhs_order = Order::kRowMajor;\n test_set.rhs_order = Order::kColMajor;\n test_set.dst_order = Order::kColMajor;\n test_set.layout_style = LayoutStyle::kPackedLinear;\n test_set.benchmark = true;\n const int asymmetry_lhs = shape.symm_lhs ? 0 : 1;\n const int asymmetry_rhs = shape.symm_rhs ? 0 : 1;\n test_set.lhs_zero_point = SymmetricZeroPoint() + asymmetry_lhs;\n test_set.rhs_zero_point = SymmetricZeroPoint() + asymmetry_rhs;\n test_set.use_specified_zero_points = true;\n test_set.perchannel = GetBoolEnvVarOrFalse(\"PERCHANNEL\");\n test_set.benchmark_prepack_lhs = GetBoolEnvVarOrFalse(\"PREPACK_LHS\");\n test_set.benchmark_prepack_rhs = GetBoolEnvVarOrFalse(\"PREPACK_RHS\");\n test_set.Run();\n return std::move(test_set.results);\n}\n\nstd::vector ParseCommaSeparatedInts(\n const std::string& comma_separated_ints) {\n std::vector result;\n for (std::size_t pos = 0; pos < comma_separated_ints.size();) {\n std::size_t delim_pos = comma_separated_ints.find(',', pos);\n if (delim_pos == std::string::npos) {\n delim_pos = comma_separated_ints.size();\n }\n result.push_back(\n std::stoi(comma_separated_ints.substr(pos, delim_pos - pos)));\n pos = delim_pos + 1;\n }\n return result;\n}\n\nvoid Benchmark() {\n const bool symm_lhs = std::is_floating_point::value ||\n GetBoolEnvVarOrFalse(\"SYMM_LHS\");\n const bool symm_rhs = std::is_floating_point::value ||\n GetBoolEnvVarOrFalse(\"SYMM_RHS\");\n const bool benchmark_cubic = GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_CUBIC\") ||\n GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_CUBIC_LIST\");\n const int explicit_rows = GetIntEnvVarOrZero(\"ROWS\");\n const int explicit_cols = GetIntEnvVarOrZero(\"COLS\");\n const int explicit_depth = GetIntEnvVarOrZero(\"DEPTH\");\n\n std::vector shapes;\n\n if (benchmark_cubic) {\n std::vector sizes;\n const char* benchmark_cubic_list_env = getenv(\"RUY_BENCHMARK_CUBIC_LIST\");\n if (benchmark_cubic_list_env) {\n sizes = ParseCommaSeparatedInts(benchmark_cubic_list_env);\n } else {\n \/\/ Often 8 is used for this multiplier, but to check teeny sizes one can\n \/\/ use 1.\n static constexpr int cubic_size_multiplier = 8;\n for (int i = 2 * cubic_size_multiplier;\n i <= (512 * cubic_size_multiplier); i *= 2) {\n sizes.push_back(i);\n if (i < (512 * cubic_size_multiplier)) {\n sizes.push_back(i * 3 \/ 2);\n }\n }\n }\n for (int i : sizes) {\n BenchmarkShape shape;\n \/\/ Even in cubic mode, one may still override an individual dimension\n \/\/ to allow testing a batch of rectangular sizes.\n shape.rows = explicit_rows ? explicit_rows : i;\n shape.cols = explicit_cols ? explicit_cols : i;\n shape.depth = explicit_depth ? explicit_depth : i;\n shape.symm_lhs = symm_lhs;\n shape.symm_rhs = symm_rhs;\n shapes.push_back(shape);\n }\n } else {\n BenchmarkShape shape;\n shape.rows = explicit_rows;\n shape.cols = explicit_cols;\n shape.depth = explicit_depth;\n if (!shape.rows || !shape.depth || !shape.cols) {\n fprintf(stderr,\n \"Please specify positive sizes with these env vars: ROWS, DEPTH, \"\n \"COLS.\\n\");\n exit(1);\n }\n shape.symm_lhs = symm_lhs;\n shape.symm_rhs = symm_rhs;\n shapes.push_back(shape);\n }\n\n for (int i = 0; i < shapes.size(); i++) {\n const auto& shape = shapes[i];\n const auto& results = BenchmarkRCC(shape);\n if (i == 0) {\n if (benchmark_cubic) {\n printf(\"size\");\n for (const auto& result : results) {\n if (results.size() > 1) {\n printf(\",%s:Gop\/s\", PathName(*result).c_str());\n } else {\n printf(\",Gop\/s\");\n }\n if (GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_PMU\")) {\n printf(\n \",l1_refill,l2_refill,l3_refill,l1tlb_refill,l2tlb_refill,\"\n \"mispred,frontend_stall,backend_stall\");\n }\n }\n printf(\"\\n\");\n } else {\n printf(\"path,shape,Gop\/s\\n\");\n }\n fflush(stdout);\n }\n if (benchmark_cubic) {\n printf(\"%d\", shape.rows);\n for (const auto& result : results) {\n printf(\",%.4g\", 2.0e-9 * shape.rows * shape.cols * shape.depth \/\n result->latency);\n if (GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_PMU\")) {\n printf(\",%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g\",\n result->l1_refill_rate, result->l2_refill_rate,\n result->l3_refill_rate, result->l1tlb_refill_rate,\n result->l2tlb_refill_rate, result->mispred_rate,\n result->frontend_stall_rate, result->backend_stall_rate);\n }\n }\n printf(\"\\n\");\n fflush(stdout);\n } else {\n for (const auto& result : results) {\n printf(\n \"%s,%dx%dx%d,%.4g\", PathName(*result).c_str(), shape.rows,\n shape.depth, shape.cols,\n 2.0e-9 * shape.rows * shape.cols * shape.depth \/ result->latency);\n if (GetBoolEnvVarOrFalse(\"RUY_BENCHMARK_PMU\")) {\n printf(\",%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g,%.3g\",\n result->l1_refill_rate, result->l2_refill_rate,\n result->l3_refill_rate, result->l1tlb_refill_rate,\n result->l2tlb_refill_rate, result->mispred_rate,\n result->frontend_stall_rate, result->backend_stall_rate);\n }\n printf(\"\\n\");\n }\n fflush(stdout);\n }\n }\n}\n\n} \/\/ namespace ruy\n\nint main() { ruy::Benchmark(); }\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\nusing rclcpp::callback_group::CallbackGroupType;\nusing std::chrono::steady_clock;\ntypedef std::chrono::duration floating_seconds;\n\nvoid on_timer_group1()\n{\n auto this_id = rclcpp::thread_id;\n auto start = steady_clock::now();\n std::cout << \"[1:\" << this_id << \"] Start\" << std::endl;\n rclcpp::sleep_for(0.001_s);\n std::cout << \"[1:\" << this_id << \"] Stop after \"\n << std::chrono::duration_cast(\n steady_clock::now() - start).count()\n << std::endl;\n}\n\nvoid on_timer_group2()\n{\n auto this_id = rclcpp::thread_id;\n auto start = steady_clock::now();\n std::cout << \"[2:\" << this_id << \"] Start\" << std::endl;\n rclcpp::sleep_for(0.001_s);\n std::cout << \"[2:\" << this_id << \"] Stop after \"\n << std::chrono::duration_cast(\n steady_clock::now() - start).count()\n << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n rclcpp::init(argc, argv);\n\n auto node = rclcpp::Node::make_shared(\"my_node\");\n\n \/\/ auto g1 = node->create_callback_group(CallbackGroupType::MutuallyExclusive);\n auto g2 = node->create_callback_group(CallbackGroupType::MutuallyExclusive);\n \/\/ auto g2 = node->create_callback_group(CallbackGroupType::Reentrant);\n\n \/\/ auto timer1 = node->create_wall_timer(2.0_s, on_timer_group1, g1);\n \/\/ auto timer2 = node->create_wall_timer(0.25_s, on_timer_group2, g2);\n auto timer3 = node->create_wall_timer(0.001_s, on_timer_group1, g2);\n\n \/\/ rclcpp::executors::MultiThreadedExecutor executor;\n rclcpp::executors::SingleThreadedExecutor executor;\n executor.add_node(node);\n\n executor.spin();\n\n rclcpp::utilities::sleep_for(std::chrono::seconds(1));\n\n return 0;\n}\ndifferent_groups: remove vestigial code#include \n#include \n#include \n\n#include \n\nusing rclcpp::callback_group::CallbackGroupType;\nusing std::chrono::steady_clock;\ntypedef std::chrono::duration floating_seconds;\n\nvoid on_timer_group1()\n{\n auto this_id = rclcpp::thread_id;\n auto start = steady_clock::now();\n std::cout << \"[1:\" << this_id << \"] Start\" << std::endl;\n rclcpp::sleep_for(0.001_s);\n std::cout << \"[1:\" << this_id << \"] Stop after \"\n << std::chrono::duration_cast(\n steady_clock::now() - start).count()\n << std::endl;\n}\n\nvoid on_timer_group2()\n{\n auto this_id = rclcpp::thread_id;\n auto start = steady_clock::now();\n std::cout << \"[2:\" << this_id << \"] Start\" << std::endl;\n rclcpp::sleep_for(0.001_s);\n std::cout << \"[2:\" << this_id << \"] Stop after \"\n << std::chrono::duration_cast(\n steady_clock::now() - start).count()\n << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n rclcpp::init(argc, argv);\n\n auto node = rclcpp::Node::make_shared(\"my_node\");\n\n \/\/ auto g1 = node->create_callback_group(CallbackGroupType::MutuallyExclusive);\n auto g2 = node->create_callback_group(CallbackGroupType::MutuallyExclusive);\n \/\/ auto g2 = node->create_callback_group(CallbackGroupType::Reentrant);\n\n \/\/ auto timer1 = node->create_wall_timer(2.0_s, on_timer_group1, g1);\n \/\/ auto timer2 = node->create_wall_timer(0.25_s, on_timer_group2, g2);\n auto timer3 = node->create_wall_timer(0.001_s, on_timer_group1, g2);\n\n \/\/ rclcpp::executors::MultiThreadedExecutor executor;\n rclcpp::executors::SingleThreadedExecutor executor;\n executor.add_node(node);\n\n executor.spin();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ These tablegen backends emit Clang diagnostics tables.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ClangDiagnosticsEmitter.h\"\n#include \"llvm\/TableGen\/Record.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/VectorExtras.h\"\n#include \n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Diagnostic category computation code.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nclass DiagGroupParentMap {\n RecordKeeper &Records;\n std::map > Mapping;\npublic:\n DiagGroupParentMap(RecordKeeper &records) : Records(records) {\n std::vector DiagGroups\n = Records.getAllDerivedDefinitions(\"DiagGroup\");\n for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {\n std::vector SubGroups =\n DiagGroups[i]->getValueAsListOfDefs(\"SubGroups\");\n for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)\n Mapping[SubGroups[j]].push_back(DiagGroups[i]);\n }\n }\n \n const std::vector &getParents(const Record *Group) {\n return Mapping[Group];\n }\n};\n} \/\/ end anonymous namespace.\n\n\nstatic std::string\ngetCategoryFromDiagGroup(const Record *Group,\n DiagGroupParentMap &DiagGroupParents) {\n \/\/ If the DiagGroup has a category, return it.\n std::string CatName = Group->getValueAsString(\"CategoryName\");\n if (!CatName.empty()) return CatName;\n \n \/\/ The diag group may the subgroup of one or more other diagnostic groups,\n \/\/ check these for a category as well.\n const std::vector &Parents = DiagGroupParents.getParents(Group);\n for (unsigned i = 0, e = Parents.size(); i != e; ++i) {\n CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);\n if (!CatName.empty()) return CatName;\n }\n return \"\";\n}\n\n\/\/\/ getDiagnosticCategory - Return the category that the specified diagnostic\n\/\/\/ lives in.\nstatic std::string getDiagnosticCategory(const Record *R,\n DiagGroupParentMap &DiagGroupParents) {\n \/\/ If the diagnostic is in a group, and that group has a category, use it.\n if (DefInit *Group = dynamic_cast(R->getValueInit(\"Group\"))) {\n \/\/ Check the diagnostic's diag group for a category.\n std::string CatName = getCategoryFromDiagGroup(Group->getDef(),\n DiagGroupParents);\n if (!CatName.empty()) return CatName;\n }\n \n \/\/ If the diagnostic itself has a category, get it.\n return R->getValueAsString(\"CategoryName\");\n}\n\nnamespace {\n class DiagCategoryIDMap {\n RecordKeeper &Records;\n StringMap CategoryIDs;\n std::vector CategoryStrings;\n public:\n DiagCategoryIDMap(RecordKeeper &records) : Records(records) {\n DiagGroupParentMap ParentInfo(Records);\n \n \/\/ The zero'th category is \"\".\n CategoryStrings.push_back(\"\");\n CategoryIDs[\"\"] = 0;\n \n std::vector Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);\n if (Category.empty()) continue; \/\/ Skip diags with no category.\n \n unsigned &ID = CategoryIDs[Category];\n if (ID != 0) continue; \/\/ Already seen.\n \n ID = CategoryStrings.size();\n CategoryStrings.push_back(Category);\n }\n }\n \n unsigned getID(StringRef CategoryString) {\n return CategoryIDs[CategoryString];\n }\n \n typedef std::vector::iterator iterator;\n iterator begin() { return CategoryStrings.begin(); }\n iterator end() { return CategoryStrings.end(); }\n };\n} \/\/ end anonymous namespace.\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Warning Tables (.inc file) generation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid ClangDiagsDefsEmitter::run(raw_ostream &OS) {\n \/\/ Write the #if guard\n if (!Component.empty()) {\n std::string ComponentName = StringRef(Component).upper();\n OS << \"#ifdef \" << ComponentName << \"START\\n\";\n OS << \"__\" << ComponentName << \"START = DIAG_START_\" << ComponentName\n << \",\\n\";\n OS << \"#undef \" << ComponentName << \"START\\n\";\n OS << \"#endif\\n\\n\";\n }\n\n const std::vector &Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n \n DiagCategoryIDMap CategoryIDs(Records);\n DiagGroupParentMap DGParentMap(Records);\n\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n const Record &R = *Diags[i];\n \/\/ Filter by component.\n if (!Component.empty() && Component != R.getValueAsString(\"Component\"))\n continue;\n\n OS << \"DIAG(\" << R.getName() << \", \";\n OS << R.getValueAsDef(\"Class\")->getName();\n OS << \", diag::\" << R.getValueAsDef(\"DefaultMapping\")->getName();\n \n \/\/ Description string.\n OS << \", \\\"\";\n OS.write_escaped(R.getValueAsString(\"Text\")) << '\"';\n \n \/\/ Warning associated with the diagnostic.\n if (DefInit *DI = dynamic_cast(R.getValueInit(\"Group\"))) {\n OS << \", \\\"\";\n OS.write_escaped(DI->getDef()->getValueAsString(\"GroupName\")) << '\"';\n } else {\n OS << \", \\\"\\\"\";\n }\n\n \/\/ SFINAE bit\n if (R.getValueAsBit(\"SFINAE\"))\n OS << \", true\";\n else\n OS << \", false\";\n\n \/\/ Access control bit\n if (R.getValueAsBit(\"AccessControl\"))\n OS << \", true\";\n else\n OS << \", false\";\n\n \/\/ FIXME: This condition is just to avoid temporary revlock, it can be\n \/\/ removed.\n if (R.getValue(\"WarningNoWerror\")) {\n \/\/ Default warning has no Werror bit.\n if (R.getValueAsBit(\"WarningNoWerror\"))\n OS << \", true\";\n else\n OS << \", false\";\n \n \/\/ Default warning show in system header bit.\n if (R.getValueAsBit(\"WarningShowInSystemHeader\"))\n OS << \", true\";\n else\n OS << \", false\";\n }\n \n \/\/ Category number.\n OS << \", \" << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));\n\n \/\/ Brief\n OS << \", \\\"\";\n OS.write_escaped(R.getValueAsString(\"Brief\")) << '\"';\n\n \/\/ Explanation \n OS << \", \\\"\";\n OS.write_escaped(R.getValueAsString(\"Explanation\")) << '\"';\n OS << \")\\n\";\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Warning Group Tables generation\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic std::string getDiagCategoryEnum(llvm::StringRef name) {\n if (name.empty())\n return \"DiagCat_None\";\n llvm::SmallString<256> enumName = llvm::StringRef(\"DiagCat_\");\n for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)\n enumName += isalnum(*I) ? *I : '_';\n return enumName.str();\n}\n\nnamespace {\nstruct GroupInfo {\n std::vector DiagsInGroup;\n std::vector SubGroups;\n unsigned IDNo;\n};\n} \/\/ end anonymous namespace.\n\nvoid ClangDiagGroupsEmitter::run(raw_ostream &OS) {\n \/\/ Compute a mapping from a DiagGroup to all of its parents.\n DiagGroupParentMap DGParentMap(Records);\n \n \/\/ Invert the 1-[0\/1] mapping of diags to group into a one to many mapping of\n \/\/ groups to diags in the group.\n std::map DiagsInGroup;\n \n std::vector Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n const Record *R = Diags[i];\n DefInit *DI = dynamic_cast(R->getValueInit(\"Group\"));\n if (DI == 0) continue;\n std::string GroupName = DI->getDef()->getValueAsString(\"GroupName\");\n DiagsInGroup[GroupName].DiagsInGroup.push_back(R);\n }\n \n \/\/ Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty\n \/\/ groups (these are warnings that GCC supports that clang never produces).\n std::vector DiagGroups\n = Records.getAllDerivedDefinitions(\"DiagGroup\");\n for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {\n Record *Group = DiagGroups[i];\n GroupInfo &GI = DiagsInGroup[Group->getValueAsString(\"GroupName\")];\n \n std::vector SubGroups = Group->getValueAsListOfDefs(\"SubGroups\");\n for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)\n GI.SubGroups.push_back(SubGroups[j]->getValueAsString(\"GroupName\"));\n }\n \n \/\/ Assign unique ID numbers to the groups.\n unsigned IDNo = 0;\n for (std::map::iterator\n I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)\n I->second.IDNo = IDNo;\n \n \/\/ Walk through the groups emitting an array for each diagnostic of the diags\n \/\/ that are mapped to.\n OS << \"\\n#ifdef GET_DIAG_ARRAYS\\n\";\n unsigned MaxLen = 0;\n for (std::map::iterator\n I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {\n MaxLen = std::max(MaxLen, (unsigned)I->first.size());\n \n std::vector &V = I->second.DiagsInGroup;\n if (!V.empty()) {\n OS << \"static const short DiagArray\" << I->second.IDNo << \"[] = { \";\n for (unsigned i = 0, e = V.size(); i != e; ++i)\n OS << \"diag::\" << V[i]->getName() << \", \";\n OS << \"-1 };\\n\";\n }\n \n const std::vector &SubGroups = I->second.SubGroups;\n if (!SubGroups.empty()) {\n OS << \"static const short DiagSubGroup\" << I->second.IDNo << \"[] = { \";\n for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {\n std::map::iterator RI =\n DiagsInGroup.find(SubGroups[i]);\n assert(RI != DiagsInGroup.end() && \"Referenced without existing?\");\n OS << RI->second.IDNo << \", \";\n }\n OS << \"-1 };\\n\";\n }\n }\n OS << \"#endif \/\/ GET_DIAG_ARRAYS\\n\\n\";\n \n \/\/ Emit the table now.\n OS << \"\\n#ifdef GET_DIAG_TABLE\\n\";\n for (std::map::iterator\n I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {\n \/\/ Group option string.\n OS << \" { \";\n OS << I->first.size() << \", \";\n OS << \"\\\"\";\n if (I->first.find_first_not_of(\"abcdefghijklmnopqrstuvwxyz\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"0123456789!@#$%^*-+=:?\")!=std::string::npos)\n throw \"Invalid character in diagnostic group '\" + I->first + \"'\";\n OS.write_escaped(I->first) << \"\\\",\"\n << std::string(MaxLen-I->first.size()+1, ' ');\n \n \/\/ Diagnostics in the group.\n if (I->second.DiagsInGroup.empty())\n OS << \"0, \";\n else\n OS << \"DiagArray\" << I->second.IDNo << \", \";\n \n \/\/ Subgroups.\n if (I->second.SubGroups.empty())\n OS << 0;\n else\n OS << \"DiagSubGroup\" << I->second.IDNo;\n OS << \" },\\n\";\n }\n OS << \"#endif \/\/ GET_DIAG_TABLE\\n\\n\";\n \n \/\/ Emit the category table next.\n DiagCategoryIDMap CategoriesByID(Records);\n OS << \"\\n#ifdef GET_CATEGORY_TABLE\\n\";\n for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(),\n E = CategoriesByID.end(); I != E; ++I)\n OS << \"CATEGORY(\\\"\" << *I << \"\\\", \" << getDiagCategoryEnum(*I) << \")\\n\";\n OS << \"#endif \/\/ GET_CATEGORY_TABLE\\n\\n\";\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Diagnostic name index generation\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nstruct RecordIndexElement\n{\n RecordIndexElement() {}\n explicit RecordIndexElement(Record const &R):\n Name(R.getName()) {}\n \n std::string Name;\n};\n\nstruct RecordIndexElementSorter :\n public std::binary_function {\n \n bool operator()(RecordIndexElement const &Lhs,\n RecordIndexElement const &Rhs) const {\n return Lhs.Name < Rhs.Name;\n }\n \n};\n\n} \/\/ end anonymous namespace.\n\nvoid ClangDiagsIndexNameEmitter::run(raw_ostream &OS) {\n const std::vector &Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n \n std::vector Index;\n Index.reserve(Diags.size());\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n const Record &R = *(Diags[i]); \n Index.push_back(RecordIndexElement(R));\n }\n \n std::sort(Index.begin(), Index.end(), RecordIndexElementSorter());\n \n for (unsigned i = 0, e = Index.size(); i != e; ++i) {\n const RecordIndexElement &R = Index[i];\n \n OS << \"DIAG_NAME_INDEX(\" << R.Name << \")\\n\";\n }\n}\nRemove unused include of VectorExtras.h.\/\/=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ These tablegen backends emit Clang diagnostics tables.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ClangDiagnosticsEmitter.h\"\n#include \"llvm\/TableGen\/Record.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"llvm\/ADT\/StringMap.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Diagnostic category computation code.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nclass DiagGroupParentMap {\n RecordKeeper &Records;\n std::map > Mapping;\npublic:\n DiagGroupParentMap(RecordKeeper &records) : Records(records) {\n std::vector DiagGroups\n = Records.getAllDerivedDefinitions(\"DiagGroup\");\n for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {\n std::vector SubGroups =\n DiagGroups[i]->getValueAsListOfDefs(\"SubGroups\");\n for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)\n Mapping[SubGroups[j]].push_back(DiagGroups[i]);\n }\n }\n \n const std::vector &getParents(const Record *Group) {\n return Mapping[Group];\n }\n};\n} \/\/ end anonymous namespace.\n\n\nstatic std::string\ngetCategoryFromDiagGroup(const Record *Group,\n DiagGroupParentMap &DiagGroupParents) {\n \/\/ If the DiagGroup has a category, return it.\n std::string CatName = Group->getValueAsString(\"CategoryName\");\n if (!CatName.empty()) return CatName;\n \n \/\/ The diag group may the subgroup of one or more other diagnostic groups,\n \/\/ check these for a category as well.\n const std::vector &Parents = DiagGroupParents.getParents(Group);\n for (unsigned i = 0, e = Parents.size(); i != e; ++i) {\n CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);\n if (!CatName.empty()) return CatName;\n }\n return \"\";\n}\n\n\/\/\/ getDiagnosticCategory - Return the category that the specified diagnostic\n\/\/\/ lives in.\nstatic std::string getDiagnosticCategory(const Record *R,\n DiagGroupParentMap &DiagGroupParents) {\n \/\/ If the diagnostic is in a group, and that group has a category, use it.\n if (DefInit *Group = dynamic_cast(R->getValueInit(\"Group\"))) {\n \/\/ Check the diagnostic's diag group for a category.\n std::string CatName = getCategoryFromDiagGroup(Group->getDef(),\n DiagGroupParents);\n if (!CatName.empty()) return CatName;\n }\n \n \/\/ If the diagnostic itself has a category, get it.\n return R->getValueAsString(\"CategoryName\");\n}\n\nnamespace {\n class DiagCategoryIDMap {\n RecordKeeper &Records;\n StringMap CategoryIDs;\n std::vector CategoryStrings;\n public:\n DiagCategoryIDMap(RecordKeeper &records) : Records(records) {\n DiagGroupParentMap ParentInfo(Records);\n \n \/\/ The zero'th category is \"\".\n CategoryStrings.push_back(\"\");\n CategoryIDs[\"\"] = 0;\n \n std::vector Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);\n if (Category.empty()) continue; \/\/ Skip diags with no category.\n \n unsigned &ID = CategoryIDs[Category];\n if (ID != 0) continue; \/\/ Already seen.\n \n ID = CategoryStrings.size();\n CategoryStrings.push_back(Category);\n }\n }\n \n unsigned getID(StringRef CategoryString) {\n return CategoryIDs[CategoryString];\n }\n \n typedef std::vector::iterator iterator;\n iterator begin() { return CategoryStrings.begin(); }\n iterator end() { return CategoryStrings.end(); }\n };\n} \/\/ end anonymous namespace.\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Warning Tables (.inc file) generation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid ClangDiagsDefsEmitter::run(raw_ostream &OS) {\n \/\/ Write the #if guard\n if (!Component.empty()) {\n std::string ComponentName = StringRef(Component).upper();\n OS << \"#ifdef \" << ComponentName << \"START\\n\";\n OS << \"__\" << ComponentName << \"START = DIAG_START_\" << ComponentName\n << \",\\n\";\n OS << \"#undef \" << ComponentName << \"START\\n\";\n OS << \"#endif\\n\\n\";\n }\n\n const std::vector &Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n \n DiagCategoryIDMap CategoryIDs(Records);\n DiagGroupParentMap DGParentMap(Records);\n\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n const Record &R = *Diags[i];\n \/\/ Filter by component.\n if (!Component.empty() && Component != R.getValueAsString(\"Component\"))\n continue;\n\n OS << \"DIAG(\" << R.getName() << \", \";\n OS << R.getValueAsDef(\"Class\")->getName();\n OS << \", diag::\" << R.getValueAsDef(\"DefaultMapping\")->getName();\n \n \/\/ Description string.\n OS << \", \\\"\";\n OS.write_escaped(R.getValueAsString(\"Text\")) << '\"';\n \n \/\/ Warning associated with the diagnostic.\n if (DefInit *DI = dynamic_cast(R.getValueInit(\"Group\"))) {\n OS << \", \\\"\";\n OS.write_escaped(DI->getDef()->getValueAsString(\"GroupName\")) << '\"';\n } else {\n OS << \", \\\"\\\"\";\n }\n\n \/\/ SFINAE bit\n if (R.getValueAsBit(\"SFINAE\"))\n OS << \", true\";\n else\n OS << \", false\";\n\n \/\/ Access control bit\n if (R.getValueAsBit(\"AccessControl\"))\n OS << \", true\";\n else\n OS << \", false\";\n\n \/\/ FIXME: This condition is just to avoid temporary revlock, it can be\n \/\/ removed.\n if (R.getValue(\"WarningNoWerror\")) {\n \/\/ Default warning has no Werror bit.\n if (R.getValueAsBit(\"WarningNoWerror\"))\n OS << \", true\";\n else\n OS << \", false\";\n \n \/\/ Default warning show in system header bit.\n if (R.getValueAsBit(\"WarningShowInSystemHeader\"))\n OS << \", true\";\n else\n OS << \", false\";\n }\n \n \/\/ Category number.\n OS << \", \" << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));\n\n \/\/ Brief\n OS << \", \\\"\";\n OS.write_escaped(R.getValueAsString(\"Brief\")) << '\"';\n\n \/\/ Explanation \n OS << \", \\\"\";\n OS.write_escaped(R.getValueAsString(\"Explanation\")) << '\"';\n OS << \")\\n\";\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Warning Group Tables generation\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic std::string getDiagCategoryEnum(llvm::StringRef name) {\n if (name.empty())\n return \"DiagCat_None\";\n llvm::SmallString<256> enumName = llvm::StringRef(\"DiagCat_\");\n for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)\n enumName += isalnum(*I) ? *I : '_';\n return enumName.str();\n}\n\nnamespace {\nstruct GroupInfo {\n std::vector DiagsInGroup;\n std::vector SubGroups;\n unsigned IDNo;\n};\n} \/\/ end anonymous namespace.\n\nvoid ClangDiagGroupsEmitter::run(raw_ostream &OS) {\n \/\/ Compute a mapping from a DiagGroup to all of its parents.\n DiagGroupParentMap DGParentMap(Records);\n \n \/\/ Invert the 1-[0\/1] mapping of diags to group into a one to many mapping of\n \/\/ groups to diags in the group.\n std::map DiagsInGroup;\n \n std::vector Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n const Record *R = Diags[i];\n DefInit *DI = dynamic_cast(R->getValueInit(\"Group\"));\n if (DI == 0) continue;\n std::string GroupName = DI->getDef()->getValueAsString(\"GroupName\");\n DiagsInGroup[GroupName].DiagsInGroup.push_back(R);\n }\n \n \/\/ Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty\n \/\/ groups (these are warnings that GCC supports that clang never produces).\n std::vector DiagGroups\n = Records.getAllDerivedDefinitions(\"DiagGroup\");\n for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {\n Record *Group = DiagGroups[i];\n GroupInfo &GI = DiagsInGroup[Group->getValueAsString(\"GroupName\")];\n \n std::vector SubGroups = Group->getValueAsListOfDefs(\"SubGroups\");\n for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)\n GI.SubGroups.push_back(SubGroups[j]->getValueAsString(\"GroupName\"));\n }\n \n \/\/ Assign unique ID numbers to the groups.\n unsigned IDNo = 0;\n for (std::map::iterator\n I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)\n I->second.IDNo = IDNo;\n \n \/\/ Walk through the groups emitting an array for each diagnostic of the diags\n \/\/ that are mapped to.\n OS << \"\\n#ifdef GET_DIAG_ARRAYS\\n\";\n unsigned MaxLen = 0;\n for (std::map::iterator\n I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {\n MaxLen = std::max(MaxLen, (unsigned)I->first.size());\n \n std::vector &V = I->second.DiagsInGroup;\n if (!V.empty()) {\n OS << \"static const short DiagArray\" << I->second.IDNo << \"[] = { \";\n for (unsigned i = 0, e = V.size(); i != e; ++i)\n OS << \"diag::\" << V[i]->getName() << \", \";\n OS << \"-1 };\\n\";\n }\n \n const std::vector &SubGroups = I->second.SubGroups;\n if (!SubGroups.empty()) {\n OS << \"static const short DiagSubGroup\" << I->second.IDNo << \"[] = { \";\n for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {\n std::map::iterator RI =\n DiagsInGroup.find(SubGroups[i]);\n assert(RI != DiagsInGroup.end() && \"Referenced without existing?\");\n OS << RI->second.IDNo << \", \";\n }\n OS << \"-1 };\\n\";\n }\n }\n OS << \"#endif \/\/ GET_DIAG_ARRAYS\\n\\n\";\n \n \/\/ Emit the table now.\n OS << \"\\n#ifdef GET_DIAG_TABLE\\n\";\n for (std::map::iterator\n I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {\n \/\/ Group option string.\n OS << \" { \";\n OS << I->first.size() << \", \";\n OS << \"\\\"\";\n if (I->first.find_first_not_of(\"abcdefghijklmnopqrstuvwxyz\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"0123456789!@#$%^*-+=:?\")!=std::string::npos)\n throw \"Invalid character in diagnostic group '\" + I->first + \"'\";\n OS.write_escaped(I->first) << \"\\\",\"\n << std::string(MaxLen-I->first.size()+1, ' ');\n \n \/\/ Diagnostics in the group.\n if (I->second.DiagsInGroup.empty())\n OS << \"0, \";\n else\n OS << \"DiagArray\" << I->second.IDNo << \", \";\n \n \/\/ Subgroups.\n if (I->second.SubGroups.empty())\n OS << 0;\n else\n OS << \"DiagSubGroup\" << I->second.IDNo;\n OS << \" },\\n\";\n }\n OS << \"#endif \/\/ GET_DIAG_TABLE\\n\\n\";\n \n \/\/ Emit the category table next.\n DiagCategoryIDMap CategoriesByID(Records);\n OS << \"\\n#ifdef GET_CATEGORY_TABLE\\n\";\n for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(),\n E = CategoriesByID.end(); I != E; ++I)\n OS << \"CATEGORY(\\\"\" << *I << \"\\\", \" << getDiagCategoryEnum(*I) << \")\\n\";\n OS << \"#endif \/\/ GET_CATEGORY_TABLE\\n\\n\";\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Diagnostic name index generation\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nstruct RecordIndexElement\n{\n RecordIndexElement() {}\n explicit RecordIndexElement(Record const &R):\n Name(R.getName()) {}\n \n std::string Name;\n};\n\nstruct RecordIndexElementSorter :\n public std::binary_function {\n \n bool operator()(RecordIndexElement const &Lhs,\n RecordIndexElement const &Rhs) const {\n return Lhs.Name < Rhs.Name;\n }\n \n};\n\n} \/\/ end anonymous namespace.\n\nvoid ClangDiagsIndexNameEmitter::run(raw_ostream &OS) {\n const std::vector &Diags =\n Records.getAllDerivedDefinitions(\"Diagnostic\");\n \n std::vector Index;\n Index.reserve(Diags.size());\n for (unsigned i = 0, e = Diags.size(); i != e; ++i) {\n const Record &R = *(Diags[i]); \n Index.push_back(RecordIndexElement(R));\n }\n \n std::sort(Index.begin(), Index.end(), RecordIndexElementSorter());\n \n for (unsigned i = 0, e = Index.size(); i != e; ++i) {\n const RecordIndexElement &R = Index[i];\n \n OS << \"DIAG_NAME_INDEX(\" << R.Name << \")\\n\";\n }\n}\n<|endoftext|>"} {"text":"#include \"mugen\/storyboard.h\"\n\n#include \"util\/bitmap.h\"\n#include \"init.h\"\n#include \"resource.h\"\n#include \"util\/funcs.h\"\n#include \"globals.h\"\n#include \"factory\/font_render.h\"\n\n#include \"mugen_animation.h\"\n#include \"mugen\/background.h\"\n#include \"mugen_sound.h\"\n#include \"mugen_reader.h\"\n#include \"mugen_sprite.h\"\n#include \"mugen_util.h\"\n#include \"mugen_font.h\"\n\n#include \"util\/timedifference.h\"\n#include \"ast\/all.h\"\n#include \"parser\/all.h\"\n#include \"input\/input-map.h\"\n#include \"input\/input-manager.h\"\n\nnamespace PaintownUtil = ::Util;\n\nusing namespace std;\nusing namespace Mugen;\n\nstatic const int DEFAULT_WIDTH = 320;\nstatic const int DEFAULT_HEIGHT = 240;\nstatic const int DEFAULT_SCREEN_X_AXIS = 160;\nstatic const int DEFAULT_SCREEN_Y_AXIS = 0;\n\nLayer::Layer():\nstartTime(0),\nenabled(false),\nanimation(0){\n}\n\nLayer::~Layer(){\n}\n\nvoid Layer::act(int currentTime){\n if (startTime >= currentTime && !enabled){\n enabled = true;\n }\n if (enabled){\n animation->logic();\n }\n}\n\nvoid Layer::render(int x, int y, const Bitmap &bmp){\n if (enabled){\n animation->render(x + offset.x, y + offset.y, bmp);\n }\n}\n\nvoid Layer::reset(){\n enabled = false;\n animation->reset();\n}\n\t\nScene::Scene(Ast::Section * data, const std::string & file, Ast::AstParse & parsed, SpriteMap & sprites):\nclearColor(-2),\nticker(0),\nendTime(0),\nbackground(0),\nlayers(9){\n class SceneWalker: public Ast::Walker {\n\tpublic:\n\t SceneWalker(Scene & scene, const std::string & file, SpriteMap & sprites, Ast::AstParse & parse):\n\t scene(scene),\n\t file(file),\n\t sprites(sprites),\n\t parsed(parsed){\n\t }\n\t ~SceneWalker(){\n\t }\n\t \n\t Scene & scene;\n\t const std::string & file;\n\t SpriteMap & sprites;\n\t Ast::AstParse & parsed;\n\t \n\t virtual void onAttributeSimple(const Ast::AttributeSimple & simple){\n\t\tif (simple == \"fadein.time\"){\n\t\t int time;\n\t\t simple >> time;\n\t\t scene.fader.setFadeInTime(time);\n\t\t} else if (simple == \"fadein.col\"){\n\t\t int r=0,g=0,b=0;\n\t\t try{\n\t\t\tsimple >> r >> g >> b;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t scene.fader.setFadeInColor(Bitmap::makeColor(r,g,b));\n\t\t} else if (simple == \"fadeout.time\"){\n\t\t int time;\n\t\t simple >> time;\n\t\t scene.fader.setFadeOutTime(time);\n\t\t} else if (simple == \"fadeout.col\"){\n\t\t int r=0,g=0,b=0;\n\t\t try {\n\t\t\tsimple >> r >> g >> b;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t scene.fader.setFadeOutColor(Bitmap::makeColor(r,g,b));\n\t\t} else if (simple == \"bg.name\"){\n\t\t std::string name;\n\t\t simple >> name;\n\t\t scene.background = new Background(file,name);\n\t\t} else if (simple == \"clearcolor\"){\n\t\t int r=0,g=0,b=0;\n\t\t try {\n\t\t\tsimple >> r >> g >> b;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t scene.clearColor = (r == -1 ? r : Bitmap::makeColor(r,g,b));\n\t\t} else if (simple == \"end.time\"){\n\t\t simple >> scene.endTime;\n\t\t} else if (simple == \"layerall.pos\"){\n\t\t try{\n\t\t\tsimple >> scene.defaultPosition.x;\n\t\t\tsimple >> scene.defaultPosition.y;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t} else if (PaintownUtil::matchRegex(simple.idString(), \"layer[0-9]\\\\.anim\")){\n\t\t std::string action = PaintownUtil::captureRegex(simple.idString(), \"layer([0-9])\\\\.anim\", 0);\n\t\t int num = atoi(action.c_str());\n\t\t if (num >= 0 && num < 10){\n\t\t\tLayer *layer = scene.layers[num];\n\t\t\tAst::Section * section = parsed.findSection(\"begin action \" + action);\n\t\t\tlayer->setAnimation(Util::getAnimation(section,sprites));\n\t\t }\n\t\t} else if (PaintownUtil::matchRegex(simple.idString(), \"layer[0-9]\\\\.offset\")){\n\t\t int num = atoi(PaintownUtil::captureRegex(simple.idString(), \"layer([0-9])\\\\.offset\", 0).c_str());\n\t\t if (num >= 0 && num < 10){\n\t\t\tint x=0,y=0;\n\t\t\ttry{\n\t\t\t simple >> x >> y;\n\t\t\t} catch (Ast::Exception & e){\n\t\t\t}\n\t\t\tLayer *layer = scene.layers[num];\n\t\t\tlayer->setOffset(x,y);\n\t\t }\n\t\t} else if (PaintownUtil::matchRegex(simple.idString(), \"layer[0-9]\\\\.starttime\")){\n\t\t int num = atoi(PaintownUtil::captureRegex(simple.idString(), \"layer([0-9])\\\\.starttime\", 0).c_str());\n\t\t if (num >= 0 && num < 10){\n\t\t\tint time;\n\t\t\tsimple >> time;\n\t\t\tLayer *layer = scene.layers[num];\n\t\t\tlayer->setStartTime(time);\n\t\t }\n\t\t} else if (simple == \"bgm\"){\n\t\t \/\/ do nothing\n\t\t} else if (simple == \"bgm.loop\"){\n\t\t \/\/ do nothing\n\t\t} else {\n\t\t\tGlobal::debug(0) << \"Unhandled option in Scene Section: \" << simple.toString();\n\t\t}\n\t }\n };\n\n SceneWalker walker(*this,file,sprites,parsed);\n data->walk(walker);\n\n \/\/ set initial fade state\n fader.setState(FADEIN);\n}\n\nScene::~Scene(){\n\n if (background){\n delete background;\n }\n\n \/\/ layers\n for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n if ((*i))delete (*i);\n }\n}\n\nvoid Scene::act(){\n \/\/ backgrounds\n if (background){\n background->act();\n }\n \/\/ layers\n for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n Layer *layer = *i;\n layer->act(ticker);\n }\n \/\/ Fader\n fader.act();\n if (ticker == endTime - fader.getFadeOutTime()){\n fader.setState(FADEOUT);\n }\n \/\/ tick tick\n ticker++;\n}\nvoid Scene::render(const Bitmap & bmp){\n if (clearColor != -1 && clearColor != -2){\n bmp.fill(clearColor);\n }\n \/\/ backgrounds\n if (background){\n background->renderBackground(0,0, bmp);\n }\n \/\/ layers\n for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n Layer *layer = *i;\n layer->render(defaultPosition.x,defaultPosition.y,bmp);\n }\n \/\/ foregrounds\n if (background){\n background->renderForeground(0,0, bmp);\n }\n \/\/ fader\n fader.draw(bmp);\n}\n\nbool Scene::isDone(){\n return (ticker >= endTime);\n}\n\nvoid Scene::reset(){\n ticker = 0;\n fader.setState(FADEIN);\n \/\/ layers\n for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n\tLayer *layer = *i;\n\tlayer->reset();\n }\n}\n\nStoryboard::Storyboard( const string & s )throw (MugenException):\nstoryBoardFile(s),\nstartscene(0){\n \/\/ Lets look for our def since some people think that all file systems are case insensitive\n std::string baseDir = Util::getFileDir(storyBoardFile);\n const std::string ourDefFile = Util::fixFileName( baseDir, Util::stripDir(storyBoardFile) );\n \/\/ get real basedir\n \/\/baseDir = Util::getFileDir( ourDefFile );\n Global::debug(1) << baseDir << endl;\n\n if (ourDefFile.empty()){\n throw MugenException(\"Cannot locate storyboard definition file for: \" + storyBoardFile);\n }\n\n std::string filesdir = \"\";\n\n Global::debug(1) << \"Got subdir: \" << filesdir << endl;\n\n TimeDifference diff;\n diff.startTime();\n Ast::AstParse parsed((list*) Def::main(ourDefFile));\n diff.endTime();\n Global::debug(1) << \"Parsed mugen file \" + ourDefFile + \" in\" + diff.printTime(\"\") << endl;\n\n \/* set by bg.name = \"foo\" *\/\n string bgname;\n\n for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){\n Ast::Section * section = *section_it;\n\tstd::string head = section->getName();\n\t\n\thead = Util::fixCase(head);\n\t\n if (head == \"info\"){\n class InfoWalk: public Ast::Walker{\n public:\n virtual void onAttributeSimple(const Ast::AttributeSimple & simple){\n if (simple == \"name\"){\n string name;\n simple >> name;\n Global::debug(1) << \"Read name '\" << name << \"'\" << endl;\n } else if (simple == \"author\"){\n string name;\n simple >> name;\n Global::debug(1) << \"Made by: '\" << name << \"'\" << endl;\n } else {\n Global::debug(0) << \"Warning: ignored attribute: \" << simple.toString() << endl;\n }\n }\n };\n\n InfoWalk walk;\n section->walk(walk);\n\n } else if (head == \"scenedef\"){\n class SceneWalk: public Ast::Walker{\n public:\n SceneWalk(const string & baseDir, Storyboard & board):\n baseDir(baseDir),\n board(board){\n }\n\n const string & baseDir;\n Storyboard & board;\n\n virtual void onAttributeSimple(const Ast::AttributeSimple & simple){\n if (simple == \"spr\"){\n\t\t\tstd::string temp;\n simple >> temp;\n Util::readSprites(Util::getCorrectFileLocation(this->baseDir, temp), \"\", board.sprites);\n } else if (simple == \"startscene\"){\n simple >> board.startscene;\n Global::debug(1) << \"Starting storyboard at: '\" << board.startscene << \"'\" << endl;\n } else {\n Global::debug(0) << \"Warning: ignored attribute: \" << simple.toString() << endl;\n }\n }\n };\n\n SceneWalk walk(baseDir, *this);\n section->walk(walk);\n } else if (PaintownUtil::matchRegex(head, \"^scene\")){\n\t Scene *scene = new Scene(section,ourDefFile,parsed,sprites);\n\t scenes.push_back(scene);\n\t}\n }\n}\n\nStoryboard::~Storyboard(){\n \/\/ Get rid of animation lists;\n for( std::map< int, MugenAnimation * >::iterator i = animations.begin() ; i != animations.end() ; ++i ){\n if( i->second )delete i->second;\n }\n\n \/\/ Get rid of scene lists;\n for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){\n if( (*i) )delete (*i);\n }\n \/\/ sprites\n for( SpriteMap::iterator i = sprites.begin() ; i != sprites.end() ; ++i ){\n for( std::map< unsigned int, MugenSprite * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){\n if( j->second )delete j->second;\n }\n }\n}\n\nvoid Storyboard::run(const Bitmap &bmp, bool repeat){\n double gameSpeed = 1.0;\n double runCounter = 0;\n bool quit = false;\n\n Bitmap work( 320, 240 );\n\n for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){\n if( (*i) ){\n (*i)->reset();\n }\n }\n\n std::vector< Scene * >::iterator sceneIterator = scenes.begin() + startscene;\n\n while( !quit ){\n bool draw = false;\n\n Scene *scene = *sceneIterator;\n if ( Global::speed_counter > 0 ){\n\n runCounter += Global::speed_counter * gameSpeed * Global::LOGIC_MULTIPLIER;\/\/(double) 90 \/ (double) 60;\n while (runCounter > 1){\n runCounter -= 1;\n draw = true;\n \/\/ Key handler\n\t\tInputManager::poll();\n\n InputMap::Output out = InputManager::getMap(input);\n\n if (out[Up]){\n\t }\n\t if (out[Down]){\n\t }\n\t if (out[Left]){\n\t }\n\t if (out[Right]){\n\t }\n\t if (out[A]){\n quit = true;\n return;\n\t }\n\t if (out[B]){\n quit = true;\n return;\n\t }\n\t if (out[C]){\n quit = true;\n return;\n\t }\n\t if (out[X]){\n quit = true;\n return;\n\t }\n\t if (out[Y]){\n quit = true;\n return;\n\t }\n\t if (out[Z]){\n quit = true;\n return;\n\t }\n\t if (out[Start]){\n quit = true;\n return;\n\t }\n scene->act();\n \n if (scene->isDone()){\n sceneIterator++;\n if (sceneIterator == scenes.end()){\n if (repeat){\n sceneIterator = scenes.begin();\n } else {\n return;\n }\n }\n scene = *sceneIterator;\n scene->reset();\n }\n }\n Global::speed_counter = 0;\n }\n\n if (draw){\n scene->render(work);\n work.Stretch(bmp);\n if (Global::getDebug() > 0){\n Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor(0,255,128), bmp, \"Scene: Time(%i) : EndTime(%i) : Fade in(%i) : Fade out(%i)\",0, scene->getTicker(),scene->getEndTime(),scene->getFadeTool().getFadeInTime(),scene->getFadeTool().getFadeOutTime() );\n }\n bmp.BlitToScreen();\n }\n\n while (Global::speed_counter == 0){\n PaintownUtil::rest(1);\n }\n }\n}\n\nFixed unitialized layers.#include \"mugen\/storyboard.h\"\n\n#include \"util\/bitmap.h\"\n#include \"init.h\"\n#include \"resource.h\"\n#include \"util\/funcs.h\"\n#include \"globals.h\"\n#include \"factory\/font_render.h\"\n\n#include \"mugen_animation.h\"\n#include \"mugen\/background.h\"\n#include \"mugen_sound.h\"\n#include \"mugen_reader.h\"\n#include \"mugen_sprite.h\"\n#include \"mugen_util.h\"\n#include \"mugen_font.h\"\n\n#include \"util\/timedifference.h\"\n#include \"ast\/all.h\"\n#include \"parser\/all.h\"\n#include \"input\/input-map.h\"\n#include \"input\/input-manager.h\"\n\nnamespace PaintownUtil = ::Util;\n\nusing namespace std;\nusing namespace Mugen;\n\nstatic const int DEFAULT_WIDTH = 320;\nstatic const int DEFAULT_HEIGHT = 240;\nstatic const int DEFAULT_SCREEN_X_AXIS = 160;\nstatic const int DEFAULT_SCREEN_Y_AXIS = 0;\n\nLayer::Layer():\nstartTime(0),\nenabled(false),\nanimation(0){\n}\n\nLayer::~Layer(){\n}\n\nvoid Layer::act(int currentTime){\n if (startTime >= currentTime && !enabled){\n enabled = true;\n }\n if (enabled && animation){\n animation->logic();\n }\n}\n\nvoid Layer::render(int x, int y, const Bitmap &bmp){\n if (enabled && animation){\n animation->render(x + offset.x, y + offset.y, bmp);\n }\n}\n\nvoid Layer::reset(){\n enabled = false;\n if (animation){\n\tanimation->reset();\n }\n}\n\t\nScene::Scene(Ast::Section * data, const std::string & file, Ast::AstParse & parsed, SpriteMap & sprites):\nclearColor(-2),\nticker(0),\nendTime(0),\nbackground(0){\n for (int i = 0; i < 10; ++i){\n\tLayer *layer = new Layer();\n\tlayers.push_back(layer);\n }\n class SceneWalker: public Ast::Walker {\n\tpublic:\n\t SceneWalker(Scene & scene, const std::string & file, SpriteMap & sprites, Ast::AstParse & parse):\n\t scene(scene),\n\t file(file),\n\t sprites(sprites),\n\t parsed(parse){\n\t }\n\t ~SceneWalker(){\n\t }\n\t \n\t Scene & scene;\n\t const std::string & file;\n\t SpriteMap & sprites;\n\t Ast::AstParse & parsed;\n\t \n\t virtual void onAttributeSimple(const Ast::AttributeSimple & simple){\n\t\tif (simple == \"fadein.time\"){\n\t\t int time;\n\t\t simple >> time;\n\t\t scene.fader.setFadeInTime(time);\n\t\t} else if (simple == \"fadein.col\"){\n\t\t int r=0,g=0,b=0;\n\t\t try{\n\t\t\tsimple >> r >> g >> b;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t scene.fader.setFadeInColor(Bitmap::makeColor(r,g,b));\n\t\t} else if (simple == \"fadeout.time\"){\n\t\t int time;\n\t\t simple >> time;\n\t\t scene.fader.setFadeOutTime(time);\n\t\t} else if (simple == \"fadeout.col\"){\n\t\t int r=0,g=0,b=0;\n\t\t try {\n\t\t\tsimple >> r >> g >> b;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t scene.fader.setFadeOutColor(Bitmap::makeColor(r,g,b));\n\t\t} else if (simple == \"bg.name\"){\n\t\t std::string name;\n\t\t simple >> name;\n\t\t scene.background = new Background(file,name);\n\t\t} else if (simple == \"clearcolor\"){\n\t\t int r=0,g=0,b=0;\n\t\t try {\n\t\t\tsimple >> r >> g >> b;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t scene.clearColor = (r == -1 ? r : Bitmap::makeColor(r,g,b));\n\t\t} else if (simple == \"end.time\"){\n\t\t simple >> scene.endTime;\n\t\t} else if (simple == \"layerall.pos\"){\n\t\t try{\n\t\t\tsimple >> scene.defaultPosition.x;\n\t\t\tsimple >> scene.defaultPosition.y;\n\t\t } catch (const Ast::Exception & e){\n\t\t }\n\t\t} else if (PaintownUtil::matchRegex(simple.idString(), \"layer[0-9]\\\\.anim\")){\n\t\t int num = atoi(PaintownUtil::captureRegex(simple.idString(), \"layer([0-9])\\\\.anim\", 0).c_str());\n\t\t if (num >= 0 && num < 10){\n\t\t\tstd::string action;\n\t\t\tsimple >> action;\n\t\t\tLayer *layer = scene.layers[num];\n\t\t\tAst::Section * section = parsed.findSection(\"begin action \" + action);\n\t\t\tlayer->setAnimation(Util::getAnimation(section,sprites));\n\t\t }\n\t\t} else if (PaintownUtil::matchRegex(simple.idString(), \"layer[0-9]\\\\.offset\")){\n\t\t int num = atoi(PaintownUtil::captureRegex(simple.idString(), \"layer([0-9])\\\\.offset\", 0).c_str());\n\t\t if (num >= 0 && num < 10){\n\t\t\tint x=0,y=0;\n\t\t\ttry{\n\t\t\t simple >> x >> y;\n\t\t\t} catch (Ast::Exception & e){\n\t\t\t}\n\t\t\tLayer *layer = scene.layers[num];\n\t\t\tlayer->setOffset(x, y);\n\t\t }\n\t\t} else if (PaintownUtil::matchRegex(simple.idString(), \"layer[0-9]\\\\.starttime\")){\n\t\t int num = atoi(PaintownUtil::captureRegex(simple.idString(), \"layer([0-9])\\\\.starttime\", 0).c_str());\n\t\t if (num >= 0 && num < 10){\n\t\t\tint time;\n\t\t\tsimple >> time;\n\t\t\tLayer *layer = scene.layers[num];\n\t\t\tlayer->setStartTime(time);\n\t\t }\n\t\t} else if (simple == \"bgm\"){\n\t\t \/\/ do nothing\n\t\t} else if (simple == \"bgm.loop\"){\n\t\t \/\/ do nothing\n\t\t} else {\n\t\t\tGlobal::debug(0) << \"Unhandled option in Scene Section: \" << simple.toString();\n\t\t}\n\t }\n };\n\n SceneWalker walker(*this, file, sprites, parsed);\n data->walk(walker);\n\n \/\/ set initial fade state\n fader.setState(FADEIN);\n}\n\nScene::~Scene(){\n\n if (background){\n delete background;\n }\n\n \/\/ layers\n for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n if ((*i))delete (*i);\n }\n}\n\nvoid Scene::act(){\n \/\/ backgrounds\n if (background){\n background->act();\n }\n \/\/ layers\n for ( std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n Layer *layer = *i;\n layer->act(ticker);\n }\n \/\/ Fader\n fader.act();\n if (ticker == endTime - fader.getFadeOutTime()){\n fader.setState(FADEOUT);\n }\n \/\/ tick tick\n ticker++;\n}\nvoid Scene::render(const Bitmap & bmp){\n if (clearColor != -1 && clearColor != -2){\n bmp.fill(clearColor);\n }\n \/\/ backgrounds\n if (background){\n background->renderBackground(0,0, bmp);\n }\n \/\/ layers\n for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n Layer *layer = *i;\n layer->render(defaultPosition.x,defaultPosition.y,bmp);\n }\n \/\/ foregrounds\n if (background){\n background->renderForeground(0,0, bmp);\n }\n \/\/ fader\n fader.draw(bmp);\n}\n\nbool Scene::isDone(){\n return (ticker >= endTime);\n}\n\nvoid Scene::reset(){\n ticker = 0;\n fader.setState(FADEIN);\n \/\/ layers\n for (std::vector< Layer *>::iterator i = layers.begin(); i != layers.end(); ++i ){\n\tLayer *layer = *i;\n\tlayer->reset();\n }\n}\n\nStoryboard::Storyboard( const string & s )throw (MugenException):\nstoryBoardFile(s),\nstartscene(0){\n \/\/ Lets look for our def since some people think that all file systems are case insensitive\n std::string baseDir = Util::getFileDir(storyBoardFile);\n const std::string ourDefFile = Util::fixFileName( baseDir, Util::stripDir(storyBoardFile) );\n \/\/ get real basedir\n \/\/baseDir = Util::getFileDir( ourDefFile );\n Global::debug(1) << baseDir << endl;\n\n if (ourDefFile.empty()){\n throw MugenException(\"Cannot locate storyboard definition file for: \" + storyBoardFile);\n }\n\n std::string filesdir = \"\";\n\n Global::debug(1) << \"Got subdir: \" << filesdir << endl;\n\n TimeDifference diff;\n diff.startTime();\n Ast::AstParse parsed((list*) Def::main(ourDefFile));\n diff.endTime();\n Global::debug(1) << \"Parsed mugen file \" + ourDefFile + \" in\" + diff.printTime(\"\") << endl;\n\n \/* set by bg.name = \"foo\" *\/\n string bgname;\n\n for (Ast::AstParse::section_iterator section_it = parsed.getSections()->begin(); section_it != parsed.getSections()->end(); section_it++){\n Ast::Section * section = *section_it;\n\tstd::string head = section->getName();\n\t\n\thead = Util::fixCase(head);\n\t\n if (head == \"info\"){\n class InfoWalk: public Ast::Walker{\n public:\n virtual void onAttributeSimple(const Ast::AttributeSimple & simple){\n if (simple == \"name\"){\n string name;\n simple >> name;\n Global::debug(1) << \"Read name '\" << name << \"'\" << endl;\n } else if (simple == \"author\"){\n string name;\n simple >> name;\n Global::debug(1) << \"Made by: '\" << name << \"'\" << endl;\n } else {\n Global::debug(0) << \"Warning: ignored attribute: \" << simple.toString() << endl;\n }\n }\n };\n\n InfoWalk walk;\n section->walk(walk);\n\n } else if (head == \"scenedef\"){\n class SceneWalk: public Ast::Walker{\n public:\n SceneWalk(const string & baseDir, Storyboard & board):\n baseDir(baseDir),\n board(board){\n }\n\n const string & baseDir;\n Storyboard & board;\n\n virtual void onAttributeSimple(const Ast::AttributeSimple & simple){\n if (simple == \"spr\"){\n\t\t\tstd::string temp;\n simple >> temp;\n Util::readSprites(Util::getCorrectFileLocation(this->baseDir, temp), \"\", board.sprites);\n } else if (simple == \"startscene\"){\n simple >> board.startscene;\n Global::debug(1) << \"Starting storyboard at: '\" << board.startscene << \"'\" << endl;\n } else {\n Global::debug(0) << \"Warning: ignored attribute: \" << simple.toString() << endl;\n }\n }\n };\n\n SceneWalk walk(baseDir, *this);\n section->walk(walk);\n } else if (PaintownUtil::matchRegex(head, \"^scene\")){\n\t Scene *scene = new Scene(section,ourDefFile,parsed,sprites);\n\t scenes.push_back(scene);\n\t}\n }\n}\n\nStoryboard::~Storyboard(){\n \/\/ Get rid of animation lists;\n for( std::map< int, MugenAnimation * >::iterator i = animations.begin() ; i != animations.end() ; ++i ){\n if( i->second )delete i->second;\n }\n\n \/\/ Get rid of scene lists;\n for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){\n if( (*i) )delete (*i);\n }\n \/\/ sprites\n for( SpriteMap::iterator i = sprites.begin() ; i != sprites.end() ; ++i ){\n for( std::map< unsigned int, MugenSprite * >::iterator j = i->second.begin() ; j != i->second.end() ; ++j ){\n if( j->second )delete j->second;\n }\n }\n}\n\nvoid Storyboard::run(const Bitmap &bmp, bool repeat){\n double gameSpeed = 1.0;\n double runCounter = 0;\n bool quit = false;\n\n Bitmap work( 320, 240 );\n\n for( std::vector< Scene * >::iterator i = scenes.begin() ; i != scenes.end() ; ++i ){\n if( (*i) ){\n (*i)->reset();\n }\n }\n\n std::vector< Scene * >::iterator sceneIterator = scenes.begin() + startscene;\n\n while( !quit ){\n bool draw = false;\n\n Scene *scene = *sceneIterator;\n if ( Global::speed_counter > 0 ){\n\n runCounter += Global::speed_counter * gameSpeed * Global::LOGIC_MULTIPLIER;\/\/(double) 90 \/ (double) 60;\n while (runCounter > 1){\n runCounter -= 1;\n draw = true;\n \/\/ Key handler\n\t\tInputManager::poll();\n\n InputMap::Output out = InputManager::getMap(input);\n\n if (out[Up]){\n\t }\n\t if (out[Down]){\n\t }\n\t if (out[Left]){\n\t }\n\t if (out[Right]){\n\t }\n\t if (out[A]){\n quit = true;\n return;\n\t }\n\t if (out[B]){\n quit = true;\n return;\n\t }\n\t if (out[C]){\n quit = true;\n return;\n\t }\n\t if (out[X]){\n quit = true;\n return;\n\t }\n\t if (out[Y]){\n quit = true;\n return;\n\t }\n\t if (out[Z]){\n quit = true;\n return;\n\t }\n\t if (out[Start]){\n quit = true;\n return;\n\t }\n scene->act();\n \n if (scene->isDone()){\n sceneIterator++;\n if (sceneIterator == scenes.end()){\n if (repeat){\n sceneIterator = scenes.begin();\n } else {\n return;\n }\n }\n scene = *sceneIterator;\n scene->reset();\n }\n }\n Global::speed_counter = 0;\n }\n\n if (draw){\n scene->render(work);\n work.Stretch(bmp);\n if (Global::getDebug() > 0){\n Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor(0,255,128), bmp, \"Scene: Time(%i) : EndTime(%i) : Fade in(%i) : Fade out(%i)\",0, scene->getTicker(),scene->getEndTime(),scene->getFadeTool().getFadeInTime(),scene->getFadeTool().getFadeOutTime() );\n }\n bmp.BlitToScreen();\n }\n\n while (Global::speed_counter == 0){\n PaintownUtil::rest(1);\n }\n }\n}\n\n<|endoftext|>"} {"text":"Include the header to get QDesktopWidget defined<|endoftext|>"} {"text":"#ifndef __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_\n#define __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_\n\n#ifndef _SVARRAY_HXX\n#include \n#endif\n#ifndef _SV_BITMAP_HXX\n#include \n#endif\n#ifndef _STRING_HXX\n#include \n#endif\n#ifndef _STREAM_HXX\n#include \n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include \n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include \n#endif\n\n\nnamespace framework\n{\n\nstruct ToolBoxItemDescriptor\n{\n Bitmap* pBmp; \/\/ Bitmap ptr not used by xml configuration\n String aBitmapName; \/\/ bitmap name => use to find correct bmp file\n String aItemText; \/\/ label for this toolbox item\n String aURL; \/\/ URL command to dispatch\n USHORT nId; \/\/ internal id not used by xml configuration\n USHORT nItemBits; \/\/ properties for this toolbox item (WinBits)\n USHORT nItemType; \/\/ toolbox item type (BUTTON, SPACE, BREAK, SEPARATOR)\n USHORT nVisible; \/\/ toolbox item visible?\n USHORT nWidth; \/\/ width of a toolbox window (edit field, etc.)\n USHORT nUserDef; \/\/ user defined toolbox item (1=yes\/0=no)\n String aHelpId; \/\/ A help id associated with this toolbox item\n\n public:\n\n ToolBoxItemDescriptor() : pBmp( 0 )\n ,nId( 0 )\n ,nItemBits( 0 )\n ,nItemType( (USHORT)TOOLBOXITEM_SPACE )\n ,nVisible( sal_True )\n ,nWidth( 0 )\n ,nUserDef( sal_False ) {}\n};\n\ntypedef ToolBoxItemDescriptor* ToolBoxItemDescriptorPtr;\nSV_DECL_PTRARR_DEL( ToolBoxDescriptor, ToolBoxItemDescriptorPtr, 10, 2)\n\nstruct ToolBoxLayoutItemDescriptor\n{\n String aName; \/\/ Unique name of the toolbox ( Objectbar, Toolbar etc. )\n String aUserName; \/\/ Userspecified name for this toolbar\n Point aFloatingPos; \/\/ Position in floating mode\n USHORT nFloatingLines; \/\/ Number of lines in floating mode\n USHORT nLines; \/\/ Number of lines in docking mode\n ToolBoxAlign eAlign; \/\/ Aligned position in docking mode\n BOOL bVisible; \/\/ Visible or not\n BOOL bFloating; \/\/ Floating mode on\/off\n ButtonType eType; \/\/ text, symbol or text+symbol\n\n ToolBoxLayoutItemDescriptor() : nFloatingLines( 0 )\n ,nLines( 1 )\n ,eAlign( BOXALIGN_LEFT )\n ,bVisible( sal_False )\n ,bFloating( sal_False )\n ,eType( BUTTON_SYMBOL ) {}\n};\n\ntypedef ToolBoxLayoutItemDescriptor* ToolBoxLayoutItemDescriptorPtr;\nSV_DECL_PTRARR_DEL( ToolBoxLayoutDescriptor, ToolBoxLayoutItemDescriptorPtr, 10, 2)\n\nclass ToolBoxConfiguration\n{\n public:\n static sal_Bool LoadToolBox( SvStream& rInStream, ToolBoxDescriptor& aItems );\n static sal_Bool StoreToolBox( SvStream& rOutStream, const ToolBoxDescriptor& aItems );\n static sal_Bool LoadToolBoxLayout( SvStream& rInStream, ToolBoxLayoutDescriptor& aItems );\n static sal_Bool StoreToolBoxLayout( SvStream& rOutStream, ToolBoxLayoutDescriptor& aItems );\n};\n\n} \/\/ namespace framework\n\n#endif \/\/ __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_\nINTEGRATION: CWS vclcleanup02 (1.6.170); FILE MERGED 2003\/12\/04 17:08:40 mt 1.6.170.1: #i23061# Removed\/Changed old StarView stuff#ifndef __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_\n#define __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_\n\n#ifndef _SVARRAY_HXX\n#include \n#endif\n#ifndef _SV_BITMAP_HXX\n#include \n#endif\n#ifndef _STRING_HXX\n#include \n#endif\n#ifndef _STREAM_HXX\n#include \n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include \n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include \n#endif\n\n\nnamespace framework\n{\n\nstruct ToolBoxItemDescriptor\n{\n Bitmap* pBmp; \/\/ Bitmap ptr not used by xml configuration\n String aBitmapName; \/\/ bitmap name => use to find correct bmp file\n String aItemText; \/\/ label for this toolbox item\n String aURL; \/\/ URL command to dispatch\n USHORT nId; \/\/ internal id not used by xml configuration\n USHORT nItemBits; \/\/ properties for this toolbox item (WinBits)\n USHORT nItemType; \/\/ toolbox item type (BUTTON, SPACE, BREAK, SEPARATOR)\n USHORT nVisible; \/\/ toolbox item visible?\n USHORT nWidth; \/\/ width of a toolbox window (edit field, etc.)\n USHORT nUserDef; \/\/ user defined toolbox item (1=yes\/0=no)\n String aHelpId; \/\/ A help id associated with this toolbox item\n\n public:\n\n ToolBoxItemDescriptor() : pBmp( 0 )\n ,nId( 0 )\n ,nItemBits( 0 )\n ,nItemType( (USHORT)TOOLBOXITEM_SPACE )\n ,nVisible( sal_True )\n ,nWidth( 0 )\n ,nUserDef( sal_False ) {}\n};\n\ntypedef ToolBoxItemDescriptor* ToolBoxItemDescriptorPtr;\nSV_DECL_PTRARR_DEL( ToolBoxDescriptor, ToolBoxItemDescriptorPtr, 10, 2)\n\nstruct ToolBoxLayoutItemDescriptor\n{\n String aName; \/\/ Unique name of the toolbox ( Objectbar, Toolbar etc. )\n String aUserName; \/\/ Userspecified name for this toolbar\n Point aFloatingPos; \/\/ Position in floating mode\n USHORT nFloatingLines; \/\/ Number of lines in floating mode\n USHORT nLines; \/\/ Number of lines in docking mode\n WindowAlign eAlign; \/\/ Aligned position in docking mode\n BOOL bVisible; \/\/ Visible or not\n BOOL bFloating; \/\/ Floating mode on\/off\n ButtonType eType; \/\/ text, symbol or text+symbol\n\n ToolBoxLayoutItemDescriptor() : nFloatingLines( 0 )\n ,nLines( 1 )\n ,eAlign( WINDOWALIGN_LEFT )\n ,bVisible( sal_False )\n ,bFloating( sal_False )\n ,eType( BUTTON_SYMBOL ) {}\n};\n\ntypedef ToolBoxLayoutItemDescriptor* ToolBoxLayoutItemDescriptorPtr;\nSV_DECL_PTRARR_DEL( ToolBoxLayoutDescriptor, ToolBoxLayoutItemDescriptorPtr, 10, 2)\n\nclass ToolBoxConfiguration\n{\n public:\n static sal_Bool LoadToolBox( SvStream& rInStream, ToolBoxDescriptor& aItems );\n static sal_Bool StoreToolBox( SvStream& rOutStream, const ToolBoxDescriptor& aItems );\n static sal_Bool LoadToolBoxLayout( SvStream& rInStream, ToolBoxLayoutDescriptor& aItems );\n static sal_Bool StoreToolBoxLayout( SvStream& rOutStream, ToolBoxLayoutDescriptor& aItems );\n};\n\n} \/\/ namespace framework\n\n#endif \/\/ __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: framelistanalyzer.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-25 18:21:30 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"classes\/framelistanalyzer.hxx\"\n\n\/\/_______________________________________________\n\/\/ my own includes\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_TARGETS_H_\n#include \n#endif\n\n#ifndef __FRAMEWORK_PROPERTIES_H_\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ interface includes\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ includes of other projects\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ namespace\n\nnamespace framework{\n\n\/\/_______________________________________________\n\/\/ non exported const\n\n\/\/_______________________________________________\n\/\/ non exported definitions\n\n\/\/_______________________________________________\n\/\/ declarations\n\n\/\/_______________________________________________\n\n\/**\n *\/\n\nFrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier ,\n const css::uno::Reference< css::frame::XFrame >& xReferenceFrame ,\n sal_uInt32 eDetectMode )\n : m_xSupplier (xSupplier )\n , m_xReferenceFrame(xReferenceFrame)\n , m_eDetectMode (eDetectMode )\n{\n impl_analyze();\n}\n\n\/\/_______________________________________________\n\n\/**\n *\/\n\nFrameListAnalyzer::~FrameListAnalyzer()\n{\n}\n\n\/\/_______________________________________________\n\n\/** returns an analyzed list of all currently opened (top!) frames inside the desktop tree.\n\n We try to get a snapshot of all opened frames, which are part of the desktop frame container.\n Of course we can't access frames, which stands outside of this tree.\n But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last\n frame wrong. Further we analyze this list and split into different parts.\n E.g. for \"CloseDoc\" we must know, which frames of the given list referr to the same model.\n These frames must be closed then. But all other frames must be untouched.\n In case the request was \"CloseWin\" these splitted lists can be used too, to decide if the last window\n or document was closed. Then we have to initialize the backing window ...\n Last but not least we must know something about our special help frame. It must be handled\n seperatly. And last but not least - the backing component frame must be detected too.\n*\/\n\nvoid FrameListAnalyzer::impl_analyze()\n{\n \/\/ reset all members to get a consistent state\n m_bReferenceIsHidden = sal_False;\n m_bReferenceIsHelp = sal_False;\n m_bReferenceIsBacking = sal_False;\n m_xHelp = css::uno::Reference< css::frame::XFrame >();\n m_xBackingComponent = css::uno::Reference< css::frame::XFrame >();\n\n \/\/ try to get the task container by using the given supplier\n css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY);\n\n \/\/ All return list get an initial size to include all possible frames.\n \/\/ They will be packed at the end of this method ... using the actual step positions then.\n sal_Int32 nVisibleStep = 0;\n sal_Int32 nHiddenStep = 0;\n sal_Int32 nModelStep = 0;\n sal_Int32 nCount = xFrameContainer->getCount();\n\n m_lOtherVisibleFrames.realloc(nCount);\n m_lOtherHiddenFrames.realloc(nCount);\n m_lModelFrames.realloc(nCount);\n\n \/\/ ask for the model of the given reference frame.\n \/\/ It must be compared with the model of every frame of the container\n \/\/ to sort it into the list of frames with the same model.\n \/\/ Supress this step, if right detect mode isn't set.\n css::uno::Reference< css::frame::XModel > xReferenceModel;\n if ((m_eDetectMode & E_MODEL) == E_MODEL )\n {\n css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController();\n if (xReferenceController.is())\n xReferenceModel = xReferenceController->getModel();\n }\n\n \/\/ check, if the reference frame is in hidden mode.\n \/\/ But look, if this analyze step is realy needed.\n css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY);\n if (\n ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) &&\n (xSet.is() )\n )\n {\n css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);\n aValue >>= m_bReferenceIsHidden;\n }\n\n \/\/ check, if the reference frame includes the backing component.\n \/\/ But look, if this analyze step is realy needed.\n if (\n ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) &&\n (xSet.is() )\n )\n {\n css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE);\n aValue >>= m_bReferenceIsBacking;\n }\n\n \/\/ check, if the reference frame includes the help module.\n \/\/ But look, if this analyze step is realy needed.\n if (\n ((m_eDetectMode & E_HELP) == E_HELP ) &&\n (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK)\n )\n {\n m_bReferenceIsHelp = sal_True;\n }\n\n try\n {\n \/\/ Step over all frames of the desktop frame container and analyze it.\n for (sal_Int32 i=0; i xFrame;\n if (\n !(xFrameContainer->getByIndex(i) >>= xFrame) ||\n !(xFrame.is() ) ||\n (xFrame==m_xReferenceFrame )\n )\n continue;\n\n #ifdef ENABLE_WARNINGS\n if (\n ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) &&\n (\n (!xFrame->getContainerWindow().is()) ||\n (!xFrame->getComponentWindow().is())\n )\n )\n {\n LOG_WARNING(\"FrameListAnalyzer::impl_analyze()\", \"ZOMBIE!\")\n }\n #endif\n\n \/\/ -------------------------------------------------\n \/\/ a) Is it the special help task?\n \/\/ Return it seperated from any return list.\n if (\n ((m_eDetectMode & E_HELP) == E_HELP ) &&\n (xFrame->getName()==SPECIALTARGET_HELPTASK)\n )\n {\n m_xHelp = xFrame;\n continue;\n }\n\n \/\/ -------------------------------------------------\n \/\/ b) Or is includes this task the special backing component?\n \/\/ Return it seperated from any return list.\n \/\/ But check if the reference task itself is the backing frame.\n \/\/ Our user mst know it to decide right.\n if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)\n {\n xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);\n sal_Bool bIsBacking;\n\n if (\n (xSet.is() ) &&\n (xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE)>>=bIsBacking) &&\n (bIsBacking )\n )\n {\n m_xBackingComponent = xFrame;\n continue;\n }\n }\n\n \/\/ -------------------------------------------------\n \/\/ c) Or is it the a task, which uses the specified model?\n \/\/ Add it to the list of \"model frames\".\n if ((m_eDetectMode & E_MODEL) == E_MODEL)\n {\n css::uno::Reference< css::frame::XController > xController = xFrame->getController();\n css::uno::Reference< css::frame::XModel > xModel ;\n if (xController.is())\n xModel = xController->getModel();\n if (xModel==xReferenceModel)\n {\n m_lModelFrames[nModelStep] = xFrame;\n ++nModelStep;\n continue;\n }\n }\n\n \/\/ -------------------------------------------------\n \/\/ d) Or is it the a task, which use another or no model at all?\n \/\/ Add it to the list of \"other frames\". But look for it's\n \/\/ visible state ... if it's allowed to do so.\n \/\/ -------------------------------------------------\n sal_Bool bHidden = sal_False;\n if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN )\n {\n xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);\n if (xSet.is())\n {\n css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);\n aValue >>= bHidden;\n }\n }\n\n if (bHidden)\n {\n m_lOtherHiddenFrames[nHiddenStep] = xFrame;\n ++nHiddenStep;\n }\n else\n {\n m_lOtherVisibleFrames[nVisibleStep] = xFrame;\n ++nVisibleStep;\n }\n }\n }\n catch(css::lang::IndexOutOfBoundsException)\n {\n \/\/ stop copying if index seams to be wrong.\n \/\/ This interface can't realy guarantee its count for multithreaded\n \/\/ environments. So it can occure!\n }\n\n \/\/ Pack both lists by using the actual step positions.\n \/\/ All empty or ignorable items should exist at the end of these lists\n \/\/ behind the position pointers. So they will be removed by a reallocation.\n m_lOtherVisibleFrames.realloc(nVisibleStep);\n m_lOtherHiddenFrames.realloc(nHiddenStep);\n m_lModelFrames.realloc(nModelStep);\n}\n\n} \/\/ namespace framework\nINTEGRATION: CWS fwk01 (1.1.8.2.6); FILE MERGED 2003\/03\/11 13:21:04 as 1.1.8.2.6.1: #107864# function without reference frame\/*************************************************************************\n *\n * $RCSfile: framelistanalyzer.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2003-04-04 17:14:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"classes\/framelistanalyzer.hxx\"\n\n\/\/_______________________________________________\n\/\/ my own includes\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_TARGETS_H_\n#include \n#endif\n\n#ifndef __FRAMEWORK_PROPERTIES_H_\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ interface includes\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ includes of other projects\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ namespace\n\nnamespace framework{\n\n\/\/_______________________________________________\n\/\/ non exported const\n\n\/\/_______________________________________________\n\/\/ non exported definitions\n\n\/\/_______________________________________________\n\/\/ declarations\n\n\/\/_______________________________________________\n\n\/**\n *\/\n\nFrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier ,\n const css::uno::Reference< css::frame::XFrame >& xReferenceFrame ,\n sal_uInt32 eDetectMode )\n : m_xSupplier (xSupplier )\n , m_xReferenceFrame(xReferenceFrame)\n , m_eDetectMode (eDetectMode )\n{\n impl_analyze();\n}\n\n\/\/_______________________________________________\n\n\/**\n *\/\n\nFrameListAnalyzer::~FrameListAnalyzer()\n{\n}\n\n\/\/_______________________________________________\n\n\/** returns an analyzed list of all currently opened (top!) frames inside the desktop tree.\n\n We try to get a snapshot of all opened frames, which are part of the desktop frame container.\n Of course we can't access frames, which stands outside of this tree.\n But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last\n frame wrong. Further we analyze this list and split into different parts.\n E.g. for \"CloseDoc\" we must know, which frames of the given list referr to the same model.\n These frames must be closed then. But all other frames must be untouched.\n In case the request was \"CloseWin\" these splitted lists can be used too, to decide if the last window\n or document was closed. Then we have to initialize the backing window ...\n Last but not least we must know something about our special help frame. It must be handled\n seperatly. And last but not least - the backing component frame must be detected too.\n*\/\n\nvoid FrameListAnalyzer::impl_analyze()\n{\n \/\/ reset all members to get a consistent state\n m_bReferenceIsHidden = sal_False;\n m_bReferenceIsHelp = sal_False;\n m_bReferenceIsBacking = sal_False;\n m_xHelp = css::uno::Reference< css::frame::XFrame >();\n m_xBackingComponent = css::uno::Reference< css::frame::XFrame >();\n\n \/\/ try to get the task container by using the given supplier\n css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY);\n\n \/\/ All return list get an initial size to include all possible frames.\n \/\/ They will be packed at the end of this method ... using the actual step positions then.\n sal_Int32 nVisibleStep = 0;\n sal_Int32 nHiddenStep = 0;\n sal_Int32 nModelStep = 0;\n sal_Int32 nCount = xFrameContainer->getCount();\n\n m_lOtherVisibleFrames.realloc(nCount);\n m_lOtherHiddenFrames.realloc(nCount);\n m_lModelFrames.realloc(nCount);\n\n \/\/ ask for the model of the given reference frame.\n \/\/ It must be compared with the model of every frame of the container\n \/\/ to sort it into the list of frames with the same model.\n \/\/ Supress this step, if right detect mode isn't set.\n css::uno::Reference< css::frame::XModel > xReferenceModel;\n if ((m_eDetectMode & E_MODEL) == E_MODEL )\n {\n css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController();\n if (xReferenceController.is())\n xReferenceModel = xReferenceController->getModel();\n }\n\n \/\/ check, if the reference frame is in hidden mode.\n \/\/ But look, if this analyze step is realy needed.\n css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY);\n if (\n ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) &&\n (xSet.is() )\n )\n {\n css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);\n aValue >>= m_bReferenceIsHidden;\n }\n\n \/\/ check, if the reference frame includes the backing component.\n \/\/ But look, if this analyze step is realy needed.\n if (\n ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) &&\n (xSet.is() )\n )\n {\n css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE);\n aValue >>= m_bReferenceIsBacking;\n }\n\n \/\/ check, if the reference frame includes the help module.\n \/\/ But look, if this analyze step is realy needed.\n if (\n ((m_eDetectMode & E_HELP) == E_HELP ) &&\n (m_xReferenceFrame.is() ) &&\n (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK)\n )\n {\n m_bReferenceIsHelp = sal_True;\n }\n\n try\n {\n \/\/ Step over all frames of the desktop frame container and analyze it.\n for (sal_Int32 i=0; i xFrame;\n if (\n !(xFrameContainer->getByIndex(i) >>= xFrame) ||\n !(xFrame.is() ) ||\n (xFrame==m_xReferenceFrame )\n )\n continue;\n\n #ifdef ENABLE_WARNINGS\n if (\n ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) &&\n (\n (!xFrame->getContainerWindow().is()) ||\n (!xFrame->getComponentWindow().is())\n )\n )\n {\n LOG_WARNING(\"FrameListAnalyzer::impl_analyze()\", \"ZOMBIE!\")\n }\n #endif\n\n \/\/ -------------------------------------------------\n \/\/ a) Is it the special help task?\n \/\/ Return it seperated from any return list.\n if (\n ((m_eDetectMode & E_HELP) == E_HELP ) &&\n (xFrame->getName()==SPECIALTARGET_HELPTASK)\n )\n {\n m_xHelp = xFrame;\n continue;\n }\n\n \/\/ -------------------------------------------------\n \/\/ b) Or is includes this task the special backing component?\n \/\/ Return it seperated from any return list.\n \/\/ But check if the reference task itself is the backing frame.\n \/\/ Our user mst know it to decide right.\n if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT)\n {\n xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);\n sal_Bool bIsBacking;\n\n if (\n (xSet.is() ) &&\n (xSet->getPropertyValue(FRAME_PROPNAME_ISBACKINGMODE)>>=bIsBacking) &&\n (bIsBacking )\n )\n {\n m_xBackingComponent = xFrame;\n continue;\n }\n }\n\n \/\/ -------------------------------------------------\n \/\/ c) Or is it the a task, which uses the specified model?\n \/\/ Add it to the list of \"model frames\".\n if ((m_eDetectMode & E_MODEL) == E_MODEL)\n {\n css::uno::Reference< css::frame::XController > xController = xFrame->getController();\n css::uno::Reference< css::frame::XModel > xModel ;\n if (xController.is())\n xModel = xController->getModel();\n if (xModel==xReferenceModel)\n {\n m_lModelFrames[nModelStep] = xFrame;\n ++nModelStep;\n continue;\n }\n }\n\n \/\/ -------------------------------------------------\n \/\/ d) Or is it the a task, which use another or no model at all?\n \/\/ Add it to the list of \"other frames\". But look for it's\n \/\/ visible state ... if it's allowed to do so.\n \/\/ -------------------------------------------------\n sal_Bool bHidden = sal_False;\n if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN )\n {\n xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY);\n if (xSet.is())\n {\n css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN);\n aValue >>= bHidden;\n }\n }\n\n if (bHidden)\n {\n m_lOtherHiddenFrames[nHiddenStep] = xFrame;\n ++nHiddenStep;\n }\n else\n {\n m_lOtherVisibleFrames[nVisibleStep] = xFrame;\n ++nVisibleStep;\n }\n }\n }\n catch(css::lang::IndexOutOfBoundsException)\n {\n \/\/ stop copying if index seams to be wrong.\n \/\/ This interface can't realy guarantee its count for multithreaded\n \/\/ environments. So it can occure!\n }\n\n \/\/ Pack both lists by using the actual step positions.\n \/\/ All empty or ignorable items should exist at the end of these lists\n \/\/ behind the position pointers. So they will be removed by a reallocation.\n m_lOtherVisibleFrames.realloc(nVisibleStep);\n m_lOtherHiddenFrames.realloc(nHiddenStep);\n m_lModelFrames.realloc(nModelStep);\n}\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#pragma once\n\n#include \"node_types.hpp\"\n\nnamespace realm {\nnamespace js {\n\ntemplate<>\nclass String {\n std::string m_str;\n\n public:\n String(const char* s) : m_str(s) {}\n String(const std::string &s) : m_str(s) {}\n String(const v8::Local &s);\n String(v8::Local &&s) : String(s) {}\n\n operator std::string() const& {\n return m_str;\n }\n operator std::string() && {\n return std::move(m_str);\n }\n operator v8::Local() const {\n return Nan::New(m_str).ToLocalChecked();\n }\n};\n\ninline String::String(const v8::Local &s) {\n if (s.IsEmpty() || s->Length() == 0) {\n return;\n }\n if (s->IsOneByte()) {\n m_str.resize(s->Length());\n }\n else {\n \/\/ Length is in UCS-2 code units, which can take up to 3 bytes each to encode\n m_str.resize(3 * s->Length());\n }\n const int flags = v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8;\n auto length = s->WriteUtf8(&m_str[0], m_str.size(), 0, flags);\n m_str.resize(length);\n}\n\n} \/\/ js\n} \/\/ realm\nDon't bother special-casing one-byte strings as they're more complicated than it seemed\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#pragma once\n\n#include \"node_types.hpp\"\n\nnamespace realm {\nnamespace js {\n\ntemplate<>\nclass String {\n std::string m_str;\n\n public:\n String(const char* s) : m_str(s) {}\n String(const std::string &s) : m_str(s) {}\n String(const v8::Local &s);\n String(v8::Local &&s) : String(s) {}\n\n operator std::string() const& {\n return m_str;\n }\n operator std::string() && {\n return std::move(m_str);\n }\n operator v8::Local() const {\n return Nan::New(m_str).ToLocalChecked();\n }\n};\n\ninline String::String(const v8::Local &s) {\n if (s.IsEmpty() || s->Length() == 0) {\n return;\n }\n m_str.resize(s->Utf8Length());\n const int flags = v8::String::NO_NULL_TERMINATION | v8::String::REPLACE_INVALID_UTF8;\n s->WriteUtf8(&m_str[0], m_str.size(), 0, flags);\n}\n\n} \/\/ js\n} \/\/ realm\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: registerservices.cxx,v $\n *\n * $Revision: 1.33 $\n *\n * last change: $Author: hr $ $Date: 2006-01-24 15:12:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes of my own project\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_\n#include \n#endif\n\n\/*=================================================================================================================\n Add new include and new register info to for new services.\n\n Example:\n\n #ifndef __YOUR_SERVICE_1_HXX_\n #include \n #endif\n\n #ifndef __YOUR_SERVICE_2_HXX_\n #include \n #endif\n\n COMPONENTGETIMPLEMENTATIONENVIRONMENT\n\n COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )\n COMPONENTINFO( Service2 )\n )\n\n COMPONENTGETFACTORY ( IFFACTORIE( Service1 )\n else\n IFFACTORIE( Service2 )\n )\n=================================================================================================================*\/\n\n#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_\n#include \"uiconfiguration\/windowstateconfiguration.hxx\"\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_\n#include \"uifactory\/toolbarcontrollerfactory.hxx\"\n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_\n#include \"uifactory\/statusbarcontrollerfactory.hxx\"\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_AUTORECOVERY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_SESSIONLISTENER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_LOGOIMAGESTATUSBARCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_LOGOTEXTSTATUSBARCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_NEWMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_SIMPLETEXTSTATUSBARCONTROLLER_HXX_\n#include \n#endif\n\nCOMPONENTGETIMPLEMENTATIONENVIRONMENT\n\nCOMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )\n COMPONENTINFO( ::framework::Desktop )\n COMPONENTINFO( ::framework::Frame )\n COMPONENTINFO( ::framework::DocumentProperties )\n COMPONENTINFO( ::framework::SoundHandler )\n COMPONENTINFO( ::framework::JobExecutor )\n COMPONENTINFO( ::framework::DispatchRecorderSupplier )\n COMPONENTINFO( ::framework::DispatchRecorder )\n COMPONENTINFO( ::framework::MailToDispatcher )\n COMPONENTINFO( ::framework::ServiceHandler )\n COMPONENTINFO( ::framework::JobDispatch )\n COMPONENTINFO( ::framework::BackingComp )\n COMPONENTINFO( ::framework::DispatchHelper )\n COMPONENTINFO( ::framework::LayoutManager )\n COMPONENTINFO( ::framework::License )\n COMPONENTINFO( ::framework::UIElementFactoryManager )\n COMPONENTINFO( ::framework::PopupMenuControllerFactory )\n COMPONENTINFO( ::framework::FontMenuController )\n COMPONENTINFO( ::framework::FontSizeMenuController )\n COMPONENTINFO( ::framework::ObjectMenuController )\n COMPONENTINFO( ::framework::HeaderMenuController )\n COMPONENTINFO( ::framework::FooterMenuController )\n COMPONENTINFO( ::framework::ControlMenuController )\n COMPONENTINFO( ::framework::MacrosMenuController )\n COMPONENTINFO( ::framework::UICommandDescription )\n COMPONENTINFO( ::framework::ModuleManager )\n COMPONENTINFO( ::framework::UIConfigurationManager )\n COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier )\n COMPONENTINFO( ::framework::ModuleUIConfigurationManager )\n COMPONENTINFO( ::framework::MenuBarFactory )\n COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration )\n COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration )\n COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration )\n COMPONENTINFO( ::framework::ToolBoxFactory )\n COMPONENTINFO( ::framework::AddonsToolBoxFactory )\n COMPONENTINFO( ::framework::WindowStateConfiguration )\n COMPONENTINFO( ::framework::ToolbarControllerFactory )\n COMPONENTINFO( ::framework::ToolbarsMenuController )\n COMPONENTINFO( ::framework::AutoRecovery )\n COMPONENTINFO( ::framework::StatusIndicatorFactory )\n COMPONENTINFO( ::framework::RecentFilesMenuController )\n COMPONENTINFO( ::framework::StatusBarFactory )\n COMPONENTINFO( ::framework::UICategoryDescription )\n COMPONENTINFO( ::framework::StatusbarControllerFactory )\n COMPONENTINFO( ::framework::SessionListener )\n COMPONENTINFO( ::framework::LogoImageStatusbarController )\n COMPONENTINFO( ::framework::LogoTextStatusbarController )\n COMPONENTINFO( ::framework::NewMenuController )\n COMPONENTINFO( ::framework::SimpleTextStatusbarController )\n )\n\nCOMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else\n IFFACTORY( ::framework::Desktop ) else\n IFFACTORY( ::framework::Frame ) else\n IFFACTORY( ::framework::DocumentProperties ) else\n IFFACTORY( ::framework::SoundHandler ) else\n IFFACTORY( ::framework::JobExecutor ) else\n IFFACTORY( ::framework::DispatchRecorderSupplier ) else\n IFFACTORY( ::framework::DispatchRecorder ) else\n IFFACTORY( ::framework::MailToDispatcher ) else\n IFFACTORY( ::framework::ServiceHandler ) else\n IFFACTORY( ::framework::JobDispatch ) else\n IFFACTORY( ::framework::BackingComp ) else\n IFFACTORY( ::framework::DispatchHelper ) else\n IFFACTORY( ::framework::LayoutManager ) else\n IFFACTORY( ::framework::License ) else\n IFFACTORY( ::framework::UIElementFactoryManager ) else\n IFFACTORY( ::framework::PopupMenuControllerFactory ) else\n IFFACTORY( ::framework::FontMenuController ) else\n IFFACTORY( ::framework::FontSizeMenuController ) else\n IFFACTORY( ::framework::ObjectMenuController ) else\n IFFACTORY( ::framework::HeaderMenuController ) else\n IFFACTORY( ::framework::FooterMenuController ) else\n IFFACTORY( ::framework::ControlMenuController ) else\n IFFACTORY( ::framework::MacrosMenuController ) else\n IFFACTORY( ::framework::UICommandDescription ) else\n IFFACTORY( ::framework::ModuleManager ) else\n IFFACTORY( ::framework::UIConfigurationManager ) else\n IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else\n IFFACTORY( ::framework::ModuleUIConfigurationManager ) else\n IFFACTORY( ::framework::MenuBarFactory ) else\n IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else\n IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else\n IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else\n IFFACTORY( ::framework::ToolBoxFactory ) else\n IFFACTORY( ::framework::AddonsToolBoxFactory ) else\n IFFACTORY( ::framework::WindowStateConfiguration ) else\n IFFACTORY( ::framework::ToolbarControllerFactory ) else\n IFFACTORY( ::framework::ToolbarsMenuController ) else\n IFFACTORY( ::framework::AutoRecovery ) else\n IFFACTORY( ::framework::StatusIndicatorFactory ) else\n IFFACTORY( ::framework::RecentFilesMenuController ) else\n IFFACTORY( ::framework::StatusBarFactory ) else\n IFFACTORY( ::framework::UICategoryDescription ) else\n IFFACTORY( ::framework::SessionListener ) else\n IFFACTORY( ::framework::StatusbarControllerFactory ) else\n IFFACTORY( ::framework::SessionListener ) else\n IFFACTORY( ::framework::LogoImageStatusbarController ) else\n IFFACTORY( ::framework::LogoTextStatusbarController ) else\n IFFACTORY( ::framework::NewMenuController ) else\n IFFACTORY( ::framework::SimpleTextStatusbarController )\n )\n\nINTEGRATION: CWS gsoc (1.32.6); FILE MERGED 2006\/02\/07 10:14:08 as 1.32.6.2: RESYNC: (1.32-1.33); FILE MERGED resolve merge conflicts 2005\/09\/20 10:22:31 as 1.32.6.1: #i54847# first revision of 'TabBrowse' feature\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: registerservices.cxx,v $\n *\n * $Revision: 1.34 $\n *\n * last change: $Author: vg $ $Date: 2006-09-08 08:32:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes of my own project\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_\n#include \n#endif\n\n\/*=================================================================================================================\n Add new include and new register info to for new services.\n\n Example:\n\n #ifndef __YOUR_SERVICE_1_HXX_\n #include \n #endif\n\n #ifndef __YOUR_SERVICE_2_HXX_\n #include \n #endif\n\n COMPONENTGETIMPLEMENTATIONENVIRONMENT\n\n COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )\n COMPONENTINFO( Service2 )\n )\n\n COMPONENTGETFACTORY ( IFFACTORIE( Service1 )\n else\n IFFACTORIE( Service2 )\n )\n=================================================================================================================*\/\n\n#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_\n#include \"uiconfiguration\/windowstateconfiguration.hxx\"\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_\n#include \"uifactory\/toolbarcontrollerfactory.hxx\"\n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_\n#include \"uifactory\/statusbarcontrollerfactory.hxx\"\n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_AUTORECOVERY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_HELPER_STATUSINDICATORFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_SESSIONLISTENER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_LOGOIMAGESTATUSBARCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_LOGOTEXTSTATUSBARCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_NEWMENUCONTROLLER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_TASKCREATORSRV_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_UIELEMENT_SIMPLETEXTSTATUSBARCONTROLLER_HXX_\n#include \n#endif\n\nCOMPONENTGETIMPLEMENTATIONENVIRONMENT\n\nCOMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )\n COMPONENTINFO( ::framework::Desktop )\n COMPONENTINFO( ::framework::Frame )\n COMPONENTINFO( ::framework::DocumentProperties )\n COMPONENTINFO( ::framework::SoundHandler )\n COMPONENTINFO( ::framework::JobExecutor )\n COMPONENTINFO( ::framework::DispatchRecorderSupplier )\n COMPONENTINFO( ::framework::DispatchRecorder )\n COMPONENTINFO( ::framework::MailToDispatcher )\n COMPONENTINFO( ::framework::ServiceHandler )\n COMPONENTINFO( ::framework::JobDispatch )\n COMPONENTINFO( ::framework::BackingComp )\n COMPONENTINFO( ::framework::DispatchHelper )\n COMPONENTINFO( ::framework::LayoutManager )\n COMPONENTINFO( ::framework::License )\n COMPONENTINFO( ::framework::UIElementFactoryManager )\n COMPONENTINFO( ::framework::PopupMenuControllerFactory )\n COMPONENTINFO( ::framework::FontMenuController )\n COMPONENTINFO( ::framework::FontSizeMenuController )\n COMPONENTINFO( ::framework::ObjectMenuController )\n COMPONENTINFO( ::framework::HeaderMenuController )\n COMPONENTINFO( ::framework::FooterMenuController )\n COMPONENTINFO( ::framework::ControlMenuController )\n COMPONENTINFO( ::framework::MacrosMenuController )\n COMPONENTINFO( ::framework::UICommandDescription )\n COMPONENTINFO( ::framework::ModuleManager )\n COMPONENTINFO( ::framework::UIConfigurationManager )\n COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier )\n COMPONENTINFO( ::framework::ModuleUIConfigurationManager )\n COMPONENTINFO( ::framework::MenuBarFactory )\n COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration )\n COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration )\n COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration )\n COMPONENTINFO( ::framework::ToolBoxFactory )\n COMPONENTINFO( ::framework::AddonsToolBoxFactory )\n COMPONENTINFO( ::framework::WindowStateConfiguration )\n COMPONENTINFO( ::framework::ToolbarControllerFactory )\n COMPONENTINFO( ::framework::ToolbarsMenuController )\n COMPONENTINFO( ::framework::AutoRecovery )\n COMPONENTINFO( ::framework::StatusIndicatorFactory )\n COMPONENTINFO( ::framework::RecentFilesMenuController )\n COMPONENTINFO( ::framework::StatusBarFactory )\n COMPONENTINFO( ::framework::UICategoryDescription )\n COMPONENTINFO( ::framework::StatusbarControllerFactory )\n COMPONENTINFO( ::framework::SessionListener )\n COMPONENTINFO( ::framework::LogoImageStatusbarController )\n COMPONENTINFO( ::framework::LogoTextStatusbarController )\n COMPONENTINFO( ::framework::NewMenuController )\n COMPONENTINFO( ::framework::TaskCreatorService )\n COMPONENTINFO( ::framework::SimpleTextStatusbarController )\n )\n\nCOMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else\n IFFACTORY( ::framework::Desktop ) else\n IFFACTORY( ::framework::Frame ) else\n IFFACTORY( ::framework::DocumentProperties ) else\n IFFACTORY( ::framework::SoundHandler ) else\n IFFACTORY( ::framework::JobExecutor ) else\n IFFACTORY( ::framework::DispatchRecorderSupplier ) else\n IFFACTORY( ::framework::DispatchRecorder ) else\n IFFACTORY( ::framework::MailToDispatcher ) else\n IFFACTORY( ::framework::ServiceHandler ) else\n IFFACTORY( ::framework::JobDispatch ) else\n IFFACTORY( ::framework::BackingComp ) else\n IFFACTORY( ::framework::DispatchHelper ) else\n IFFACTORY( ::framework::LayoutManager ) else\n IFFACTORY( ::framework::License ) else\n IFFACTORY( ::framework::UIElementFactoryManager ) else\n IFFACTORY( ::framework::PopupMenuControllerFactory ) else\n IFFACTORY( ::framework::FontMenuController ) else\n IFFACTORY( ::framework::FontSizeMenuController ) else\n IFFACTORY( ::framework::ObjectMenuController ) else\n IFFACTORY( ::framework::HeaderMenuController ) else\n IFFACTORY( ::framework::FooterMenuController ) else\n IFFACTORY( ::framework::ControlMenuController ) else\n IFFACTORY( ::framework::MacrosMenuController ) else\n IFFACTORY( ::framework::UICommandDescription ) else\n IFFACTORY( ::framework::ModuleManager ) else\n IFFACTORY( ::framework::UIConfigurationManager ) else\n IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else\n IFFACTORY( ::framework::ModuleUIConfigurationManager ) else\n IFFACTORY( ::framework::MenuBarFactory ) else\n IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else\n IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else\n IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else\n IFFACTORY( ::framework::ToolBoxFactory ) else\n IFFACTORY( ::framework::AddonsToolBoxFactory ) else\n IFFACTORY( ::framework::WindowStateConfiguration ) else\n IFFACTORY( ::framework::ToolbarControllerFactory ) else\n IFFACTORY( ::framework::ToolbarsMenuController ) else\n IFFACTORY( ::framework::AutoRecovery ) else\n IFFACTORY( ::framework::StatusIndicatorFactory ) else\n IFFACTORY( ::framework::RecentFilesMenuController ) else\n IFFACTORY( ::framework::StatusBarFactory ) else\n IFFACTORY( ::framework::UICategoryDescription ) else\n IFFACTORY( ::framework::SessionListener ) else\n IFFACTORY( ::framework::StatusbarControllerFactory ) else\n IFFACTORY( ::framework::SessionListener ) else\n IFFACTORY( ::framework::LogoImageStatusbarController ) else\n IFFACTORY( ::framework::LogoTextStatusbarController ) else\n IFFACTORY( ::framework::TaskCreatorService ) else\n IFFACTORY( ::framework::NewMenuController ) else\n IFFACTORY( ::framework::SimpleTextStatusbarController )\n )\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)\n{\n err_string_out = state.ToString();\n if (state.IsInvalid()) {\n if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {\n return TransactionError::MISSING_INPUTS;\n }\n return TransactionError::MEMPOOL_REJECTED;\n } else {\n return TransactionError::MEMPOOL_ERROR;\n }\n}\n\nTransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback)\n{\n \/\/ BroadcastTransaction can be called by either sendrawtransaction RPC or wallet RPCs.\n \/\/ node.peerman is assigned both before chain clients and before RPC server is accepting calls,\n \/\/ and reset after chain clients and RPC sever are stopped. node.peerman should never be null here.\n assert(node.peerman);\n assert(node.mempool);\n std::promise promise;\n uint256 hashTx = tx->GetHash();\n bool callback_set = false;\n\n { \/\/ cs_main scope\n assert(node.chainman);\n LOCK(cs_main);\n \/\/ If the transaction is already confirmed in the chain, don't do anything\n \/\/ and return early.\n CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();\n for (size_t o = 0; o < tx->vout.size(); o++) {\n const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));\n \/\/ IsSpent doesn't mean the coin is spent, it means the output doesn't exist.\n \/\/ So if the output does exist, then this transaction exists in the chain.\n if (!existingCoin.IsSpent()) return TransactionError::ALREADY_IN_CHAIN;\n }\n if (!node.mempool->exists(hashTx)) {\n \/\/ Transaction is not already in the mempool.\n if (max_tx_fee > 0) {\n \/\/ First, call ATMP with test_accept and check the fee. If ATMP\n \/\/ fails here, return error immediately.\n const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false \/* bypass_limits *\/,\n true \/* test_accept *\/);\n if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {\n return HandleATMPError(result.m_state, err_string);\n } else if (result.m_base_fees.value() > max_tx_fee) {\n return TransactionError::MAX_FEE_EXCEEDED;\n }\n }\n \/\/ Try to submit the transaction to the mempool.\n const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false \/* bypass_limits *\/,\n false \/* test_accept *\/);\n if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {\n return HandleATMPError(result.m_state, err_string);\n }\n\n \/\/ Transaction was accepted to the mempool.\n\n if (relay) {\n \/\/ the mempool tracks locally submitted transactions to make a\n \/\/ best-effort of initial broadcast\n node.mempool->AddUnbroadcastTx(hashTx);\n }\n\n if (wait_callback) {\n \/\/ For transactions broadcast from outside the wallet, make sure\n \/\/ that the wallet has been notified of the transaction before\n \/\/ continuing.\n \/\/\n \/\/ This prevents a race where a user might call sendrawtransaction\n \/\/ with a transaction to\/from their wallet, immediately call some\n \/\/ wallet RPC, and get a stale result because callbacks have not\n \/\/ yet been processed.\n CallFunctionInValidationInterfaceQueue([&promise] {\n promise.set_value();\n });\n callback_set = true;\n }\n }\n\n } \/\/ cs_main\n\n if (callback_set) {\n \/\/ Wait until Validation Interface clients have been notified of the\n \/\/ transaction entering the mempool.\n promise.get_future().wait();\n }\n\n if (relay) {\n node.peerman->RelayTransaction(hashTx, tx->GetWitnessHash());\n }\n\n return TransactionError::OK;\n}\n[mempool] Allow rebroadcast for same-txid-different-wtxid transactions\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic TransactionError HandleATMPError(const TxValidationState& state, std::string& err_string_out)\n{\n err_string_out = state.ToString();\n if (state.IsInvalid()) {\n if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) {\n return TransactionError::MISSING_INPUTS;\n }\n return TransactionError::MEMPOOL_REJECTED;\n } else {\n return TransactionError::MEMPOOL_ERROR;\n }\n}\n\nTransactionError BroadcastTransaction(NodeContext& node, const CTransactionRef tx, std::string& err_string, const CAmount& max_tx_fee, bool relay, bool wait_callback)\n{\n \/\/ BroadcastTransaction can be called by either sendrawtransaction RPC or wallet RPCs.\n \/\/ node.peerman is assigned both before chain clients and before RPC server is accepting calls,\n \/\/ and reset after chain clients and RPC sever are stopped. node.peerman should never be null here.\n assert(node.peerman);\n assert(node.mempool);\n std::promise promise;\n uint256 txid = tx->GetHash();\n uint256 wtxid = tx->GetWitnessHash();\n bool callback_set = false;\n\n { \/\/ cs_main scope\n assert(node.chainman);\n LOCK(cs_main);\n \/\/ If the transaction is already confirmed in the chain, don't do anything\n \/\/ and return early.\n CCoinsViewCache &view = node.chainman->ActiveChainstate().CoinsTip();\n for (size_t o = 0; o < tx->vout.size(); o++) {\n const Coin& existingCoin = view.AccessCoin(COutPoint(txid, o));\n \/\/ IsSpent doesn't mean the coin is spent, it means the output doesn't exist.\n \/\/ So if the output does exist, then this transaction exists in the chain.\n if (!existingCoin.IsSpent()) return TransactionError::ALREADY_IN_CHAIN;\n }\n if (auto mempool_tx = node.mempool->get(txid); mempool_tx) {\n \/\/ There's already a transaction in the mempool with this txid. Don't\n \/\/ try to submit this transaction to the mempool (since it'll be\n \/\/ rejected as a TX_CONFLICT), but do attempt to reannounce the mempool\n \/\/ transaction if relay=true.\n \/\/\n \/\/ The mempool transaction may have the same or different witness (and\n \/\/ wtxid) as this transaction. Use the mempool's wtxid for reannouncement.\n wtxid = mempool_tx->GetWitnessHash();\n } else {\n \/\/ Transaction is not already in the mempool.\n if (max_tx_fee > 0) {\n \/\/ First, call ATMP with test_accept and check the fee. If ATMP\n \/\/ fails here, return error immediately.\n const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false \/* bypass_limits *\/,\n true \/* test_accept *\/);\n if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {\n return HandleATMPError(result.m_state, err_string);\n } else if (result.m_base_fees.value() > max_tx_fee) {\n return TransactionError::MAX_FEE_EXCEEDED;\n }\n }\n \/\/ Try to submit the transaction to the mempool.\n const MempoolAcceptResult result = AcceptToMemoryPool(node.chainman->ActiveChainstate(), *node.mempool, tx, false \/* bypass_limits *\/,\n false \/* test_accept *\/);\n if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {\n return HandleATMPError(result.m_state, err_string);\n }\n\n \/\/ Transaction was accepted to the mempool.\n\n if (relay) {\n \/\/ the mempool tracks locally submitted transactions to make a\n \/\/ best-effort of initial broadcast\n node.mempool->AddUnbroadcastTx(txid);\n }\n\n if (wait_callback) {\n \/\/ For transactions broadcast from outside the wallet, make sure\n \/\/ that the wallet has been notified of the transaction before\n \/\/ continuing.\n \/\/\n \/\/ This prevents a race where a user might call sendrawtransaction\n \/\/ with a transaction to\/from their wallet, immediately call some\n \/\/ wallet RPC, and get a stale result because callbacks have not\n \/\/ yet been processed.\n CallFunctionInValidationInterfaceQueue([&promise] {\n promise.set_value();\n });\n callback_set = true;\n }\n }\n\n } \/\/ cs_main\n\n if (callback_set) {\n \/\/ Wait until Validation Interface clients have been notified of the\n \/\/ transaction entering the mempool.\n promise.get_future().wait();\n }\n\n if (relay) {\n node.peerman->RelayTransaction(txid, wtxid);\n }\n\n return TransactionError::OK;\n}\n<|endoftext|>"} {"text":"Update All_combines<|endoftext|>"} {"text":"#include \"ofxNDIRecvStream.h\"\n\n\ntemplate<>\nbool ofxNDIRecvVideoBlocking::captureFrame(ofxNDI::VideoFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, &frame, nullptr, nullptr, timeout_ms_) == NDIlib_frame_type_video;\n}\ntemplate<>\nvoid ofxNDIRecvVideoBlocking::freeFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_recv_free_video_v2(instance_, &frame);\n}\ntemplate<>\nbool ofxNDIRecvVideoThreading::captureFrame(ofxNDI::VideoFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, &frame, nullptr, nullptr, timeout_ms_) == NDIlib_frame_type_video;\n}\ntemplate<>\nvoid ofxNDIRecvVideoThreading::freeFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_recv_free_video_v2(instance_, &frame);\n}\nbool ofxNDIRecvVideoFrameSync::captureFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_framesync_capture_video(sync_, &frame, field_type_);\n\treturn true;\n}\nvoid ofxNDIRecvVideoFrameSync::freeFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_framesync_free_video(sync_, &frame);\n}\n\n#pragma mark Audio Stream\ntemplate<>\nbool ofxNDIRecvAudioBlocking::captureFrame(ofxNDI::AudioFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, nullptr, &frame, nullptr, timeout_ms_) == NDIlib_frame_type_audio;\n}\ntemplate<>\nvoid ofxNDIRecvAudioBlocking::freeFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_recv_free_audio_v2(instance_, &frame);\n}\ntemplate<>\nbool ofxNDIRecvAudioThreading::captureFrame(ofxNDI::AudioFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, nullptr, &frame, nullptr, timeout_ms_) == NDIlib_frame_type_audio;\n}\ntemplate<>\nvoid ofxNDIRecvAudioThreading::freeFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_recv_free_audio_v2(instance_, &frame);\n}\nbool ofxNDIRecvAudioFrameSync::captureFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_framesync_capture_audio(sync_, &frame, sample_rate_, num_channels_, num_samples_);\n\treturn true;\n}\nvoid ofxNDIRecvAudioFrameSync::freeFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_framesync_free_audio(sync_, &frame);\n}\nint ofxNDIRecvAudioFrameSync::getNumQueuedSamples() const {\n\treturn NDIlib_framesync_audio_queue_depth(sync_);\n}\n\n\n#pragma mark Metadata Stream\n\ntemplate<>\nbool ofxNDIRecvMetadata::captureFrame(ofxNDI::MetadataFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, nullptr, nullptr, &frame, timeout_ms_) == NDIlib_frame_type_metadata;\n}\ntemplate<>\nvoid ofxNDIRecvMetadata::freeFrame(ofxNDI::MetadataFrame &frame) {\n\tNDIlib_recv_free_metadata(instance_, &frame);\n}\n\nhandle errors when received empty data#include \"ofxNDIRecvStream.h\"\n\n\ntemplate<>\nbool ofxNDIRecvVideoBlocking::captureFrame(ofxNDI::VideoFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, &frame, nullptr, nullptr, timeout_ms_) == NDIlib_frame_type_video;\n}\ntemplate<>\nvoid ofxNDIRecvVideoBlocking::freeFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_recv_free_video_v2(instance_, &frame);\n}\ntemplate<>\nbool ofxNDIRecvVideoThreading::captureFrame(ofxNDI::VideoFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, &frame, nullptr, nullptr, timeout_ms_) == NDIlib_frame_type_video;\n}\ntemplate<>\nvoid ofxNDIRecvVideoThreading::freeFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_recv_free_video_v2(instance_, &frame);\n}\nbool ofxNDIRecvVideoFrameSync::captureFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_framesync_capture_video(sync_, &frame, field_type_);\n\treturn frame.p_data != nullptr;\n}\nvoid ofxNDIRecvVideoFrameSync::freeFrame(ofxNDI::VideoFrame &frame) {\n\tNDIlib_framesync_free_video(sync_, &frame);\n}\n\n#pragma mark Audio Stream\ntemplate<>\nbool ofxNDIRecvAudioBlocking::captureFrame(ofxNDI::AudioFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, nullptr, &frame, nullptr, timeout_ms_) == NDIlib_frame_type_audio;\n}\ntemplate<>\nvoid ofxNDIRecvAudioBlocking::freeFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_recv_free_audio_v2(instance_, &frame);\n}\ntemplate<>\nbool ofxNDIRecvAudioThreading::captureFrame(ofxNDI::AudioFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, nullptr, &frame, nullptr, timeout_ms_) == NDIlib_frame_type_audio;\n}\ntemplate<>\nvoid ofxNDIRecvAudioThreading::freeFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_recv_free_audio_v2(instance_, &frame);\n}\nbool ofxNDIRecvAudioFrameSync::captureFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_framesync_capture_audio(sync_, &frame, sample_rate_, num_channels_, num_samples_);\n\treturn frame.no_channels != 0;\n}\nvoid ofxNDIRecvAudioFrameSync::freeFrame(ofxNDI::AudioFrame &frame) {\n\tNDIlib_framesync_free_audio(sync_, &frame);\n}\nint ofxNDIRecvAudioFrameSync::getNumQueuedSamples() const {\n\treturn NDIlib_framesync_audio_queue_depth(sync_);\n}\n\n\n#pragma mark Metadata Stream\n\ntemplate<>\nbool ofxNDIRecvMetadata::captureFrame(ofxNDI::MetadataFrame &frame) {\n\treturn NDIlib_recv_capture_v2(instance_, nullptr, nullptr, &frame, timeout_ms_) == NDIlib_frame_type_metadata;\n}\ntemplate<>\nvoid ofxNDIRecvMetadata::freeFrame(ofxNDI::MetadataFrame &frame) {\n\tNDIlib_recv_free_metadata(instance_, &frame);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include \"base\/compiler_specific.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#include \"ContextMenu.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"Editor.h\"\n#include \"EventHandler.h\"\n#include \"FrameLoader.h\"\n#include \"FrameView.h\"\n#include \"HitTestResult.h\"\n#include \"KURL.h\"\n#include \"Widget.h\"\nMSVC_POP_WARNING();\n#undef LOG\n\n#include \"webkit\/glue\/context_menu_client_impl.h\"\n\n#include \"base\/string_util.h\"\n#include \"webkit\/glue\/context_menu.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdocumentloader_impl.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\n#include \"base\/word_iterator.h\"\n\nnamespace {\n\n\/\/ Helper function to determine whether text is a single word or a sentence.\nbool IsASingleWord(const std::wstring& text) {\n WordIterator iter(text, WordIterator::BREAK_WORD);\n int word_count = 0;\n if (!iter.Init()) return false;\n while (iter.Advance()) {\n if (iter.IsWord()) {\n word_count++;\n if (word_count > 1) \/\/ More than one word.\n return false;\n }\n }\n \n \/\/ Check for 0 words.\n if (!word_count)\n return false;\n \n \/\/ Has a single word.\n return true;\n}\n\n\/\/ Helper function to get misspelled word on which context menu \n\/\/ is to be evolked. This function also sets the word on which context menu\n\/\/ has been evoked to be the selected word, as required.\nstd::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,\n WebCore::Frame* selected_frame) {\n std::wstring misspelled_word_string;\n\n \/\/ First select from selectedText to check for multiple word selection.\n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n\n \/\/ Don't provide suggestions for multiple words.\n if (!misspelled_word_string.empty() && \n !IsASingleWord(misspelled_word_string))\n return L\"\";\n\n WebCore::HitTestResult hit_test_result = selected_frame->eventHandler()->\n hitTestResultAtPoint(default_menu->hitTestResult().point(), true);\n WebCore::Node* inner_node = hit_test_result.innerNode();\n WebCore::VisiblePosition pos(inner_node->renderer()->positionForPoint(\n hit_test_result.localPoint()));\n\n WebCore::Selection selection;\n if (pos.isNotNull()) {\n selection = WebCore::Selection(pos);\n selection.expandUsingGranularity(WebCore::WordGranularity);\n }\n \n if (selection.isRange()) { \n selected_frame->setSelectionGranularity(WebCore::WordGranularity);\n }\n \n if (selected_frame->shouldChangeSelection(selection))\n selected_frame->selection()->setSelection(selection);\n \n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()), \n false);\n \n return misspelled_word_string;\n}\n\n} \/\/ namespace\n\nContextMenuClientImpl::~ContextMenuClientImpl() {\n}\n\nvoid ContextMenuClientImpl::contextMenuDestroyed() {\n delete this;\n}\n\n\/\/ Figure out the URL of a page or subframe. Returns |page_type| as the type,\n\/\/ which indicates page or subframe, or ContextNode::NONE if the URL could not\n\/\/ be determined for some reason.\nstatic ContextNode GetTypeAndURLFromFrame(WebCore::Frame* frame,\n GURL* url,\n ContextNode page_node) {\n ContextNode node;\n if (frame) {\n WebCore::DocumentLoader* dl = frame->loader()->documentLoader();\n if (dl) {\n WebDataSource* ds = static_cast(dl)->\n GetDataSource();\n if (ds) {\n node = page_node;\n *url = ds->HasUnreachableURL() ? ds->GetUnreachableURL()\n : ds->GetRequest().GetURL();\n }\n }\n }\n return node;\n}\n\nWebCore::PlatformMenuDescription\n ContextMenuClientImpl::getCustomMenuFromDefaultItems(\n WebCore::ContextMenu* default_menu) {\n \/\/ Displaying the context menu in this function is a big hack as we don't\n \/\/ have context, i.e. whether this is being invoked via a script or in \n \/\/ response to user input (Mouse event WM_RBUTTONDOWN,\n \/\/ Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked\n \/\/ in response to the above input events before popping up the context menu.\n if (!webview_->context_menu_allowed())\n return NULL;\n\n WebCore::HitTestResult r = default_menu->hitTestResult();\n WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();\n\n WebCore::IntPoint menu_point =\n selected_frame->view()->contentsToWindow(r.point());\n\n ContextNode node;\n\n \/\/ Links, Images and Image-Links take preference over all else.\n WebCore::KURL link_url = r.absoluteLinkURL();\n if (!link_url.isEmpty()) {\n node.type |= ContextNode::LINK;\n }\n WebCore::KURL image_url = r.absoluteImageURL();\n if (!image_url.isEmpty()) {\n node.type |= ContextNode::IMAGE;\n }\n\n \/\/ If it's not a link, an image or an image link, show a selection menu or a\n \/\/ more generic page menu.\n std::wstring selection_text_string;\n std::wstring misspelled_word_string;\n GURL frame_url;\n GURL page_url;\n std::string security_info;\n \n std::wstring frame_encoding;\n \/\/ Send the frame and page URLs in any case.\n ContextNode frame_node = ContextNode(ContextNode::NONE);\n ContextNode page_node =\n GetTypeAndURLFromFrame(webview_->main_frame()->frame(),\n &page_url,\n ContextNode(ContextNode::PAGE));\n if (selected_frame != webview_->main_frame()->frame()) {\n frame_node = GetTypeAndURLFromFrame(selected_frame,\n &frame_url,\n ContextNode(ContextNode::FRAME));\n frame_encoding = webkit_glue::StringToStdWString(\n selected_frame->loader()->encoding());\n }\n\n if (r.isSelected()) {\n node.type |= ContextNode::SELECTION;\n selection_text_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n }\n\n if (r.isContentEditable()) {\n node.type |= ContextNode::EDITABLE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->\n isContinuousSpellCheckingEnabled()) {\n misspelled_word_string = GetMisspelledWord(default_menu,\n selected_frame);\n }\n }\n \n if (node.type == ContextNode::NONE) {\n if (selected_frame != webview_->main_frame()->frame()) {\n node = frame_node;\n } else {\n node = page_node;\n }\n }\n\n \/\/ Now retrieve the security info.\n WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();\n if (dl) {\n WebDataSource* ds = static_cast(dl)->\n GetDataSource();\n if (ds) {\n const WebResponse& response = ds->GetResponse();\n security_info = response.GetSecurityInfo();\n }\n }\n\n int edit_flags = ContextNode::CAN_DO_NONE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())\n edit_flags |= ContextNode::CAN_UNDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())\n edit_flags |= ContextNode::CAN_REDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())\n edit_flags |= ContextNode::CAN_CUT;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())\n edit_flags |= ContextNode::CAN_COPY;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())\n edit_flags |= ContextNode::CAN_PASTE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())\n edit_flags |= ContextNode::CAN_DELETE;\n \/\/ We can always select all...\n edit_flags |= ContextNode::CAN_SELECT_ALL;\n\n WebViewDelegate* d = webview_->delegate();\n if (d) {\n d->ShowContextMenu(webview_,\n node,\n menu_point.x(),\n menu_point.y(),\n webkit_glue::KURLToGURL(link_url),\n webkit_glue::KURLToGURL(image_url),\n page_url,\n frame_url,\n selection_text_string,\n misspelled_word_string,\n edit_flags,\n security_info);\n }\n return NULL;\n}\n\nvoid ContextMenuClientImpl::contextMenuItemSelected(\n WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {\n}\n\nvoid ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {\n}\n\nvoid ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {\n}\n\nvoid ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::speak(const WebCore::String&) {\n}\n\nvoid ContextMenuClientImpl::stopSpeaking() {\n}\n\nbool ContextMenuClientImpl::shouldIncludeInspectElementItem() {\n return false; \/\/ TODO(jackson): Eventually include the inspector context menu item\n}\n\n#if defined(OS_MACOSX)\nvoid ContextMenuClientImpl::searchWithSpotlight() {\n \/\/ TODO(pinkerton): write this\n}\n#endif\nFix bug where right click in a text area selects empty space.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include \"base\/compiler_specific.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#include \"ContextMenu.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"Editor.h\"\n#include \"EventHandler.h\"\n#include \"FrameLoader.h\"\n#include \"FrameView.h\"\n#include \"HitTestResult.h\"\n#include \"KURL.h\"\n#include \"Widget.h\"\nMSVC_POP_WARNING();\n#undef LOG\n\n#include \"webkit\/glue\/context_menu_client_impl.h\"\n\n#include \"base\/string_util.h\"\n#include \"webkit\/glue\/context_menu.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdocumentloader_impl.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\n#include \"base\/word_iterator.h\"\n\nnamespace {\n\n\/\/ Helper function to determine whether text is a single word or a sentence.\nbool IsASingleWord(const std::wstring& text) {\n WordIterator iter(text, WordIterator::BREAK_WORD);\n int word_count = 0;\n if (!iter.Init()) return false;\n while (iter.Advance()) {\n if (iter.IsWord()) {\n word_count++;\n if (word_count > 1) \/\/ More than one word.\n return false;\n }\n }\n \n \/\/ Check for 0 words.\n if (!word_count)\n return false;\n \n \/\/ Has a single word.\n return true;\n}\n\n\/\/ Helper function to get misspelled word on which context menu \n\/\/ is to be evolked. This function also sets the word on which context menu\n\/\/ has been evoked to be the selected word, as required.\nstd::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,\n WebCore::Frame* selected_frame) {\n std::wstring misspelled_word_string;\n\n \/\/ First select from selectedText to check for multiple word selection.\n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n\n \/\/ Don't provide suggestions for multiple words.\n if (!misspelled_word_string.empty() && \n !IsASingleWord(misspelled_word_string))\n return L\"\";\n\n WebCore::HitTestResult hit_test_result = selected_frame->eventHandler()->\n hitTestResultAtPoint(default_menu->hitTestResult().point(), true);\n WebCore::Node* inner_node = hit_test_result.innerNode();\n WebCore::VisiblePosition pos(inner_node->renderer()->positionForPoint(\n hit_test_result.localPoint()));\n\n WebCore::Selection selection;\n if (pos.isNotNull()) {\n selection = WebCore::Selection(pos);\n selection.expandUsingGranularity(WebCore::WordGranularity);\n }\n \n if (selection.isRange()) { \n selected_frame->setSelectionGranularity(WebCore::WordGranularity);\n }\n \n if (selected_frame->shouldChangeSelection(selection))\n selected_frame->selection()->setSelection(selection);\n \n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()), \n false);\n\n \/\/ If misspelled word is empty, then that portion should not be selected.\n \/\/ Set the selection to that position only, and do not expand.\n if (misspelled_word_string.empty()) {\n selection = WebCore::Selection(pos);\n selected_frame->selection()->setSelection(selection);\n }\n\n return misspelled_word_string;\n}\n\n} \/\/ namespace\n\nContextMenuClientImpl::~ContextMenuClientImpl() {\n}\n\nvoid ContextMenuClientImpl::contextMenuDestroyed() {\n delete this;\n}\n\n\/\/ Figure out the URL of a page or subframe. Returns |page_type| as the type,\n\/\/ which indicates page or subframe, or ContextNode::NONE if the URL could not\n\/\/ be determined for some reason.\nstatic ContextNode GetTypeAndURLFromFrame(WebCore::Frame* frame,\n GURL* url,\n ContextNode page_node) {\n ContextNode node;\n if (frame) {\n WebCore::DocumentLoader* dl = frame->loader()->documentLoader();\n if (dl) {\n WebDataSource* ds = static_cast(dl)->\n GetDataSource();\n if (ds) {\n node = page_node;\n *url = ds->HasUnreachableURL() ? ds->GetUnreachableURL()\n : ds->GetRequest().GetURL();\n }\n }\n }\n return node;\n}\n\nWebCore::PlatformMenuDescription\n ContextMenuClientImpl::getCustomMenuFromDefaultItems(\n WebCore::ContextMenu* default_menu) {\n \/\/ Displaying the context menu in this function is a big hack as we don't\n \/\/ have context, i.e. whether this is being invoked via a script or in \n \/\/ response to user input (Mouse event WM_RBUTTONDOWN,\n \/\/ Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked\n \/\/ in response to the above input events before popping up the context menu.\n if (!webview_->context_menu_allowed())\n return NULL;\n\n WebCore::HitTestResult r = default_menu->hitTestResult();\n WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();\n\n WebCore::IntPoint menu_point =\n selected_frame->view()->contentsToWindow(r.point());\n\n ContextNode node;\n\n \/\/ Links, Images and Image-Links take preference over all else.\n WebCore::KURL link_url = r.absoluteLinkURL();\n if (!link_url.isEmpty()) {\n node.type |= ContextNode::LINK;\n }\n WebCore::KURL image_url = r.absoluteImageURL();\n if (!image_url.isEmpty()) {\n node.type |= ContextNode::IMAGE;\n }\n\n \/\/ If it's not a link, an image or an image link, show a selection menu or a\n \/\/ more generic page menu.\n std::wstring selection_text_string;\n std::wstring misspelled_word_string;\n GURL frame_url;\n GURL page_url;\n std::string security_info;\n \n std::wstring frame_encoding;\n \/\/ Send the frame and page URLs in any case.\n ContextNode frame_node = ContextNode(ContextNode::NONE);\n ContextNode page_node =\n GetTypeAndURLFromFrame(webview_->main_frame()->frame(),\n &page_url,\n ContextNode(ContextNode::PAGE));\n if (selected_frame != webview_->main_frame()->frame()) {\n frame_node = GetTypeAndURLFromFrame(selected_frame,\n &frame_url,\n ContextNode(ContextNode::FRAME));\n frame_encoding = webkit_glue::StringToStdWString(\n selected_frame->loader()->encoding());\n }\n\n if (r.isSelected()) {\n node.type |= ContextNode::SELECTION;\n selection_text_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n }\n\n if (r.isContentEditable()) {\n node.type |= ContextNode::EDITABLE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->\n isContinuousSpellCheckingEnabled()) {\n misspelled_word_string = GetMisspelledWord(default_menu,\n selected_frame);\n }\n }\n \n if (node.type == ContextNode::NONE) {\n if (selected_frame != webview_->main_frame()->frame()) {\n node = frame_node;\n } else {\n node = page_node;\n }\n }\n\n \/\/ Now retrieve the security info.\n WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();\n if (dl) {\n WebDataSource* ds = static_cast(dl)->\n GetDataSource();\n if (ds) {\n const WebResponse& response = ds->GetResponse();\n security_info = response.GetSecurityInfo();\n }\n }\n\n int edit_flags = ContextNode::CAN_DO_NONE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())\n edit_flags |= ContextNode::CAN_UNDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())\n edit_flags |= ContextNode::CAN_REDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())\n edit_flags |= ContextNode::CAN_CUT;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())\n edit_flags |= ContextNode::CAN_COPY;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())\n edit_flags |= ContextNode::CAN_PASTE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())\n edit_flags |= ContextNode::CAN_DELETE;\n \/\/ We can always select all...\n edit_flags |= ContextNode::CAN_SELECT_ALL;\n\n WebViewDelegate* d = webview_->delegate();\n if (d) {\n d->ShowContextMenu(webview_,\n node,\n menu_point.x(),\n menu_point.y(),\n webkit_glue::KURLToGURL(link_url),\n webkit_glue::KURLToGURL(image_url),\n page_url,\n frame_url,\n selection_text_string,\n misspelled_word_string,\n edit_flags,\n security_info);\n }\n return NULL;\n}\n\nvoid ContextMenuClientImpl::contextMenuItemSelected(\n WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {\n}\n\nvoid ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {\n}\n\nvoid ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {\n}\n\nvoid ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::speak(const WebCore::String&) {\n}\n\nvoid ContextMenuClientImpl::stopSpeaking() {\n}\n\nbool ContextMenuClientImpl::shouldIncludeInspectElementItem() {\n return false; \/\/ TODO(jackson): Eventually include the inspector context menu item\n}\n\n#if defined(OS_MACOSX)\nvoid ContextMenuClientImpl::searchWithSpotlight() {\n \/\/ TODO(pinkerton): write this\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n\n#include \"v8_helpers.h\"\n#include \"v8_npobject.h\"\n#include \"v8_np_utils.h\"\n#include \"np_v8object.h\"\n#include \"npruntime_priv.h\"\n#include \"v8_proxy.h\"\n#include \"dom_wrapper_map.h\"\n#include \"HTMLPlugInElement.h\"\n#include \"V8HTMLAppletElement.h\"\n#include \"V8HTMLEmbedElement.h\"\n#include \"V8HTMLObjectElement.h\"\n\nusing namespace WebCore;\n\nenum InvokeFunctionType {\n INVOKE_METHOD = 1,\n INVOKE_DEFAULT = 2\n};\n\n\/\/ TODO(mbelshe): need comments.\n\/\/ Params: holder could be HTMLEmbedElement or NPObject\nstatic v8::Handle NPObjectInvokeImpl(\n const v8::Arguments& args, InvokeFunctionType func_id) {\n NPObject* npobject;\n\n \/\/ These three types are subtypes of HTMLPlugInElement.\n if (V8HTMLAppletElement::HasInstance(args.Holder()) ||\n V8HTMLEmbedElement::HasInstance(args.Holder()) ||\n V8HTMLObjectElement::HasInstance(args.Holder())) {\n \/\/ The holder object is a subtype of HTMLPlugInElement.\n HTMLPlugInElement* imp =\n V8Proxy::DOMWrapperToNode(args.Holder());\n v8::Handle instance = imp->getInstance();\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, instance);\n\n } else {\n \/\/ The holder object is not a subtype of HTMLPlugInElement, it\n \/\/ must be an NPObject which has three internal fields.\n ASSERT(args.Holder()->InternalFieldCount() == 3);\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, args.Holder());\n }\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Undefined();\n }\n\n \/\/ wrap up parameters\n int argc = args.Length();\n NPVariant* np_args = new NPVariant[argc];\n\n for (int i = 0; i < argc; i++) {\n ConvertV8ObjectToNPVariant(args[i], npobject, &np_args[i]);\n }\n\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n\n switch (func_id) {\n case INVOKE_METHOD:\n if (npobject->_class->invoke) {\n v8::Handle function_name(v8::String::Cast(*args.Data()));\n NPIdentifier ident = GetStringIdentifier(function_name);\n npobject->_class->invoke(npobject, ident, np_args, argc, &result);\n }\n break;\n case INVOKE_DEFAULT:\n if (npobject->_class->invokeDefault) {\n npobject->_class->invokeDefault(npobject, np_args, argc, &result);\n }\n break;\n default:\n break;\n }\n\n for (int i=0; i < argc; i++) {\n NPN_ReleaseVariantValue(&np_args[i]);\n }\n delete[] np_args;\n\n \/\/ unwrap return values\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n\n return rv;\n}\n\n\nv8::Handle NPObjectMethodHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_METHOD);\n}\n\n\nv8::Handle NPObjectInvokeDefaultHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_DEFAULT);\n}\n\n\nstatic void WeakTemplateCallback(v8::Persistent obj, void* param);\n\n\/\/ NPIdentifier is PrivateIdentifier*.\nstatic WeakReferenceMap \\\n static_template_map(&WeakTemplateCallback);\n\nstatic void WeakTemplateCallback(v8::Persistent obj,\n void* param) {\n PrivateIdentifier* iden = static_cast(param);\n ASSERT(iden != NULL);\n ASSERT(static_template_map.contains(iden));\n\n static_template_map.forget(iden);\n}\n\n\nstatic v8::Handle NPObjectGetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local key) {\n NPObject* npobject = V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT,\n self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Handle();\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->getProperty) {\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n if (!npobject->_class->getProperty(npobject, ident, &result)) {\n return v8::Handle();\n }\n\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n return rv;\n\n } else if (key->IsString() &&\n npobject->_class->hasMethod &&\n npobject->_class->hasMethod(npobject, ident)) {\n PrivateIdentifier* id = static_cast(ident);\n v8::Persistent desc = static_template_map.get(id);\n \/\/ Cache templates using identifier as the key.\n if (desc.IsEmpty()) {\n \/\/ Create a new template\n v8::Local temp = v8::FunctionTemplate::New();\n temp->SetCallHandler(NPObjectMethodHandler, key);\n desc = v8::Persistent::New(temp);\n static_template_map.set(id, desc);\n }\n\n \/\/ FunctionTemplate caches function for each context.\n v8::Local func = desc->GetFunction();\n func->SetName(v8::Handle::Cast(key));\n return func;\n }\n\n return v8::Handle();\n}\n\nv8::Handle NPObjectNamedPropertyGetter(v8::Local name,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(info.Holder(), ident, name);\n}\n\nv8::Handle NPObjectIndexedPropertyGetter(uint32_t index,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(info.Holder(), ident, v8::Number::New(index));\n}\n\nv8::Handle NPObjectGetNamedProperty(v8::Local self,\n v8::Local name) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(self, ident, name);\n}\n\nv8::Handle NPObjectGetIndexedProperty(v8::Local self,\n uint32_t index) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(self, ident, v8::Number::New(index));\n}\n\nstatic v8::Handle NPObjectSetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local value) {\n NPObject* npobject =\n V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT, self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return value; \/\/ intercepted, but an exception was thrown\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->setProperty) {\n NPVariant npvalue;\n VOID_TO_NPVARIANT(npvalue);\n ConvertV8ObjectToNPVariant(value, npobject, &npvalue);\n bool succ = npobject->_class->setProperty(npobject, ident, &npvalue);\n NPN_ReleaseVariantValue(&npvalue);\n if (succ) return value; \/\/ intercept the call\n }\n return v8::Local(); \/\/ do not intercept the call\n}\n\n\nv8::Handle NPObjectNamedPropertySetter(v8::Local name,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\n\nv8::Handle NPObjectIndexedPropertySetter(uint32_t index,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\nv8::Handle NPObjectSetNamedProperty(v8::Local self,\n v8::Local name,\n v8::Local value) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(self, ident, value);\n}\n\nv8::Handle NPObjectSetIndexedProperty(v8::Local self,\n uint32_t index,\n v8::Local value) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(self, ident, value);\n}\n\n\nstatic void WeakNPObjectCallback(v8::Persistent obj, void* param);\n\nstatic DOMWrapperMap static_npobject_map(&WeakNPObjectCallback);\n\nstatic void WeakNPObjectCallback(v8::Persistent obj,\n void* param) {\n NPObject* npobject = static_cast(param);\n ASSERT(static_npobject_map.contains(npobject));\n ASSERT(npobject != NULL);\n\n \/\/ Must remove from our map before calling NPN_ReleaseObject().\n \/\/ NPN_ReleaseObject can call ForgetV8ObjectForNPObject, which\n \/\/ uses the table as well.\n static_npobject_map.forget(npobject);\n\n if (_NPN_IsAlive(npobject))\n NPN_ReleaseObject(npobject);\n}\n\n\nv8::Local CreateV8ObjectForNPObject(NPObject* object,\n NPObject* root) {\n static v8::Persistent np_object_desc;\n\n ASSERT(v8::Context::InContext());\n\n \/\/ If this is a v8 object, just return it.\n if (object->_class == NPScriptObjectClass) {\n V8NPObject* v8npobject = reinterpret_cast(object);\n return v8::Local::New(v8npobject->v8_object);\n }\n\n \/\/ If we've already wrapped this object, just return it.\n if (static_npobject_map.contains(object))\n return v8::Local::New(static_npobject_map.get(object));\n\n \/\/ TODO: we should create a Wrapper type as a subclass of JSObject.\n \/\/ It has two internal fields, field 0 is the wrapped pointer,\n \/\/ and field 1 is the type. There should be an api function that\n \/\/ returns unused type id.\n \/\/ The same Wrapper type can be used by DOM bindings.\n if (np_object_desc.IsEmpty()) {\n np_object_desc =\n v8::Persistent::New(v8::FunctionTemplate::New());\n np_object_desc->InstanceTemplate()->SetInternalFieldCount(3);\n np_object_desc->InstanceTemplate()->SetNamedPropertyHandler(\n NPObjectNamedPropertyGetter, NPObjectNamedPropertySetter);\n np_object_desc->InstanceTemplate()->SetIndexedPropertyHandler(\n NPObjectIndexedPropertyGetter, NPObjectIndexedPropertySetter);\n np_object_desc->InstanceTemplate()->SetCallAsFunctionHandler(\n NPObjectInvokeDefaultHandler); \n }\n\n v8::Handle func = np_object_desc->GetFunction();\n v8::Local value = SafeAllocation::NewInstance(func);\n \n \/\/ If we were unable to allocate the instance we avoid wrapping \n \/\/ and registering the NP object. \n if (value.IsEmpty()) \n return value;\n\n WrapNPObject(value, object);\n\n \/\/ KJS retains the object as part of its wrapper (see Bindings::CInstance)\n NPN_RetainObject(object);\n\n _NPN_RegisterObject(object, root);\n\n \/\/ Maintain a weak pointer for v8 so we can cleanup the object.\n v8::Persistent weak_ref = v8::Persistent::New(value);\n static_npobject_map.set(object, weak_ref);\n\n return value;\n}\n\nvoid ForgetV8ObjectForNPObject(NPObject* object) {\n if (static_npobject_map.contains(object)) {\n v8::HandleScope scope;\n v8::Persistent handle(static_npobject_map.get(object));\n WebCore::V8Proxy::SetDOMWrapper(handle,\n WebCore::V8ClassIndex::NPOBJECT, NULL);\n static_npobject_map.forget(object);\n NPN_ReleaseObject(object);\n }\n}\nFix a renderer crashing bug with NPObject method references. http:\/\/www.corp.google.com\/~michaeln\/flash_crash\/crash.html\/\/ Copyright (c) 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n\n#include \"v8_helpers.h\"\n#include \"v8_npobject.h\"\n#include \"v8_np_utils.h\"\n#include \"np_v8object.h\"\n#include \"npruntime_priv.h\"\n#include \"v8_proxy.h\"\n#include \"dom_wrapper_map.h\"\n#include \"HTMLPlugInElement.h\"\n#include \"V8HTMLAppletElement.h\"\n#include \"V8HTMLEmbedElement.h\"\n#include \"V8HTMLObjectElement.h\"\n\nusing namespace WebCore;\n\nenum InvokeFunctionType {\n INVOKE_METHOD = 1,\n INVOKE_DEFAULT = 2\n};\n\n\/\/ TODO(mbelshe): need comments.\n\/\/ Params: holder could be HTMLEmbedElement or NPObject\nstatic v8::Handle NPObjectInvokeImpl(\n const v8::Arguments& args, InvokeFunctionType func_id) {\n NPObject* npobject;\n\n \/\/ These three types are subtypes of HTMLPlugInElement.\n if (V8HTMLAppletElement::HasInstance(args.Holder()) ||\n V8HTMLEmbedElement::HasInstance(args.Holder()) ||\n V8HTMLObjectElement::HasInstance(args.Holder())) {\n \/\/ The holder object is a subtype of HTMLPlugInElement.\n HTMLPlugInElement* imp =\n V8Proxy::DOMWrapperToNode(args.Holder());\n v8::Handle instance = imp->getInstance();\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, instance);\n\n } else {\n \/\/ The holder object is not a subtype of HTMLPlugInElement, it\n \/\/ must be an NPObject which has three internal fields.\n if (args.Holder()->InternalFieldCount() != 3) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR,\n \"NPMethod called on non-NPObject\");\n return v8::Undefined();\n }\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, args.Holder());\n }\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Undefined();\n }\n\n \/\/ wrap up parameters\n int argc = args.Length();\n NPVariant* np_args = new NPVariant[argc];\n\n for (int i = 0; i < argc; i++) {\n ConvertV8ObjectToNPVariant(args[i], npobject, &np_args[i]);\n }\n\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n\n switch (func_id) {\n case INVOKE_METHOD:\n if (npobject->_class->invoke) {\n v8::Handle function_name(v8::String::Cast(*args.Data()));\n NPIdentifier ident = GetStringIdentifier(function_name);\n npobject->_class->invoke(npobject, ident, np_args, argc, &result);\n }\n break;\n case INVOKE_DEFAULT:\n if (npobject->_class->invokeDefault) {\n npobject->_class->invokeDefault(npobject, np_args, argc, &result);\n }\n break;\n default:\n break;\n }\n\n for (int i=0; i < argc; i++) {\n NPN_ReleaseVariantValue(&np_args[i]);\n }\n delete[] np_args;\n\n \/\/ unwrap return values\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n\n return rv;\n}\n\n\nv8::Handle NPObjectMethodHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_METHOD);\n}\n\n\nv8::Handle NPObjectInvokeDefaultHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_DEFAULT);\n}\n\n\nstatic void WeakTemplateCallback(v8::Persistent obj, void* param);\n\n\/\/ NPIdentifier is PrivateIdentifier*.\nstatic WeakReferenceMap \\\n static_template_map(&WeakTemplateCallback);\n\nstatic void WeakTemplateCallback(v8::Persistent obj,\n void* param) {\n PrivateIdentifier* iden = static_cast(param);\n ASSERT(iden != NULL);\n ASSERT(static_template_map.contains(iden));\n\n static_template_map.forget(iden);\n}\n\n\nstatic v8::Handle NPObjectGetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local key) {\n NPObject* npobject = V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT,\n self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Handle();\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->getProperty) {\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n if (!npobject->_class->getProperty(npobject, ident, &result)) {\n return v8::Handle();\n }\n\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n return rv;\n\n } else if (key->IsString() &&\n npobject->_class->hasMethod &&\n npobject->_class->hasMethod(npobject, ident)) {\n PrivateIdentifier* id = static_cast(ident);\n v8::Persistent desc = static_template_map.get(id);\n \/\/ Cache templates using identifier as the key.\n if (desc.IsEmpty()) {\n \/\/ Create a new template\n v8::Local temp = v8::FunctionTemplate::New();\n temp->SetCallHandler(NPObjectMethodHandler, key);\n desc = v8::Persistent::New(temp);\n static_template_map.set(id, desc);\n }\n\n \/\/ FunctionTemplate caches function for each context.\n v8::Local func = desc->GetFunction();\n func->SetName(v8::Handle::Cast(key));\n return func;\n }\n\n return v8::Handle();\n}\n\nv8::Handle NPObjectNamedPropertyGetter(v8::Local name,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(info.Holder(), ident, name);\n}\n\nv8::Handle NPObjectIndexedPropertyGetter(uint32_t index,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(info.Holder(), ident, v8::Number::New(index));\n}\n\nv8::Handle NPObjectGetNamedProperty(v8::Local self,\n v8::Local name) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(self, ident, name);\n}\n\nv8::Handle NPObjectGetIndexedProperty(v8::Local self,\n uint32_t index) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(self, ident, v8::Number::New(index));\n}\n\nstatic v8::Handle NPObjectSetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local value) {\n NPObject* npobject =\n V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT, self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return value; \/\/ intercepted, but an exception was thrown\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->setProperty) {\n NPVariant npvalue;\n VOID_TO_NPVARIANT(npvalue);\n ConvertV8ObjectToNPVariant(value, npobject, &npvalue);\n bool succ = npobject->_class->setProperty(npobject, ident, &npvalue);\n NPN_ReleaseVariantValue(&npvalue);\n if (succ) return value; \/\/ intercept the call\n }\n return v8::Local(); \/\/ do not intercept the call\n}\n\n\nv8::Handle NPObjectNamedPropertySetter(v8::Local name,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\n\nv8::Handle NPObjectIndexedPropertySetter(uint32_t index,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\nv8::Handle NPObjectSetNamedProperty(v8::Local self,\n v8::Local name,\n v8::Local value) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(self, ident, value);\n}\n\nv8::Handle NPObjectSetIndexedProperty(v8::Local self,\n uint32_t index,\n v8::Local value) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(self, ident, value);\n}\n\n\nstatic void WeakNPObjectCallback(v8::Persistent obj, void* param);\n\nstatic DOMWrapperMap static_npobject_map(&WeakNPObjectCallback);\n\nstatic void WeakNPObjectCallback(v8::Persistent obj,\n void* param) {\n NPObject* npobject = static_cast(param);\n ASSERT(static_npobject_map.contains(npobject));\n ASSERT(npobject != NULL);\n\n \/\/ Must remove from our map before calling NPN_ReleaseObject().\n \/\/ NPN_ReleaseObject can call ForgetV8ObjectForNPObject, which\n \/\/ uses the table as well.\n static_npobject_map.forget(npobject);\n\n if (_NPN_IsAlive(npobject))\n NPN_ReleaseObject(npobject);\n}\n\n\nv8::Local CreateV8ObjectForNPObject(NPObject* object,\n NPObject* root) {\n static v8::Persistent np_object_desc;\n\n ASSERT(v8::Context::InContext());\n\n \/\/ If this is a v8 object, just return it.\n if (object->_class == NPScriptObjectClass) {\n V8NPObject* v8npobject = reinterpret_cast(object);\n return v8::Local::New(v8npobject->v8_object);\n }\n\n \/\/ If we've already wrapped this object, just return it.\n if (static_npobject_map.contains(object))\n return v8::Local::New(static_npobject_map.get(object));\n\n \/\/ TODO: we should create a Wrapper type as a subclass of JSObject.\n \/\/ It has two internal fields, field 0 is the wrapped pointer,\n \/\/ and field 1 is the type. There should be an api function that\n \/\/ returns unused type id.\n \/\/ The same Wrapper type can be used by DOM bindings.\n if (np_object_desc.IsEmpty()) {\n np_object_desc =\n v8::Persistent::New(v8::FunctionTemplate::New());\n np_object_desc->InstanceTemplate()->SetInternalFieldCount(3);\n np_object_desc->InstanceTemplate()->SetNamedPropertyHandler(\n NPObjectNamedPropertyGetter, NPObjectNamedPropertySetter);\n np_object_desc->InstanceTemplate()->SetIndexedPropertyHandler(\n NPObjectIndexedPropertyGetter, NPObjectIndexedPropertySetter);\n np_object_desc->InstanceTemplate()->SetCallAsFunctionHandler(\n NPObjectInvokeDefaultHandler); \n }\n\n v8::Handle func = np_object_desc->GetFunction();\n v8::Local value = SafeAllocation::NewInstance(func);\n \n \/\/ If we were unable to allocate the instance we avoid wrapping \n \/\/ and registering the NP object. \n if (value.IsEmpty()) \n return value;\n\n WrapNPObject(value, object);\n\n \/\/ KJS retains the object as part of its wrapper (see Bindings::CInstance)\n NPN_RetainObject(object);\n\n _NPN_RegisterObject(object, root);\n\n \/\/ Maintain a weak pointer for v8 so we can cleanup the object.\n v8::Persistent weak_ref = v8::Persistent::New(value);\n static_npobject_map.set(object, weak_ref);\n\n return value;\n}\n\nvoid ForgetV8ObjectForNPObject(NPObject* object) {\n if (static_npobject_map.contains(object)) {\n v8::HandleScope scope;\n v8::Persistent handle(static_npobject_map.get(object));\n WebCore::V8Proxy::SetDOMWrapper(handle,\n WebCore::V8ClassIndex::NPOBJECT, NULL);\n static_npobject_map.forget(object);\n NPN_ReleaseObject(object);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2011, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing pcl::console::print_error;\nusing pcl::console::print_info;\nusing pcl::console::print_value;\n\nboost::mutex mutex_;\nboost::shared_ptr > grabber;\npcl::PointCloud::ConstPtr cloud_;\n\nvoid\nprintHelp (int, char **argv)\n{\n \/\/print_error (\"Syntax is: %s .pcd \\n\", argv[0]);\n print_error (\"Syntax is: %s \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -file file_name = PCD file to be read from\\n\");\n print_info (\" -dir directory_path = directory path to PCD file(s) to be read from\\n\");\n print_info (\" -fps frequency = frames per second\\n\");\n print_info (\" -repeat = optional parameter that tells wheter the PCD file(s) should be \\\"grabbed\\\" in a endless loop.\\n\");\n print_info (\"\\n\");\n print_info (\" -cam (*) = use given camera settings as initial view\\n\");\n print_info (stderr, \" (*) [Clipping Range \/ Focal Point \/ Position \/ ViewUp \/ Distance \/ Window Size \/ Window Pos] or use a that contains the same information.\\n\");\n}\n\n\/\/ Create the PCLVisualizer object\nboost::shared_ptr cloud_viewer;\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\nboost::shared_ptr img_viewer;\n#endif\n\nstd::vector fcolor_r, fcolor_b, fcolor_g;\nbool fcolorparam = false;\n\nstruct EventHelper\n{\n void \n cloud_cb (const pcl::PointCloud::ConstPtr & cloud)\n {\n if (mutex_.try_lock ())\n {\n cloud_ = cloud;\n mutex_.unlock ();\n }\n }\n};\n\nvoid \nkeyboard_callback (const pcl::visualization::KeyboardEvent& event, void*)\n{\n \/\/\/ If SPACE is pressed, trigger new cloud callback (only works if framerate is set to 0)\n if (event.getKeyCode() == ' ' && grabber)\n grabber->trigger ();\n}\n\nvoid \nmouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)\n{\n std::string* message = static_cast (cookie);\n if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton)\n {\n cout << (*message) << \" :: \" << mouse_event.getX () << \" , \" << mouse_event.getY () << endl;\n }\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n srand (unsigned (time (0)));\n\n if (argc > 1)\n {\n for (int i = 1; i < argc; i++)\n {\n if (std::string (argv[i]) == \"-h\")\n {\n printHelp (argc, argv);\n return (-1);\n }\n }\n }\n\n \/\/ Command line parsing\n double bcolor[3] = {0, 0, 0};\n pcl::console::parse_3x_arguments (argc, argv, \"-bc\", bcolor[0], bcolor[1], bcolor[2]);\n\n fcolorparam = pcl::console::parse_multiple_3x_arguments (argc, argv, \"-fc\", fcolor_r, fcolor_g, fcolor_b);\n\n int psize = 0;\n pcl::console::parse_argument (argc, argv, \"-ps\", psize);\n\n double opaque;\n pcl::console::parse_argument (argc, argv, \"-opaque\", opaque);\n\n cloud_viewer.reset (new pcl::visualization::PCLVisualizer (argc, argv, \"PCD viewer\"));\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer.reset (new pcl::visualization::ImageViewer (\"OpenNI Viewer\"));\n#endif\n\n \/\/ \/\/ Change the cloud rendered point size\n \/\/ if (psize > 0)\n \/\/ p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, \"OpenNICloud\");\n \/\/\n \/\/ \/\/ Change the cloud rendered opacity\n \/\/ if (opaque >= 0)\n \/\/ p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opaque, \"OpenNICloud\");\n\n cloud_viewer->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);\n\n \/\/ Read axes settings\n double axes = 0.0;\n pcl::console::parse_argument (argc, argv, \"-ax\", axes);\n if (axes != 0.0 && cloud_viewer)\n {\n float ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;\n pcl::console::parse_3x_arguments (argc, argv, \"-ax_pos\", ax_x, ax_y, ax_z, false);\n \/\/ Draw XYZ axes if command-line enabled\n cloud_viewer->addCoordinateSystem (axes, ax_x, ax_y, ax_z);\n }\n\n float frames_per_second = 0; \/\/ 0 means only if triggered!\n pcl::console::parse (argc, argv, \"-fps\", frames_per_second);\n if (frames_per_second < 0)\n frames_per_second = 0.0;\n\n bool repeat = (pcl::console::find_argument (argc, argv, \"-repeat\") != -1);\n\n std::cout << \"fps: \" << frames_per_second << \" , repeat: \" << repeat << std::endl;\n std::string path = \"\";\n pcl::console::parse_argument (argc, argv, \"-file\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && boost::filesystem::exists (path))\n {\n grabber.reset (new pcl::PCDGrabber (path, frames_per_second, repeat));\n }\n else\n {\n std::vector pcd_files;\n pcl::console::parse_argument (argc, argv, \"-dir\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && boost::filesystem::exists (path))\n {\n boost::filesystem::directory_iterator end_itr;\n for (boost::filesystem::directory_iterator itr (path); itr != end_itr; ++itr)\n {\n#if BOOST_FILESYSTEM_VERSION == 3\n if (!is_directory (itr->status ()) && boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->path ())) == \".PCD\" )\n#else\n if (!is_directory (itr->status ()) && boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->leaf ())) == \".PCD\" )\n#endif\n {\n#if BOOST_FILESYSTEM_VERSION == 3\n pcd_files.push_back (itr->path ().string ());\n std::cout << \"added: \" << itr->path ().string () << std::endl;\n#else\n pcd_files.push_back (itr->path ());\n std::cout << \"added: \" << itr->path () << std::endl;\n#endif\n }\n }\n }\n else\n {\n std::cout << \"Neither a pcd file given using the \\\"-file\\\" option, nor given a directory containing pcd files using the \\\"-dir\\\" option.\" << std::endl;\n }\n\n \/\/ Sort the read files by name\n sort (pcd_files.begin (), pcd_files.end ());\n grabber.reset (new pcl::PCDGrabber (pcd_files, frames_per_second, repeat));\n }\n\n EventHelper h;\n boost::function::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);\n boost::signals2::connection c1 = grabber->registerCallback (f);\n\n std::string mouse_msg_3D (\"Mouse coordinates in PCL Visualizer\");\n std::string key_msg_3D (\"Key event for PCL Visualizer\");\n\n cloud_viewer->registerMouseCallback (&mouse_callback, static_cast (&mouse_msg_3D));\n cloud_viewer->registerKeyboardCallback(&keyboard_callback, static_cast (&key_msg_3D));\n\n std::string mouse_msg_2D (\"Mouse coordinates in image viewer\");\n std::string key_msg_2D (\"Key event for image viewer\");\n\n img_viewer->registerMouseCallback (&mouse_callback, static_cast (&mouse_msg_2D));\n img_viewer->registerKeyboardCallback(&keyboard_callback, static_cast (&key_msg_2D));\n\n grabber->start ();\n while (!cloud_viewer->wasStopped ())\n {\n cloud_viewer->spinOnce ();\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer->spinOnce ();\n#endif\n\n if (!cloud_)\n {\n boost::this_thread::sleep(boost::posix_time::microseconds(10000));\n continue;\n }\n\n if (mutex_.try_lock ())\n {\n pcl::PointCloud::ConstPtr temp_cloud;\n temp_cloud.swap (cloud_);\n mutex_.unlock ();\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer->showRGBImage (*temp_cloud);\n#endif\n\n if (!cloud_viewer->updatePointCloud (temp_cloud, \"PCDCloud\"))\n {\n cloud_viewer->addPointCloud (temp_cloud, \"PCDCloud\");\n cloud_viewer->resetCameraViewpoint (\"PCDCloud\");\n }\n }\n }\n\n grabber->stop ();\n}\n\/* ]--- *\/\nfixes for 1.x\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2011, Willow Garage, Inc.\n * Copyright (c) 2012-, Open Perception, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing pcl::console::print_error;\nusing pcl::console::print_info;\nusing pcl::console::print_value;\n\nboost::mutex mutex_;\nboost::shared_ptr > grabber;\npcl::PointCloud::ConstPtr cloud_;\n\nvoid\nprintHelp (int, char **argv)\n{\n \/\/print_error (\"Syntax is: %s .pcd \\n\", argv[0]);\n print_error (\"Syntax is: %s \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -file file_name = PCD file to be read from\\n\");\n print_info (\" -dir directory_path = directory path to PCD file(s) to be read from\\n\");\n print_info (\" -fps frequency = frames per second\\n\");\n print_info (\" -repeat = optional parameter that tells wheter the PCD file(s) should be \\\"grabbed\\\" in a endless loop.\\n\");\n print_info (\"\\n\");\n print_info (\" -cam (*) = use given camera settings as initial view\\n\");\n print_info (stderr, \" (*) [Clipping Range \/ Focal Point \/ Position \/ ViewUp \/ Distance \/ Window Size \/ Window Pos] or use a that contains the same information.\\n\");\n}\n\n\/\/ Create the PCLVisualizer object\nboost::shared_ptr cloud_viewer;\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\nboost::shared_ptr img_viewer;\n#endif\n\nstd::vector fcolor_r, fcolor_b, fcolor_g;\nbool fcolorparam = false;\n\nstruct EventHelper\n{\n void \n cloud_cb (const pcl::PointCloud::ConstPtr & cloud)\n {\n if (mutex_.try_lock ())\n {\n cloud_ = cloud;\n mutex_.unlock ();\n }\n }\n};\n\nvoid \nkeyboard_callback (const pcl::visualization::KeyboardEvent& event, void*)\n{\n \/\/\/ If SPACE is pressed, trigger new cloud callback (only works if framerate is set to 0)\n if (event.getKeyCode() == ' ' && grabber)\n grabber->trigger ();\n}\n\nvoid \nmouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)\n{\n std::string* message = static_cast (cookie);\n if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton)\n {\n cout << (*message) << \" :: \" << mouse_event.getX () << \" , \" << mouse_event.getY () << endl;\n }\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n srand (unsigned (time (0)));\n\n if (argc > 1)\n {\n for (int i = 1; i < argc; i++)\n {\n if (std::string (argv[i]) == \"-h\")\n {\n printHelp (argc, argv);\n return (-1);\n }\n }\n }\n\n \/\/ Command line parsing\n double bcolor[3] = {0, 0, 0};\n pcl::console::parse_3x_arguments (argc, argv, \"-bc\", bcolor[0], bcolor[1], bcolor[2]);\n\n fcolorparam = pcl::console::parse_multiple_3x_arguments (argc, argv, \"-fc\", fcolor_r, fcolor_g, fcolor_b);\n\n int psize = 0;\n pcl::console::parse_argument (argc, argv, \"-ps\", psize);\n\n double opaque;\n pcl::console::parse_argument (argc, argv, \"-opaque\", opaque);\n\n cloud_viewer.reset (new pcl::visualization::PCLVisualizer (argc, argv, \"PCD viewer\"));\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer.reset (new pcl::visualization::ImageViewer (\"OpenNI Viewer\"));\n#endif\n\n \/\/ \/\/ Change the cloud rendered point size\n \/\/ if (psize > 0)\n \/\/ p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, psize, \"OpenNICloud\");\n \/\/\n \/\/ \/\/ Change the cloud rendered opacity\n \/\/ if (opaque >= 0)\n \/\/ p->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, opaque, \"OpenNICloud\");\n\n cloud_viewer->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);\n\n \/\/ Read axes settings\n double axes = 0.0;\n pcl::console::parse_argument (argc, argv, \"-ax\", axes);\n if (axes != 0.0 && cloud_viewer)\n {\n float ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;\n pcl::console::parse_3x_arguments (argc, argv, \"-ax_pos\", ax_x, ax_y, ax_z, false);\n \/\/ Draw XYZ axes if command-line enabled\n cloud_viewer->addCoordinateSystem (axes, ax_x, ax_y, ax_z);\n }\n\n float frames_per_second = 0; \/\/ 0 means only if triggered!\n pcl::console::parse (argc, argv, \"-fps\", frames_per_second);\n if (frames_per_second < 0)\n frames_per_second = 0.0;\n\n bool repeat = (pcl::console::find_argument (argc, argv, \"-repeat\") != -1);\n\n std::cout << \"fps: \" << frames_per_second << \" , repeat: \" << repeat << std::endl;\n std::string path = \"\";\n pcl::console::parse_argument (argc, argv, \"-file\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && boost::filesystem::exists (path))\n {\n grabber.reset (new pcl::PCDGrabber (path, frames_per_second, repeat));\n }\n else\n {\n std::vector pcd_files;\n pcl::console::parse_argument (argc, argv, \"-dir\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && boost::filesystem::exists (path))\n {\n boost::filesystem::directory_iterator end_itr;\n for (boost::filesystem::directory_iterator itr (path); itr != end_itr; ++itr)\n {\n#if BOOST_FILESYSTEM_VERSION == 3\n if (!is_directory (itr->status ()) && boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->path ())) == \".PCD\" )\n#else\n if (!is_directory (itr->status ()) && boost::algorithm::to_upper_copy (boost::filesystem::extension (itr->leaf ())) == \".PCD\" )\n#endif\n {\n#if BOOST_FILESYSTEM_VERSION == 3\n pcd_files.push_back (itr->path ().string ());\n std::cout << \"added: \" << itr->path ().string () << std::endl;\n#else\n pcd_files.push_back (itr->path ().string ());\n std::cout << \"added: \" << itr->path () << std::endl;\n#endif\n }\n }\n }\n else\n {\n std::cout << \"Neither a pcd file given using the \\\"-file\\\" option, nor given a directory containing pcd files using the \\\"-dir\\\" option.\" << std::endl;\n }\n\n \/\/ Sort the read files by name\n sort (pcd_files.begin (), pcd_files.end ());\n grabber.reset (new pcl::PCDGrabber (pcd_files, frames_per_second, repeat));\n }\n\n EventHelper h;\n boost::function::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);\n boost::signals2::connection c1 = grabber->registerCallback (f);\n\n std::string mouse_msg_3D (\"Mouse coordinates in PCL Visualizer\");\n std::string key_msg_3D (\"Key event for PCL Visualizer\");\n\n cloud_viewer->registerMouseCallback (&mouse_callback, static_cast (&mouse_msg_3D));\n cloud_viewer->registerKeyboardCallback(&keyboard_callback, static_cast (&key_msg_3D));\n\n std::string mouse_msg_2D (\"Mouse coordinates in image viewer\");\n std::string key_msg_2D (\"Key event for image viewer\");\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer->registerMouseCallback (&mouse_callback, static_cast (&mouse_msg_2D));\n img_viewer->registerKeyboardCallback(&keyboard_callback, static_cast (&key_msg_2D));\n#endif\n\n grabber->start ();\n while (!cloud_viewer->wasStopped ())\n {\n cloud_viewer->spinOnce ();\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer->spinOnce ();\n#endif\n\n if (!cloud_)\n {\n boost::this_thread::sleep(boost::posix_time::microseconds(10000));\n continue;\n }\n\n if (mutex_.try_lock ())\n {\n pcl::PointCloud::ConstPtr temp_cloud;\n temp_cloud.swap (cloud_);\n mutex_.unlock ();\n\n#if !((VTK_MAJOR_VERSION == 5)&&(VTK_MINOR_VERSION <= 4))\n img_viewer->showRGBImage (*temp_cloud);\n#endif\n\n if (!cloud_viewer->updatePointCloud (temp_cloud, \"PCDCloud\"))\n {\n cloud_viewer->addPointCloud (temp_cloud, \"PCDCloud\");\n cloud_viewer->resetCameraViewpoint (\"PCDCloud\");\n }\n }\n }\n\n grabber->stop ();\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Radu Bogdan rusu, Suat Gedikli\n *\n *\/\n\/\/ PCL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing terminal_tools::print_color;\nusing terminal_tools::print_error;\nusing terminal_tools::print_error;\nusing terminal_tools::print_warn;\nusing terminal_tools::print_info;\nusing terminal_tools::print_debug;\nusing terminal_tools::print_value;\nusing terminal_tools::print_highlight;\nusing terminal_tools::TT_BRIGHT;\nusing terminal_tools::TT_RED;\nusing terminal_tools::TT_GREEN;\nusing terminal_tools::TT_BLUE;\nusing namespace boost::filesystem;\n\ntypedef pcl_visualization::PointCloudColorHandler > ColorHandler;\ntypedef ColorHandler::Ptr ColorHandlerPtr;\ntypedef ColorHandler::ConstPtr ColorHandlerConstPtr;\n\ntypedef pcl_visualization::PointCloudGeometryHandler > GeometryHandler;\ntypedef GeometryHandler::Ptr GeometryHandlerPtr;\ntypedef GeometryHandler::ConstPtr GeometryHandlerConstPtr;\nboost::mutex mutex_;\n\n#define NORMALS_SCALE 0.01\n#define PC_SCALE 0.001\n\nvoid\nprintHelp (int argc, char **argv)\n{\n \/\/print_error (\"Syntax is: %s .pcd \\n\", argv[0]);\n print_error (\"Syntax is: %s \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -file file_name = PCD file to be read from\\n\");\n print_info (\" -dir directory_path = directory path to PCD file(s) to be read from\\n\");\n print_info (\" -fps frequency = frames per second\\n\");\n print_info (\" -repeat = optional parameter that tells wheter the PCD file(s) should be \\\"grabbed\\\" in a endless loop.\\n\");\n print_info (\" -bc r,g,b = background color\\n\");\n print_info (\" -fc r,g,b = foreground color\\n\");\n print_info (\" -ps X = point size (\");\n print_value (\"1..64\");\n print_info (\") \\n\");\n print_info (\" -opaque X = rendered point cloud opacity (\");\n print_value (\"0..1\");\n print_info (\")\\n\");\n\n print_info (\" -ax \");\n print_value (\"n\");\n print_info (\" = enable on-screen display of \");\n print_color (stdout, TT_BRIGHT, TT_RED, \"X\");\n print_color (stdout, TT_BRIGHT, TT_GREEN, \"Y\");\n print_color (stdout, TT_BRIGHT, TT_BLUE, \"Z\");\n print_info (\" axes and scale them to \");\n print_value (\"n\\n\");\n print_info (\" -ax_pos X,Y,Z = if axes are enabled, set their X,Y,Z position in space (default \");\n print_value (\"0,0,0\");\n print_info (\")\\n\");\n\n print_info (\"\\n\");\n print_info (\" -cam (*) = use given camera settings as initial view\\n\");\n print_info (stderr, \" (*) [Clipping Range \/ Focal Point \/ Position \/ ViewUp \/ Distance \/ Window Size \/ Window Pos] or use a that contains the same information.\\n\");\n\n print_info (\"\\n\");\n print_info (\" -multiview 0\/1 = enable\/disable auto-multi viewport rendering (default \");\n print_value (\"disabled\");\n print_info (\")\\n\");\n print_info (\"\\n\");\n\n print_info (\"\\n\");\n print_info (\" -normals 0\/X = disable\/enable the display of every Xth point's surface normal as lines (default \");\n print_value (\"disabled\");\n print_info (\")\\n\");\n print_info (\" -normals_scale X = resize the normal unit vector size to X (default \");\n print_value (\"0.02\");\n print_info (\")\\n\");\n print_info (\"\\n\");\n print_info (\" -pc 0\/X = disable\/enable the display of every Xth point's principal curvatures as lines (default \");\n print_value (\"disabled\");\n print_info (\")\\n\");\n print_info (\" -pc_scale X = resize the principal curvatures vectors size to X (default \");\n print_value (\"0.02\");\n print_info (\")\\n\");\n print_info (\"\\n\");\n\n print_info (\"\\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\\n\");\n}\n\n\/\/ Create the PCLVisualizer object\nboost::shared_ptr p;\nColorHandlerPtr color_handler;\nGeometryHandlerPtr geometry_handler;\nstd::vector fcolor_r, fcolor_b, fcolor_g;\nbool fcolorparam = false;\n\nstruct EventHelper\n{\n\n void cloud_cb (const pcl::PointCloud::ConstPtr & cloud)\n {\n \/\/std::cout << __PRETTY_FUNCTION__ << \" \" << cloud->width << std::endl;\n \/\/ Add the dataset with a XYZ and a random handler \n \/\/ geometry_handler.reset (new pcl_visualization::PointCloudGeometryHandlerXYZ > (*cloud));\n\n \/\/\/\/ If color was given, ues that\n \/\/if (fcolorparam)\n \/\/ color_handler.reset (new pcl_visualization::PointCloudColorHandlerCustom > (cloud, fcolor_r, fcolor_g, fcolor_b));\n \/\/else\n \/\/ color_handler.reset (new pcl_visualization::PointCloudColorHandlerRandom > (cloud));\n\n \/\/ Add the cloud to the renderer\n\n boost::mutex::scoped_lock lock (mutex_);\n if (!cloud)\n return;\n p->removePointCloud (\"PCDCloud\");\n p->addPointCloud (*cloud, \"PCDCloud\");\n }\n};\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n srand (time (0));\n\n if (argc > 1)\n {\n for (int i = 1; i < argc; i++)\n {\n if (std::string (argv[i]) == \"-h\")\n {\n printHelp (argc, argv);\n return (-1);\n }\n }\n }\n\n \/\/ Command line parsing\n double bcolor[3] = {0, 0, 0};\n terminal_tools::parse_3x_arguments (argc, argv, \"-bc\", bcolor[0], bcolor[1], bcolor[2]);\n\n fcolorparam = terminal_tools::parse_multiple_3x_arguments (argc, argv, \"-fc\", fcolor_r, fcolor_g, fcolor_b);\n\n int psize = 0;\n terminal_tools::parse_argument (argc, argv, \"-ps\", psize);\n\n double opaque;\n terminal_tools::parse_argument (argc, argv, \"-opaque\", opaque);\n\n p.reset (new pcl_visualization::PCLVisualizer (argc, argv, \"PCD viewer\"));\n\n \/\/ \/\/ Change the cloud rendered point size\n \/\/ if (psize > 0)\n \/\/ p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_POINT_SIZE, psize, \"KinectCloud\");\n \/\/\n \/\/ \/\/ Change the cloud rendered opacity\n \/\/ if (opaque >= 0)\n \/\/ p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_OPACITY, opaque, \"KinectCloud\");\n\n p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);\n\n\n\n \/\/boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1));\n \/\/boost::function >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1);\n \/\/boost::signals2::connection c =\n \/\/ interface->registerCallback >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).);\n\n \/\/ Read axes settings\n double axes = 0.0;\n terminal_tools::parse_argument (argc, argv, \"-ax\", axes);\n if (axes != 0.0 && p)\n {\n double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;\n terminal_tools::parse_3x_arguments (argc, argv, \"-ax_pos\", ax_x, ax_y, ax_z, false);\n \/\/ Draw XYZ axes if command-line enabled\n p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);\n }\n\n pcl::Grabber* interface = 0;\n\n float frames_per_second = 0; \/\/ 0 means only if triggered!\n terminal_tools::parse (argc, argv, \"-fps\", frames_per_second);\n if (frames_per_second < 0)\n frames_per_second = 0.0;\n\n std::cout << terminal_tools::find_argument (argc, argv, \"-repeat\") << \" : repaet\" << std::endl;\n bool repeat = (terminal_tools::find_argument (argc, argv, \"-repeat\") != -1);\n\n std::cout << \"fps: \" << frames_per_second << \" , repeat: \" << repeat << std::endl;\n std::string path = \"\";\n terminal_tools::parse_argument (argc, argv, \"-file\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && exists (path))\n {\n interface = new pcl::PCDGrabber (path, frames_per_second, repeat);\n }\n else\n {\n std::vector pcd_files;\n terminal_tools::parse_argument (argc, argv, \"-dir\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && exists (path))\n {\n directory_iterator end_itr;\n for (directory_iterator itr (path); itr != end_itr; ++itr)\n {\n if (!is_directory (itr->status()) && boost::algorithm::to_upper_copy(extension (itr->leaf())) == \".PCD\" )\n {\n pcd_files.push_back (itr->path ().string());\n std::cout << \"added: \" << itr->path ().string() << std::endl;\n }\n }\n }\n else\n {\n std::cout << \"Neither a pcd file given using the \\\"-file\\\" option, nor given a directory containing pcd files using the \\\"-dir\\\" option.\" << std::endl;\n }\n interface = new pcl::PCDGrabber (pcd_files, frames_per_second, repeat);\n }\n\n EventHelper h;\n boost::function::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);\n boost::signals2::connection c1 = interface->registerCallback (f);\n\n interface->start ();\n while (true)\n {\n usleep (10000);\n {\n boost::mutex::scoped_lock lock (mutex_);\n p->spinOnce ();\n if (p->wasStopped ())\n break;\n }\n }\n\n interface->stop ();\n}\n\/* ]--- *\/\nFix: force using boost::filesystem2 to fix bug 60 and 62 Note: gaurdians must be added to the line 287 to prevent using leaf methode \t\t\twhile BOOST_VERSION >= 104600\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Radu Bogdan rusu, Suat Gedikli\n *\n *\/\n\/\/ PCL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define BOOST_FILESYSTEM_VERSION 2\n#include \n#include \n\nusing terminal_tools::print_color;\nusing terminal_tools::print_error;\nusing terminal_tools::print_error;\nusing terminal_tools::print_warn;\nusing terminal_tools::print_info;\nusing terminal_tools::print_debug;\nusing terminal_tools::print_value;\nusing terminal_tools::print_highlight;\nusing terminal_tools::TT_BRIGHT;\nusing terminal_tools::TT_RED;\nusing terminal_tools::TT_GREEN;\nusing terminal_tools::TT_BLUE;\nusing namespace boost::filesystem;\n\ntypedef pcl_visualization::PointCloudColorHandler > ColorHandler;\ntypedef ColorHandler::Ptr ColorHandlerPtr;\ntypedef ColorHandler::ConstPtr ColorHandlerConstPtr;\n\ntypedef pcl_visualization::PointCloudGeometryHandler > GeometryHandler;\ntypedef GeometryHandler::Ptr GeometryHandlerPtr;\ntypedef GeometryHandler::ConstPtr GeometryHandlerConstPtr;\nboost::mutex mutex_;\n\n#define NORMALS_SCALE 0.01\n#define PC_SCALE 0.001\n\nvoid\nprintHelp (int argc, char **argv)\n{\n \/\/print_error (\"Syntax is: %s .pcd \\n\", argv[0]);\n print_error (\"Syntax is: %s \\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -file file_name = PCD file to be read from\\n\");\n print_info (\" -dir directory_path = directory path to PCD file(s) to be read from\\n\");\n print_info (\" -fps frequency = frames per second\\n\");\n print_info (\" -repeat = optional parameter that tells wheter the PCD file(s) should be \\\"grabbed\\\" in a endless loop.\\n\");\n print_info (\" -bc r,g,b = background color\\n\");\n print_info (\" -fc r,g,b = foreground color\\n\");\n print_info (\" -ps X = point size (\");\n print_value (\"1..64\");\n print_info (\") \\n\");\n print_info (\" -opaque X = rendered point cloud opacity (\");\n print_value (\"0..1\");\n print_info (\")\\n\");\n\n print_info (\" -ax \");\n print_value (\"n\");\n print_info (\" = enable on-screen display of \");\n print_color (stdout, TT_BRIGHT, TT_RED, \"X\");\n print_color (stdout, TT_BRIGHT, TT_GREEN, \"Y\");\n print_color (stdout, TT_BRIGHT, TT_BLUE, \"Z\");\n print_info (\" axes and scale them to \");\n print_value (\"n\\n\");\n print_info (\" -ax_pos X,Y,Z = if axes are enabled, set their X,Y,Z position in space (default \");\n print_value (\"0,0,0\");\n print_info (\")\\n\");\n\n print_info (\"\\n\");\n print_info (\" -cam (*) = use given camera settings as initial view\\n\");\n print_info (stderr, \" (*) [Clipping Range \/ Focal Point \/ Position \/ ViewUp \/ Distance \/ Window Size \/ Window Pos] or use a that contains the same information.\\n\");\n\n print_info (\"\\n\");\n print_info (\" -multiview 0\/1 = enable\/disable auto-multi viewport rendering (default \");\n print_value (\"disabled\");\n print_info (\")\\n\");\n print_info (\"\\n\");\n\n print_info (\"\\n\");\n print_info (\" -normals 0\/X = disable\/enable the display of every Xth point's surface normal as lines (default \");\n print_value (\"disabled\");\n print_info (\")\\n\");\n print_info (\" -normals_scale X = resize the normal unit vector size to X (default \");\n print_value (\"0.02\");\n print_info (\")\\n\");\n print_info (\"\\n\");\n print_info (\" -pc 0\/X = disable\/enable the display of every Xth point's principal curvatures as lines (default \");\n print_value (\"disabled\");\n print_info (\")\\n\");\n print_info (\" -pc_scale X = resize the principal curvatures vectors size to X (default \");\n print_value (\"0.02\");\n print_info (\")\\n\");\n print_info (\"\\n\");\n\n print_info (\"\\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\\n\");\n}\n\n\/\/ Create the PCLVisualizer object\nboost::shared_ptr p;\nColorHandlerPtr color_handler;\nGeometryHandlerPtr geometry_handler;\nstd::vector fcolor_r, fcolor_b, fcolor_g;\nbool fcolorparam = false;\n\nstruct EventHelper\n{\n\n void cloud_cb (const pcl::PointCloud::ConstPtr & cloud)\n {\n \/\/std::cout << __PRETTY_FUNCTION__ << \" \" << cloud->width << std::endl;\n \/\/ Add the dataset with a XYZ and a random handler \n \/\/ geometry_handler.reset (new pcl_visualization::PointCloudGeometryHandlerXYZ > (*cloud));\n\n \/\/\/\/ If color was given, ues that\n \/\/if (fcolorparam)\n \/\/ color_handler.reset (new pcl_visualization::PointCloudColorHandlerCustom > (cloud, fcolor_r, fcolor_g, fcolor_b));\n \/\/else\n \/\/ color_handler.reset (new pcl_visualization::PointCloudColorHandlerRandom > (cloud));\n\n \/\/ Add the cloud to the renderer\n\n boost::mutex::scoped_lock lock (mutex_);\n if (!cloud)\n return;\n p->removePointCloud (\"PCDCloud\");\n p->addPointCloud (*cloud, \"PCDCloud\");\n }\n};\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n srand (time (0));\n\n if (argc > 1)\n {\n for (int i = 1; i < argc; i++)\n {\n if (std::string (argv[i]) == \"-h\")\n {\n printHelp (argc, argv);\n return (-1);\n }\n }\n }\n\n \/\/ Command line parsing\n double bcolor[3] = {0, 0, 0};\n terminal_tools::parse_3x_arguments (argc, argv, \"-bc\", bcolor[0], bcolor[1], bcolor[2]);\n\n fcolorparam = terminal_tools::parse_multiple_3x_arguments (argc, argv, \"-fc\", fcolor_r, fcolor_g, fcolor_b);\n\n int psize = 0;\n terminal_tools::parse_argument (argc, argv, \"-ps\", psize);\n\n double opaque;\n terminal_tools::parse_argument (argc, argv, \"-opaque\", opaque);\n\n p.reset (new pcl_visualization::PCLVisualizer (argc, argv, \"PCD viewer\"));\n\n \/\/ \/\/ Change the cloud rendered point size\n \/\/ if (psize > 0)\n \/\/ p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_POINT_SIZE, psize, \"KinectCloud\");\n \/\/\n \/\/ \/\/ Change the cloud rendered opacity\n \/\/ if (opaque >= 0)\n \/\/ p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_OPACITY, opaque, \"KinectCloud\");\n\n p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]);\n\n\n\n \/\/boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1));\n \/\/boost::function >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1);\n \/\/boost::signals2::connection c =\n \/\/ interface->registerCallback >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).);\n\n \/\/ Read axes settings\n double axes = 0.0;\n terminal_tools::parse_argument (argc, argv, \"-ax\", axes);\n if (axes != 0.0 && p)\n {\n double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0;\n terminal_tools::parse_3x_arguments (argc, argv, \"-ax_pos\", ax_x, ax_y, ax_z, false);\n \/\/ Draw XYZ axes if command-line enabled\n p->addCoordinateSystem (axes, ax_x, ax_y, ax_z);\n }\n\n pcl::Grabber* interface = 0;\n\n float frames_per_second = 0; \/\/ 0 means only if triggered!\n terminal_tools::parse (argc, argv, \"-fps\", frames_per_second);\n if (frames_per_second < 0)\n frames_per_second = 0.0;\n\n std::cout << terminal_tools::find_argument (argc, argv, \"-repeat\") << \" : repaet\" << std::endl;\n bool repeat = (terminal_tools::find_argument (argc, argv, \"-repeat\") != -1);\n\n std::cout << \"fps: \" << frames_per_second << \" , repeat: \" << repeat << std::endl;\n std::string path = \"\";\n terminal_tools::parse_argument (argc, argv, \"-file\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && exists (path))\n {\n interface = new pcl::PCDGrabber (path, frames_per_second, repeat);\n }\n else\n {\n std::vector pcd_files;\n terminal_tools::parse_argument (argc, argv, \"-dir\", path);\n std::cout << \"path: \" << path << std::endl;\n if (path != \"\" && exists (path))\n {\n directory_iterator end_itr;\n for (directory_iterator itr (path); itr != end_itr; ++itr)\n {\n if (!is_directory (itr->status()) && boost::algorithm::to_upper_copy(extension (itr->leaf())) == \".PCD\" )\n {\n pcd_files.push_back (itr->path ().string());\n std::cout << \"added: \" << itr->path ().string() << std::endl;\n }\n }\n }\n else\n {\n std::cout << \"Neither a pcd file given using the \\\"-file\\\" option, nor given a directory containing pcd files using the \\\"-dir\\\" option.\" << std::endl;\n }\n interface = new pcl::PCDGrabber (pcd_files, frames_per_second, repeat);\n }\n\n EventHelper h;\n boost::function::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);\n boost::signals2::connection c1 = interface->registerCallback (f);\n\n interface->start ();\n while (true)\n {\n usleep (10000);\n {\n boost::mutex::scoped_lock lock (mutex_);\n p->spinOnce ();\n if (p->wasStopped ())\n break;\n }\n }\n\n interface->stop ();\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n#include \n\nusing namespace osg;\n\nvoid DrawArrays::draw(State&, bool) const \n{\n glDrawArrays(_mode,_first,_count);\n}\n\nvoid DrawArrays::accept(PrimitiveFunctor& functor) const\n{\n functor.drawArrays(_mode,_first,_count);\n}\n\nvoid DrawArrays::accept(PrimitiveIndexFunctor& functor) const\n{\n functor.drawArrays(_mode,_first,_count);\n}\n\nvoid DrawArrayLengths::draw(State&, bool) const\n{\n GLint first = _first;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n glDrawArrays(_mode,first,*itr);\n first += *itr;\n }\n}\n\nvoid DrawArrayLengths::accept(PrimitiveFunctor& functor) const\n{\n GLint first = _first;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n functor.drawArrays(_mode,first,*itr);\n first += *itr;\n }\n}\n\nvoid DrawArrayLengths::accept(PrimitiveIndexFunctor& functor) const\n{\n GLint first = _first;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n functor.drawArrays(_mode,first,*itr);\n first += *itr;\n }\n}\n\nunsigned int DrawArrayLengths::getNumIndices() const\n{\n unsigned int count = 0;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n count += *itr;\n }\n return count;\n}\n\nDrawElementsUByte::~DrawElementsUByte()\n{\n for(unsigned int i=0;i<_vboList.size();++i)\n {\n if (_vboList[i] != 0)\n {\n BufferObject::deleteBufferObject(i,_vboList[i]);\n _vboList[i] = 0;\n }\n }\n}\n\nvoid DrawElementsUByte::draw(State& state, bool useVertexBufferObjects) const \n{\n if (useVertexBufferObjects)\n {\n const BufferObject::Extensions* extensions = BufferObject::getExtensions(state.getContextID(), true);\n\n GLuint& buffer = _vboList[state.getContextID()];\n if (!buffer)\n {\n extensions->glGenBuffers(1, &buffer);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n extensions->glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, size() * 1, &front(), GL_STATIC_DRAW_ARB);\n }\n else\n {\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n }\n \n glDrawElements(_mode, size(), GL_UNSIGNED_BYTE, 0);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n }\n else \n {\n glDrawElements(_mode, size(), GL_UNSIGNED_BYTE, &front());\n }\n}\n\nvoid DrawElementsUByte::accept(PrimitiveFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUByte::accept(PrimitiveIndexFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUByte::offsetIndices(int offset)\n{\n for(iterator itr=begin();\n itr!=end();\n ++itr)\n {\n *itr += offset;\n }\n}\n\n\nDrawElementsUShort::~DrawElementsUShort()\n{\n for(unsigned int i=0;i<_vboList.size();++i)\n {\n if (_vboList[i] != 0)\n {\n BufferObject::deleteBufferObject(i,_vboList[i]);\n _vboList[i] = 0;\n }\n }\n}\n\nvoid DrawElementsUShort::draw(State& state, bool useVertexBufferObjects) const \n{\n if (useVertexBufferObjects)\n {\n const BufferObject::Extensions* extensions = BufferObject::getExtensions(state.getContextID(), true);\n\n GLuint& buffer = _vboList[state.getContextID()];\n if (!buffer)\n {\n extensions->glGenBuffers(1, &buffer);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n extensions->glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, size() * 2, &front(), GL_STATIC_DRAW_ARB);\n }\n else\n {\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n }\n \n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n glDrawElements(_mode, size(), GL_UNSIGNED_SHORT, 0);\n }\n else \n {\n glDrawElements(_mode, size(), GL_UNSIGNED_SHORT, &front());\n }\n}\n\nvoid DrawElementsUShort::accept(PrimitiveFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUShort::accept(PrimitiveIndexFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUShort::offsetIndices(int offset)\n{\n for(iterator itr=begin();\n itr!=end();\n ++itr)\n {\n *itr += offset;\n }\n}\n\n\nDrawElementsUInt::~DrawElementsUInt()\n{\n for(unsigned int i=0;i<_vboList.size();++i)\n {\n if (_vboList[i] != 0)\n {\n BufferObject::deleteBufferObject(i,_vboList[i]);\n _vboList[i] = 0;\n }\n }\n}\n\nvoid DrawElementsUInt::draw(State& state, bool useVertexBufferObjects) const \n{\n if (useVertexBufferObjects)\n {\n const BufferObject::Extensions* extensions = BufferObject::getExtensions(state.getContextID(), true);\n\n GLuint& buffer = _vboList[state.getContextID()];\n if (!buffer)\n {\n extensions->glGenBuffers(1, &buffer);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n extensions->glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, size() * 4, &front(), GL_STATIC_DRAW_ARB);\n }\n else\n {\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n }\n \n glDrawElements(_mode, size(), GL_UNSIGNED_INT, 0);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n }\n else \n {\n glDrawElements(_mode, size(), GL_UNSIGNED_INT, &front());\n }\n}\n\nvoid DrawElementsUInt::accept(PrimitiveFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUInt::accept(PrimitiveIndexFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUInt::offsetIndices(int offset)\n{\n for(iterator itr=begin();\n itr!=end();\n ++itr)\n {\n *itr += offset;\n }\n}\nFixed position of glBindBuffer.\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n#include \n\nusing namespace osg;\n\nvoid DrawArrays::draw(State&, bool) const \n{\n glDrawArrays(_mode,_first,_count);\n}\n\nvoid DrawArrays::accept(PrimitiveFunctor& functor) const\n{\n functor.drawArrays(_mode,_first,_count);\n}\n\nvoid DrawArrays::accept(PrimitiveIndexFunctor& functor) const\n{\n functor.drawArrays(_mode,_first,_count);\n}\n\nvoid DrawArrayLengths::draw(State&, bool) const\n{\n GLint first = _first;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n glDrawArrays(_mode,first,*itr);\n first += *itr;\n }\n}\n\nvoid DrawArrayLengths::accept(PrimitiveFunctor& functor) const\n{\n GLint first = _first;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n functor.drawArrays(_mode,first,*itr);\n first += *itr;\n }\n}\n\nvoid DrawArrayLengths::accept(PrimitiveIndexFunctor& functor) const\n{\n GLint first = _first;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n functor.drawArrays(_mode,first,*itr);\n first += *itr;\n }\n}\n\nunsigned int DrawArrayLengths::getNumIndices() const\n{\n unsigned int count = 0;\n for(VectorSizei::const_iterator itr=begin();\n itr!=end();\n ++itr)\n {\n count += *itr;\n }\n return count;\n}\n\nDrawElementsUByte::~DrawElementsUByte()\n{\n for(unsigned int i=0;i<_vboList.size();++i)\n {\n if (_vboList[i] != 0)\n {\n BufferObject::deleteBufferObject(i,_vboList[i]);\n _vboList[i] = 0;\n }\n }\n}\n\nvoid DrawElementsUByte::draw(State& state, bool useVertexBufferObjects) const \n{\n if (useVertexBufferObjects)\n {\n const BufferObject::Extensions* extensions = BufferObject::getExtensions(state.getContextID(), true);\n\n GLuint& buffer = _vboList[state.getContextID()];\n if (!buffer)\n {\n extensions->glGenBuffers(1, &buffer);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n extensions->glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, size() * 1, &front(), GL_STATIC_DRAW_ARB);\n }\n else\n {\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n }\n \n glDrawElements(_mode, size(), GL_UNSIGNED_BYTE, 0);\n \n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n }\n else \n {\n glDrawElements(_mode, size(), GL_UNSIGNED_BYTE, &front());\n }\n}\n\nvoid DrawElementsUByte::accept(PrimitiveFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUByte::accept(PrimitiveIndexFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUByte::offsetIndices(int offset)\n{\n for(iterator itr=begin();\n itr!=end();\n ++itr)\n {\n *itr += offset;\n }\n}\n\n\nDrawElementsUShort::~DrawElementsUShort()\n{\n for(unsigned int i=0;i<_vboList.size();++i)\n {\n if (_vboList[i] != 0)\n {\n BufferObject::deleteBufferObject(i,_vboList[i]);\n _vboList[i] = 0;\n }\n }\n}\n\nvoid DrawElementsUShort::draw(State& state, bool useVertexBufferObjects) const \n{\n if (useVertexBufferObjects)\n {\n const BufferObject::Extensions* extensions = BufferObject::getExtensions(state.getContextID(), true);\n\n GLuint& buffer = _vboList[state.getContextID()];\n if (!buffer)\n {\n extensions->glGenBuffers(1, &buffer);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n extensions->glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, size() * 2, &front(), GL_STATIC_DRAW_ARB);\n }\n else\n {\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n }\n \n glDrawElements(_mode, size(), GL_UNSIGNED_SHORT, 0);\n\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n }\n else \n {\n glDrawElements(_mode, size(), GL_UNSIGNED_SHORT, &front());\n }\n}\n\nvoid DrawElementsUShort::accept(PrimitiveFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUShort::accept(PrimitiveIndexFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUShort::offsetIndices(int offset)\n{\n for(iterator itr=begin();\n itr!=end();\n ++itr)\n {\n *itr += offset;\n }\n}\n\n\nDrawElementsUInt::~DrawElementsUInt()\n{\n for(unsigned int i=0;i<_vboList.size();++i)\n {\n if (_vboList[i] != 0)\n {\n BufferObject::deleteBufferObject(i,_vboList[i]);\n _vboList[i] = 0;\n }\n }\n}\n\nvoid DrawElementsUInt::draw(State& state, bool useVertexBufferObjects) const \n{\n if (useVertexBufferObjects)\n {\n const BufferObject::Extensions* extensions = BufferObject::getExtensions(state.getContextID(), true);\n\n GLuint& buffer = _vboList[state.getContextID()];\n if (!buffer)\n {\n extensions->glGenBuffers(1, &buffer);\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n extensions->glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, size() * 4, &front(), GL_STATIC_DRAW_ARB);\n }\n else\n {\n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, buffer);\n }\n \n glDrawElements(_mode, size(), GL_UNSIGNED_INT, 0);\n \n extensions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n }\n else \n {\n glDrawElements(_mode, size(), GL_UNSIGNED_INT, &front());\n }\n}\n\nvoid DrawElementsUInt::accept(PrimitiveFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUInt::accept(PrimitiveIndexFunctor& functor) const\n{\n if (!empty()) functor.drawElements(_mode,size(),&front());\n}\n\nvoid DrawElementsUInt::offsetIndices(int offset)\n{\n for(iterator itr=begin();\n itr!=end();\n ++itr)\n {\n *itr += offset;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Floating Temple\n\/\/ Copyright 2015 Derek S. Snyder\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"python\/local_object_impl.h\"\n\n#include \"third_party\/Python-3.4.2\/Include\/Python.h\"\n\n#include \n#include \n#include \n\n#include \"base\/escape.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"include\/c++\/value.h\"\n#include \"python\/dict_local_object.h\"\n#include \"python\/false_local_object.h\"\n#include \"python\/get_serialized_object_type.h\"\n#include \"python\/interpreter_impl.h\"\n#include \"python\/list_local_object.h\"\n#include \"python\/long_local_object.h\"\n#include \"python\/make_value.h\"\n#include \"python\/method_context.h\"\n#include \"python\/none_local_object.h\"\n#include \"python\/proto\/serialization.pb.h\"\n#include \"python\/python_gil_lock.h\"\n#include \"python\/thread_substitution.h\"\n#include \"python\/true_local_object.h\"\n\nusing std::size_t;\nusing std::string;\nusing std::vector;\n\nnamespace floating_temple {\nnamespace python {\n\nLocalObjectImpl::LocalObjectImpl(PyObject* py_object)\n : py_object_(CHECK_NOTNULL(py_object)) {\n}\n\nLocalObjectImpl::~LocalObjectImpl() {\n PythonGilLock lock;\n Py_DECREF(py_object_);\n}\n\nsize_t LocalObjectImpl::Serialize(void* buffer, size_t buffer_size,\n SerializationContext* context) const {\n ObjectProto object_proto;\n PopulateObjectProto(&object_proto, context);\n\n const size_t byte_size = static_cast(object_proto.ByteSize());\n if (byte_size <= buffer_size) {\n object_proto.SerializeWithCachedSizesToArray(static_cast(buffer));\n }\n\n return byte_size;\n}\n\n#define CALL_TP_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->method)(py_object_), return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_TP_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_TP_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_NB_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_number != nullptr); \\\n CHECK(object_type->tp_as_number->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->tp_as_number->method)(py_object_), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_NB_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_number != nullptr); \\\n CHECK(object_type->tp_as_number->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_number->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_NB_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_number != nullptr); \\\n CHECK(object_type->tp_as_number->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_number->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_SQ_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_sequence != nullptr); \\\n CHECK(object_type->tp_as_sequence->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->tp_as_sequence->method)(py_object_), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_SQ_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_sequence != nullptr); \\\n CHECK(object_type->tp_as_sequence->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_sequence->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_SQ_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_sequence != nullptr); \\\n CHECK(object_type->tp_as_sequence->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_sequence->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_MP_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_mapping != nullptr); \\\n CHECK(object_type->tp_as_mapping->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->tp_as_mapping->method)(py_object_), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_MP_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_mapping != nullptr); \\\n CHECK(object_type->tp_as_mapping->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_mapping->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_MP_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_mapping != nullptr); \\\n CHECK(object_type->tp_as_mapping->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_mapping->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\nvoid LocalObjectImpl::InvokeMethod(Thread* thread,\n PeerObject* peer_object,\n const string& method_name,\n const vector& parameters,\n Value* return_value) {\n CHECK(thread != nullptr);\n CHECK(peer_object != nullptr);\n\n VLOG(3) << \"Invoke method on local object: \" << method_name;\n\n MethodContext method_context;\n ThreadSubstitution thread_substitution(InterpreterImpl::instance(), thread);\n\n PythonGilLock lock;\n\n const PyTypeObject* const object_type = Py_TYPE(py_object_);\n CHECK(object_type != nullptr);\n\n \/\/ TODO(dss): Consider using binary search instead of linear search to find\n \/\/ the method given its name.\n\n \/\/ TODO(dss): Fail gracefully if the peer passes the wrong number of\n \/\/ parameters, or the wrong types of parameters.\n\n CALL_TP_METHOD1(tp_getattr, char*);\n CALL_TP_METHOD2(tp_setattr, char*, PyObject*);\n CALL_TP_METHOD0(tp_repr);\n CALL_TP_METHOD0(tp_hash);\n CALL_TP_METHOD2(tp_call, PyObject*, PyObject*);\n CALL_TP_METHOD0(tp_str);\n CALL_TP_METHOD1(tp_getattro, PyObject*);\n CALL_TP_METHOD2(tp_setattro, PyObject*, PyObject*);\n CALL_TP_METHOD2(tp_richcompare, PyObject*, int);\n CALL_TP_METHOD0(tp_iter);\n CALL_TP_METHOD0(tp_iternext);\n CALL_TP_METHOD2(tp_descr_get, PyObject*, PyObject*);\n CALL_TP_METHOD2(tp_descr_set, PyObject*, PyObject*);\n CALL_TP_METHOD2(tp_init, PyObject*, PyObject*);\n\n CALL_NB_METHOD1(nb_add, PyObject*);\n CALL_NB_METHOD1(nb_subtract, PyObject*);\n CALL_NB_METHOD1(nb_multiply, PyObject*);\n CALL_NB_METHOD1(nb_remainder, PyObject*);\n CALL_NB_METHOD1(nb_divmod, PyObject*);\n CALL_NB_METHOD2(nb_power, PyObject*, PyObject*);\n CALL_NB_METHOD0(nb_negative);\n CALL_NB_METHOD0(nb_positive);\n CALL_NB_METHOD0(nb_absolute);\n CALL_NB_METHOD0(nb_bool);\n CALL_NB_METHOD0(nb_invert);\n CALL_NB_METHOD1(nb_lshift, PyObject*);\n CALL_NB_METHOD1(nb_rshift, PyObject*);\n CALL_NB_METHOD1(nb_and, PyObject*);\n CALL_NB_METHOD1(nb_xor, PyObject*);\n CALL_NB_METHOD1(nb_or, PyObject*);\n CALL_NB_METHOD0(nb_int);\n CALL_NB_METHOD0(nb_float);\n CALL_NB_METHOD1(nb_inplace_add, PyObject*);\n CALL_NB_METHOD1(nb_inplace_subtract, PyObject*);\n CALL_NB_METHOD1(nb_inplace_multiply, PyObject*);\n CALL_NB_METHOD1(nb_inplace_remainder, PyObject*);\n CALL_NB_METHOD2(nb_inplace_power, PyObject*, PyObject*);\n CALL_NB_METHOD1(nb_inplace_lshift, PyObject*);\n CALL_NB_METHOD1(nb_inplace_rshift, PyObject*);\n CALL_NB_METHOD1(nb_inplace_and, PyObject*);\n CALL_NB_METHOD1(nb_inplace_xor, PyObject*);\n CALL_NB_METHOD1(nb_inplace_or, PyObject*);\n CALL_NB_METHOD1(nb_floor_divide, PyObject*);\n CALL_NB_METHOD1(nb_true_divide, PyObject*);\n CALL_NB_METHOD1(nb_inplace_floor_divide, PyObject*);\n CALL_NB_METHOD1(nb_inplace_true_divide, PyObject*);\n CALL_NB_METHOD0(nb_index);\n\n CALL_SQ_METHOD0(sq_length);\n CALL_SQ_METHOD1(sq_concat, PyObject*);\n CALL_SQ_METHOD1(sq_repeat, Py_ssize_t);\n CALL_SQ_METHOD1(sq_item, Py_ssize_t);\n CALL_SQ_METHOD2(sq_ass_item, Py_ssize_t, PyObject*);\n CALL_SQ_METHOD1(sq_contains, PyObject*);\n CALL_SQ_METHOD1(sq_inplace_concat, PyObject*);\n CALL_SQ_METHOD1(sq_inplace_repeat, Py_ssize_t);\n\n CALL_MP_METHOD0(mp_length);\n CALL_MP_METHOD1(mp_subscript, PyObject*);\n CALL_MP_METHOD2(mp_ass_subscript, PyObject*, PyObject*);\n\n \/\/ TODO(dss): Fail gracefully if a remote peer sends an invalid method name.\n LOG(FATAL) << \"Unexpected method name \\\"\" << CEscape(method_name) << \"\\\"\";\n}\n\n#undef CALL_TP_METHOD0\n#undef CALL_TP_METHOD1\n#undef CALL_TP_METHOD2\n#undef CALL_NB_METHOD0\n#undef CALL_NB_METHOD1\n#undef CALL_NB_METHOD2\n#undef CALL_SQ_METHOD0\n#undef CALL_SQ_METHOD1\n#undef CALL_SQ_METHOD2\n#undef CALL_MP_METHOD0\n#undef CALL_MP_METHOD1\n#undef CALL_MP_METHOD2\n\n\/\/ static\nLocalObjectImpl* LocalObjectImpl::Deserialize(const void* buffer,\n size_t buffer_size,\n DeserializationContext* context) {\n CHECK(buffer != nullptr);\n\n ObjectProto object_proto;\n CHECK(object_proto.ParseFromArray(buffer, buffer_size));\n\n const ObjectProto::Type object_type = GetSerializedObjectType(object_proto);\n\n switch (object_type) {\n case ObjectProto::PY_NONE:\n return new NoneLocalObject();\n\n case ObjectProto::LONG:\n return LongLocalObject::ParseLongProto(object_proto.long_object());\n\n case ObjectProto::FALSE:\n return new FalseLocalObject();\n\n case ObjectProto::TRUE:\n return new TrueLocalObject();\n\n case ObjectProto::LIST:\n return ListLocalObject::ParseListProto(object_proto.list_object(),\n context);\n\n case ObjectProto::DICT:\n return DictLocalObject::ParseDictProto(object_proto.dict_object(),\n context);\n\n case ObjectProto::FLOAT:\n case ObjectProto::COMPLEX:\n case ObjectProto::BYTES:\n case ObjectProto::BYTE_ARRAY:\n case ObjectProto::UNICODE:\n case ObjectProto::TUPLE:\n case ObjectProto::SET:\n case ObjectProto::FROZEN_SET:\n case ObjectProto::UNSERIALIZABLE:\n LOG(FATAL) << \"Not yet implemented\";\n return nullptr;\n\n default:\n LOG(FATAL) << \"Unexpected object type: \" << static_cast(object_type);\n }\n\n return nullptr;\n}\n\n} \/\/ namespace python\n} \/\/ namespace floating_temple\nAdd more detailed debug log output for the case where a Python object can't be deserialized.\/\/ Floating Temple\n\/\/ Copyright 2015 Derek S. Snyder\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"python\/local_object_impl.h\"\n\n#include \"third_party\/Python-3.4.2\/Include\/Python.h\"\n\n#include \n#include \n#include \n\n#include \"base\/escape.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"include\/c++\/value.h\"\n#include \"python\/dict_local_object.h\"\n#include \"python\/false_local_object.h\"\n#include \"python\/get_serialized_object_type.h\"\n#include \"python\/interpreter_impl.h\"\n#include \"python\/list_local_object.h\"\n#include \"python\/long_local_object.h\"\n#include \"python\/make_value.h\"\n#include \"python\/method_context.h\"\n#include \"python\/none_local_object.h\"\n#include \"python\/proto\/serialization.pb.h\"\n#include \"python\/python_gil_lock.h\"\n#include \"python\/thread_substitution.h\"\n#include \"python\/true_local_object.h\"\n\nusing std::size_t;\nusing std::string;\nusing std::vector;\n\nnamespace floating_temple {\nnamespace python {\n\nLocalObjectImpl::LocalObjectImpl(PyObject* py_object)\n : py_object_(CHECK_NOTNULL(py_object)) {\n}\n\nLocalObjectImpl::~LocalObjectImpl() {\n PythonGilLock lock;\n Py_DECREF(py_object_);\n}\n\nsize_t LocalObjectImpl::Serialize(void* buffer, size_t buffer_size,\n SerializationContext* context) const {\n ObjectProto object_proto;\n PopulateObjectProto(&object_proto, context);\n\n const size_t byte_size = static_cast(object_proto.ByteSize());\n if (byte_size <= buffer_size) {\n object_proto.SerializeWithCachedSizesToArray(static_cast(buffer));\n }\n\n return byte_size;\n}\n\n#define CALL_TP_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->method)(py_object_), return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_TP_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_TP_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_NB_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_number != nullptr); \\\n CHECK(object_type->tp_as_number->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->tp_as_number->method)(py_object_), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_NB_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_number != nullptr); \\\n CHECK(object_type->tp_as_number->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_number->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_NB_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_number != nullptr); \\\n CHECK(object_type->tp_as_number->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_number->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_SQ_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_sequence != nullptr); \\\n CHECK(object_type->tp_as_sequence->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->tp_as_sequence->method)(py_object_), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_SQ_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_sequence != nullptr); \\\n CHECK(object_type->tp_as_sequence->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_sequence->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_SQ_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_sequence != nullptr); \\\n CHECK(object_type->tp_as_sequence->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_sequence->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_MP_METHOD0(method) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_mapping != nullptr); \\\n CHECK(object_type->tp_as_mapping->method != nullptr); \\\n CHECK_EQ(parameters.size(), 0u); \\\n MakeReturnValue((*object_type->tp_as_mapping->method)(py_object_), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_MP_METHOD1(method, param_type1) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_mapping != nullptr); \\\n CHECK(object_type->tp_as_mapping->method != nullptr); \\\n CHECK_EQ(parameters.size(), 1u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_mapping->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\n#define CALL_MP_METHOD2(method, param_type1, param_type2) \\\n do { \\\n if (method_name == #method) { \\\n CHECK(object_type->tp_as_mapping != nullptr); \\\n CHECK(object_type->tp_as_mapping->method != nullptr); \\\n CHECK_EQ(parameters.size(), 2u); \\\n MakeReturnValue( \\\n (*object_type->tp_as_mapping->method)( \\\n py_object_, \\\n ExtractValue(parameters[0], &method_context), \\\n ExtractValue(parameters[1], &method_context)), \\\n return_value); \\\n return; \\\n } \\\n } while (false)\n\nvoid LocalObjectImpl::InvokeMethod(Thread* thread,\n PeerObject* peer_object,\n const string& method_name,\n const vector& parameters,\n Value* return_value) {\n CHECK(thread != nullptr);\n CHECK(peer_object != nullptr);\n\n VLOG(3) << \"Invoke method on local object: \" << method_name;\n\n MethodContext method_context;\n ThreadSubstitution thread_substitution(InterpreterImpl::instance(), thread);\n\n PythonGilLock lock;\n\n const PyTypeObject* const object_type = Py_TYPE(py_object_);\n CHECK(object_type != nullptr);\n\n \/\/ TODO(dss): Consider using binary search instead of linear search to find\n \/\/ the method given its name.\n\n \/\/ TODO(dss): Fail gracefully if the peer passes the wrong number of\n \/\/ parameters, or the wrong types of parameters.\n\n CALL_TP_METHOD1(tp_getattr, char*);\n CALL_TP_METHOD2(tp_setattr, char*, PyObject*);\n CALL_TP_METHOD0(tp_repr);\n CALL_TP_METHOD0(tp_hash);\n CALL_TP_METHOD2(tp_call, PyObject*, PyObject*);\n CALL_TP_METHOD0(tp_str);\n CALL_TP_METHOD1(tp_getattro, PyObject*);\n CALL_TP_METHOD2(tp_setattro, PyObject*, PyObject*);\n CALL_TP_METHOD2(tp_richcompare, PyObject*, int);\n CALL_TP_METHOD0(tp_iter);\n CALL_TP_METHOD0(tp_iternext);\n CALL_TP_METHOD2(tp_descr_get, PyObject*, PyObject*);\n CALL_TP_METHOD2(tp_descr_set, PyObject*, PyObject*);\n CALL_TP_METHOD2(tp_init, PyObject*, PyObject*);\n\n CALL_NB_METHOD1(nb_add, PyObject*);\n CALL_NB_METHOD1(nb_subtract, PyObject*);\n CALL_NB_METHOD1(nb_multiply, PyObject*);\n CALL_NB_METHOD1(nb_remainder, PyObject*);\n CALL_NB_METHOD1(nb_divmod, PyObject*);\n CALL_NB_METHOD2(nb_power, PyObject*, PyObject*);\n CALL_NB_METHOD0(nb_negative);\n CALL_NB_METHOD0(nb_positive);\n CALL_NB_METHOD0(nb_absolute);\n CALL_NB_METHOD0(nb_bool);\n CALL_NB_METHOD0(nb_invert);\n CALL_NB_METHOD1(nb_lshift, PyObject*);\n CALL_NB_METHOD1(nb_rshift, PyObject*);\n CALL_NB_METHOD1(nb_and, PyObject*);\n CALL_NB_METHOD1(nb_xor, PyObject*);\n CALL_NB_METHOD1(nb_or, PyObject*);\n CALL_NB_METHOD0(nb_int);\n CALL_NB_METHOD0(nb_float);\n CALL_NB_METHOD1(nb_inplace_add, PyObject*);\n CALL_NB_METHOD1(nb_inplace_subtract, PyObject*);\n CALL_NB_METHOD1(nb_inplace_multiply, PyObject*);\n CALL_NB_METHOD1(nb_inplace_remainder, PyObject*);\n CALL_NB_METHOD2(nb_inplace_power, PyObject*, PyObject*);\n CALL_NB_METHOD1(nb_inplace_lshift, PyObject*);\n CALL_NB_METHOD1(nb_inplace_rshift, PyObject*);\n CALL_NB_METHOD1(nb_inplace_and, PyObject*);\n CALL_NB_METHOD1(nb_inplace_xor, PyObject*);\n CALL_NB_METHOD1(nb_inplace_or, PyObject*);\n CALL_NB_METHOD1(nb_floor_divide, PyObject*);\n CALL_NB_METHOD1(nb_true_divide, PyObject*);\n CALL_NB_METHOD1(nb_inplace_floor_divide, PyObject*);\n CALL_NB_METHOD1(nb_inplace_true_divide, PyObject*);\n CALL_NB_METHOD0(nb_index);\n\n CALL_SQ_METHOD0(sq_length);\n CALL_SQ_METHOD1(sq_concat, PyObject*);\n CALL_SQ_METHOD1(sq_repeat, Py_ssize_t);\n CALL_SQ_METHOD1(sq_item, Py_ssize_t);\n CALL_SQ_METHOD2(sq_ass_item, Py_ssize_t, PyObject*);\n CALL_SQ_METHOD1(sq_contains, PyObject*);\n CALL_SQ_METHOD1(sq_inplace_concat, PyObject*);\n CALL_SQ_METHOD1(sq_inplace_repeat, Py_ssize_t);\n\n CALL_MP_METHOD0(mp_length);\n CALL_MP_METHOD1(mp_subscript, PyObject*);\n CALL_MP_METHOD2(mp_ass_subscript, PyObject*, PyObject*);\n\n \/\/ TODO(dss): Fail gracefully if a remote peer sends an invalid method name.\n LOG(FATAL) << \"Unexpected method name \\\"\" << CEscape(method_name) << \"\\\"\";\n}\n\n#undef CALL_TP_METHOD0\n#undef CALL_TP_METHOD1\n#undef CALL_TP_METHOD2\n#undef CALL_NB_METHOD0\n#undef CALL_NB_METHOD1\n#undef CALL_NB_METHOD2\n#undef CALL_SQ_METHOD0\n#undef CALL_SQ_METHOD1\n#undef CALL_SQ_METHOD2\n#undef CALL_MP_METHOD0\n#undef CALL_MP_METHOD1\n#undef CALL_MP_METHOD2\n\n\/\/ static\nLocalObjectImpl* LocalObjectImpl::Deserialize(const void* buffer,\n size_t buffer_size,\n DeserializationContext* context) {\n CHECK(buffer != nullptr);\n\n ObjectProto object_proto;\n CHECK(object_proto.ParseFromArray(buffer, buffer_size));\n\n const ObjectProto::Type object_type = GetSerializedObjectType(object_proto);\n\n switch (object_type) {\n case ObjectProto::PY_NONE:\n return new NoneLocalObject();\n\n case ObjectProto::LONG:\n return LongLocalObject::ParseLongProto(object_proto.long_object());\n\n case ObjectProto::FALSE:\n return new FalseLocalObject();\n\n case ObjectProto::TRUE:\n return new TrueLocalObject();\n\n case ObjectProto::LIST:\n return ListLocalObject::ParseListProto(object_proto.list_object(),\n context);\n\n case ObjectProto::DICT:\n return DictLocalObject::ParseDictProto(object_proto.dict_object(),\n context);\n\n case ObjectProto::FLOAT:\n case ObjectProto::COMPLEX:\n case ObjectProto::BYTES:\n case ObjectProto::BYTE_ARRAY:\n case ObjectProto::UNICODE:\n case ObjectProto::TUPLE:\n case ObjectProto::SET:\n case ObjectProto::FROZEN_SET:\n LOG(FATAL) << \"Not yet implemented (object_type == \"\n << static_cast(object_type) << \")\";\n return nullptr;\n\n case ObjectProto::UNSERIALIZABLE:\n LOG(FATAL) << \"The object is unserializable.\";\n return nullptr;\n\n default:\n LOG(FATAL) << \"Unexpected object type: \" << static_cast(object_type);\n }\n\n return nullptr;\n}\n\n} \/\/ namespace python\n} \/\/ namespace floating_temple\n<|endoftext|>"} {"text":"#ifndef VAST_DATA_HPP\n#define VAST_DATA_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"vast\/aliases.hpp\"\n#include \"vast\/address.hpp\"\n#include \"vast\/pattern.hpp\"\n#include \"vast\/subnet.hpp\"\n#include \"vast\/port.hpp\"\n#include \"vast\/none.hpp\"\n#include \"vast\/offset.hpp\"\n#include \"vast\/optional.hpp\"\n#include \"vast\/time.hpp\"\n#include \"vast\/type.hpp\"\n#include \"vast\/variant.hpp\"\n#include \"vast\/detail\/flat_set.hpp\"\n#include \"vast\/detail\/operators.hpp\"\n#include \"vast\/detail\/string.hpp\"\n\nnamespace vast {\n\nclass data;\nclass json;\n\nnamespace detail {\n\ntemplate \nusing make_data_type = std::conditional_t<\n std::is_floating_point::value,\n real,\n std::conditional_t<\n std::is_same::value,\n boolean,\n std::conditional_t<\n std::is_unsigned::value,\n count,\n std::conditional_t<\n std::is_signed::value,\n integer,\n std::conditional_t<\n std::is_convertible::value,\n std::string,\n std::conditional_t<\n std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value,\n T,\n std::false_type\n >\n >\n >\n >\n >\n >;\n\nusing data_variant = variant<\n none,\n boolean,\n integer,\n count,\n real,\n timespan,\n timestamp,\n std::string,\n pattern,\n address,\n subnet,\n port,\n enumeration,\n vector,\n set,\n table\n>;\n\n} \/\/ namespace detail\n\n\/\/\/ Converts a C++ type to the corresponding VAST data type.\ntemplate \nusing data_type = detail::make_data_type>;\n\n\/\/\/ A type-erased represenation of various types of data.\nclass data : detail::totally_ordered,\n detail::addable {\n friend access;\n\npublic:\n \/\/\/ Default-constructs empty data.\n data(none = nil);\n\n \/\/\/ Constructs data from optional data.\n \/\/\/ @param x The optional data instance.\n template \n data(optional x) : data{x ? std::move(*x) : data{}} {\n }\n\n \/\/\/ Constructs data from a `std::chrono::duration`.\n \/\/\/ @param x The duration to construct data from.\n template \n data(std::chrono::duration x) : data_{timespan{x}} {\n }\n\n \/\/\/ Constructs data.\n \/\/\/ @param x The instance to construct data from.\n template <\n class T,\n class = detail::disable_if_t<\n detail::is_same_or_derived::value\n || std::is_same, std::false_type>::value\n >\n >\n data(T&& x)\n : data_(data_type(std::forward(x))) {\n }\n\n data& operator+=(data const& rhs);\n\n friend bool operator==(data const& lhs, data const& rhs);\n friend bool operator<(data const& lhs, data const& rhs);\n\n template \n friend auto inspect(Inspector&f, data& d) {\n return f(d.data_);\n }\n\n friend detail::data_variant& expose(data& d);\n\nprivate:\n detail::data_variant data_;\n};\n\n\/\/template \n\/\/using is_basic_data = std::integral_constant<\n\/\/ bool,\n\/\/ std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ >;\n\/\/\n\/\/template \n\/\/using is_container_data = std::integral_constant<\n\/\/ bool,\n\/\/ std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ >;\n\n\/\/ -- helpers -----------------------------------------------------------------\n\n\/\/\/ Retrieves data at a given offset.\n\/\/\/ @param v The vector to lookup.\n\/\/\/ @param o The offset to access.\n\/\/\/ @returns A pointer to the data at *o* or `nullptr` if *o* does not\n\/\/\/ describe a valid offset.\ndata const* get(vector const& v, offset const& o);\ndata const* get(data const& d, offset const& o);\n\n\/\/\/ Flattens a vector.\n\/\/\/ @param xs The vector to flatten.\n\/\/\/ @returns The flattened vector.\n\/\/\/ @see unflatten\nvector flatten(vector const& xs);\nvector flatten(vector&& xs);\n\n\/\/\/ Flattens a vector.\n\/\/\/ @param x The vector to flatten.\n\/\/\/ @returns The flattened vector as `data` if *x* is a `vector`.\n\/\/\/ @see unflatten\ndata flatten(data const& x);\ndata flatten(data&& x);\n\n\/\/\/ Unflattens a vector according to a record type.\n\/\/\/ @param xs The vector to unflatten according to *rt*.\n\/\/\/ @param rt The type that defines the vector structure.\n\/\/\/ @returns The unflattened vector of *xs* according to *rt*.\n\/\/\/ @see flatten\noptional unflatten(vector const& xs, record_type const& rt);\noptional unflatten(vector&& xs, record_type const& rt);\n\n\/\/\/ Unflattens a vector according to a record type.\n\/\/\/ @param x The vector to unflatten according to *t*.\n\/\/\/ @param t The type that defines the vector structure.\n\/\/\/ @returns The unflattened vector of *x* according to *t* if *x* is a\n\/\/\/ `vector` and *t* a `record_type`.\n\/\/\/ @see flatten\noptional unflatten(data const& x, type const& t);\noptional unflatten(data&& x, type const& t);\n\n\/\/\/ Evaluates a data predicate.\n\/\/\/ @param lhs The LHS of the predicate.\n\/\/\/ @param op The relational operator.\n\/\/\/ @param rhs The RHS of the predicate.\nbool evaluate(data const& lhs, relational_operator op, data const& rhs);\n\n\/\/ -- convertible -------------------------------------------------------------\n\nbool convert(vector const& v, json& j);\nbool convert(set const& v, json& j);\nbool convert(table const& v, json& j);\nbool convert(data const& v, json& j);\n\n\/\/\/ Converts data with a type to \"zipped\" JSON, i.e., the JSON object for\n\/\/\/ records contains the field names from the type corresponding to the given\n\/\/\/ data.\nbool convert(data const& v, json& j, type const& t);\n\n} \/\/ namespace vast\n\n#endif\nMake data hashable#ifndef VAST_DATA_HPP\n#define VAST_DATA_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"vast\/concept\/hashable\/uhash.hpp\"\n#include \"vast\/concept\/hashable\/xxhash.hpp\"\n\n#include \"vast\/aliases.hpp\"\n#include \"vast\/address.hpp\"\n#include \"vast\/pattern.hpp\"\n#include \"vast\/subnet.hpp\"\n#include \"vast\/port.hpp\"\n#include \"vast\/none.hpp\"\n#include \"vast\/offset.hpp\"\n#include \"vast\/optional.hpp\"\n#include \"vast\/time.hpp\"\n#include \"vast\/type.hpp\"\n#include \"vast\/variant.hpp\"\n#include \"vast\/detail\/flat_set.hpp\"\n#include \"vast\/detail\/operators.hpp\"\n#include \"vast\/detail\/string.hpp\"\n\nnamespace vast {\n\nclass data;\nclass json;\n\nnamespace detail {\n\ntemplate \nusing make_data_type = std::conditional_t<\n std::is_floating_point::value,\n real,\n std::conditional_t<\n std::is_same::value,\n boolean,\n std::conditional_t<\n std::is_unsigned::value,\n count,\n std::conditional_t<\n std::is_signed::value,\n integer,\n std::conditional_t<\n std::is_convertible::value,\n std::string,\n std::conditional_t<\n std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value\n || std::is_same::value,\n T,\n std::false_type\n >\n >\n >\n >\n >\n >;\n\nusing data_variant = variant<\n none,\n boolean,\n integer,\n count,\n real,\n timespan,\n timestamp,\n std::string,\n pattern,\n address,\n subnet,\n port,\n enumeration,\n vector,\n set,\n table\n>;\n\n} \/\/ namespace detail\n\n\/\/\/ Converts a C++ type to the corresponding VAST data type.\ntemplate \nusing data_type = detail::make_data_type>;\n\n\/\/\/ A type-erased represenation of various types of data.\nclass data : detail::totally_ordered,\n detail::addable {\n friend access;\n\npublic:\n \/\/\/ Default-constructs empty data.\n data(none = nil);\n\n \/\/\/ Constructs data from optional data.\n \/\/\/ @param x The optional data instance.\n template \n data(optional x) : data{x ? std::move(*x) : data{}} {\n }\n\n \/\/\/ Constructs data from a `std::chrono::duration`.\n \/\/\/ @param x The duration to construct data from.\n template \n data(std::chrono::duration x) : data_{timespan{x}} {\n }\n\n \/\/\/ Constructs data.\n \/\/\/ @param x The instance to construct data from.\n template <\n class T,\n class = detail::disable_if_t<\n detail::is_same_or_derived::value\n || std::is_same, std::false_type>::value\n >\n >\n data(T&& x)\n : data_(data_type(std::forward(x))) {\n }\n\n data& operator+=(data const& rhs);\n\n friend bool operator==(data const& lhs, data const& rhs);\n friend bool operator<(data const& lhs, data const& rhs);\n\n template \n friend auto inspect(Inspector&f, data& d) {\n return f(d.data_);\n }\n\n friend detail::data_variant& expose(data& d);\n\nprivate:\n detail::data_variant data_;\n};\n\n\/\/template \n\/\/using is_basic_data = std::integral_constant<\n\/\/ bool,\n\/\/ std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ >;\n\/\/\n\/\/template \n\/\/using is_container_data = std::integral_constant<\n\/\/ bool,\n\/\/ std::is_same::value\n\/\/ || std::is_same::value\n\/\/ || std::is_same::value\n\/\/ >;\n\n\/\/ -- helpers -----------------------------------------------------------------\n\n\/\/\/ Retrieves data at a given offset.\n\/\/\/ @param v The vector to lookup.\n\/\/\/ @param o The offset to access.\n\/\/\/ @returns A pointer to the data at *o* or `nullptr` if *o* does not\n\/\/\/ describe a valid offset.\ndata const* get(vector const& v, offset const& o);\ndata const* get(data const& d, offset const& o);\n\n\/\/\/ Flattens a vector.\n\/\/\/ @param xs The vector to flatten.\n\/\/\/ @returns The flattened vector.\n\/\/\/ @see unflatten\nvector flatten(vector const& xs);\nvector flatten(vector&& xs);\n\n\/\/\/ Flattens a vector.\n\/\/\/ @param x The vector to flatten.\n\/\/\/ @returns The flattened vector as `data` if *x* is a `vector`.\n\/\/\/ @see unflatten\ndata flatten(data const& x);\ndata flatten(data&& x);\n\n\/\/\/ Unflattens a vector according to a record type.\n\/\/\/ @param xs The vector to unflatten according to *rt*.\n\/\/\/ @param rt The type that defines the vector structure.\n\/\/\/ @returns The unflattened vector of *xs* according to *rt*.\n\/\/\/ @see flatten\noptional unflatten(vector const& xs, record_type const& rt);\noptional unflatten(vector&& xs, record_type const& rt);\n\n\/\/\/ Unflattens a vector according to a record type.\n\/\/\/ @param x The vector to unflatten according to *t*.\n\/\/\/ @param t The type that defines the vector structure.\n\/\/\/ @returns The unflattened vector of *x* according to *t* if *x* is a\n\/\/\/ `vector` and *t* a `record_type`.\n\/\/\/ @see flatten\noptional unflatten(data const& x, type const& t);\noptional unflatten(data&& x, type const& t);\n\n\/\/\/ Evaluates a data predicate.\n\/\/\/ @param lhs The LHS of the predicate.\n\/\/\/ @param op The relational operator.\n\/\/\/ @param rhs The RHS of the predicate.\nbool evaluate(data const& lhs, relational_operator op, data const& rhs);\n\n\/\/ -- convertible -------------------------------------------------------------\n\nbool convert(vector const& v, json& j);\nbool convert(set const& v, json& j);\nbool convert(table const& v, json& j);\nbool convert(data const& v, json& j);\n\n\/\/\/ Converts data with a type to \"zipped\" JSON, i.e., the JSON object for\n\/\/\/ records contains the field names from the type corresponding to the given\n\/\/\/ data.\nbool convert(data const& v, json& j, type const& t);\n\n} \/\/ namespace vast\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(const vast::data& x) const {\n return vast::uhash{}(x);\n }\n};\n\n} \/\/ namespace std\n\n#endif\n<|endoftext|>"} {"text":"\/** \\brief Test cases for delete_unused_local_data\n * \\author Oliver Obenland (oliver.obenland@uni-tuebingen.de)\n *\n * \\copyright 2016 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n\n#define BOOST_TEST_MODULE MarcRecord\n#define BOOST_TEST_DYN_LINK\n\n#include \n#include \n#include \"ExecUtil.h\"\n\n\nTEST(DeleteUnusedBlocks) {\n int exit_code(ExecUtil::Exec(\"\/usr\/local\/bin\/delete_unused_local_data\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/LOK_withoutUsedBlock.mrc\", \"\/tmp\/output.mrc\"}));\n BOOST_CHECK_EQUAL(exit_code, 0);\n\n exit_code = ExecUtil::Exec(\"\/usr\/bin\/diff\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/default.mrc\", \"\/tmp\/output.mrc\"});\n BOOST_CHECK_EQUAL(exit_code, 0);\n}\n\nTEST(DeleteUnusedBlockAndLeaveOneBlock) {\n int exit_code(ExecUtil::Exec(\"\/usr\/local\/bin\/delete_unused_local_data\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/LOK_withUsedBlock.mrc\", \"\/tmp\/output.mrc\"}));\n BOOST_CHECK_EQUAL(exit_code, 0);\n\n exit_code = ExecUtil::Exec(\"\/usr\/bin\/diff\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/LOK_withUsedBlock.expected.mrc\", \"\/tmp\/output.mrc\"});\n BOOST_CHECK_EQUAL(exit_code, 0);\n}\n\nTEST(DeleteNoBlock) {\n int exit_code(ExecUtil::Exec(\"\/usr\/local\/bin\/delete_unused_local_data\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/default.mrc\", \"\/tmp\/output.mrc\"}));\n BOOST_CHECK_EQUAL(exit_code, 0);\n\n exit_code = ExecUtil::Exec(\"\/usr\/bin\/diff\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/default.mrc\", \"\/tmp\/output.mrc\"});\n BOOST_CHECK_EQUAL(exit_code, 0);\n}\nPorted to our own test framework.\/** \\brief Test cases for delete_unused_local_data\n * \\author Oliver Obenland (oliver.obenland@uni-tuebingen.de)\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2016,2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n#include \n#include \"ExecUtil.h\"\n#include \"UnitTest.h\"\n\n\nTEST(DeleteUnusedBlocks) {\n int exit_code(ExecUtil::Exec(\"\/usr\/local\/bin\/delete_unused_local_data\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/LOK_withoutUsedBlock.mrc\", \"\/tmp\/output.mrc\"}));\n CHECK_EQ(exit_code, 0);\n\n exit_code = ExecUtil::Exec(\"\/usr\/bin\/diff\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/default.mrc\", \"\/tmp\/output.mrc\"});\n CHECK_EQ(exit_code, 0);\n}\n\n\nTEST(DeleteUnusedBlockAndLeaveOneBlock) {\n int exit_code(ExecUtil::Exec(\"\/usr\/local\/bin\/delete_unused_local_data\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/LOK_withUsedBlock.mrc\", \"\/tmp\/output.mrc\"}));\n CHECK_EQ(exit_code, 0);\n\n exit_code = ExecUtil::Exec(\"\/usr\/bin\/diff\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/LOK_withUsedBlock.expected.mrc\", \"\/tmp\/output.mrc\"});\n CHECK_EQ(exit_code, 0);\n}\n\n\nTEST(DeleteNoBlock) {\n int exit_code(ExecUtil::Exec(\"\/usr\/local\/bin\/delete_unused_local_data\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/default.mrc\", \"\/tmp\/output.mrc\"}));\n CHECK_EQ(exit_code, 0);\n\n exit_code = ExecUtil::Exec(\"\/usr\/bin\/diff\", {\"\/usr\/local\/ub_tools\/cpp\/tests\/data\/default.mrc\", \"\/tmp\/output.mrc\"});\n CHECK_EQ(exit_code, 0);\n}\n\n\nTEST_MAIN(MarcRecord)\n<|endoftext|>"} {"text":"#include \"bam_util.h\"\n#include \"char_util.h\"\n\n\n#ifdef __cplusplus\nnamespace dlib {\n#endif\n\n\nint abstract_single_iter(samFile *in, bam_hdr_t *hdr, samFile *out, single_aux_fn function, void *data)\n{\n bam1_t *b;\n b = bam_init1();\n while (LIKELY(sam_read1(in, hdr, b) >= 0)) {\n if(function(b, data))\n continue;\n sam_write1(out, hdr, b);\n }\n bam_destroy1(b);\n return 0;\n}\n\n#ifdef __cplusplus\n\n std::string bam2cppstr(bam1_t *b)\n {\n char *qual, *seqbuf;\n int i;\n uint8_t *seq, *rvdata;\n uint32_t *pv, *fa;\n int8_t t;\n kstring_t ks = {1, 256uL, (char *)malloc(256uL)};\n ks.s[0] = '@', ks.s[1] = '\\0';\n kputs(bam_get_qname(b), &ks);\n kputsn(\" PV:B:I\", 7uL, &ks);\n pv = (uint32_t *)dlib::array_tag(b, \"PV\");\n fa = (uint32_t *)dlib::array_tag(b, \"FA\");\n for(i = 0; i < b->core.l_qseq; ++i) ksprintf(&ks, \",%u\", pv[i]);\n kputs(\"\\tFA:B:I\", &ks);\n for(i = 0; i < b->core.l_qseq; ++i) ksprintf(&ks, \",%u\", fa[i]);\n ksprintf(&ks, \"\\tFM:i:%i\\tFP:i:%i\", bam_itag(b, \"FM\"), bam_itag(b, \"FP\"));\n write_tag_if_found(rvdata, b, \"RV\", ks);\n write_tag_if_found(rvdata, b, \"NC\", ks);\n write_tag_if_found(rvdata, b, \"NP\", ks);\n write_tag_if_found(rvdata, b, \"DR\", ks);\n kputc('\\n', &ks);\n seq = bam_get_seq(b);\n seqbuf = (char *)malloc(b->core.l_qseq + 1);\n for (i = 0; i < b->core.l_qseq; ++i) seqbuf[i] = seq_nt16_str[bam_seqi(seq, i)];\n seqbuf[i] = '\\0';\n if (b->core.flag & BAM_FREVERSE) { \/\/ reverse complement\n for(i = 0; i < b->core.l_qseq>>1; ++i) {\n t = seqbuf[b->core.l_qseq - i - 1];\n seqbuf[b->core.l_qseq - i - 1] = nuc_cmpl(seqbuf[i]);\n seqbuf[i] = nuc_cmpl(t);\n }\n if(b->core.l_qseq&1) seqbuf[i] = nuc_cmpl(seqbuf[i]);\n }\n seqbuf[b->core.l_qseq] = '\\0';\n assert(strlen(seqbuf) == (uint64_t)b->core.l_qseq);\n kputs(seqbuf, &ks);\n kputs(\"\\n+\\n\", &ks);\n qual = (char *)bam_get_qual(b);\n for(i = 0; i < b->core.l_qseq; ++i) seqbuf[i] = 33 + qual[i];\n if (b->core.flag & BAM_FREVERSE) { \/\/ reverse\n for (i = 0; i < b->core.l_qseq>>1; ++i) {\n t = seqbuf[b->core.l_qseq - 1 - i];\n seqbuf[b->core.l_qseq - 1 - i] = seqbuf[i];\n seqbuf[i] = t;\n }\n }\n assert(strlen(seqbuf) == (uint64_t)b->core.l_qseq);\n kputs(seqbuf, &ks), free(seqbuf);\n kputc('\\n', &ks);\n std::string ret(ks.s), free(ks.s);\n return ret;\n }\n\n std::string get_SO(bam_hdr_t *hdr) {\n char *end, *so_start;\n std::string ret;\n if (strncmp(hdr->text, \"@HD\", 3) != 0) goto NA;\n if ((end = strchr(hdr->text, '\\n')) == 0) goto NA;\n *end = '\\0';\n\n if((so_start = strstr(hdr->text, \"SO:\")) == nullptr) goto NA;\n ret = std::string(so_start + strlen(\"SO:\"));\n *end = '\\n';\n return ret;\n\n NA:\n LOG_WARNING(\"Sort order not found. Returning N\/A.\\n\");\n return std::string(\"N\/A\");\n }\n\n void resize_stack(tmp_stack_t *stack, size_t n) {\n if(n > stack->max) {\n stack->max = n;\n stack->a = (bam1_t **)realloc(stack->a, sizeof(bam1_t *) * n);\n if(!stack->a) LOG_EXIT(\"Failed to reallocate memory for %lu bam1_t * objects. Abort!\\n\", stack->max);\n } else if(n < stack->n){\n for(uint64_t i = stack->n;i > n;) free(stack->a[--i]->data);\n stack->max = n;\n stack->a = (bam1_t **)realloc(stack->a, sizeof(bam1_t *) * n);\n }\n }\n\n void abstract_pair_set(samFile *in, bam_hdr_t *hdr, samFile *ofp, std::unordered_set functions)\n {\n bam1_t *b = bam_init1(), *b1 = bam_init1();\n while (LIKELY(sam_read1(in, hdr, b) >= 0)) {\n if(b->core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) continue;\n if(b->core.flag & BAM_FREAD1) {\n bam_copy1(b1, b); continue;\n }\n for(auto f: functions) f(b1, b);\n sam_write1(ofp, hdr, b1), sam_write1(ofp, hdr, b);\n }\n bam_destroy1(b), bam_destroy1(b1);\n }\n\n#endif\n\n\nint abstract_pair_iter(samFile *in, bam_hdr_t *hdr, samFile *ofp, pair_aux_fn function, void *aux)\n{\n#if !NDEBUG\n size_t npairs = 0, nfailed = 0;\n#endif\n bam1_t *b = bam_init1(), *b1 = bam_init1();\n while (LIKELY(sam_read1(in, hdr, b) >= 0)) {\n if(b->core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY))\n continue;\n if(b->core.flag & BAM_FREAD1) {\n bam_copy1(b1, b); continue;\n }\n#if !NDEBUG\n ++npairs;\n#endif\n if(strcmp(bam_get_qname(b1), bam_get_qname(b)))\n LOG_EXIT(\"Is the bam name sorted? Reads in 'pair' don't have the same name (%s, %s). Abort!\\n\", bam_get_qname(b1), bam_get_qname(b));\n if(function(b1, b, aux) == 0) {\n sam_write1(ofp, hdr, b1), sam_write1(ofp, hdr, b);\n }\n#if !NDEBUG\n else ++nfailed;\n#endif\n }\n bam_destroy1(b), bam_destroy1(b1);\n#if !NDEBUG\n LOG_DEBUG(\"Number of pairs considered: %lu. Number of pairs failed: %lu.\\n\", npairs, nfailed);\n#endif\n return EXIT_SUCCESS;\n}\n\nint bampath_has_tag(char *bampath, const char *tag)\n{\n samFile *fp = sam_open(bampath, \"r\");\n bam_hdr_t *header = sam_hdr_read(fp);\n if(!header || !fp) {\n LOG_EXIT(\"Could not open bam file at '%s' for reading. Abort!\\n\", bampath);\n }\n LOG_DEBUG(\"header: %p. fp: %p.\\n\", (void *)header, (void *)fp);\n bam1_t *b = bam_init1();\n if(sam_read1(fp, header, b) < 0) {\n LOG_EXIT(\"Empty bam file at '%s'. Abort!\\n\", bampath);\n }\n int ret = !!bam_aux_get(b, tag);\n bam_destroy1(b);\n bam_hdr_destroy(header);\n sam_close(fp);\n return ret;\n}\n\nvoid check_bam_tag_exit(char *bampath, const char *tag)\n{\n if(strcmp(bampath, \"-\") && strcmp(bampath, \"stdin\")) {\n if(!bampath_has_tag(bampath, tag))\n LOG_EXIT(\"Required bam tag '%s' missing from bam file at path '%s'. Abort!\\n\", tag, bampath);\n } else {\n LOG_WARNING(\"Could not check for bam tag without exhausting a pipe. \"\n \"Tag '%s' has not been verified.\\n\", tag);\n }\n}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\nvoid add_pg_line(bam_hdr_t *hdr, int argc, char **argv,\n const char *id, const char *version, const char *name, const char *ds) {\n char *tmp = hdr->text + hdr->l_text - 2;\n char *old_pg{nullptr};\n while(--tmp > hdr->text) {\n if(memcmp(tmp, \"@PG\", 3) == 0) {\n while(memcmp(++tmp, \"ID:\", 3));\n tmp += 3;\n char *end = tmp - 1;\n while(*++end != '\\t'); \/\/ Zoom ahead to \\t\n *end = '\\0';\n old_pg = (char *)malloc(end - tmp + 1);\n memcpy(old_pg, tmp, end - tmp + 1);\n *end = '\\t';\n break;\n \/\/ Found the last @PG line!\n }\n }\n kstring_t new_text{hdr->l_text, hdr->l_text, hdr->text}; \/\/ I now have ownership\n ksprintf(&new_text, \"@PG\\tID:%s\\tPN:%s\\tCL:\", id, name ? name: id);\n kputs((const char *)argv[0], &new_text);\n for(int i = 1; i < argc; ++i) {\n kputc(' ', &new_text);\n kputs((const char *)argv[i], &new_text);\n }\n if(old_pg) {\n LOG_DEBUG(\"Found old pg: %s\\n\", old_pg);\n ksprintf(&new_text, \"\\tPP:%s\", old_pg);\n free(old_pg);\n }\n if(ds) ksprintf(&new_text, \"\\tDS:%s\", ds);\n if(version) ksprintf(&new_text, \"\\tVN:%s\", version);\n kputc('\\n', &new_text);\n hdr->text = new_text.s; \/\/ In case it was invalidated, reassign.\n hdr->l_text = new_text.l;\n}\n\n\n#ifdef __cplusplus\n \/*\n * Applies fn\n *\/\n int BamHandle::for_each(std::function fn, BamHandle& ofp, void *data) {\n int ret;\n while(next() >= 0) {\n if((ret = fn(rec, data)) != 0) continue;\n ofp.write(rec);\n }\n return 0;\n }\n int BamHandle::for_each_pair(std::function fn, BamHandle& ofp, void *data) {\n LOG_EXIT(\"Broken function.\\n\");\n int ret;\n bam1_t *r1 = bam_init1();\n while(next() >= 0) {\n if(rec->core.flag & BAM_FREAD1) {\n bam_copy1(r1, rec);\n continue;\n }\n if((rec->core.flag & BAM_FREAD2) == 0) continue;\n assert(strcmp(bam_get_qname(r1), bam_get_qname(rec)) == 0);\n if((ret = fn(r1, rec, data)) != 0) continue;\n if(strcmp(bam_get_qname(r1), bam_get_qname(rec)))\n LOG_EXIT(\"WTF\\n\");\n ofp.write(r1), ofp.write(rec);\n }\n bam_destroy1(r1);\n return 0;\n }\n int BamHandle::write() {return write(rec);}\n int bam_apply_function(char *infname, char *outfname,\n std::function func, void *data, const char *mode) {\n BamHandle in(infname);\n BamHandle out(outfname, in.header, mode);\n return in.for_each(func, out, data);\n }\n int BamHandle::bed_plp_auto(khash_t(bed) *bed, std::function fn,\n BedPlpAuxBase *auxen) {\n plp = bam_plp_init((bam_plp_auto_f)&read_bam, (void *)auxen);\n auxen->handle = this;\n for(khiter_t ki = kh_begin(bed); ki != kh_end(bed); ++ki) {\n if(!kh_exist(bed, ki)) continue;\n for(unsigned i = 0; i < kh_val(bed, ki).n; ++i) {\n const int start = get_start(kh_val(bed, ki).intervals[i]);\n const int stop = get_stop(kh_val(bed, ki).intervals[i]);\n const int bed_tid = (int)kh_key(bed, ki);\n int tid, n_plp, pos;\n if(iter) hts_itr_destroy(iter);\n iter = bam_itr_queryi(idx, bed_tid, start, stop);\n bam_plp_reset(plp);\n while(bam_plp_auto(plp, &tid, &pos, &n_plp) != 0) {\n assert(tid == bed_tid);\n if(pos < start) continue;\n if(pos >= stop) break;\n fn(pileups, n_plp, auxen);\n }\n }\n }\n return 0;\n }\n \/*\n * Does not own aux.\n *\/\n class BedPlpAux {\n BamHandle in;\n BamHandle out;\n BedPlpAuxBase *aux;\n khash_t(bed) *bed;\n BedPlpAux(char *inpath, char *outpath, char *bedpath, BedPlpAuxBase *data):\n in(inpath),\n out(outpath, in.header),\n aux(data),\n bed(parse_bed_hash(bedpath, in.header, data->padding))\n {\n if(!bed) LOG_EXIT(\"Failed to open bedfile %s. Abort!\\n\", bedpath);\n }\n ~BedPlpAux() {\n if(bed) bed_destroy_hash(bed);\n }\n int process(std::function fn) {\n return in.bed_plp_auto(bed,fn, aux);\n }\n };\n} \/* namespace dlib *\/\n#endif \/* ifdef __cplusplus *\/\nCheck each read in abstract pair iter to make sure that it's marked as a paired-end read.#include \"bam_util.h\"\n#include \"char_util.h\"\n\n\n#ifdef __cplusplus\nnamespace dlib {\n#endif\n\n\nint abstract_single_iter(samFile *in, bam_hdr_t *hdr, samFile *out, single_aux_fn function, void *data)\n{\n bam1_t *b;\n b = bam_init1();\n while (LIKELY(sam_read1(in, hdr, b) >= 0)) {\n if(function(b, data))\n continue;\n sam_write1(out, hdr, b);\n }\n bam_destroy1(b);\n return 0;\n}\n\n#ifdef __cplusplus\n\n std::string bam2cppstr(bam1_t *b)\n {\n char *qual, *seqbuf;\n int i;\n uint8_t *seq, *rvdata;\n uint32_t *pv, *fa;\n int8_t t;\n kstring_t ks = {1, 256uL, (char *)malloc(256uL)};\n ks.s[0] = '@', ks.s[1] = '\\0';\n kputs(bam_get_qname(b), &ks);\n kputsn(\" PV:B:I\", 7uL, &ks);\n pv = (uint32_t *)dlib::array_tag(b, \"PV\");\n fa = (uint32_t *)dlib::array_tag(b, \"FA\");\n for(i = 0; i < b->core.l_qseq; ++i) ksprintf(&ks, \",%u\", pv[i]);\n kputs(\"\\tFA:B:I\", &ks);\n for(i = 0; i < b->core.l_qseq; ++i) ksprintf(&ks, \",%u\", fa[i]);\n ksprintf(&ks, \"\\tFM:i:%i\\tFP:i:%i\", bam_itag(b, \"FM\"), bam_itag(b, \"FP\"));\n write_tag_if_found(rvdata, b, \"RV\", ks);\n write_tag_if_found(rvdata, b, \"NC\", ks);\n write_tag_if_found(rvdata, b, \"NP\", ks);\n write_tag_if_found(rvdata, b, \"DR\", ks);\n kputc('\\n', &ks);\n seq = bam_get_seq(b);\n seqbuf = (char *)malloc(b->core.l_qseq + 1);\n for (i = 0; i < b->core.l_qseq; ++i) seqbuf[i] = seq_nt16_str[bam_seqi(seq, i)];\n seqbuf[i] = '\\0';\n if (b->core.flag & BAM_FREVERSE) { \/\/ reverse complement\n for(i = 0; i < b->core.l_qseq>>1; ++i) {\n t = seqbuf[b->core.l_qseq - i - 1];\n seqbuf[b->core.l_qseq - i - 1] = nuc_cmpl(seqbuf[i]);\n seqbuf[i] = nuc_cmpl(t);\n }\n if(b->core.l_qseq&1) seqbuf[i] = nuc_cmpl(seqbuf[i]);\n }\n seqbuf[b->core.l_qseq] = '\\0';\n assert(strlen(seqbuf) == (uint64_t)b->core.l_qseq);\n kputs(seqbuf, &ks);\n kputs(\"\\n+\\n\", &ks);\n qual = (char *)bam_get_qual(b);\n for(i = 0; i < b->core.l_qseq; ++i) seqbuf[i] = 33 + qual[i];\n if (b->core.flag & BAM_FREVERSE) { \/\/ reverse\n for (i = 0; i < b->core.l_qseq>>1; ++i) {\n t = seqbuf[b->core.l_qseq - 1 - i];\n seqbuf[b->core.l_qseq - 1 - i] = seqbuf[i];\n seqbuf[i] = t;\n }\n }\n assert(strlen(seqbuf) == (uint64_t)b->core.l_qseq);\n kputs(seqbuf, &ks), free(seqbuf);\n kputc('\\n', &ks);\n std::string ret(ks.s), free(ks.s);\n return ret;\n }\n\n std::string get_SO(bam_hdr_t *hdr) {\n char *end, *so_start;\n std::string ret;\n if (strncmp(hdr->text, \"@HD\", 3) != 0) goto NA;\n if ((end = strchr(hdr->text, '\\n')) == 0) goto NA;\n *end = '\\0';\n\n if((so_start = strstr(hdr->text, \"SO:\")) == nullptr) goto NA;\n ret = std::string(so_start + strlen(\"SO:\"));\n *end = '\\n';\n return ret;\n\n NA:\n LOG_WARNING(\"Sort order not found. Returning N\/A.\\n\");\n return std::string(\"N\/A\");\n }\n\n void resize_stack(tmp_stack_t *stack, size_t n) {\n if(n > stack->max) {\n stack->max = n;\n stack->a = (bam1_t **)realloc(stack->a, sizeof(bam1_t *) * n);\n if(!stack->a) LOG_EXIT(\"Failed to reallocate memory for %lu bam1_t * objects. Abort!\\n\", stack->max);\n } else if(n < stack->n){\n for(uint64_t i = stack->n;i > n;) free(stack->a[--i]->data);\n stack->max = n;\n stack->a = (bam1_t **)realloc(stack->a, sizeof(bam1_t *) * n);\n }\n }\n\n void abstract_pair_set(samFile *in, bam_hdr_t *hdr, samFile *ofp, std::unordered_set functions)\n {\n bam1_t *b = bam_init1(), *b1 = bam_init1();\n while (LIKELY(sam_read1(in, hdr, b) >= 0)) {\n if(b->core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY)) continue;\n if(b->core.flag & BAM_FREAD1) {\n bam_copy1(b1, b); continue;\n }\n for(auto f: functions) f(b1, b);\n sam_write1(ofp, hdr, b1), sam_write1(ofp, hdr, b);\n }\n bam_destroy1(b), bam_destroy1(b1);\n }\n\n#endif\n\n\nint abstract_pair_iter(samFile *in, bam_hdr_t *hdr, samFile *ofp, pair_aux_fn function, void *aux)\n{\n#if !NDEBUG\n size_t npairs = 0, nfailed = 0;\n#endif\n bam1_t *b = bam_init1(), *b1 = bam_init1();\n while (LIKELY(sam_read1(in, hdr, b) >= 0)) {\n if(UNLIKELY(b->core.flag & BAM_FPAIRED == 0))\n LOG_EXIT(\"Unpaired (single-end) read found in pairwise iterator. Abort!\\n\");\n if(b->core.flag & (BAM_FSECONDARY | BAM_FSUPPLEMENTARY))\n continue;\n if(b->core.flag & BAM_FREAD1) {\n bam_copy1(b1, b); continue;\n }\n#if !NDEBUG\n ++npairs;\n#endif\n if(strcmp(bam_get_qname(b1), bam_get_qname(b)))\n LOG_EXIT(\"Is the bam name sorted? Reads in 'pair' don't have the same name (%s, %s). Abort!\\n\", bam_get_qname(b1), bam_get_qname(b));\n if(function(b1, b, aux) == 0) {\n sam_write1(ofp, hdr, b1), sam_write1(ofp, hdr, b);\n }\n#if !NDEBUG\n else ++nfailed;\n#endif\n }\n bam_destroy1(b), bam_destroy1(b1);\n#if !NDEBUG\n LOG_DEBUG(\"Number of pairs considered: %lu. Number of pairs failed: %lu.\\n\", npairs, nfailed);\n#endif\n return EXIT_SUCCESS;\n}\n\nint bampath_has_tag(char *bampath, const char *tag)\n{\n samFile *fp = sam_open(bampath, \"r\");\n bam_hdr_t *header = sam_hdr_read(fp);\n if(!header || !fp) {\n LOG_EXIT(\"Could not open bam file at '%s' for reading. Abort!\\n\", bampath);\n }\n LOG_DEBUG(\"header: %p. fp: %p.\\n\", (void *)header, (void *)fp);\n bam1_t *b = bam_init1();\n if(sam_read1(fp, header, b) < 0) {\n LOG_EXIT(\"Empty bam file at '%s'. Abort!\\n\", bampath);\n }\n int ret = !!bam_aux_get(b, tag);\n bam_destroy1(b);\n bam_hdr_destroy(header);\n sam_close(fp);\n return ret;\n}\n\nvoid check_bam_tag_exit(char *bampath, const char *tag)\n{\n if(strcmp(bampath, \"-\") && strcmp(bampath, \"stdin\")) {\n if(!bampath_has_tag(bampath, tag))\n LOG_EXIT(\"Required bam tag '%s' missing from bam file at path '%s'. Abort!\\n\", tag, bampath);\n } else {\n LOG_WARNING(\"Could not check for bam tag without exhausting a pipe. \"\n \"Tag '%s' has not been verified.\\n\", tag);\n }\n}\n\n#ifdef __cplusplus\nextern \"C\"\n#endif\nvoid add_pg_line(bam_hdr_t *hdr, int argc, char **argv,\n const char *id, const char *version, const char *name, const char *ds) {\n char *tmp = hdr->text + hdr->l_text - 2;\n char *old_pg{nullptr};\n while(--tmp > hdr->text) {\n if(memcmp(tmp, \"@PG\", 3) == 0) {\n while(memcmp(++tmp, \"ID:\", 3));\n tmp += 3;\n char *end = tmp - 1;\n while(*++end != '\\t'); \/\/ Zoom ahead to \\t\n *end = '\\0';\n old_pg = (char *)malloc(end - tmp + 1);\n memcpy(old_pg, tmp, end - tmp + 1);\n *end = '\\t';\n break;\n \/\/ Found the last @PG line!\n }\n }\n kstring_t new_text{hdr->l_text, hdr->l_text, hdr->text}; \/\/ I now have ownership\n ksprintf(&new_text, \"@PG\\tID:%s\\tPN:%s\\tCL:\", id, name ? name: id);\n kputs((const char *)argv[0], &new_text);\n for(int i = 1; i < argc; ++i) {\n kputc(' ', &new_text);\n kputs((const char *)argv[i], &new_text);\n }\n if(old_pg) {\n LOG_DEBUG(\"Found old pg: %s\\n\", old_pg);\n ksprintf(&new_text, \"\\tPP:%s\", old_pg);\n free(old_pg);\n }\n if(ds) ksprintf(&new_text, \"\\tDS:%s\", ds);\n if(version) ksprintf(&new_text, \"\\tVN:%s\", version);\n kputc('\\n', &new_text);\n hdr->text = new_text.s; \/\/ In case it was invalidated, reassign.\n hdr->l_text = new_text.l;\n}\n\n\n#ifdef __cplusplus\n \/*\n * Applies fn\n *\/\n int BamHandle::for_each(std::function fn, BamHandle& ofp, void *data) {\n int ret;\n while(next() >= 0) {\n if((ret = fn(rec, data)) != 0) continue;\n ofp.write(rec);\n }\n return 0;\n }\n int BamHandle::for_each_pair(std::function fn, BamHandle& ofp, void *data) {\n LOG_EXIT(\"Broken function.\\n\");\n int ret;\n bam1_t *r1 = bam_init1();\n while(next() >= 0) {\n if(rec->core.flag & BAM_FREAD1) {\n bam_copy1(r1, rec);\n continue;\n }\n if((rec->core.flag & BAM_FREAD2) == 0) continue;\n assert(strcmp(bam_get_qname(r1), bam_get_qname(rec)) == 0);\n if((ret = fn(r1, rec, data)) != 0) continue;\n if(strcmp(bam_get_qname(r1), bam_get_qname(rec)))\n LOG_EXIT(\"WTF\\n\");\n ofp.write(r1), ofp.write(rec);\n }\n bam_destroy1(r1);\n return 0;\n }\n int BamHandle::write() {return write(rec);}\n int bam_apply_function(char *infname, char *outfname,\n std::function func, void *data, const char *mode) {\n BamHandle in(infname);\n BamHandle out(outfname, in.header, mode);\n return in.for_each(func, out, data);\n }\n int BamHandle::bed_plp_auto(khash_t(bed) *bed, std::function fn,\n BedPlpAuxBase *auxen) {\n plp = bam_plp_init((bam_plp_auto_f)&read_bam, (void *)auxen);\n auxen->handle = this;\n for(khiter_t ki = kh_begin(bed); ki != kh_end(bed); ++ki) {\n if(!kh_exist(bed, ki)) continue;\n for(unsigned i = 0; i < kh_val(bed, ki).n; ++i) {\n const int start = get_start(kh_val(bed, ki).intervals[i]);\n const int stop = get_stop(kh_val(bed, ki).intervals[i]);\n const int bed_tid = (int)kh_key(bed, ki);\n int tid, n_plp, pos;\n if(iter) hts_itr_destroy(iter);\n iter = bam_itr_queryi(idx, bed_tid, start, stop);\n bam_plp_reset(plp);\n while(bam_plp_auto(plp, &tid, &pos, &n_plp) != 0) {\n assert(tid == bed_tid);\n if(pos < start) continue;\n if(pos >= stop) break;\n fn(pileups, n_plp, auxen);\n }\n }\n }\n return 0;\n }\n \/*\n * Does not own aux.\n *\/\n class BedPlpAux {\n BamHandle in;\n BamHandle out;\n BedPlpAuxBase *aux;\n khash_t(bed) *bed;\n BedPlpAux(char *inpath, char *outpath, char *bedpath, BedPlpAuxBase *data):\n in(inpath),\n out(outpath, in.header),\n aux(data),\n bed(parse_bed_hash(bedpath, in.header, data->padding))\n {\n if(!bed) LOG_EXIT(\"Failed to open bedfile %s. Abort!\\n\", bedpath);\n }\n ~BedPlpAux() {\n if(bed) bed_destroy_hash(bed);\n }\n int process(std::function fn) {\n return in.bed_plp_auto(bed,fn, aux);\n }\n };\n} \/* namespace dlib *\/\n#endif \/* ifdef __cplusplus *\/\n<|endoftext|>"} {"text":"\/*\n Privacy Plugin - Filter messages \n\n Copyright (c) 2006 by Andre Duffeck \n Kopete (c) 2002-2006 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \n#include \n#include \n\n#include \"kopetecontact.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetemessage.h\"\n#include \"kopetemessageevent.h\"\n#include \"kopetechatsessionmanager.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopetepluginmanager.h\"\n#include \"privacymessagehandler.h\"\n#include \"privacyconfig.h\"\n\n#include \"privacyplugin.h\"\n\ntypedef KGenericFactory PrivacyPluginFactory;\nK_EXPORT_COMPONENT_FACTORY( kopete_privacy, PrivacyPluginFactory( \"kopete_privacy\" ) )\nPrivacyPlugin * PrivacyPlugin::pluginStatic_ = 0L;\n\nPrivacyPlugin::PrivacyPlugin( QObject *parent, const QStringList & )\n: Kopete::Plugin( PrivacyPluginFactory::instance(), parent )\n{\n\tkDebug(14313) << k_funcinfo << endl;\n\tif( !pluginStatic_ )\n\t\tpluginStatic_ = this;\n\n\tKAction *addToWhiteList = new KAction( KIcon(\"privacy_whitelist\"), i18n(\"Add to WhiteList\" ),\n\t\tactionCollection(), \"addToWhiteList\" );\n\tconnect(addToWhiteList, SIGNAL(triggered(bool)), this, SLOT(slotAddToWhiteList()));\n\tconnect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)),\n\t\taddToWhiteList, SLOT(setEnabled(bool)));\n\tKAction *addToBlackList = new KAction( KIcon(\"privacy_blacklist\"), i18n(\"Add to BlackList\" ),\n\t\tactionCollection(), \"addToBlackList\" );\n\tconnect(addToBlackList, SIGNAL(triggered(bool)), this, SLOT(slotAddToBlackList()));\n\tconnect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)),\n\t\taddToBlackList, SLOT(setEnabled(bool)));\n\n\tsetXMLFile(\"privacyui.rc\");\n\n\tm_inboundHandler = new PrivacyMessageHandlerFactory( Kopete::Message::Inbound,\n\t\tKopete::MessageHandlerFactory::InStageStart, this, SLOT( slotIncomingMessage( Kopete::MessageEvent * ) ) );\n\n\tconnect( this, SIGNAL( settingsChanged() ), this, SLOT( slotSettingsChanged() ) );\n}\n\n\nPrivacyPlugin::~PrivacyPlugin()\n{\n\tkDebug(14313) << k_funcinfo << endl;\n\tpluginStatic_ = 0L;\n\tdelete m_inboundHandler;\n}\n\nPrivacyPlugin *PrivacyPlugin::plugin()\n{\n\treturn pluginStatic_ ;\n}\n\nPrivacyConfig *PrivacyPlugin::config()\n{\n\treturn PrivacyConfig::self();\n}\n\nvoid PrivacyPlugin::slotSettingsChanged()\n{\n\tPrivacyConfig::self()->readConfig();\n}\n\nvoid PrivacyPlugin::slotAddToWhiteList()\n{\t\n\tQStringList whitelist = PrivacyConfig::whiteList();\n\tforeach( Kopete::MetaContact *metacontact, Kopete::ContactList::self()->selectedMetaContacts() )\n\t{\n\t\tforeach( Kopete::Contact *contact, metacontact->contacts() )\n\t\t{\n\t\t\tQString entry( contact->protocol()->pluginId() + \":\" + contact->contactId() );\n\t\t\tif( !whitelist.contains( entry ) )\n\t\t\t\twhitelist.append( entry );\n\t\t}\n\t}\n\tPrivacyConfig::setWhiteList( whitelist );\n\tPrivacyConfig::self()->writeConfig();\n}\n\nvoid PrivacyPlugin::slotAddToBlackList()\n{\t\n\tQStringList blacklist = PrivacyConfig::blackList();\n\tforeach( Kopete::MetaContact *metacontact, Kopete::ContactList::self()->selectedMetaContacts() )\n\t{\n\t\tforeach( Kopete::Contact *contact, metacontact->contacts() )\n\t\t{\n\t\t\tQString entry( contact->protocol()->pluginId() + \":\" + contact->contactId() );\n\t\t\tif( !blacklist.contains( entry ) )\n\t\t\t\tblacklist.append( entry );\n\t\t}\n\t}\n\tPrivacyConfig::setBlackList( blacklist );\n\tPrivacyConfig::self()->writeConfig();\n}\n\nvoid PrivacyPlugin::slotIncomingMessage( Kopete::MessageEvent *event )\n{\n\tKopete::Message msg = event->message();\n\n\tif( msg.direction() == Kopete::Message::Outbound ||\n\t\tmsg.direction() == Kopete::Message::Internal )\n\t\treturn;\n\n\t\/\/ Verify sender\n\tif( PrivacyConfig::sender_AllowNoneButWhiteList() )\n\t{\n\t\tif( !PrivacyConfig::whiteList().contains( msg.from()->protocol()->pluginId() + \":\" + msg.from()->contactId() ) )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message from \" << msg.from()->protocol()->pluginId() << \":\" << msg.from()->contactId() << \" dropped (not whitelisted)\" << endl;\n\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because this contact is not on your whitelist.\") );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n\telse if( PrivacyConfig::sender_AllowAllButBlackList() )\n\t{\n\t\tif( PrivacyConfig::blackList().contains( msg.from()->protocol()->pluginId() + \":\" + msg.from()->contactId() ) )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message from \" << msg.from()->protocol()->pluginId() << \":\" << msg.from()->contactId() << \" dropped (blacklisted)\" << endl;\n\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because this contact is on your blacklist.\") );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n\telse if( PrivacyConfig::sender_AllowNoneButContactList() )\n\t{\n\t\tif( msg.from()->metaContact()->isTemporary() )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message from \" << msg.from()->contactId() << \" dropped (not on the contactlist)\" << endl;\n\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because this contact is not on your contactlist.\") );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Verify content\n\tif( PrivacyConfig::content_DropIfAny() )\n\t{\n\t\tforeach(QString word, PrivacyConfig::dropIfAny().split(',') )\n\t\t{\n\t\t\tif( msg.plainBody().contains( word ) )\n\t\t\t{\n\t\t\t\tkDebug(14313) << k_funcinfo << \"Message dropped because it contained: \" << word << endl;\n\t\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because it contained a blacklisted word.\") );\n\t\t\t\tevent->discard();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( PrivacyConfig::content_DropIfAll() )\n\t{\n\t\tbool drop = true;\n\t\tforeach(QString word, PrivacyConfig::dropIfAll().split(',') )\n\t\t{\n\t\t\tif( !msg.plainBody().contains( word ) )\n\t\t\t{\n\t\t\t\tdrop = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif( drop )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message dropped because it contained blacklisted words.\" << endl;\n\t\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because it contained blacklisted words.\") );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n}\n\n#include \"privacyplugin.moc\"\nups :)\/*\n Privacy Plugin - Filter messages \n\n Copyright (c) 2006 by Andre Duffeck \n Kopete (c) 2002-2006 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \n#include \n#include \n\n#include \"kopetecontact.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetemessage.h\"\n#include \"kopetemessageevent.h\"\n#include \"kopetechatsessionmanager.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopetepluginmanager.h\"\n#include \"privacymessagehandler.h\"\n#include \"privacyconfig.h\"\n\n#include \"privacyplugin.h\"\n\ntypedef KGenericFactory PrivacyPluginFactory;\nK_EXPORT_COMPONENT_FACTORY( kopete_privacy, PrivacyPluginFactory( \"kopete_privacy\" ) )\nPrivacyPlugin * PrivacyPlugin::pluginStatic_ = 0L;\n\nPrivacyPlugin::PrivacyPlugin( QObject *parent, const QStringList & )\n: Kopete::Plugin( PrivacyPluginFactory::instance(), parent )\n{\n\tkDebug(14313) << k_funcinfo << endl;\n\tif( !pluginStatic_ )\n\t\tpluginStatic_ = this;\n\n\tKAction *addToWhiteList = new KAction( KIcon(\"privacy_whitelist\"), i18n(\"Add to WhiteList\" ),\n\t\tactionCollection(), \"addToWhiteList\" );\n\tconnect(addToWhiteList, SIGNAL(triggered(bool)), this, SLOT(slotAddToWhiteList()));\n\tconnect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)),\n\t\taddToWhiteList, SLOT(setEnabled(bool)));\n\tKAction *addToBlackList = new KAction( KIcon(\"privacy_blacklist\"), i18n(\"Add to BlackList\" ),\n\t\tactionCollection(), \"addToBlackList\" );\n\tconnect(addToBlackList, SIGNAL(triggered(bool)), this, SLOT(slotAddToBlackList()));\n\tconnect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)),\n\t\taddToBlackList, SLOT(setEnabled(bool)));\n\n\tsetXMLFile(\"privacyui.rc\");\n\n\tm_inboundHandler = new PrivacyMessageHandlerFactory( Kopete::Message::Inbound,\n\t\tKopete::MessageHandlerFactory::InStageStart, this, SLOT( slotIncomingMessage( Kopete::MessageEvent * ) ) );\n\n\tconnect( this, SIGNAL( settingsChanged() ), this, SLOT( slotSettingsChanged() ) );\n}\n\n\nPrivacyPlugin::~PrivacyPlugin()\n{\n\tkDebug(14313) << k_funcinfo << endl;\n\tpluginStatic_ = 0L;\n\tdelete m_inboundHandler;\n}\n\nPrivacyPlugin *PrivacyPlugin::plugin()\n{\n\treturn pluginStatic_ ;\n}\n\nPrivacyConfig *PrivacyPlugin::config()\n{\n\treturn PrivacyConfig::self();\n}\n\nvoid PrivacyPlugin::slotSettingsChanged()\n{\n\tPrivacyConfig::self()->readConfig();\n}\n\nvoid PrivacyPlugin::slotAddToWhiteList()\n{\t\n\tQStringList whitelist = PrivacyConfig::whiteList();\n\tforeach( Kopete::MetaContact *metacontact, Kopete::ContactList::self()->selectedMetaContacts() )\n\t{\n\t\tforeach( Kopete::Contact *contact, metacontact->contacts() )\n\t\t{\n\t\t\tQString entry( contact->protocol()->pluginId() + \":\" + contact->contactId() );\n\t\t\tif( !whitelist.contains( entry ) )\n\t\t\t\twhitelist.append( entry );\n\t\t}\n\t}\n\tPrivacyConfig::setWhiteList( whitelist );\n\tPrivacyConfig::self()->writeConfig();\n}\n\nvoid PrivacyPlugin::slotAddToBlackList()\n{\t\n\tQStringList blacklist = PrivacyConfig::blackList();\n\tforeach( Kopete::MetaContact *metacontact, Kopete::ContactList::self()->selectedMetaContacts() )\n\t{\n\t\tforeach( Kopete::Contact *contact, metacontact->contacts() )\n\t\t{\n\t\t\tQString entry( contact->protocol()->pluginId() + \":\" + contact->contactId() );\n\t\t\tif( !blacklist.contains( entry ) )\n\t\t\t\tblacklist.append( entry );\n\t\t}\n\t}\n\tPrivacyConfig::setBlackList( blacklist );\n\tPrivacyConfig::self()->writeConfig();\n}\n\nvoid PrivacyPlugin::slotIncomingMessage( Kopete::MessageEvent *event )\n{\n\tKopete::Message msg = event->message();\n\n\tif( msg.direction() == Kopete::Message::Outbound ||\n\t\tmsg.direction() == Kopete::Message::Internal )\n\t\treturn;\n\n\t\/\/ Verify sender\n\tif( PrivacyConfig::sender_AllowNoneButWhiteList() )\n\t{\n\t\tif( !PrivacyConfig::whiteList().contains( msg.from()->protocol()->pluginId() + \":\" + msg.from()->contactId() ) )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message from \" << msg.from()->protocol()->pluginId() << \":\" << msg.from()->contactId() << \" dropped (not whitelisted)\" << endl;\n\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because this contact is not on your whitelist.\").arg(msg.from()->contactId()) );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n\telse if( PrivacyConfig::sender_AllowAllButBlackList() )\n\t{\n\t\tif( PrivacyConfig::blackList().contains( msg.from()->protocol()->pluginId() + \":\" + msg.from()->contactId() ) )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message from \" << msg.from()->protocol()->pluginId() << \":\" << msg.from()->contactId() << \" dropped (blacklisted)\" << endl;\n\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because this contact is on your blacklist.\").arg(msg.from()->contactId()) );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n\telse if( PrivacyConfig::sender_AllowNoneButContactList() )\n\t{\n\t\tif( msg.from()->metaContact()->isTemporary() )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message from \" << msg.from()->contactId() << \" dropped (not on the contactlist)\" << endl;\n\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because this contact is not on your contactlist.\").arg(msg.from()->contactId()) );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Verify content\n\tif( PrivacyConfig::content_DropIfAny() )\n\t{\n\t\tforeach(QString word, PrivacyConfig::dropIfAny().split(',') )\n\t\t{\n\t\t\tif( msg.plainBody().contains( word ) )\n\t\t\t{\n\t\t\t\tkDebug(14313) << k_funcinfo << \"Message dropped because it contained: \" << word << endl;\n\t\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because it contained a blacklisted word.\").arg(msg.from()->contactId()) );\n\t\t\t\tevent->discard();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tif( PrivacyConfig::content_DropIfAll() )\n\t{\n\t\tbool drop = true;\n\t\tforeach(QString word, PrivacyConfig::dropIfAll().split(',') )\n\t\t{\n\t\t\tif( !msg.plainBody().contains( word ) )\n\t\t\t{\n\t\t\t\tdrop = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif( drop )\n\t\t{\n\t\t\tkDebug(14313) << k_funcinfo << \"Message dropped because it contained blacklisted words.\" << endl;\n\t\t\t\tKNotification::event( \"message_dropped\", i18n(\"A message from %1 was dropped, because it contained blacklisted words.\").arg(msg.from()->contactId()) );\n\t\t\tevent->discard();\n\t\t\treturn;\n\t\t}\n\t}\n}\n\n#include \"privacyplugin.moc\"\n<|endoftext|>"} {"text":"#include \"BadGuyContainer.hpp\"\n#include \"SDL.hpp\" \/\/ randomNumberBetween()\n#include \"Window.hpp\"\n\n\nBadGuyContainer::BadGuyContainer(unsigned int maxAmmount, Rectangle *gameArea, PlatformManager *platforms) :\n venusCount(0),\n griffinCount(0),\n maxAmmount(maxAmmount),\n currentAmmount(0),\n gameArea(gameArea),\n platforms(platforms)\n{\n unsigned int i;\n int occupied = 0; \/\/ Say's if platform already occupied by Venus copy\n\n \/\/ ADDING EVERYONE\n \/\/ for (i = 0; i < this->maxAmmount; i++)\n \/\/ {\n \/\/ Point p;\n\n \/\/ if ((i % 2) == 0)\n \/\/ this->type = BadGuy::GRIFFIN;\n \/\/ else\n \/\/ this->type = BadGuy::VENUS;\n\n \/\/ if (this->type == BadGuy::GRIFFIN)\n \/\/ {\n \/\/ p.x = SDL::randomNumberBetween(0, this->gameArea->w);\n \/\/ p.y = SDL::randomNumberBetween(0, this->gameArea->h);\n \/\/ }\n \/\/ else \/\/ VENUS\n \/\/ {\n \/\/ std::list::iterator it = this->platforms->container->platforms.begin();\n \/\/ int j = 0;\n \/\/ while (j != occupied && it != this->platforms->container->platforms.end())\n \/\/ {\n \/\/ it++;\n \/\/ j++;\n \/\/ }\n\n \/\/ if (it != this->platforms->container->platforms.end() &&\n \/\/ (*it)->type != Platform::VANISHING &&\n \/\/ (*it)->type != Platform::MOVABLE)\n \/\/ {\n \/\/ p = (*it)->box->topLeft;\n \/\/ }\n \/\/ else\n \/\/ {\n \/\/ p.x = 0;\n \/\/ p.y = 0;\n \/\/ }\n \/\/ occupied++;\n \/\/ }\n \/\/ if (p.x != 0 && p.y != 0)\n \/\/ this->add(p, type);\n \/\/ }\n }\nBadGuyContainer::~BadGuyContainer()\n{\n unsigned int size = this->badguy.size();\n for (unsigned int i = 0; i < size; i++)\n if (this->badguy[i])\n delete (this->badguy[i]);\n}\nvoid BadGuyContainer::add(Point p, BadGuy::BadGuyType type)\n{\n std::vector::iterator it;\n it = this->badguy.begin();\n\n if (type == BadGuy::VENUS)\n {\n BadGuyVenus* v = new BadGuyVenus(p.x, p.y - 391, 142, 391, 1, Config::playerAcceleration);\n it = this->badguy.insert(it, v);\n\n this->venus.push_back(v);\n Log::verbose(\"Venus\");\n }\n else\n {\n BadGuyGriffin* g = new BadGuyGriffin(p.x - 292, p.y - 215, 292, 215, 1, Config::playerAcceleration);\n it = this->badguy.insert(it, g);\n\n this->griffin.push_back(g);\n Log::verbose(\"Griffin\");\n (*it)->setHorizontalLimit(60, this->gameArea->w - 119);\n (*it)->setVerticalLimit(215, rand()%this->gameArea->h);\n }\n\n Log::verbose(\"BadGuy::add (\" + SDL::intToString(p.x) +\n \", \" + SDL::intToString(p.y) +\n \") \" );\n}\nvoid BadGuyContainer::render(float cameraX, float cameraY)\n{\n this->cameraY = cameraY;\n\n unsigned int size = this->badguy.size();\n for (unsigned int i = 0; i < size; i++)\n if (this->badguy[i])\n this->badguy[i]->render(cameraX, cameraY);\n}\nvoid BadGuyContainer::update(float dt)\n{\n unsigned int size = this->badguy.size();\n for (unsigned int i = 0; i < size; i++)\n if (this->badguy[i])\n {\n \/\/ Will kill it if it's below current camera level\n if ((this->badguy[i]->box->bottom) > (this->cameraY + Window::height + 100))\n this->badguy[i]->die();\n\n if (this->badguy[i]->died())\n {\n if (this->badguy[i]->type == BadGuy::VENUS)\n this->venusCount--;\n else\n this->griffinCount--;\n\n delete this->badguy[i];\n this->badguy[i] = NULL;\n }\n else\n {\n this->badguy[i]->update(dt);\n this->badguy[i]->commitMovement();\n }\n }\n}\nvoid BadGuyContainer::addVenus()\n{\n for (std::list::iterator it = this->platforms->container->platforms.begin();\n it != this->platforms->container->platforms.end();\n it++)\n {\n \/\/ Kinda limited, right?\n if (((*it)->type == Platform::VANISHING) ||\n ((*it)->type == Platform::MOVABLE) ||\n ((*it)->type == Platform::CLOUD) ||\n ((*it)->occupied))\n continue;\n\n \/\/ Adding only on platforms above the current camera level\n if ((*it)->box->bottom < this->cameraY)\n {\n this->addVenusTo((*it));\n break;\n }\n }\n}\nvoid BadGuyContainer::addVenusTo(Platform* p)\n{\n p->occupied = true;\n\n BadGuyVenus* v = new BadGuyVenus(p->box->center.x - 30,\n p->box->top - 270,\n 98,\n 270,\n 1,\n Config::playerAcceleration);\n this->badguy.push_back(v);\n this->venusCount++;\n\n Log::verbose(\"Venus\");\n Log::verbose(\"BadGuy::add (\" + SDL::intToString(p->box->x) +\n \", \" + SDL::intToString(p->box->y) +\n \") \" );\n}\nvoid BadGuyContainer::addGriffin()\n{\n Point p;\n p.x = SDL::randomNumberBetween(0, this->gameArea->w);\n p.y = SDL::randomNumberBetween(this->cameraY - 100,\n this->cameraY);\n\n BadGuyGriffin* g = new BadGuyGriffin(p.x - 292,\n p.y - 215,\n 292,\n 215,\n 1,\n Config::playerAcceleration);\n\n g->setHorizontalLimit(60, this->gameArea->w - 119);\n\/\/ g->setVerticalLimit(215, SDL::randomNumberBetween(p.y - 1000, p.y + 1000));\n\n this->badguy.push_back(g);\n this->griffinCount++;\n\n Log::verbose(\"Griffin\");\n Log::verbose(\"BadGuy::add (\" + SDL::intToString(p.x) +\n \", \" + SDL::intToString(p.y) +\n \") \" );\n}\n\ngambiarras#include \"BadGuyContainer.hpp\"\n#include \"SDL.hpp\" \/\/ randomNumberBetween()\n#include \"Window.hpp\"\n\n\nBadGuyContainer::BadGuyContainer(unsigned int maxAmmount, Rectangle *gameArea, PlatformManager *platforms) :\n venusCount(0),\n griffinCount(0),\n maxAmmount(maxAmmount),\n currentAmmount(0),\n gameArea(gameArea),\n platforms(platforms)\n{\n unsigned int i;\n int occupied = 0; \/\/ Say's if platform already occupied by Venus copy\n\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n this->addGriffin();\n \/\/ ADDING EVERYONE\n \/\/ for (i = 0; i < this->maxAmmount; i++)\n \/\/ {\n \/\/ Point p;\n\n \/\/ if ((i % 2) == 0)\n \/\/ this->type = BadGuy::GRIFFIN;\n \/\/ else\n \/\/ this->type = BadGuy::VENUS;\n\n \/\/ if (this->type == BadGuy::GRIFFIN)\n \/\/ {\n \/\/ p.x = SDL::randomNumberBetween(0, this->gameArea->w);\n \/\/ p.y = SDL::randomNumberBetween(0, this->gameArea->h);\n \/\/ }\n \/\/ else \/\/ VENUS\n \/\/ {\n \/\/ std::list::iterator it = this->platforms->container->platforms.begin();\n \/\/ int j = 0;\n \/\/ while (j != occupied && it != this->platforms->container->platforms.end())\n \/\/ {\n \/\/ it++;\n \/\/ j++;\n \/\/ }\n\n \/\/ if (it != this->platforms->container->platforms.end() &&\n \/\/ (*it)->type != Platform::VANISHING &&\n \/\/ (*it)->type != Platform::MOVABLE)\n \/\/ {\n \/\/ p = (*it)->box->topLeft;\n \/\/ }\n \/\/ else\n \/\/ {\n \/\/ p.x = 0;\n \/\/ p.y = 0;\n \/\/ }\n \/\/ occupied++;\n \/\/ }\n \/\/ if (p.x != 0 && p.y != 0)\n \/\/ this->add(p, type);\n \/\/ }\n }\nBadGuyContainer::~BadGuyContainer()\n{\n unsigned int size = this->badguy.size();\n for (unsigned int i = 0; i < size; i++)\n if (this->badguy[i])\n delete (this->badguy[i]);\n}\nvoid BadGuyContainer::add(Point p, BadGuy::BadGuyType type)\n{\n std::vector::iterator it;\n it = this->badguy.begin();\n\n if (type == BadGuy::VENUS)\n {\n BadGuyVenus* v = new BadGuyVenus(p.x, p.y - 391, 142, 391, 1, Config::playerAcceleration);\n it = this->badguy.insert(it, v);\n\n this->venus.push_back(v);\n Log::verbose(\"Venus\");\n }\n else\n {\n BadGuyGriffin* g = new BadGuyGriffin(p.x - 292, p.y - 215, 292, 215, 1, Config::playerAcceleration);\n it = this->badguy.insert(it, g);\n\n this->griffin.push_back(g);\n Log::verbose(\"Griffin\");\n (*it)->setHorizontalLimit(60, this->gameArea->w - 119);\n (*it)->setVerticalLimit(215, rand()%this->gameArea->h);\n }\n\n Log::verbose(\"BadGuy::add (\" + SDL::intToString(p.x) +\n \", \" + SDL::intToString(p.y) +\n \") \" );\n}\nvoid BadGuyContainer::render(float cameraX, float cameraY)\n{\n this->cameraY = cameraY;\n\n unsigned int size = this->badguy.size();\n for (unsigned int i = 0; i < size; i++)\n if (this->badguy[i])\n this->badguy[i]->render(cameraX, cameraY);\n}\nvoid BadGuyContainer::update(float dt)\n{\n unsigned int size = this->badguy.size();\n for (unsigned int i = 0; i < size; i++)\n if (this->badguy[i])\n {\n \/\/ Will kill it if it's below current camera level\n if ((this->badguy[i]->box->bottom) > (this->cameraY + Window::height + 100))\n this->badguy[i]->die();\n\n if (this->badguy[i]->died())\n {\n if (this->badguy[i]->type == BadGuy::VENUS)\n this->venusCount--;\n else\n this->griffinCount--;\n\n delete this->badguy[i];\n this->badguy[i] = NULL;\n }\n else\n {\n this->badguy[i]->update(dt);\n this->badguy[i]->commitMovement();\n }\n }\n}\nvoid BadGuyContainer::addVenus()\n{\n for (std::list::iterator it = this->platforms->container->platforms.begin();\n it != this->platforms->container->platforms.end();\n it++)\n {\n \/\/ Kinda limited, right?\n if (((*it)->type == Platform::VANISHING) ||\n ((*it)->type == Platform::MOVABLE) ||\n ((*it)->type == Platform::CLOUD) ||\n ((*it)->occupied))\n continue;\n\n \/\/ Adding only on platforms above the current camera level\n if ((*it)->box->bottom < this->cameraY)\n {\n this->addVenusTo((*it));\n break;\n }\n }\n}\nvoid BadGuyContainer::addVenusTo(Platform* p)\n{\n p->occupied = true;\n\n BadGuyVenus* v = new BadGuyVenus(p->box->center.x - 30,\n p->box->top - 270,\n 98,\n 270,\n 1,\n Config::playerAcceleration);\n this->badguy.push_back(v);\n this->venusCount++;\n\n Log::verbose(\"Venus\");\n Log::verbose(\"BadGuy::add (\" + SDL::intToString(p->box->x) +\n \", \" + SDL::intToString(p->box->y) +\n \") \" );\n}\nvoid BadGuyContainer::addGriffin()\n{\n Point p;\n p.x = SDL::randomNumberBetween(0, this->gameArea->w);\n p.y = SDL::randomNumberBetween(0, this->gameArea->h);\n\n BadGuyGriffin* g = new BadGuyGriffin(p.x - 292,\n p.y - 215,\n 292,\n 215,\n 1,\n Config::playerAcceleration);\n\n g->setHorizontalLimit(60, this->gameArea->w - 119);\n g->setVerticalLimit(215, SDL::randomNumberBetween(0, this->gameArea->h));\n\n this->badguy.push_back(g);\n this->griffinCount++;\n\n Log::verbose(\"Griffin\");\n Log::verbose(\"BadGuy::add (\" + SDL::intToString(p.x) +\n \", \" + SDL::intToString(p.y) +\n \") \" );\n}\n\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ SymbolicMath toolkit\n\/\/\/ (c) 2017-2020 by Daniel Schwen\n\/\/\/\n\n#include \"SMTransformHash.h\"\n#include \"SMFunction.h\"\n\nnamespace SymbolicMath\n{\n\ntemplate \nHash::Hash(Function & fb) : Transform(fb)\n{\n apply();\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, SymbolData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n setHash(node, salt ^ std::hash{}(data._name));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, UnaryOperatorData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n setHash(node, salt ^ std::hash{}(data._type) ^ (_hash << 1));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, BinaryOperatorData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n const auto hashA = _hash << 1;\n data._args[1].apply(*this);\n const auto hashB = _hash << 2;\n setHash(node, salt ^ std::hash{}(data._type) ^ hashA ^ hashB);\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, MultinaryOperatorData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n auto h = salt ^ std::hash{}(data._type);\n for (auto & arg : data._args)\n {\n arg.apply(*this);\n h = (h << 1) ^ _hash;\n }\n setHash(node, h);\n}\n\ntemplate <>\nvoid\nHash::operator()(Node & node, UnaryFunctionData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n setHash(node, salt ^ std::hash{}(data._type) ^ (_hash << 1));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, BinaryFunctionData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n const auto hashA = _hash << 1;\n data._args[1].apply(*this);\n const auto hashB = _hash << 2;\n setHash(node, salt ^ std::hash{}(data._type) ^ hashA ^ hashB);\n}\n\ntemplate <>\nvoid\nHash::operator()(Node & node, RealNumberData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n setHash(node, salt ^ std::hash{}(data._value));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, RealReferenceData & data)\n{\n setHash(node, std::hash{}(&data._ref));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, RealArrayReferenceData & data)\n{\n fatalError(\"Not implemented yet\");\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, LocalVariableData & data)\n{\n fatalError(\"Not implemented\");\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, ConditionalData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n const auto hashA = _hash << 1;\n data._args[1].apply(*this);\n const auto hashB = _hash << 2;\n data._args[2].apply(*this);\n const auto hashC = _hash << 3;\n setHash(node, salt ^ hashA ^ hashB ^ hashC);\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, IntegerPowerData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._arg.apply(*this);\n setHash(node, salt ^ _hash ^ (std::hash{}(data._exponent) << 1));\n}\n\ntemplate \nvoid\nHash::setHash(Node & node, std::size_t h)\n{\n _hash = h;\n _hash_map.emplace(h, &node);\n}\n\ntemplate class Hash;\n\n} \/\/ namespace SymbolicMath\nadd missing header\/\/\/\n\/\/\/ SymbolicMath toolkit\n\/\/\/ (c) 2017-2020 by Daniel Schwen\n\/\/\/\n\n#include \"SMTransformHash.h\"\n#include \"SMFunction.h\"\n\n#include \n\nnamespace SymbolicMath\n{\n\ntemplate \nHash::Hash(Function & fb) : Transform(fb)\n{\n apply();\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, SymbolData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n setHash(node, salt ^ std::hash{}(data._name));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, UnaryOperatorData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n setHash(node, salt ^ std::hash{}(data._type) ^ (_hash << 1));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, BinaryOperatorData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n const auto hashA = _hash << 1;\n data._args[1].apply(*this);\n const auto hashB = _hash << 2;\n setHash(node, salt ^ std::hash{}(data._type) ^ hashA ^ hashB);\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, MultinaryOperatorData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n auto h = salt ^ std::hash{}(data._type);\n for (auto & arg : data._args)\n {\n arg.apply(*this);\n h = (h << 1) ^ _hash;\n }\n setHash(node, h);\n}\n\ntemplate <>\nvoid\nHash::operator()(Node & node, UnaryFunctionData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n setHash(node, salt ^ std::hash{}(data._type) ^ (_hash << 1));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, BinaryFunctionData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n const auto hashA = _hash << 1;\n data._args[1].apply(*this);\n const auto hashB = _hash << 2;\n setHash(node, salt ^ std::hash{}(data._type) ^ hashA ^ hashB);\n}\n\ntemplate <>\nvoid\nHash::operator()(Node & node, RealNumberData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n setHash(node, salt ^ std::hash{}(data._value));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, RealReferenceData & data)\n{\n setHash(node, std::hash{}(&data._ref));\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, RealArrayReferenceData & data)\n{\n fatalError(\"Not implemented yet\");\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, LocalVariableData & data)\n{\n fatalError(\"Not implemented\");\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, ConditionalData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._args[0].apply(*this);\n const auto hashA = _hash << 1;\n data._args[1].apply(*this);\n const auto hashB = _hash << 2;\n data._args[2].apply(*this);\n const auto hashC = _hash << 3;\n setHash(node, salt ^ hashA ^ hashB ^ hashC);\n}\n\ntemplate \nvoid\nHash::operator()(Node & node, IntegerPowerData & data)\n{\n static const std::size_t salt = std::hash{}(reinterpret_cast(&salt));\n\n data._arg.apply(*this);\n setHash(node, salt ^ _hash ^ (std::hash{}(data._exponent) << 1));\n}\n\ntemplate \nvoid\nHash::setHash(Node & node, std::size_t h)\n{\n _hash = h;\n _hash_map.emplace(h, &node);\n}\n\ntemplate class Hash;\n\n} \/\/ namespace SymbolicMath\n<|endoftext|>"} {"text":"fixed typo<|endoftext|>"} {"text":"\n\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \"libtorrent\/invariant_check.hpp\"\n#include \"libtorrent\/connection_queue.hpp\"\n\nnamespace libtorrent\n{\n\n\tconnection_queue::connection_queue(io_service& ios): m_next_ticket(0)\n\t\t, m_num_connecting(0)\n\t\t, m_half_open_limit(0)\n\t\t, m_timer(ios)\n#ifndef NDEBUG\n\t\t, m_in_timeout_function(false)\n#endif\n\t{}\n\n\tbool connection_queue::free_slots() const\n\t{ return m_num_connecting < m_half_open_limit || m_half_open_limit <= 0; }\n\n\tvoid connection_queue::enqueue(boost::function const& on_connect\n\t\t, boost::function const& on_timeout\n\t\t, time_duration timeout)\n\t{\n\t\tmutex_t::scoped_lock l(m_mutex);\n\n\t\tINVARIANT_CHECK;\n\n\t\tm_queue.push_back(entry());\n\t\tentry& e = m_queue.back();\n\t\te.on_connect = on_connect;\n\t\te.on_timeout = on_timeout;\n\t\te.ticket = m_next_ticket;\n\t\te.timeout = timeout;\n\t\t++m_next_ticket;\n\t\ttry_connect();\n\t}\n\n\tvoid connection_queue::done(int ticket)\n\t{\n\t\tmutex_t::scoped_lock l(m_mutex);\n\n\t\tINVARIANT_CHECK;\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);\n\t\tif (i == m_queue.end())\n\t\t{\n\t\t\t\/\/ this might not be here in case on_timeout calls remove\n\t\t\treturn;\n\t\t}\n\t\tif (i->connecting) --m_num_connecting;\n\t\tm_queue.erase(i);\n\t\ttry_connect();\n\t}\n\n\tvoid connection_queue::close()\n\t{\n\t\tm_timer.cancel();\n\t}\n\n\tvoid connection_queue::limit(int limit)\n\t{ m_half_open_limit = limit; }\n\n\tint connection_queue::limit() const\n\t{ return m_half_open_limit; }\n\n#ifndef NDEBUG\n\n\tvoid connection_queue::check_invariant() const\n\t{\n\t\tint num_connecting = 0;\n\t\tfor (std::list::const_iterator i = m_queue.begin();\n\t\t\ti != m_queue.end(); ++i)\n\t\t{\n\t\t\tif (i->connecting) ++num_connecting;\n\t\t}\n\t\tTORRENT_ASSERT(num_connecting == m_num_connecting);\n\t}\n\n#endif\n\n\tvoid connection_queue::try_connect()\n\t{\n\t\tINVARIANT_CHECK;\n\n\t\tif (!free_slots())\n\t\t\treturn;\n\t\n\t\tif (m_queue.empty())\n\t\t{\n\t\t\tm_timer.cancel();\n\t\t\treturn;\n\t\t}\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\t\twhile (i != m_queue.end())\n\t\t{\n\t\t\tTORRENT_ASSERT(i->connecting == false);\n\t\t\tptime expire = time_now() + i->timeout;\n\t\t\tif (m_num_connecting == 0)\n\t\t\t{\n\t\t\t\tm_timer.expires_at(expire);\n\t\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t\t}\n\t\t\ti->connecting = true;\n\t\t\t++m_num_connecting;\n\t\t\ti->expires = expire;\n\n\t\t\tINVARIANT_CHECK;\n\n\t\t\tentry& ent = *i;\n\t\t\t++i;\n\t\t\ttry { ent.on_connect(ent.ticket); } catch (std::exception&) {}\n\n\t\t\tif (!free_slots()) break;\n\t\t\ti = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\t\t}\n\t}\n\n#ifndef NDEBUG\n\tstruct function_guard\n\t{\n\t\tfunction_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; }\n\t\t~function_guard() { val = false; }\n\n\t\tbool& val;\n\t};\n#endif\n\t\n\tvoid connection_queue::on_timeout(asio::error_code const& e)\n\t{\n\t\tmutex_t::scoped_lock l(m_mutex);\n\n\t\tINVARIANT_CHECK;\n#ifndef NDEBUG\n\t\tfunction_guard guard_(m_in_timeout_function);\n#endif\n\n\t\tTORRENT_ASSERT(!e || e == asio::error::operation_aborted);\n\t\tif (e) return;\n\n\t\tptime next_expire = max_time();\n\t\tptime now = time_now();\n\t\tstd::list timed_out;\n\t\tfor (std::list::iterator i = m_queue.begin();\n\t\t\t!m_queue.empty() && i != m_queue.end();)\n\t\t{\n\t\t\tif (i->connecting && i->expires < now)\n\t\t\t{\n\t\t\t\tstd::list::iterator j = i;\n\t\t\t\t++i;\n\t\t\t\ttimed_out.splice(timed_out.end(), m_queue, j, i);\n\t\t\t\t--m_num_connecting;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (i->expires < next_expire)\n\t\t\t\tnext_expire = i->expires;\n\t\t\t++i;\n\t\t}\n\n\t\t\/\/ we don't want to call the timeout callback while we're locked\n\t\t\/\/ since that is a recepie for dead-locks\n\t\tl.unlock();\n\n\t\tfor (std::list::iterator i = timed_out.begin()\n\t\t\t, end(timed_out.end()); i != end; ++i)\n\t\t{\n\t\t\ttry { i->on_timeout(); } catch (std::exception&) {}\n\t\t}\n\t\t\n\t\tl.lock();\n\t\t\n\t\tif (next_expire < max_time())\n\t\t{\n\t\t\tm_timer.expires_at(next_expire);\n\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t}\n\t\ttry_connect();\n\t}\n\n}\n\nmade connection queue build without exception support\n\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \"libtorrent\/invariant_check.hpp\"\n#include \"libtorrent\/connection_queue.hpp\"\n\nnamespace libtorrent\n{\n\n\tconnection_queue::connection_queue(io_service& ios): m_next_ticket(0)\n\t\t, m_num_connecting(0)\n\t\t, m_half_open_limit(0)\n\t\t, m_timer(ios)\n#ifndef NDEBUG\n\t\t, m_in_timeout_function(false)\n#endif\n\t{}\n\n\tbool connection_queue::free_slots() const\n\t{ return m_num_connecting < m_half_open_limit || m_half_open_limit <= 0; }\n\n\tvoid connection_queue::enqueue(boost::function const& on_connect\n\t\t, boost::function const& on_timeout\n\t\t, time_duration timeout)\n\t{\n\t\tmutex_t::scoped_lock l(m_mutex);\n\n\t\tINVARIANT_CHECK;\n\n\t\tm_queue.push_back(entry());\n\t\tentry& e = m_queue.back();\n\t\te.on_connect = on_connect;\n\t\te.on_timeout = on_timeout;\n\t\te.ticket = m_next_ticket;\n\t\te.timeout = timeout;\n\t\t++m_next_ticket;\n\t\ttry_connect();\n\t}\n\n\tvoid connection_queue::done(int ticket)\n\t{\n\t\tmutex_t::scoped_lock l(m_mutex);\n\n\t\tINVARIANT_CHECK;\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);\n\t\tif (i == m_queue.end())\n\t\t{\n\t\t\t\/\/ this might not be here in case on_timeout calls remove\n\t\t\treturn;\n\t\t}\n\t\tif (i->connecting) --m_num_connecting;\n\t\tm_queue.erase(i);\n\t\ttry_connect();\n\t}\n\n\tvoid connection_queue::close()\n\t{\n\t\tasio::error_code ec;\n\t\tm_timer.cancel(ec);\n\t}\n\n\tvoid connection_queue::limit(int limit)\n\t{ m_half_open_limit = limit; }\n\n\tint connection_queue::limit() const\n\t{ return m_half_open_limit; }\n\n#ifndef NDEBUG\n\n\tvoid connection_queue::check_invariant() const\n\t{\n\t\tint num_connecting = 0;\n\t\tfor (std::list::const_iterator i = m_queue.begin();\n\t\t\ti != m_queue.end(); ++i)\n\t\t{\n\t\t\tif (i->connecting) ++num_connecting;\n\t\t}\n\t\tTORRENT_ASSERT(num_connecting == m_num_connecting);\n\t}\n\n#endif\n\n\tvoid connection_queue::try_connect()\n\t{\n\t\tINVARIANT_CHECK;\n\n\t\tif (!free_slots())\n\t\t\treturn;\n\t\n\t\tif (m_queue.empty())\n\t\t{\n\t\t\tasio::error_code ec;\n\t\t\tm_timer.cancel(ec);\n\t\t\treturn;\n\t\t}\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\t\twhile (i != m_queue.end())\n\t\t{\n\t\t\tTORRENT_ASSERT(i->connecting == false);\n\t\t\tptime expire = time_now() + i->timeout;\n\t\t\tif (m_num_connecting == 0)\n\t\t\t{\n\t\t\t\tasio::error_code ec;\n\t\t\t\tm_timer.expires_at(expire, ec);\n\t\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t\t}\n\t\t\ti->connecting = true;\n\t\t\t++m_num_connecting;\n\t\t\ti->expires = expire;\n\n\t\t\tINVARIANT_CHECK;\n\n\t\t\tentry& ent = *i;\n\t\t\t++i;\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t\ttry {\n#endif\n\t\t\t\tent.on_connect(ent.ticket);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t\t} catch (std::exception&) {}\n#endif\n\n\t\t\tif (!free_slots()) break;\n\t\t\ti = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\t\t}\n\t}\n\n#ifndef NDEBUG\n\tstruct function_guard\n\t{\n\t\tfunction_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; }\n\t\t~function_guard() { val = false; }\n\n\t\tbool& val;\n\t};\n#endif\n\t\n\tvoid connection_queue::on_timeout(asio::error_code const& e)\n\t{\n\t\tmutex_t::scoped_lock l(m_mutex);\n\n\t\tINVARIANT_CHECK;\n#ifndef NDEBUG\n\t\tfunction_guard guard_(m_in_timeout_function);\n#endif\n\n\t\tTORRENT_ASSERT(!e || e == asio::error::operation_aborted);\n\t\tif (e) return;\n\n\t\tptime next_expire = max_time();\n\t\tptime now = time_now();\n\t\tstd::list timed_out;\n\t\tfor (std::list::iterator i = m_queue.begin();\n\t\t\t!m_queue.empty() && i != m_queue.end();)\n\t\t{\n\t\t\tif (i->connecting && i->expires < now)\n\t\t\t{\n\t\t\t\tstd::list::iterator j = i;\n\t\t\t\t++i;\n\t\t\t\ttimed_out.splice(timed_out.end(), m_queue, j, i);\n\t\t\t\t--m_num_connecting;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (i->expires < next_expire)\n\t\t\t\tnext_expire = i->expires;\n\t\t\t++i;\n\t\t}\n\n\t\t\/\/ we don't want to call the timeout callback while we're locked\n\t\t\/\/ since that is a recepie for dead-locks\n\t\tl.unlock();\n\n\t\tfor (std::list::iterator i = timed_out.begin()\n\t\t\t, end(timed_out.end()); i != end; ++i)\n\t\t{\n\t\t\ttry { i->on_timeout(); } catch (std::exception&) {}\n\t\t}\n\t\t\n\t\tl.lock();\n\t\t\n\t\tif (next_expire < max_time())\n\t\t{\n\t\t\tasio::error_code ec;\n\t\t\tm_timer.expires_at(next_expire, ec);\n\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t}\n\t\ttry_connect();\n\t}\n\n}\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/invariant_check.hpp\"\n#include \"libtorrent\/connection_queue.hpp\"\n#include \"libtorrent\/io_service.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/error.hpp\"\n\n#if defined TORRENT_ASIO_DEBUGGING\n#include \"libtorrent\/debug.hpp\"\n#endif\n\nnamespace libtorrent\n{\n\n\tconnection_queue::connection_queue(io_service& ios): m_next_ticket(0)\n\t\t, m_num_connecting(0)\n\t\t, m_half_open_limit(0)\n\t\t, m_timer(ios)\n#ifdef TORRENT_DEBUG\n\t\t, m_in_timeout_function(false)\n#endif\n\t{\n#ifdef TORRENT_CONNECTION_LOGGING\n\t\tm_log.open(\"connection_queue.log\");\n#endif\n\t}\n\n\tint connection_queue::free_slots() const\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\t\treturn m_half_open_limit == 0 ? (std::numeric_limits::max)()\n\t\t\t: m_half_open_limit - m_queue.size();\n\t}\n\n\tvoid connection_queue::enqueue(boost::function const& on_connect\n\t\t, boost::function const& on_timeout\n\t\t, time_duration timeout, int priority)\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\n\t\tINVARIANT_CHECK;\n\n\t\tTORRENT_ASSERT(priority >= 0);\n\t\tTORRENT_ASSERT(priority < 3);\n\n\t\tentry* e = 0;\n\n\t\tswitch (priority)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tm_queue.push_back(entry());\n\t\t\t\te = &m_queue.back();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\tcase 2:\n\t\t\t\tm_queue.push_front(entry());\n\t\t\t\te = &m_queue.front();\n\t\t\t\tbreak;\n\t\t\tdefault: return;\n\t\t}\n\n\t\te->priority = priority;\n\t\te->on_connect = on_connect;\n\t\te->on_timeout = on_timeout;\n\t\te->ticket = m_next_ticket;\n\t\te->timeout = timeout;\n\t\t++m_next_ticket;\n\n\t\tif (m_num_connecting < m_half_open_limit\n\t\t\t|| m_half_open_limit == 0)\n\t\t\tm_timer.get_io_service().post(boost::bind(\n\t\t\t\t&connection_queue::on_try_connect, this));\n\t}\n\n\tvoid connection_queue::done(int ticket)\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\n\t\tINVARIANT_CHECK;\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);\n\t\tif (i == m_queue.end())\n\t\t{\n\t\t\t\/\/ this might not be here in case on_timeout calls remove\n\t\t\treturn;\n\t\t}\n\t\tif (i->connecting) --m_num_connecting;\n\t\tm_queue.erase(i);\n\n\t\tif (m_num_connecting < m_half_open_limit\n\t\t\t|| m_half_open_limit == 0)\n\t\t\tm_timer.get_io_service().post(boost::bind(\n\t\t\t\t&connection_queue::on_try_connect, this));\n\t}\n\n\tvoid connection_queue::close()\n\t{\n\t\terror_code ec;\n\t\tTORRENT_ASSERT(is_single_thread());\n\t\tif (m_num_connecting == 0) m_timer.cancel(ec);\n\n\t\tstd::list tmp;\n\t\ttmp.swap(m_queue);\n\t\tm_num_connecting = 0;\n\n\t\twhile (!tmp.empty())\n\t\t{\n\t\t\tentry& e = tmp.front();\n\t\t\tif (e.priority > 1)\n\t\t\t{\n\t\t\t\tif (e.connecting) ++m_num_connecting;\n\t\t\t\tm_queue.push_back(e);\n\t\t\t\ttmp.pop_front();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tTORRENT_TRY {\n\t\t\t\te.on_timeout();\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t\ttmp.pop_front();\n\t\t}\n\t}\n\n\tvoid connection_queue::limit(int limit)\n\t{\n\t\tTORRENT_ASSERT(limit >= 0);\n\t\tm_half_open_limit = limit;\n\t}\n\n\tint connection_queue::limit() const\n\t{ return m_half_open_limit; }\n\n#ifdef TORRENT_DEBUG\n\n\tvoid connection_queue::check_invariant() const\n\t{\n\t\tint num_connecting = 0;\n\t\tfor (std::list::const_iterator i = m_queue.begin();\n\t\t\ti != m_queue.end(); ++i)\n\t\t{\n\t\t\tif (i->connecting) ++num_connecting;\n\t\t\telse TORRENT_ASSERT(i->expires == max_time());\n\t\t}\n\t\tTORRENT_ASSERT(num_connecting == m_num_connecting);\n\t}\n\n#endif\n\n\tvoid connection_queue::try_connect()\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\t\tINVARIANT_CHECK;\n\n#ifdef TORRENT_CONNECTION_LOGGING\n\t\tm_log << log_time() << \" \" << free_slots() << std::endl;\n#endif\n\n\t\tif (m_num_connecting >= m_half_open_limit\n\t\t\t&& m_half_open_limit > 0) return;\n\t\n\t\tif (m_queue.empty())\n\t\t{\n\t\t\tTORRENT_ASSERT(m_num_connecting == 0);\n\t\t\terror_code ec;\n\t\t\tm_timer.cancel(ec);\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ all entries are connecting, no need to look for new ones\n\t\tif (m_queue.size() == m_num_connecting)\n\t\t\treturn;\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\n\t\tstd::list to_connect;\n\n\t\twhile (i != m_queue.end())\n\t\t{\n\t\t\tTORRENT_ASSERT(i->connecting == false);\n\t\t\tptime expire = time_now_hires() + i->timeout;\n\t\t\tif (m_num_connecting == 0)\n\t\t\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\t\t\tadd_outstanding_async(\"connection_queue::on_timeout\");\n#endif\n\t\t\t\terror_code ec;\n\t\t\t\tm_timer.expires_at(expire, ec);\n\t\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t\t}\n\t\t\ti->connecting = true;\n\t\t\t++m_num_connecting;\n\t\t\ti->expires = expire;\n\n\t\t\tINVARIANT_CHECK;\n\n\t\t\tto_connect.push_back(*i);\n\n#ifdef TORRENT_CONNECTION_LOGGING\n\t\t\tm_log << log_time() << \" \" << free_slots() << std::endl;\n#endif\n\n\t\t\tif (m_num_connecting >= m_half_open_limit\n\t\t\t\t&& m_half_open_limit > 0) break;\n\t\t\ti = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\t\t}\n\n\t\twhile (!to_connect.empty())\n\t\t{\n\t\t\tentry& ent = to_connect.front();\n\t\t\tTORRENT_ASSERT(m_num_connecting > 0);\n#if defined TORRENT_ASIO_DEBUGGING\n\t\t\tTORRENT_ASSERT(has_outstanding_async(\"connection_queue::on_timeout\"));\n#endif\n\t\t\tTORRENT_TRY {\n\t\t\t\tent.on_connect(ent.ticket);\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t\tto_connect.pop_front();\n\t\t}\n\t}\n\n#ifdef TORRENT_DEBUG\n\tstruct function_guard\n\t{\n\t\tfunction_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; }\n\t\t~function_guard() { val = false; }\n\n\t\tbool& val;\n\t};\n#endif\n\t\n\tvoid connection_queue::on_timeout(error_code const& e)\n\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\tcomplete_async(\"connection_queue::on_timeout\");\n#endif\n\n\t\tINVARIANT_CHECK;\n#ifdef TORRENT_DEBUG\n\t\tfunction_guard guard_(m_in_timeout_function);\n#endif\n\n\t\tTORRENT_ASSERT(!e || e == error::operation_aborted);\n\t\tif (e && m_num_connecting == 0)\n\t\t\treturn;\n\n\t\tptime next_expire = max_time();\n\t\tptime now = time_now_hires() + milliseconds(100);\n\t\tstd::list timed_out;\n\t\tfor (std::list::iterator i = m_queue.begin();\n\t\t\t!m_queue.empty() && i != m_queue.end();)\n\t\t{\n\t\t\tif (i->connecting && i->expires < now)\n\t\t\t{\n\t\t\t\tstd::list::iterator j = i;\n\t\t\t\t++i;\n\t\t\t\ttimed_out.splice(timed_out.end(), m_queue, j, i);\n\t\t\t\t--m_num_connecting;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (i->connecting && i->expires < next_expire)\n\t\t\t\tnext_expire = i->expires;\n\t\t\t++i;\n\t\t}\n\n\t\tfor (std::list::iterator i = timed_out.begin()\n\t\t\t, end(timed_out.end()); i != end; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(i->connecting);\n\t\t\tTORRENT_ASSERT(i->ticket != -1);\n\t\t\tTORRENT_TRY {\n\t\t\t\ti->on_timeout();\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t}\n\t\t\n\t\tif (next_expire < max_time())\n\t\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\t\tadd_outstanding_async(\"connection_queue::on_timeout\");\n#endif\n\t\t\terror_code ec;\n\t\t\tm_timer.expires_at(next_expire, ec);\n\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t}\n\t\ttry_connect();\n\t}\n\n\tvoid connection_queue::on_try_connect()\n\t{\n\t\ttry_connect();\n\t}\n}\n\nrevert previous connection_queue change and one more optimization\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/invariant_check.hpp\"\n#include \"libtorrent\/connection_queue.hpp\"\n#include \"libtorrent\/io_service.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/error.hpp\"\n\n#if defined TORRENT_ASIO_DEBUGGING\n#include \"libtorrent\/debug.hpp\"\n#endif\n\nnamespace libtorrent\n{\n\n\tconnection_queue::connection_queue(io_service& ios): m_next_ticket(0)\n\t\t, m_num_connecting(0)\n\t\t, m_half_open_limit(0)\n\t\t, m_timer(ios)\n#ifdef TORRENT_DEBUG\n\t\t, m_in_timeout_function(false)\n#endif\n\t{\n#ifdef TORRENT_CONNECTION_LOGGING\n\t\tm_log.open(\"connection_queue.log\");\n#endif\n\t}\n\n\tint connection_queue::free_slots() const\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\t\treturn m_half_open_limit == 0 ? (std::numeric_limits::max)()\n\t\t\t: m_half_open_limit - m_queue.size();\n\t}\n\n\tvoid connection_queue::enqueue(boost::function const& on_connect\n\t\t, boost::function const& on_timeout\n\t\t, time_duration timeout, int priority)\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\n\t\tINVARIANT_CHECK;\n\n\t\tTORRENT_ASSERT(priority >= 0);\n\t\tTORRENT_ASSERT(priority < 3);\n\n\t\tentry* e = 0;\n\n\t\tswitch (priority)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tm_queue.push_back(entry());\n\t\t\t\te = &m_queue.back();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\tcase 2:\n\t\t\t\tm_queue.push_front(entry());\n\t\t\t\te = &m_queue.front();\n\t\t\t\tbreak;\n\t\t\tdefault: return;\n\t\t}\n\n\t\te->priority = priority;\n\t\te->on_connect = on_connect;\n\t\te->on_timeout = on_timeout;\n\t\te->ticket = m_next_ticket;\n\t\te->timeout = timeout;\n\t\t++m_next_ticket;\n\n\t\tif (m_num_connecting < m_half_open_limit\n\t\t\t|| m_half_open_limit == 0)\n\t\t\tm_timer.get_io_service().post(boost::bind(\n\t\t\t\t&connection_queue::on_try_connect, this));\n\t}\n\n\tvoid connection_queue::done(int ticket)\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\n\t\tINVARIANT_CHECK;\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);\n\t\tif (i == m_queue.end())\n\t\t{\n\t\t\t\/\/ this might not be here in case on_timeout calls remove\n\t\t\treturn;\n\t\t}\n\t\tif (i->connecting) --m_num_connecting;\n\t\tm_queue.erase(i);\n\n\t\tif (m_num_connecting < m_half_open_limit\n\t\t\t|| m_half_open_limit == 0)\n\t\t\tm_timer.get_io_service().post(boost::bind(\n\t\t\t\t&connection_queue::on_try_connect, this));\n\t}\n\n\tvoid connection_queue::close()\n\t{\n\t\terror_code ec;\n\t\tTORRENT_ASSERT(is_single_thread());\n\t\tif (m_num_connecting == 0) m_timer.cancel(ec);\n\n\t\tstd::list tmp;\n\t\ttmp.swap(m_queue);\n\t\tm_num_connecting = 0;\n\n\t\twhile (!tmp.empty())\n\t\t{\n\t\t\tentry& e = tmp.front();\n\t\t\tif (e.priority > 1)\n\t\t\t{\n\t\t\t\tif (e.connecting) ++m_num_connecting;\n\t\t\t\tm_queue.push_back(e);\n\t\t\t\ttmp.pop_front();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tTORRENT_TRY {\n\t\t\t\te.on_timeout();\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t\ttmp.pop_front();\n\t\t}\n\t}\n\n\tvoid connection_queue::limit(int limit)\n\t{\n\t\tTORRENT_ASSERT(limit >= 0);\n\t\tm_half_open_limit = limit;\n\t}\n\n\tint connection_queue::limit() const\n\t{ return m_half_open_limit; }\n\n#ifdef TORRENT_DEBUG\n\n\tvoid connection_queue::check_invariant() const\n\t{\n\t\tint num_connecting = 0;\n\t\tfor (std::list::const_iterator i = m_queue.begin();\n\t\t\ti != m_queue.end(); ++i)\n\t\t{\n\t\t\tif (i->connecting) ++num_connecting;\n\t\t\telse TORRENT_ASSERT(i->expires == max_time());\n\t\t}\n\t\tTORRENT_ASSERT(num_connecting == m_num_connecting);\n\t}\n\n#endif\n\n\tvoid connection_queue::try_connect()\n\t{\n\t\tTORRENT_ASSERT(is_single_thread());\n\t\tINVARIANT_CHECK;\n\n#ifdef TORRENT_CONNECTION_LOGGING\n\t\tm_log << log_time() << \" \" << free_slots() << std::endl;\n#endif\n\n\t\tif (m_num_connecting >= m_half_open_limit\n\t\t\t&& m_half_open_limit > 0) return;\n\t\n\t\tif (m_queue.empty())\n\t\t{\n\t\t\tTORRENT_ASSERT(m_num_connecting == 0);\n\t\t\terror_code ec;\n\t\t\tm_timer.cancel(ec);\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ all entries are connecting, no need to look for new ones\n\t\tif (m_queue.size() == m_num_connecting)\n\t\t\treturn;\n\n\t\tstd::list::iterator i = std::find_if(m_queue.begin()\n\t\t\t, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\n\t\tstd::list to_connect;\n\n\t\twhile (i != m_queue.end())\n\t\t{\n\t\t\tTORRENT_ASSERT(i->connecting == false);\n\t\t\tptime expire = time_now_hires() + i->timeout;\n\t\t\tif (m_num_connecting == 0)\n\t\t\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\t\t\tadd_outstanding_async(\"connection_queue::on_timeout\");\n#endif\n\t\t\t\terror_code ec;\n\t\t\t\tm_timer.expires_at(expire, ec);\n\t\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t\t}\n\t\t\ti->connecting = true;\n\t\t\t++m_num_connecting;\n\t\t\ti->expires = expire;\n\n\t\t\tINVARIANT_CHECK;\n\n\t\t\tto_connect.push_back(*i);\n\n#ifdef TORRENT_CONNECTION_LOGGING\n\t\t\tm_log << log_time() << \" \" << free_slots() << std::endl;\n#endif\n\n\t\t\tif (m_num_connecting >= m_half_open_limit\n\t\t\t\t&& m_half_open_limit > 0) break;\n\t\t\tif (m_num_connecting == m_queue.size()) break;\n\t\t\ti = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);\n\t\t}\n\n\t\twhile (!to_connect.empty())\n\t\t{\n\t\t\tentry& ent = to_connect.front();\n\t\t\tTORRENT_ASSERT(m_num_connecting > 0);\n#if defined TORRENT_ASIO_DEBUGGING\n\t\t\tTORRENT_ASSERT(has_outstanding_async(\"connection_queue::on_timeout\"));\n#endif\n\t\t\tTORRENT_TRY {\n\t\t\t\tent.on_connect(ent.ticket);\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t\tto_connect.pop_front();\n\t\t}\n\t}\n\n#ifdef TORRENT_DEBUG\n\tstruct function_guard\n\t{\n\t\tfunction_guard(bool& v): val(v) { TORRENT_ASSERT(!val); val = true; }\n\t\t~function_guard() { val = false; }\n\n\t\tbool& val;\n\t};\n#endif\n\t\n\tvoid connection_queue::on_timeout(error_code const& e)\n\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\tcomplete_async(\"connection_queue::on_timeout\");\n#endif\n\n\t\tINVARIANT_CHECK;\n#ifdef TORRENT_DEBUG\n\t\tfunction_guard guard_(m_in_timeout_function);\n#endif\n\n\t\tTORRENT_ASSERT(!e || e == error::operation_aborted);\n\t\tif (e) return;\n\n\t\tptime next_expire = max_time();\n\t\tptime now = time_now_hires() + milliseconds(100);\n\t\tstd::list timed_out;\n\t\tfor (std::list::iterator i = m_queue.begin();\n\t\t\t!m_queue.empty() && i != m_queue.end();)\n\t\t{\n\t\t\tif (i->connecting && i->expires < now)\n\t\t\t{\n\t\t\t\tstd::list::iterator j = i;\n\t\t\t\t++i;\n\t\t\t\ttimed_out.splice(timed_out.end(), m_queue, j, i);\n\t\t\t\t--m_num_connecting;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (i->connecting && i->expires < next_expire)\n\t\t\t\tnext_expire = i->expires;\n\t\t\t++i;\n\t\t}\n\n\t\tfor (std::list::iterator i = timed_out.begin()\n\t\t\t, end(timed_out.end()); i != end; ++i)\n\t\t{\n\t\t\tTORRENT_ASSERT(i->connecting);\n\t\t\tTORRENT_ASSERT(i->ticket != -1);\n\t\t\tTORRENT_TRY {\n\t\t\t\ti->on_timeout();\n\t\t\t} TORRENT_CATCH(std::exception&) {}\n\t\t}\n\t\t\n\t\tif (next_expire < max_time())\n\t\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\t\tadd_outstanding_async(\"connection_queue::on_timeout\");\n#endif\n\t\t\terror_code ec;\n\t\t\tm_timer.expires_at(next_expire, ec);\n\t\t\tm_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));\n\t\t}\n\t\ttry_connect();\n\t}\n\n\tvoid connection_queue::on_try_connect()\n\t{\n\t\ttry_connect();\n\t}\n}\n\n<|endoftext|>"} {"text":"#include \"GodotGlobal.hpp\"\n\n#include \"String.hpp\"\n\n#include \"Wrapped.hpp\"\n\nstatic GDCALLINGCONV void *wrapper_create(void *data, const void *type_tag, godot_object *instance) {\n\tgodot::_Wrapped *wrapper_memory = (godot::_Wrapped *)godot::api->godot_alloc(sizeof(godot::_Wrapped));\n\n\tif (!wrapper_memory)\n\t\treturn NULL;\n\twrapper_memory->_owner = instance;\n\twrapper_memory->_type_tag = (size_t)type_tag;\n\n\treturn (void *)wrapper_memory;\n}\n\nstatic GDCALLINGCONV void wrapper_destroy(void *data, void *wrapper) {\n\tif (wrapper)\n\t\tgodot::api->godot_free(wrapper);\n}\n\nnamespace godot {\n\nvoid *_RegisterState::nativescript_handle;\nint _RegisterState::language_index;\n\nconst godot_gdnative_core_api_struct *api = nullptr;\nconst godot_gdnative_core_1_1_api_struct *core_1_1_api = nullptr;\nconst godot_gdnative_core_1_2_api_struct *core_1_2_api = nullptr;\n\nconst godot_gdnative_ext_nativescript_api_struct *nativescript_api = nullptr;\nconst godot_gdnative_ext_nativescript_1_1_api_struct *nativescript_1_1_api = nullptr;\nconst godot_gdnative_ext_pluginscript_api_struct *pluginscript_api = nullptr;\nconst godot_gdnative_ext_android_api_struct *android_api = nullptr;\nconst godot_gdnative_ext_arvr_api_struct *arvr_api = nullptr;\nconst godot_gdnative_ext_videodecoder_api_struct *videodecoder_api = nullptr;\nconst godot_gdnative_ext_net_api_struct *net_api = nullptr;\nconst godot_gdnative_ext_net_3_2_api_struct *net_3_2_api = nullptr;\n\nconst void *gdnlib = NULL;\n\nvoid Godot::print(const String &message) {\n\tgodot::api->godot_print((godot_string *)&message);\n}\n\nvoid Godot::print_warning(const String &description, const String &function, const String &file, int line) {\n\tint len;\n\n\tchar *c_desc = description.alloc_c_string();\n\tchar *c_func = function.alloc_c_string();\n\tchar *c_file = file.alloc_c_string();\n\n\tif (c_desc != nullptr && c_func != nullptr && c_file != nullptr) {\n\t\tgodot::api->godot_print_warning(c_desc, c_func, c_file, line);\n\t};\n\n\tif (c_desc != nullptr) godot::api->godot_free(c_desc);\n\tif (c_func != nullptr) godot::api->godot_free(c_func);\n\tif (c_file != nullptr) godot::api->godot_free(c_file);\n}\n\nvoid Godot::print_error(const String &description, const String &function, const String &file, int line) {\n\tint len;\n\n\tchar *c_desc = description.alloc_c_string();\n\tchar *c_func = function.alloc_c_string();\n\tchar *c_file = file.alloc_c_string();\n\n\tif (c_desc != nullptr && c_func != nullptr && c_file != nullptr) {\n\t\tgodot::api->godot_print_error(c_desc, c_func, c_file, line);\n\t};\n\n\tif (c_desc != nullptr) godot::api->godot_free(c_desc);\n\tif (c_func != nullptr) godot::api->godot_free(c_func);\n\tif (c_file != nullptr) godot::api->godot_free(c_file);\n}\n\nvoid ___register_types();\nvoid ___init_method_bindings();\n\nvoid Godot::gdnative_init(godot_gdnative_init_options *options) {\n\tgodot::api = options->api_struct;\n\tgodot::gdnlib = options->gd_native_library;\n\n\tconst godot_gdnative_api_struct *core_extension = godot::api->next;\n\n\twhile (core_extension) {\n\t\tif (core_extension->version.major == 1 && core_extension->version.minor == 1) {\n\t\t\tgodot::core_1_1_api = (const godot_gdnative_core_1_1_api_struct *)core_extension;\n\t\t} else if (core_extension->version.major == 1 && core_extension->version.minor == 2) {\n\t\t\tgodot::core_1_2_api = (const godot_gdnative_core_1_2_api_struct *)core_extension;\n\t\t}\n\t\tcore_extension = core_extension->next;\n\t}\n\n\t\/\/ now find our extensions\n\tfor (int i = 0; i < godot::api->num_extensions; i++) {\n\t\tswitch (godot::api->extensions[i]->type) {\n\t\t\tcase GDNATIVE_EXT_NATIVESCRIPT: {\n\t\t\t\tgodot::nativescript_api = (const godot_gdnative_ext_nativescript_api_struct *)godot::api->extensions[i];\n\n\t\t\t\tconst godot_gdnative_api_struct *extension = godot::nativescript_api->next;\n\n\t\t\t\twhile (extension) {\n\t\t\t\t\tif (extension->version.major == 1 && extension->version.minor == 1) {\n\t\t\t\t\t\tgodot::nativescript_1_1_api = (const godot_gdnative_ext_nativescript_1_1_api_struct *)extension;\n\t\t\t\t\t}\n\n\t\t\t\t\textension = extension->next;\n\t\t\t\t}\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_PLUGINSCRIPT: {\n\t\t\t\tgodot::pluginscript_api = (const godot_gdnative_ext_pluginscript_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_ANDROID: {\n\t\t\t\tgodot::android_api = (const godot_gdnative_ext_android_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_ARVR: {\n\t\t\t\tgodot::arvr_api = (const godot_gdnative_ext_arvr_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_VIDEODECODER: {\n\t\t\t\tgodot::videodecoder_api = (const godot_gdnative_ext_videodecoder_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_NET: {\n\t\t\t\tgodot::net_api = (const godot_gdnative_ext_net_api_struct *)godot::api->extensions[i];\n\n\t\t\t\tconst godot_gdnative_api_struct *extension = godot::net_api->next;\n\n\t\t\t\twhile (extension) {\n\t\t\t\t\tif (extension->version.major == 3 && extension->version.minor == 2) {\n\t\t\t\t\t\tgodot::net_3_2_api = (const godot_gdnative_ext_net_3_2_api_struct *)extension;\n\t\t\t\t\t}\n\n\t\t\t\t\textension = extension->next;\n\t\t\t\t}\n\t\t\t} break;\n\n\t\t\tdefault: break;\n\t\t}\n\t}\n}\n\nvoid Godot::gdnative_terminate(godot_gdnative_terminate_options *options) {\n\t\/\/ reserved for future use.\n}\n\nvoid Godot::gdnative_profiling_add_data(const char *p_signature, uint64_t p_time) {\n\tgodot::nativescript_1_1_api->godot_nativescript_profiling_add_data(p_signature, p_time);\n}\n\nvoid Godot::nativescript_init(void *handle) {\n\tgodot::_RegisterState::nativescript_handle = handle;\n\n\tgodot_instance_binding_functions binding_funcs = {};\n\tbinding_funcs.alloc_instance_binding_data = wrapper_create;\n\tbinding_funcs.free_instance_binding_data = wrapper_destroy;\n\n\tgodot::_RegisterState::language_index = godot::nativescript_1_1_api->godot_nativescript_register_instance_binding_data_functions(binding_funcs);\n\n\t___register_types();\n\t___init_method_bindings();\n}\n\nvoid Godot::nativescript_terminate(void *handle) {\n\tgodot::nativescript_1_1_api->godot_nativescript_unregister_instance_binding_data_functions(godot::_RegisterState::language_index);\n}\n\n} \/\/ namespace godot\nCall register types and init earlier#include \"GodotGlobal.hpp\"\n\n#include \"String.hpp\"\n\n#include \"Wrapped.hpp\"\n\nstatic GDCALLINGCONV void *wrapper_create(void *data, const void *type_tag, godot_object *instance) {\n\tgodot::_Wrapped *wrapper_memory = (godot::_Wrapped *)godot::api->godot_alloc(sizeof(godot::_Wrapped));\n\n\tif (!wrapper_memory)\n\t\treturn NULL;\n\twrapper_memory->_owner = instance;\n\twrapper_memory->_type_tag = (size_t)type_tag;\n\n\treturn (void *)wrapper_memory;\n}\n\nstatic GDCALLINGCONV void wrapper_destroy(void *data, void *wrapper) {\n\tif (wrapper)\n\t\tgodot::api->godot_free(wrapper);\n}\n\nnamespace godot {\n\nvoid *_RegisterState::nativescript_handle;\nint _RegisterState::language_index;\n\nconst godot_gdnative_core_api_struct *api = nullptr;\nconst godot_gdnative_core_1_1_api_struct *core_1_1_api = nullptr;\nconst godot_gdnative_core_1_2_api_struct *core_1_2_api = nullptr;\n\nconst godot_gdnative_ext_nativescript_api_struct *nativescript_api = nullptr;\nconst godot_gdnative_ext_nativescript_1_1_api_struct *nativescript_1_1_api = nullptr;\nconst godot_gdnative_ext_pluginscript_api_struct *pluginscript_api = nullptr;\nconst godot_gdnative_ext_android_api_struct *android_api = nullptr;\nconst godot_gdnative_ext_arvr_api_struct *arvr_api = nullptr;\nconst godot_gdnative_ext_videodecoder_api_struct *videodecoder_api = nullptr;\nconst godot_gdnative_ext_net_api_struct *net_api = nullptr;\nconst godot_gdnative_ext_net_3_2_api_struct *net_3_2_api = nullptr;\n\nconst void *gdnlib = NULL;\n\nvoid Godot::print(const String &message) {\n\tgodot::api->godot_print((godot_string *)&message);\n}\n\nvoid Godot::print_warning(const String &description, const String &function, const String &file, int line) {\n\tint len;\n\n\tchar *c_desc = description.alloc_c_string();\n\tchar *c_func = function.alloc_c_string();\n\tchar *c_file = file.alloc_c_string();\n\n\tif (c_desc != nullptr && c_func != nullptr && c_file != nullptr) {\n\t\tgodot::api->godot_print_warning(c_desc, c_func, c_file, line);\n\t};\n\n\tif (c_desc != nullptr) godot::api->godot_free(c_desc);\n\tif (c_func != nullptr) godot::api->godot_free(c_func);\n\tif (c_file != nullptr) godot::api->godot_free(c_file);\n}\n\nvoid Godot::print_error(const String &description, const String &function, const String &file, int line) {\n\tint len;\n\n\tchar *c_desc = description.alloc_c_string();\n\tchar *c_func = function.alloc_c_string();\n\tchar *c_file = file.alloc_c_string();\n\n\tif (c_desc != nullptr && c_func != nullptr && c_file != nullptr) {\n\t\tgodot::api->godot_print_error(c_desc, c_func, c_file, line);\n\t};\n\n\tif (c_desc != nullptr) godot::api->godot_free(c_desc);\n\tif (c_func != nullptr) godot::api->godot_free(c_func);\n\tif (c_file != nullptr) godot::api->godot_free(c_file);\n}\n\nvoid ___register_types();\nvoid ___init_method_bindings();\n\nvoid Godot::gdnative_init(godot_gdnative_init_options *options) {\n\tgodot::api = options->api_struct;\n\tgodot::gdnlib = options->gd_native_library;\n\n\tconst godot_gdnative_api_struct *core_extension = godot::api->next;\n\n\twhile (core_extension) {\n\t\tif (core_extension->version.major == 1 && core_extension->version.minor == 1) {\n\t\t\tgodot::core_1_1_api = (const godot_gdnative_core_1_1_api_struct *)core_extension;\n\t\t} else if (core_extension->version.major == 1 && core_extension->version.minor == 2) {\n\t\t\tgodot::core_1_2_api = (const godot_gdnative_core_1_2_api_struct *)core_extension;\n\t\t}\n\t\tcore_extension = core_extension->next;\n\t}\n\n\t\/\/ now find our extensions\n\tfor (int i = 0; i < godot::api->num_extensions; i++) {\n\t\tswitch (godot::api->extensions[i]->type) {\n\t\t\tcase GDNATIVE_EXT_NATIVESCRIPT: {\n\t\t\t\tgodot::nativescript_api = (const godot_gdnative_ext_nativescript_api_struct *)godot::api->extensions[i];\n\n\t\t\t\tconst godot_gdnative_api_struct *extension = godot::nativescript_api->next;\n\n\t\t\t\twhile (extension) {\n\t\t\t\t\tif (extension->version.major == 1 && extension->version.minor == 1) {\n\t\t\t\t\t\tgodot::nativescript_1_1_api = (const godot_gdnative_ext_nativescript_1_1_api_struct *)extension;\n\t\t\t\t\t}\n\n\t\t\t\t\textension = extension->next;\n\t\t\t\t}\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_PLUGINSCRIPT: {\n\t\t\t\tgodot::pluginscript_api = (const godot_gdnative_ext_pluginscript_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_ANDROID: {\n\t\t\t\tgodot::android_api = (const godot_gdnative_ext_android_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_ARVR: {\n\t\t\t\tgodot::arvr_api = (const godot_gdnative_ext_arvr_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_VIDEODECODER: {\n\t\t\t\tgodot::videodecoder_api = (const godot_gdnative_ext_videodecoder_api_struct *)godot::api->extensions[i];\n\t\t\t} break;\n\t\t\tcase GDNATIVE_EXT_NET: {\n\t\t\t\tgodot::net_api = (const godot_gdnative_ext_net_api_struct *)godot::api->extensions[i];\n\n\t\t\t\tconst godot_gdnative_api_struct *extension = godot::net_api->next;\n\n\t\t\t\twhile (extension) {\n\t\t\t\t\tif (extension->version.major == 3 && extension->version.minor == 2) {\n\t\t\t\t\t\tgodot::net_3_2_api = (const godot_gdnative_ext_net_3_2_api_struct *)extension;\n\t\t\t\t\t}\n\n\t\t\t\t\textension = extension->next;\n\t\t\t\t}\n\t\t\t} break;\n\n\t\t\tdefault: break;\n\t\t}\n\t}\n\n\t\/\/ register these now\n\t___register_types();\n\t___init_method_bindings();\n}\n\nvoid Godot::gdnative_terminate(godot_gdnative_terminate_options *options) {\n\t\/\/ reserved for future use.\n}\n\nvoid Godot::gdnative_profiling_add_data(const char *p_signature, uint64_t p_time) {\n\tgodot::nativescript_1_1_api->godot_nativescript_profiling_add_data(p_signature, p_time);\n}\n\nvoid Godot::nativescript_init(void *handle) {\n\tgodot::_RegisterState::nativescript_handle = handle;\n\n\tgodot_instance_binding_functions binding_funcs = {};\n\tbinding_funcs.alloc_instance_binding_data = wrapper_create;\n\tbinding_funcs.free_instance_binding_data = wrapper_destroy;\n\n\tgodot::_RegisterState::language_index = godot::nativescript_1_1_api->godot_nativescript_register_instance_binding_data_functions(binding_funcs);\n}\n\nvoid Godot::nativescript_terminate(void *handle) {\n\tgodot::nativescript_1_1_api->godot_nativescript_unregister_instance_binding_data_functions(godot::_RegisterState::language_index);\n}\n\n} \/\/ namespace godot\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkImageInfoPriv.h\"\n#include \"SkSafeMath.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkWriteBuffer.h\"\n\nint SkColorTypeBytesPerPixel(SkColorType ct) {\n switch (ct) {\n case kUnknown_SkColorType: return 0;\n case kAlpha_8_SkColorType: return 1;\n case kRGB_565_SkColorType: return 2;\n case kARGB_4444_SkColorType: return 2;\n case kRGBA_8888_SkColorType: return 4;\n case kBGRA_8888_SkColorType: return 4;\n case kRGB_888x_SkColorType: return 4;\n case kRGBA_1010102_SkColorType: return 4;\n case kRGB_101010x_SkColorType: return 4;\n case kGray_8_SkColorType: return 1;\n case kRGBA_F16_SkColorType: return 8;\n }\n return 0;\n}\n\n\/\/ These values must be constant over revisions, though they can be renamed to reflect if\/when\n\/\/ they are deprecated.\nenum Stored_SkColorType {\n kUnknown_Stored_SkColorType = 0,\n kAlpha_8_Stored_SkColorType = 1,\n kRGB_565_Stored_SkColorType = 2,\n kARGB_4444_Stored_SkColorType = 3,\n kRGBA_8888_Stored_SkColorType = 4,\n kBGRA_8888_Stored_SkColorType = 5,\n kIndex_8_Stored_SkColorType_DEPRECATED = 6,\n kGray_8_Stored_SkColorType = 7,\n kRGBA_F16_Stored_SkColorType = 8,\n kRGB_888x_Stored_SkColorType = 9,\n kRGBA_1010102_Stored_SkColorType = 10,\n kRGB_101010x_Stored_SkColorType = 11,\n};\n\nbool SkColorTypeIsAlwaysOpaque(SkColorType ct) {\n return !(kAlpha_SkColorTypeComponentFlag & SkColorTypeComponentFlags(ct));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint SkImageInfo::bytesPerPixel() const { return SkColorTypeBytesPerPixel(fColorType); }\n\nint SkImageInfo::shiftPerPixel() const { return SkColorTypeShiftPerPixel(fColorType); }\n\nsize_t SkImageInfo::computeOffset(int x, int y, size_t rowBytes) const {\n SkASSERT((unsigned)x < (unsigned)fWidth);\n SkASSERT((unsigned)y < (unsigned)fHeight);\n return SkColorTypeComputeOffset(fColorType, x, y, rowBytes);\n}\n\nsize_t SkImageInfo::computeByteSize(size_t rowBytes) const {\n if (0 == fHeight) {\n return 0;\n }\n SkSafeMath safe;\n size_t bytes = safe.add(safe.mul(fHeight - 1, rowBytes),\n safe.mul(fWidth, this->bytesPerPixel()));\n return safe ? bytes : SK_MaxSizeT;\n}\n\nSkImageInfo SkImageInfo::MakeS32(int width, int height, SkAlphaType at) {\n return SkImageInfo(width, height, kN32_SkColorType, at,\n SkColorSpace::MakeSRGB());\n}\n\nbool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType,\n SkAlphaType* canonical) {\n switch (colorType) {\n case kUnknown_SkColorType:\n alphaType = kUnknown_SkAlphaType;\n break;\n case kAlpha_8_SkColorType:\n if (kUnpremul_SkAlphaType == alphaType) {\n alphaType = kPremul_SkAlphaType;\n }\n \/\/ fall-through\n case kARGB_4444_SkColorType:\n case kRGBA_8888_SkColorType:\n case kBGRA_8888_SkColorType:\n case kRGBA_1010102_SkColorType:\n case kRGBA_F16_SkColorType:\n if (kUnknown_SkAlphaType == alphaType) {\n return false;\n }\n break;\n case kGray_8_SkColorType:\n case kRGB_565_SkColorType:\n case kRGB_888x_SkColorType:\n case kRGB_101010x_SkColorType:\n alphaType = kOpaque_SkAlphaType;\n break;\n default:\n return false;\n }\n if (canonical) {\n *canonical = alphaType;\n }\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkReadPixelsRec.h\"\n\nbool SkReadPixelsRec::trim(int srcWidth, int srcHeight) {\n if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {\n return false;\n }\n if (0 >= fInfo.width() || 0 >= fInfo.height()) {\n return false;\n }\n\n int x = fX;\n int y = fY;\n SkIRect srcR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());\n if (!srcR.intersect(0, 0, srcWidth, srcHeight)) {\n return false;\n }\n\n \/\/ if x or y are negative, then we have to adjust pixels\n if (x > 0) {\n x = 0;\n }\n if (y > 0) {\n y = 0;\n }\n \/\/ here x,y are either 0 or negative\n \/\/ we negate and add them so UBSAN (pointer-overflow) doesn't get confused.\n fPixels = ((char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel());\n \/\/ the intersect may have shrunk info's logical size\n fInfo = fInfo.makeWH(srcR.width(), srcR.height());\n fX = srcR.x();\n fY = srcR.y();\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkWritePixelsRec.h\"\n\nbool SkWritePixelsRec::trim(int dstWidth, int dstHeight) {\n if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {\n return false;\n }\n if (0 >= fInfo.width() || 0 >= fInfo.height()) {\n return false;\n }\n\n int x = fX;\n int y = fY;\n SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());\n if (!dstR.intersect(0, 0, dstWidth, dstHeight)) {\n return false;\n }\n\n \/\/ if x or y are negative, then we have to adjust pixels\n if (x > 0) {\n x = 0;\n }\n if (y > 0) {\n y = 0;\n }\n \/\/ here x,y are either 0 or negative\n \/\/ we negate and add them so UBSAN (pointer-overflow) doesn't get confused.\n fPixels = ((const char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel());\n \/\/ the intersect may have shrunk info's logical size\n fInfo = fInfo.makeWH(dstR.width(), dstR.height());\n fX = dstR.x();\n fY = dstR.y();\n\n return true;\n}\nFix SkImageInfo::computeByteSize underflow\/*\n * Copyright 2010 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkImageInfoPriv.h\"\n#include \"SkSafeMath.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkWriteBuffer.h\"\n\nint SkColorTypeBytesPerPixel(SkColorType ct) {\n switch (ct) {\n case kUnknown_SkColorType: return 0;\n case kAlpha_8_SkColorType: return 1;\n case kRGB_565_SkColorType: return 2;\n case kARGB_4444_SkColorType: return 2;\n case kRGBA_8888_SkColorType: return 4;\n case kBGRA_8888_SkColorType: return 4;\n case kRGB_888x_SkColorType: return 4;\n case kRGBA_1010102_SkColorType: return 4;\n case kRGB_101010x_SkColorType: return 4;\n case kGray_8_SkColorType: return 1;\n case kRGBA_F16_SkColorType: return 8;\n }\n return 0;\n}\n\n\/\/ These values must be constant over revisions, though they can be renamed to reflect if\/when\n\/\/ they are deprecated.\nenum Stored_SkColorType {\n kUnknown_Stored_SkColorType = 0,\n kAlpha_8_Stored_SkColorType = 1,\n kRGB_565_Stored_SkColorType = 2,\n kARGB_4444_Stored_SkColorType = 3,\n kRGBA_8888_Stored_SkColorType = 4,\n kBGRA_8888_Stored_SkColorType = 5,\n kIndex_8_Stored_SkColorType_DEPRECATED = 6,\n kGray_8_Stored_SkColorType = 7,\n kRGBA_F16_Stored_SkColorType = 8,\n kRGB_888x_Stored_SkColorType = 9,\n kRGBA_1010102_Stored_SkColorType = 10,\n kRGB_101010x_Stored_SkColorType = 11,\n};\n\nbool SkColorTypeIsAlwaysOpaque(SkColorType ct) {\n return !(kAlpha_SkColorTypeComponentFlag & SkColorTypeComponentFlags(ct));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint SkImageInfo::bytesPerPixel() const { return SkColorTypeBytesPerPixel(fColorType); }\n\nint SkImageInfo::shiftPerPixel() const { return SkColorTypeShiftPerPixel(fColorType); }\n\nsize_t SkImageInfo::computeOffset(int x, int y, size_t rowBytes) const {\n SkASSERT((unsigned)x < (unsigned)fWidth);\n SkASSERT((unsigned)y < (unsigned)fHeight);\n return SkColorTypeComputeOffset(fColorType, x, y, rowBytes);\n}\n\nsize_t SkImageInfo::computeByteSize(size_t rowBytes) const {\n if (0 == fHeight) {\n return 0;\n }\n SkSafeMath safe;\n size_t bytes = safe.add(safe.mul(safe.addInt(fHeight, -1), rowBytes),\n safe.mul(fWidth, this->bytesPerPixel()));\n return safe ? bytes : SK_MaxSizeT;\n}\n\nSkImageInfo SkImageInfo::MakeS32(int width, int height, SkAlphaType at) {\n return SkImageInfo(width, height, kN32_SkColorType, at,\n SkColorSpace::MakeSRGB());\n}\n\nbool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType,\n SkAlphaType* canonical) {\n switch (colorType) {\n case kUnknown_SkColorType:\n alphaType = kUnknown_SkAlphaType;\n break;\n case kAlpha_8_SkColorType:\n if (kUnpremul_SkAlphaType == alphaType) {\n alphaType = kPremul_SkAlphaType;\n }\n \/\/ fall-through\n case kARGB_4444_SkColorType:\n case kRGBA_8888_SkColorType:\n case kBGRA_8888_SkColorType:\n case kRGBA_1010102_SkColorType:\n case kRGBA_F16_SkColorType:\n if (kUnknown_SkAlphaType == alphaType) {\n return false;\n }\n break;\n case kGray_8_SkColorType:\n case kRGB_565_SkColorType:\n case kRGB_888x_SkColorType:\n case kRGB_101010x_SkColorType:\n alphaType = kOpaque_SkAlphaType;\n break;\n default:\n return false;\n }\n if (canonical) {\n *canonical = alphaType;\n }\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkReadPixelsRec.h\"\n\nbool SkReadPixelsRec::trim(int srcWidth, int srcHeight) {\n if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {\n return false;\n }\n if (0 >= fInfo.width() || 0 >= fInfo.height()) {\n return false;\n }\n\n int x = fX;\n int y = fY;\n SkIRect srcR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());\n if (!srcR.intersect(0, 0, srcWidth, srcHeight)) {\n return false;\n }\n\n \/\/ if x or y are negative, then we have to adjust pixels\n if (x > 0) {\n x = 0;\n }\n if (y > 0) {\n y = 0;\n }\n \/\/ here x,y are either 0 or negative\n \/\/ we negate and add them so UBSAN (pointer-overflow) doesn't get confused.\n fPixels = ((char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel());\n \/\/ the intersect may have shrunk info's logical size\n fInfo = fInfo.makeWH(srcR.width(), srcR.height());\n fX = srcR.x();\n fY = srcR.y();\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkWritePixelsRec.h\"\n\nbool SkWritePixelsRec::trim(int dstWidth, int dstHeight) {\n if (nullptr == fPixels || fRowBytes < fInfo.minRowBytes()) {\n return false;\n }\n if (0 >= fInfo.width() || 0 >= fInfo.height()) {\n return false;\n }\n\n int x = fX;\n int y = fY;\n SkIRect dstR = SkIRect::MakeXYWH(x, y, fInfo.width(), fInfo.height());\n if (!dstR.intersect(0, 0, dstWidth, dstHeight)) {\n return false;\n }\n\n \/\/ if x or y are negative, then we have to adjust pixels\n if (x > 0) {\n x = 0;\n }\n if (y > 0) {\n y = 0;\n }\n \/\/ here x,y are either 0 or negative\n \/\/ we negate and add them so UBSAN (pointer-overflow) doesn't get confused.\n fPixels = ((const char*)fPixels + -y*fRowBytes + -x*fInfo.bytesPerPixel());\n \/\/ the intersect may have shrunk info's logical size\n fInfo = fInfo.makeWH(dstR.width(), dstR.height());\n fX = dstR.x();\n fY = dstR.y();\n\n return true;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ OpenGL Mathematics (glm.g-truc.net)\n\/\/\/\n\/\/\/ Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/ \n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/ \n\/\/\/ Restrictions:\n\/\/\/\t\tBy making use of the Software for military purposes, you choose to make\n\/\/\/\t\ta Bunny unhappy.\n\/\/\/ \n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\/\/\/ @ref gtx_matrix_decompose\n\/\/\/ @file glm\/gtx\/matrix_decompose.hpp\n\/\/\/ @date 2014-08-29 \/ 2014-08-29\n\/\/\/ @author Christophe Riccio\n\/\/\/ \n\/\/\/ @see core (dependence)\n\/\/\/\n\/\/\/ @defgroup gtx_matrix_decompose GLM_GTX_matrix_decompose\n\/\/\/ @ingroup gtx\n\/\/\/ \n\/\/\/ @brief Decomposes a model matrix to translations, rotation and scale components\n\/\/\/ \n\/\/\/ need to be included to use these functionalities.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#pragma once\n\n\/\/ Dependencies\n#include \"..\/mat4x4.hpp\"\n#include \"..\/vec3.hpp\"\n#include \"..\/vec4.hpp\"\n#include \"..\/gtc\/quaternion.hpp\"\n#include \"..\/gtc\/matrix_transform.hpp\"\n\n#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))\n#\tpragma message(\"GLM: GLM_GTX_matrix_decompose extension included\")\n#endif\n\nnamespace glm\n{\n\t\/\/\/ @addtogroup gtx_matrix_decompose\n\t\/\/\/ @{\n\n\t\/\/\/ Decomposes a model matrix to translations, rotation and scale components \n\t\/\/\/ @see gtx_matrix_decompose\n\ttemplate \n\tGLM_FUNC_DECL bool decompose(\n\t\ttmat4x4 const & modelMatrix,\n\t\ttvec3 & scale, tquat & orientation, tvec3 & translation, tvec3 & skew, tvec4 & perspective);\n\n\t\/\/\/ @}\n}\/\/namespace glm\n\n#include \"matrix_decompose.inl\"\nUpdate matrix_decompose.hpp\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ OpenGL Mathematics (glm.g-truc.net)\n\/\/\/\n\/\/\/ Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/ \n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/ \n\/\/\/ Restrictions:\n\/\/\/\t\tBy making use of the Software for military purposes, you choose to make\n\/\/\/\t\ta Bunny unhappy.\n\/\/\/ \n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\/\/\/ @ref gtx_matrix_decompose\n\/\/\/ @file glm\/gtx\/matrix_decompose.hpp\n\/\/\/ @date 2014-08-29 \/ 2014-08-29\n\/\/\/ @author Christophe Riccio\n\/\/\/ \n\/\/\/ @see core (dependence)\n\/\/\/\n\/\/\/ @defgroup gtx_matrix_decompose GLM_GTX_matrix_decompose\n\/\/\/ @ingroup gtx\n\/\/\/ \n\/\/\/ @brief Decomposes a model matrix to translations, rotation and scale components\n\/\/\/ \n\/\/\/ need to be included to use these functionalities.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#pragma once\n\n\/\/ Dependencies\n#include \"..\/mat4x4.hpp\"\n#include \"..\/vec3.hpp\"\n#include \"..\/vec4.hpp\"\n#include \"..\/gtc\/quaternion.hpp\"\n#include \"..\/gtc\/matrix_transform.hpp\"\n\n#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))\n#\tpragma message(\"GLM: GLM_GTX_matrix_decompose extension included\")\n#endif\n\nnamespace glm\n{\n\t\/\/\/ @addtogroup gtx_matrix_decompose\n\t\/\/\/ @{\n\n\t\/\/\/ Decomposes a model matrix to translations, rotation and scale components \n\t\/\/\/ @see gtx_matrix_decompose\n\ttemplate \n\tGLM_FUNC_DECL bool decompose(\n\t\ttmat4x4 const & modelMatrix,\n\t\ttvec3 & scale, tquat & orientation, tvec3 & translation, tvec3 & skew, tvec4 & perspective);\n\n\t\/\/\/ @}\n}\/\/namespace glm\n\n#include \"matrix_decompose.inl\"\n<|endoftext|>"} {"text":"#include \"nfa.hxx\"\r\n#include \r\n\r\nconst char* state_not_found::what () const throw ()\r\n{\r\n return \"state not found in delta mapping\";\r\n}\r\n\r\nstd::string printNFA (const NFA& nfa)\r\n{\r\n std::ostringstream ss;\r\n \r\n ss << \"automaton \" << nfa.name << std::endl;\r\n for (DeltaMappingT::const_iterator dmi = nfa.delta.begin();\r\n\t dmi != nfa.delta.end();\r\n\t ++dmi) {\r\n\tconst StateT& st = dmi->first;\r\n\tif (st == nfa.initial)\r\n\t ss << \"initial \";\r\n\tif (nfa.final.find(st) != nfa.final.end())\r\n\t ss << \"final \";\r\n\tss << \"state \" << st << \" {\" << std::endl;\r\n\tfor (StateDeltaT::const_iterator sdi = dmi->second.begin();\r\n\t sdi != dmi->second.end();\r\n\t ++sdi) {\r\n\t ss << sdi->first << \" -> { \";\r\n\t std::copy(sdi->second.begin(), sdi->second.end(),\r\n\t\t std::ostream_iterator(ss,\" \"));\r\n\t ss << \"}\" << std::endl;\r\n\t}\r\n\tss << \"}\" << std::endl;\r\n }\r\n\r\n return ss.str();\r\n}\r\n\r\nstd::string printNFA (const NFA_conv& nfa)\r\n{\r\n std::ostringstream ss;\r\n \r\n ss << \"automaton \" << nfa.name << std::endl;\r\n for (std::map::const_iterator dmi \r\n\t = nfa.delta.begin();\r\n\t dmi != nfa.delta.end();\r\n\t ++dmi) {\r\n\tconst SetOfStatesT& st = dmi->first;\r\n\tif (st == nfa.initial)\r\n\t ss << \"initial \";\r\n\tif (nfa.final.find(st) != nfa.final.end())\r\n\t ss << \"final \";\r\n\tss << \"state \" << join_seq(std::string(\"-\"),st) << \" {\" << std::endl;\r\n\tfor (StateDeltaT::const_iterator sdi = dmi->second.begin();\r\n\t sdi != dmi->second.end();\r\n\t ++sdi) {\r\n\t ss << sdi->first << \" -> { \";\r\n\t std::copy(sdi->second.begin(), sdi->second.end(),\r\n\t\t std::ostream_iterator(ss,\" \"));\r\n\t ss << \"}\" << std::endl;\r\n\t}\r\n\tss << \"}\" << std::endl;\r\n }\r\n \r\n return ss.str();\r\n}\r\n\r\n\/* Get set of input alphabet T from automaton's delta mapping. *\/\r\nstd::set input_alphabet (const NFA& nfa)\r\n{\r\n std::set alphabet;\r\n for (DeltaMappingT::const_iterator i = nfa.delta.begin();\r\n\t i != nfa.delta.end();\r\n\t ++i) {\r\n\tfor (StateDeltaT::const_iterator k = i->second.begin();\r\n\t k != i->second.end();\r\n\t ++k) {\r\n\t alphabet.insert(k->first);\r\n\t}\r\n }\r\n return alphabet;\r\n}\r\n\r\nNFA_conv convert_NFA2DFA (const NFA& nfa)\r\n{\r\n NFA_conv nfa_conv;\r\n \/* 1. The set Q' = {{q0}} will be defined, the state {q0} will be treated\r\n as unmarked. *\/\r\n std::set alphabet = input_alphabet(nfa);\r\n std::set Qnew, unmarked, marked;\r\n SetOfStatesT q0set;\r\n q0set.insert(nfa.initial);\r\n Qnew.insert(q0set);\r\n unmarked.insert(q0set);\r\n \r\n \/* 2. If each state in Q' is marked, then continue with step (4). *\/\r\n while (! unmarked.empty()) {\r\n\t\/* 3. An unmarked state q' will be chosen from Q' and th following\r\n\t operations will be executed: *\/\r\n\tSetOfStatesT q_ = *unmarked.begin();\r\n\t\/* (a) We will determine delta'(q',a) = union(delta(p,a)) for\r\n\t p element q' and for all a element T. *\/\r\n\tStateDeltaT stdelta;\r\n\tint cnt = 0;\r\n\tfor (std::set::const_iterator letter = alphabet.begin();\r\n\t letter != alphabet.end();\r\n\t ++letter) {\r\n\t \/* alokace promenne pro sjednoceni union(delta(p,a)) \r\n\t for p element q' *\/\r\n\t SetOfStatesT* un = new SetOfStatesT;\r\n\t int cnt2 = 0;\r\n\t for (SetOfStatesT::const_iterator p = q_.begin();\r\n\t\t p != q_.end();\r\n\t\t ++p) {\r\n\t\t\/\/ najdi StateDeltaT pro stav\r\n\t\tDeltaMappingT::const_iterator dmi = nfa.delta.find(*p);\r\n\t\t\/\/ element nenalezen\r\n\t\tif (dmi == nfa.delta.end())\r\n\t\t throw state_not_found();\r\n\t\tconst StateDeltaT& sd = dmi->second;\r\n\t\t\/* Najdi mnozinu cilovych stavu ze stavu *p pri \r\n\t\t vstupnim pismenu *letter. *\/\r\n\t\tStateDeltaT::const_iterator sdi = sd.find(*letter);\r\n\t\t\/* Element nenalezen, tzn. z tohodle stavu pri\r\n\t\t vstupu *letter nevede zadna cesta. *\/\r\n\t\tif (sdi == sd.end())\r\n\t\t continue;\r\n\t\tun->insert(sdi->second.begin(), sdi->second.end());\r\n\t }\r\n\t stdelta.insert(make_pair(*letter,*un));\r\n\t \/* (b) Q' = Q' union delta'(q',a) for all a element T. *\/\r\n\t Qnew.insert(*un);\r\n\t \/* pokud stav jeste neni oznaceny *\/\r\n\t if (marked.find(*un) == marked.end())\r\n\t\t\/* pridame ho k neoznacenym *\/\r\n\t\tunmarked.insert(*un);\r\n\t \r\n\t}\r\n\t\/* (c) The state q' element Q' will be marked. *\/\r\n\tunmarked.erase(q_);\r\n\tmarked.insert(q_);\r\n\t\/* (d) Continue with step (2). *\/\r\n\tnfa_conv.delta.insert(make_pair(q_,stdelta));\r\n }\r\n \r\n nfa_conv.name = nfa.name;\r\n \/* 4. q0' = {q0}. *\/\r\n nfa_conv.initial = q0set;\r\n \/* 5. F' = {q' : q' element Q', q' intersection F != 0}. *\/\r\n for (std::set::const_iterator q_ = Qnew.begin();\r\n\t q_ != Qnew.end();\r\n\t ++q_) {\r\n\t\/\/ promenna pro prunik\r\n\tSetOfStatesT inter;\r\n\tset_intersection(q_->begin(), q_->end(),\r\n\t\t\t nfa.final.begin(), nfa.final.end(),\r\n\t\t\t std::insert_iterator(inter,\r\n\t\t\t\t\t\t\t inter.begin()));\r\n\tif (! inter.empty())\r\n\t nfa_conv.final.insert(*q_);\r\n }\r\n \r\n return nfa_conv;\r\n}\r\n\r\nNFA fix_converted (const NFA_conv& nfa_conv, bool )\r\n{\r\n \r\n}\r\nconvert_NFA2DFA(): Osetreni nepritomnosti prechodu pro dane vstupni convert_NFA2DFA(): Osetreni nepritomnosti prechodu pro dane vstupni pismeno,#include \"nfa.hxx\"\r\n#include \r\n\r\nconst char* state_not_found::what () const throw ()\r\n{\r\n return \"state not found in delta mapping\";\r\n}\r\n\r\nstd::string printNFA (const NFA& nfa)\r\n{\r\n std::ostringstream ss;\r\n \r\n ss << \"automaton \" << nfa.name << std::endl;\r\n for (DeltaMappingT::const_iterator dmi = nfa.delta.begin();\r\n\t dmi != nfa.delta.end();\r\n\t ++dmi) {\r\n\tconst StateT& st = dmi->first;\r\n\tif (st == nfa.initial)\r\n\t ss << \"initial \";\r\n\tif (nfa.final.find(st) != nfa.final.end())\r\n\t ss << \"final \";\r\n\tss << \"state \" << st << \" {\" << std::endl;\r\n\tfor (StateDeltaT::const_iterator sdi = dmi->second.begin();\r\n\t sdi != dmi->second.end();\r\n\t ++sdi) {\r\n\t ss << sdi->first << \" -> { \";\r\n\t std::copy(sdi->second.begin(), sdi->second.end(),\r\n\t\t std::ostream_iterator(ss,\" \"));\r\n\t ss << \"}\" << std::endl;\r\n\t}\r\n\tss << \"}\" << std::endl;\r\n }\r\n\r\n return ss.str();\r\n}\r\n\r\nstd::string printNFA (const NFA_conv& nfa)\r\n{\r\n std::ostringstream ss;\r\n \r\n ss << \"automaton \" << nfa.name << std::endl;\r\n for (std::map::const_iterator dmi \r\n\t = nfa.delta.begin();\r\n\t dmi != nfa.delta.end();\r\n\t ++dmi) {\r\n\tconst SetOfStatesT& st = dmi->first;\r\n\tif (st == nfa.initial)\r\n\t ss << \"initial \";\r\n\tif (nfa.final.find(st) != nfa.final.end())\r\n\t ss << \"final \";\r\n\tss << \"state \" << join_seq(std::string(\"-\"),st) << \" {\" << std::endl;\r\n\tfor (StateDeltaT::const_iterator sdi = dmi->second.begin();\r\n\t sdi != dmi->second.end();\r\n\t ++sdi) {\r\n\t ss << sdi->first << \" -> { \";\r\n\t std::copy(sdi->second.begin(), sdi->second.end(),\r\n\t\t std::ostream_iterator(ss,\" \"));\r\n\t ss << \"}\" << std::endl;\r\n\t}\r\n\tss << \"}\" << std::endl;\r\n }\r\n \r\n return ss.str();\r\n}\r\n\r\n\/* Get set of input alphabet T from automaton's delta mapping. *\/\r\nstd::set input_alphabet (const NFA& nfa)\r\n{\r\n std::set alphabet;\r\n for (DeltaMappingT::const_iterator i = nfa.delta.begin();\r\n\t i != nfa.delta.end();\r\n\t ++i) {\r\n\tfor (StateDeltaT::const_iterator k = i->second.begin();\r\n\t k != i->second.end();\r\n\t ++k) {\r\n\t alphabet.insert(k->first);\r\n\t}\r\n }\r\n return alphabet;\r\n}\r\n\r\nNFA_conv convert_NFA2DFA (const NFA& nfa)\r\n{\r\n NFA_conv nfa_conv;\r\n \/* 1. The set Q' = {{q0}} will be defined, the state {q0} will be treated\r\n as unmarked. *\/\r\n std::set alphabet = input_alphabet(nfa);\r\n std::set Qnew, unmarked, marked;\r\n SetOfStatesT q0set;\r\n q0set.insert(nfa.initial);\r\n Qnew.insert(q0set);\r\n unmarked.insert(q0set);\r\n \r\n \/* 2. If each state in Q' is marked, then continue with step (4). *\/\r\n while (! unmarked.empty()) {\r\n\t\/* 3. An unmarked state q' will be chosen from Q' and th following\r\n\t operations will be executed: *\/\r\n\tSetOfStatesT q_ = *unmarked.begin();\r\n\t\/* (a) We will determine delta'(q',a) = union(delta(p,a)) for\r\n\t p element q' and for all a element T. *\/\r\n\tStateDeltaT stdelta;\r\n\tint cnt = 0;\r\n\tfor (std::set::const_iterator letter = alphabet.begin();\r\n\t letter != alphabet.end();\r\n\t ++letter) {\r\n\t \/* alokace promenne pro sjednoceni union(delta(p,a)) \r\n\t for p element q' *\/\r\n\t SetOfStatesT* un = new SetOfStatesT;\r\n\t int cnt2 = 0;\r\n\t for (SetOfStatesT::const_iterator p = q_.begin();\r\n\t\t p != q_.end();\r\n\t\t ++p) {\r\n\t\t\/\/ najdi StateDeltaT pro stav\r\n\t\tDeltaMappingT::const_iterator dmi = nfa.delta.find(*p);\r\n\t\t\/\/ element nenalezen\r\n\t\tif (dmi == nfa.delta.end())\r\n\t\t throw state_not_found();\r\n\t\tconst StateDeltaT& sd = dmi->second;\r\n\t\t\/* Najdi mnozinu cilovych stavu ze stavu *p pri \r\n\t\t vstupnim pismenu *letter. *\/\r\n\t\tStateDeltaT::const_iterator sdi = sd.find(*letter);\r\n\t\t\/* Element nenalezen, tzn. z tohodle stavu pri\r\n\t\t vstupu *letter nevede zadna cesta. *\/\r\n\t\tif (sdi == sd.end())\r\n\t\t continue;\r\n\t\tun->insert(sdi->second.begin(), sdi->second.end());\r\n\t }\r\n\t if (un->empty())\r\n\t\tcontinue;\r\n\t stdelta.insert(make_pair(*letter,*un));\r\n\t \/* (b) Q' = Q' union delta'(q',a) for all a element T. *\/\r\n\t Qnew.insert(*un);\r\n\t \/* pokud stav jeste neni oznaceny *\/\r\n\t if (marked.find(*un) == marked.end())\r\n\t\t\/* pridame ho k neoznacenym *\/\r\n\t\tunmarked.insert(*un);\r\n\t \r\n\t}\r\n\t\/* (c) The state q' element Q' will be marked. *\/\r\n\tunmarked.erase(q_);\r\n\tmarked.insert(q_);\r\n\t\/* (d) Continue with step (2). *\/\r\n\tnfa_conv.delta.insert(make_pair(q_,stdelta));\r\n }\r\n \r\n nfa_conv.name = nfa.name;\r\n \/* 4. q0' = {q0}. *\/\r\n nfa_conv.initial = q0set;\r\n \/* 5. F' = {q' : q' element Q', q' intersection F != 0}. *\/\r\n for (std::set::const_iterator q_ = Qnew.begin();\r\n\t q_ != Qnew.end();\r\n\t ++q_) {\r\n\t\/\/ promenna pro prunik\r\n\tSetOfStatesT inter;\r\n\tset_intersection(q_->begin(), q_->end(),\r\n\t\t\t nfa.final.begin(), nfa.final.end(),\r\n\t\t\t std::insert_iterator(inter,\r\n\t\t\t\t\t\t\t inter.begin()));\r\n\tif (! inter.empty())\r\n\t nfa_conv.final.insert(*q_);\r\n }\r\n \r\n return nfa_conv;\r\n}\r\n\r\nNFA fix_converted (const NFA_conv& nfa_conv, bool )\r\n{\r\n \r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright 2006, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \n#include \"gtest\/gtest.h\"\n\nGTEST_API_ int main(int argc, char **argv) {\n printf(\"Running main() from gtest_main.cc\\n\");\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nsmall tweaks, OSS merge cl 206357486\/\/ Copyright 2006, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include \n#include \"gtest\/gtest.h\"\n\nGTEST_API_ int main(int argc, char **argv) {\n printf(\"Running main() from %s\\n\", __FILE__);\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $\n\n\/\/ stl\n#include \n#include \n\/\/ boost\n#include \n#include \n\/\/ mapnik\n#include \n\/\/ ltdl\n#include \n\nnamespace mapnik\n{\n using namespace std;\n using namespace boost;\n \n datasource_cache::datasource_cache()\n {\n if (lt_dlinit()) throw;\n }\n\n datasource_cache::~datasource_cache()\n {\n lt_dlexit();\n }\n\n std::map > datasource_cache::plugins_;\n bool datasource_cache::registered_=false;\n \n datasource_ptr datasource_cache::create(const parameters& params)\n {\n datasource_ptr ds;\n try\n {\n boost::optional type = params.get(\"type\");\n if (type)\n {\n map >::iterator itr=plugins_.find(*type);\n if (itr!=plugins_.end())\n {\n if (itr->second->handle())\n {\n create_ds* create_datasource = \n (create_ds*) lt_dlsym(itr->second->handle(), \"create\");\n if (!create_datasource)\n {\n std::clog << \"Cannot load symbols: \" << lt_dlerror() << std::endl;\n }\n else\n {\n ds=datasource_ptr(create_datasource(params), datasource_deleter());\n }\n }\n else\n {\n std::clog << \"Cannot load library: \" << lt_dlerror() << std::endl;\n }\n }\n }\n#ifdef MAPNIK_DEBUG\n std::clog<<\"datasource=\"<\n (new PluginInfo(type,module)))).second; \n }\n\n void datasource_cache::register_datasources(const std::string& str)\n {\t\n mutex::scoped_lock lock(mapnik::singleton::mutex_);\n filesystem::path path(str);\n filesystem::directory_iterator end_itr;\n if (exists(path) && is_directory(path))\n {\n for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )\n {\n if (!is_directory( *itr ) && itr->leaf()[0]!='.')\n {\n try \n {\n lt_dlhandle module=lt_dlopen(itr->string().c_str());\n if (module)\n {\n datasource_name* ds_name = \n (datasource_name*) lt_dlsym(module, \"datasource_name\");\n if (ds_name && insert(ds_name(),module))\n { \n#ifdef MAPNIK_DEBUG\n std::clog<<\"registered datasource : \"<check if file ends with '.input' before attempting to load it\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $\n\n\/\/ stl\n#include \n#include \n\/\/ boost\n#include \n#include \n#include \n\/\/ mapnik\n#include \n\/\/ ltdl\n#include \n\nnamespace mapnik\n{\n using namespace std;\n using namespace boost;\n \n bool is_input_plugin (std::string const& filename)\n {\n return boost::algorithm::ends_with(filename,\".input\");\n }\n \n\n datasource_cache::datasource_cache()\n {\n if (lt_dlinit()) throw;\n }\n\n datasource_cache::~datasource_cache()\n {\n lt_dlexit();\n }\n\n std::map > datasource_cache::plugins_;\n bool datasource_cache::registered_=false;\n \n datasource_ptr datasource_cache::create(const parameters& params)\n {\n datasource_ptr ds;\n try\n {\n boost::optional type = params.get(\"type\");\n if (type)\n {\n map >::iterator itr=plugins_.find(*type);\n if (itr!=plugins_.end())\n {\n if (itr->second->handle())\n {\n create_ds* create_datasource = \n (create_ds*) lt_dlsym(itr->second->handle(), \"create\");\n if (!create_datasource)\n {\n std::clog << \"Cannot load symbols: \" << lt_dlerror() << std::endl;\n }\n else\n {\n ds=datasource_ptr(create_datasource(params), datasource_deleter());\n }\n }\n else\n {\n std::clog << \"Cannot load library: \" << lt_dlerror() << std::endl;\n }\n }\n }\n#ifdef MAPNIK_DEBUG\n std::clog<<\"datasource=\"<\n (new PluginInfo(type,module)))).second; \n }\n\n void datasource_cache::register_datasources(const std::string& str)\n {\t\n mutex::scoped_lock lock(mapnik::singleton::mutex_);\n filesystem::path path(str);\n filesystem::directory_iterator end_itr;\n if (exists(path) && is_directory(path))\n {\n for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )\n {\n if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))\n {\n try \n {\n lt_dlhandle module=lt_dlopen(itr->string().c_str());\n if (module)\n {\n datasource_name* ds_name = \n (datasource_name*) lt_dlsym(module, \"datasource_name\");\n if (ds_name && insert(ds_name(),module))\n { \n#ifdef MAPNIK_DEBUG\n std::clog<<\"registered datasource : \"<"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $\n\n\/\/ mapnik\n#include \n\n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\n\/\/ ltdl\n#include \n\n\/\/ stl\n#include \n#include \n#include \n\nnamespace mapnik\n{\n \nbool is_input_plugin (std::string const& filename)\n{\n return boost::algorithm::ends_with(filename,std::string(\".input\"));\n}\n \n\ndatasource_cache::datasource_cache()\n{\n if (lt_dlinit()) throw std::runtime_error(\"lt_dlinit() failed\");\n}\n\ndatasource_cache::~datasource_cache()\n{\n lt_dlexit();\n}\n\nstd::map > datasource_cache::plugins_;\nbool datasource_cache::registered_=false;\nstd::vector datasource_cache::plugin_directories_;\n \ndatasource_ptr datasource_cache::create(const parameters& params, bool bind) \n{\n boost::optional type = params.get(\"type\");\n if ( ! type)\n {\n throw config_error(std::string(\"Could not create datasource. Required \") +\n \"parameter 'type' is missing\");\n }\n\n#ifdef MAPNIK_THREADSAFE\n mutex::scoped_lock lock(mutex_);\n#endif\n datasource_ptr ds;\n std::map >::iterator itr=plugins_.find(*type);\n if ( itr == plugins_.end() )\n {\n throw config_error(std::string(\"Could not create datasource. No plugin \") +\n \"found for type '\" + * type + \"' (searched in: \" + plugin_directories() + \")\");\n }\n if ( ! itr->second->handle())\n {\n throw std::runtime_error(std::string(\"Cannot load library: \") +\n lt_dlerror());\n }\n \/\/ http:\/\/www.mr-edd.co.uk\/blog\/supressing_gcc_warnings\n #ifdef __GNUC__\n __extension__\n #endif\n create_ds* create_datasource = \n reinterpret_cast(lt_dlsym(itr->second->handle(), \"create\"));\n\n if ( ! create_datasource)\n {\n throw std::runtime_error(std::string(\"Cannot load symbols: \") +\n lt_dlerror());\n }\n#ifdef MAPNIK_DEBUG\n std::clog << \"size = \" << params.size() << \"\\n\";\n parameters::const_iterator i = params.begin();\n for (;i!=params.end();++i)\n {\n std::clog << i->first << \"=\" << i->second << \"\\n\";\n }\n#endif\n ds=datasource_ptr(create_datasource(params, bind), datasource_deleter());\n\n#ifdef MAPNIK_DEBUG\n std::clog<<\"datasource=\"<\n (type,module))).second;\n}\n\nstd::string datasource_cache::plugin_directories()\n{\n return boost::algorithm::join(plugin_directories_,\", \");\n}\n\nstd::vector datasource_cache::plugin_names ()\n{\n std::vector names;\n std::map >::const_iterator itr;\n for (itr = plugins_.begin();itr!=plugins_.end();++itr)\n {\n names.push_back(itr->first);\n }\n return names;\n}\n \nvoid datasource_cache::register_datasources(const std::string& str)\n{ \n#ifdef MAPNIK_THREADSAFE\n mutex::scoped_lock lock(mapnik::singleton::mutex_);\n#endif\n boost::filesystem::path path(str);\n plugin_directories_.push_back(str);\n boost::filesystem::directory_iterator end_itr;\n \n if (exists(path) && is_directory(path))\n {\n for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr )\n {\n\n#if BOOST_VERSION < 103400 \n if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))\n#else\n#if (BOOST_FILESYSTEM_VERSION == 3) \n if (!is_directory( *itr ) && is_input_plugin(itr->path().filename().string()))\n#else \/\/ v2\n if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf())) \n#endif \n#endif\n {\n try \n {\n#ifdef LIBTOOL_SUPPORTS_ADVISE\n \/* Note: the below was added as a workaround pre http:\/\/trac.mapnik.org\/ticket\/790\n It could now be removed, but also is not doing any harm AFAICT.\n *\/\n \n \/\/ with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the\n \/\/ ltdl advise trick which is required on linux unless plugins are directly\n \/\/ linked to libmapnik (and deps) at build time. The only other approach is to\n \/\/ set the dlopen flags in the calling process (like in the python bindings)\n\n \/\/ clear errors\n lt_dlerror();\n\n lt_dlhandle module = 0;\n lt_dladvise advise;\n int ret;\n \n ret = lt_dlinit();\n if (ret != 0) {\n std::clog << \"Datasource loader: could not intialize dynamic loading: \" << lt_dlerror() << \"\\n\";\n }\n \n ret = lt_dladvise_init(&advise);\n if (ret != 0) {\n std::clog << \"Datasource loader: could not intialize dynamic loading: \" << lt_dlerror() << \"\\n\";\n }\n \n ret = lt_dladvise_global(&advise);\n if (ret != 0) {\n std::clog << \"Datasource loader: could not intialize dynamic loading of global symbols: \" << lt_dlerror() << \"\\n\";\n }\n#if (BOOST_FILESYSTEM_VERSION == 3) \n module = lt_dlopenadvise (itr->path().string().c_str(), advise);\n#else \/\/ v2\n module = lt_dlopenadvise (itr->string().c_str(), advise);\n#endif \n\n lt_dladvise_destroy(&advise);\n#else\n\n#if (BOOST_FILESYSTEM_VERSION == 3) \n lt_dlhandle module = lt_dlopen(itr->path().string().c_str());\n#else \/\/ v2\n lt_dlhandle module = lt_dlopen(itr->string().c_str());\n#endif\n\n#endif\n if (module)\n {\n \/\/ http:\/\/www.mr-edd.co.uk\/blog\/supressing_gcc_warnings\n #ifdef __GNUC__\n __extension__\n #endif\n datasource_name* ds_name = \n reinterpret_cast(lt_dlsym(module, \"datasource_name\"));\n if (ds_name && insert(ds_name(),module))\n { \n#ifdef MAPNIK_DEBUG\n std::clog << \"Datasource loader: registered: \" << ds_name() << std::endl;\n#endif \n registered_=true;\n }\n }\n else\n {\n#if (BOOST_FILESYSTEM_VERSION == 3) \n std::clog << \"Problem loading plugin library: \" << itr->path().string() \n << \" (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)\" << std::endl;\n#else \/\/ v2\n std::clog << \"Problem loading plugin library: \" << itr->string() \n << \" (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)\" << std::endl; \n#endif\n }\n }\n catch (...) {}\n }\n }\n }\n}\n\n}\nprint warning if the plugin cannot be loaded as it is lacking an interface\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $\n\n\/\/ mapnik\n#include \n\n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\n\/\/ ltdl\n#include \n\n\/\/ stl\n#include \n#include \n#include \n\nnamespace mapnik\n{\n \nbool is_input_plugin (std::string const& filename)\n{\n return boost::algorithm::ends_with(filename,std::string(\".input\"));\n}\n \n\ndatasource_cache::datasource_cache()\n{\n if (lt_dlinit()) throw std::runtime_error(\"lt_dlinit() failed\");\n}\n\ndatasource_cache::~datasource_cache()\n{\n lt_dlexit();\n}\n\nstd::map > datasource_cache::plugins_;\nbool datasource_cache::registered_=false;\nstd::vector datasource_cache::plugin_directories_;\n \ndatasource_ptr datasource_cache::create(const parameters& params, bool bind) \n{\n boost::optional type = params.get(\"type\");\n if ( ! type)\n {\n throw config_error(std::string(\"Could not create datasource. Required \") +\n \"parameter 'type' is missing\");\n }\n\n#ifdef MAPNIK_THREADSAFE\n mutex::scoped_lock lock(mutex_);\n#endif\n datasource_ptr ds;\n std::map >::iterator itr=plugins_.find(*type);\n if ( itr == plugins_.end() )\n {\n throw config_error(std::string(\"Could not create datasource. No plugin \") +\n \"found for type '\" + * type + \"' (searched in: \" + plugin_directories() + \")\");\n }\n if ( ! itr->second->handle())\n {\n throw std::runtime_error(std::string(\"Cannot load library: \") +\n lt_dlerror());\n }\n \/\/ http:\/\/www.mr-edd.co.uk\/blog\/supressing_gcc_warnings\n #ifdef __GNUC__\n __extension__\n #endif\n create_ds* create_datasource = \n reinterpret_cast(lt_dlsym(itr->second->handle(), \"create\"));\n\n if ( ! create_datasource)\n {\n throw std::runtime_error(std::string(\"Cannot load symbols: \") +\n lt_dlerror());\n }\n#ifdef MAPNIK_DEBUG\n std::clog << \"size = \" << params.size() << \"\\n\";\n parameters::const_iterator i = params.begin();\n for (;i!=params.end();++i)\n {\n std::clog << i->first << \"=\" << i->second << \"\\n\";\n }\n#endif\n ds=datasource_ptr(create_datasource(params, bind), datasource_deleter());\n\n#ifdef MAPNIK_DEBUG\n std::clog<<\"datasource=\"<\n (type,module))).second;\n}\n\nstd::string datasource_cache::plugin_directories()\n{\n return boost::algorithm::join(plugin_directories_,\", \");\n}\n\nstd::vector datasource_cache::plugin_names ()\n{\n std::vector names;\n std::map >::const_iterator itr;\n for (itr = plugins_.begin();itr!=plugins_.end();++itr)\n {\n names.push_back(itr->first);\n }\n return names;\n}\n \nvoid datasource_cache::register_datasources(const std::string& str)\n{ \n#ifdef MAPNIK_THREADSAFE\n mutex::scoped_lock lock(mapnik::singleton::mutex_);\n#endif\n boost::filesystem::path path(str);\n plugin_directories_.push_back(str);\n boost::filesystem::directory_iterator end_itr;\n \n if (exists(path) && is_directory(path))\n {\n for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr )\n {\n\n#if BOOST_VERSION < 103400 \n if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))\n#else\n#if (BOOST_FILESYSTEM_VERSION == 3) \n if (!is_directory( *itr ) && is_input_plugin(itr->path().filename().string()))\n#else \/\/ v2\n if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf())) \n#endif \n#endif\n {\n try \n {\n#ifdef LIBTOOL_SUPPORTS_ADVISE\n \/* Note: the below was added as a workaround pre http:\/\/trac.mapnik.org\/ticket\/790\n It could now be removed, but also is not doing any harm AFAICT.\n *\/\n \n \/\/ with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the\n \/\/ ltdl advise trick which is required on linux unless plugins are directly\n \/\/ linked to libmapnik (and deps) at build time. The only other approach is to\n \/\/ set the dlopen flags in the calling process (like in the python bindings)\n\n \/\/ clear errors\n lt_dlerror();\n\n lt_dlhandle module = 0;\n lt_dladvise advise;\n int ret;\n \n ret = lt_dlinit();\n if (ret != 0) {\n std::clog << \"Datasource loader: could not intialize dynamic loading: \" << lt_dlerror() << \"\\n\";\n }\n \n ret = lt_dladvise_init(&advise);\n if (ret != 0) {\n std::clog << \"Datasource loader: could not intialize dynamic loading: \" << lt_dlerror() << \"\\n\";\n }\n \n ret = lt_dladvise_global(&advise);\n if (ret != 0) {\n std::clog << \"Datasource loader: could not intialize dynamic loading of global symbols: \" << lt_dlerror() << \"\\n\";\n }\n#if (BOOST_FILESYSTEM_VERSION == 3) \n module = lt_dlopenadvise (itr->path().string().c_str(), advise);\n#else \/\/ v2\n module = lt_dlopenadvise (itr->string().c_str(), advise);\n#endif \n\n lt_dladvise_destroy(&advise);\n#else\n\n#if (BOOST_FILESYSTEM_VERSION == 3) \n lt_dlhandle module = lt_dlopen(itr->path().string().c_str());\n#else \/\/ v2\n lt_dlhandle module = lt_dlopen(itr->string().c_str());\n#endif\n\n#endif\n if (module)\n {\n \/\/ http:\/\/www.mr-edd.co.uk\/blog\/supressing_gcc_warnings\n #ifdef __GNUC__\n __extension__\n #endif\n datasource_name* ds_name = \n reinterpret_cast(lt_dlsym(module, \"datasource_name\"));\n if (ds_name && insert(ds_name(),module))\n { \n#ifdef MAPNIK_DEBUG\n std::clog << \"Datasource loader: registered: \" << ds_name() << std::endl;\n#endif \n registered_=true;\n }\n else\n {\n std::clog << \"Problem loading plugin library '\" << itr->path().string() << \"' (plugin is lacking compatible interface\" << std::endl; \n }\n }\n else\n {\n#if (BOOST_FILESYSTEM_VERSION == 3) \n std::clog << \"Problem loading plugin library: \" << itr->path().string() \n << \" (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)\" << std::endl;\n#else \/\/ v2\n std::clog << \"Problem loading plugin library: \" << itr->string() \n << \" (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)\" << std::endl; \n#endif\n }\n }\n catch (...) {}\n }\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2019 The DigiByte Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nuint256 CBlockHeader::GetHash() const\n{\n return SerializeHash(*this);\n}\n\nint CBlockHeader::GetAlgo() const\n{\n switch (nVersion & BLOCK_VERSION_ALGO)\n {\n case BLOCK_VERSION_SCRYPT:\n return ALGO_SCRYPT;\n case BLOCK_VERSION_SHA256D:\n return ALGO_SHA256D;\n case BLOCK_VERSION_GROESTL:\n return ALGO_GROESTL;\n case BLOCK_VERSION_SKEIN:\n return ALGO_SKEIN;\n case BLOCK_VERSION_QUBIT:\n return ALGO_QUBIT;\n }\n return ALGO_UNKNOWN;\n}\n\nuint256 CBlockHeader::GetPoWAlgoHash(const Consensus::Params& params) const\n{\n switch (GetAlgo())\n {\n case ALGO_SHA256D:\n return GetHash();\n case ALGO_SCRYPT:\n {\n uint256 thash;\n scrypt_1024_1_1_256(BEGIN(nVersion), END(thash));\n return thash;\n }\n case ALGO_GROESTL:\n {\n uint256 thash;\n groestl(BEGIN(nVersion), BEGIN(thash));\n return thash;\n }\n case ALGO_SKEIN:\n {\n uint256 thash;\n skein(BEGIN(nVersion), BEGIN(thash));\n return thash;\n }\n case ALGO_QUBIT:\n {\n uint256 thash;\n thash = qubit(BEGIN(nVersion));\n return thash;\n }\n case ALGO_UNKNOWN:\n \/\/ This block will be rejected anyway, but returning an always-invalid\n \/\/ PoW hash will allow it to be rejected sooner.\n return ArithToUint256(~arith_uint256(0));\n }\n assert(false);\n return GetHash();\n}\n\nstd::string CBlock::ToString(const Consensus::Params& params) const\n{\n std::stringstream s;\n s << strprintf(\"CBlock(hash=%s, ver=0x%08x, pow_algo=%d, pow_hash=%s, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\\n\",\n GetHash().ToString(),\n nVersion,\n GetAlgo(),\n GetPoWAlgoHash(params).ToString(),\n hashPrevBlock.ToString(),\n hashMerkleRoot.ToString(),\n nTime, nBits, nNonce,\n vtx.size());\n for (const auto& tx : vtx) {\n s << \" \" << tx->ToString() << \"\\n\";\n }\n return s.str();\n}\n\nstd::string GetAlgoName(int Algo)\n{\n switch (Algo)\n {\n case ALGO_SHA256D:\n return std::string(\"sha256d\");\n case ALGO_SCRYPT:\n return std::string(\"scrypt\");\n case ALGO_GROESTL:\n return std::string(\"groestl\");\n case ALGO_SKEIN:\n return std::string(\"skein\");\n case ALGO_QUBIT:\n return std::string(\"qubit\");\n }\n return std::string(\"unknown\");\n}\n\nint GetAlgoByName(std::string strAlgo, int fallback)\n{\n transform(strAlgo.begin(),strAlgo.end(),strAlgo.begin(),::tolower);\n if (strAlgo == \"sha\" || strAlgo == \"sha256\" || strAlgo == \"sha256d\")\n return ALGO_SHA256D;\n else if (strAlgo == \"scrypt\")\n return ALGO_SCRYPT;\n else if (strAlgo == \"groestl\" || strAlgo == \"groestlsha2\")\n return ALGO_GROESTL;\n else if (strAlgo == \"skein\" || strAlgo == \"skeinsha2\")\n return ALGO_SKEIN;\n else if (strAlgo == \"q2c\" || strAlgo == \"qubit\")\n return ALGO_QUBIT;\n else\n return fallback;\n}\n\nint64_t GetBlockWeight(const CBlock& block)\n{\n \/\/ This implements the weight = (stripped_size * 4) + witness_size formula,\n \/\/ using only serialization with and without witness data. As witness_size\n \/\/ is equal to total_size - stripped_size, this formula is identical to:\n \/\/ weight = (stripped_size * 3) + total_size.\n return ::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, PROTOCOL_VERSION);\n}\nRefactoring GetPoWAlgoHash.\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2019 The DigiByte Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nuint256 CBlockHeader::GetHash() const\n{\n return SerializeHash(*this);\n}\n\nint CBlockHeader::GetAlgo() const\n{\n switch (nVersion & BLOCK_VERSION_ALGO)\n {\n case BLOCK_VERSION_SCRYPT:\n return ALGO_SCRYPT;\n case BLOCK_VERSION_SHA256D:\n return ALGO_SHA256D;\n case BLOCK_VERSION_GROESTL:\n return ALGO_GROESTL;\n case BLOCK_VERSION_SKEIN:\n return ALGO_SKEIN;\n case BLOCK_VERSION_QUBIT:\n return ALGO_QUBIT;\n }\n return ALGO_UNKNOWN;\n}\n\nuint256 CBlockHeader::GetPoWAlgoHash(const Consensus::Params& params) const\n{\n uint256 thash;\n\n switch (GetAlgo())\n {\n case ALGO_SHA256D:\n {\n return GetHash();\n }\n case ALGO_SCRYPT:\n {\n scrypt_1024_1_1_256(BEGIN(nVersion), END(thash));\n break;\n }\n case ALGO_GROESTL:\n {\n groestl(BEGIN(nVersion), BEGIN(thash));\n break;\n }\n case ALGO_SKEIN:\n {\n skein(BEGIN(nVersion), BEGIN(thash));\n break;\n }\n case ALGO_QUBIT:\n {\n thash = qubit(BEGIN(nVersion));\n break;\n }\n case ALGO_UNKNOWN:\n \/\/ This block will be rejected anyway, but returning an always-invalid\n \/\/ PoW hash will allow it to be rejected sooner.\n thash = ArithToUint256(~arith_uint256(0));\n break;\n }\n return thash;\n}\n\nstd::string CBlock::ToString(const Consensus::Params& params) const\n{\n std::stringstream s;\n s << strprintf(\"CBlock(hash=%s, ver=0x%08x, pow_algo=%d, pow_hash=%s, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\\n\",\n GetHash().ToString(),\n nVersion,\n GetAlgo(),\n GetPoWAlgoHash(params).ToString(),\n hashPrevBlock.ToString(),\n hashMerkleRoot.ToString(),\n nTime, nBits, nNonce,\n vtx.size());\n for (const auto& tx : vtx) {\n s << \" \" << tx->ToString() << \"\\n\";\n }\n return s.str();\n}\n\nstd::string GetAlgoName(int Algo)\n{\n switch (Algo)\n {\n case ALGO_SHA256D:\n return std::string(\"sha256d\");\n case ALGO_SCRYPT:\n return std::string(\"scrypt\");\n case ALGO_GROESTL:\n return std::string(\"groestl\");\n case ALGO_SKEIN:\n return std::string(\"skein\");\n case ALGO_QUBIT:\n return std::string(\"qubit\");\n }\n return std::string(\"unknown\");\n}\n\nint GetAlgoByName(std::string strAlgo, int fallback)\n{\n transform(strAlgo.begin(),strAlgo.end(),strAlgo.begin(),::tolower);\n if (strAlgo == \"sha\" || strAlgo == \"sha256\" || strAlgo == \"sha256d\")\n return ALGO_SHA256D;\n else if (strAlgo == \"scrypt\")\n return ALGO_SCRYPT;\n else if (strAlgo == \"groestl\" || strAlgo == \"groestlsha2\")\n return ALGO_GROESTL;\n else if (strAlgo == \"skein\" || strAlgo == \"skeinsha2\")\n return ALGO_SKEIN;\n else if (strAlgo == \"q2c\" || strAlgo == \"qubit\")\n return ALGO_QUBIT;\n else\n return fallback;\n}\n\nint64_t GetBlockWeight(const CBlock& block)\n{\n \/\/ This implements the weight = (stripped_size * 4) + witness_size formula,\n \/\/ using only serialization with and without witness data. As witness_size\n \/\/ is equal to total_size - stripped_size, this formula is identical to:\n \/\/ weight = (stripped_size * 3) + total_size.\n return ::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, PROTOCOL_VERSION);\n}\n<|endoftext|>"} {"text":"\/*\n This code is released under the terms of the MIT license.\n See COPYING.txt for details.\n*\/\n\n#include \n#include \n#include \"propertieswindow.h\"\n#include \"ui_propertieswindow.h\"\n#include \"stuff.h\"\n#include \"level.h\"\n#include \"graphics.h\"\n#include \"hexspinbox.h\"\n#include \"tileset.h\"\n\nPropertiesWindow::PropertiesWindow(QWidget *parent) :\n QDialog(parent, Qt::CustomizeWindowHint\n | Qt::WindowTitleHint\n | Qt::WindowCloseButtonHint\n | Qt::MSWindowsFixedSizeDialogHint\n ),\n ui(new Ui::PropertiesWindow),\n tileBox(new HexSpinBox(this, 2)),\n tilePalBox(new HexSpinBox(this, 2)),\n spriteBox(new HexSpinBox(this, 2)),\n spritePalBox(new HexSpinBox(this, 2))\n{\n ui->setupUi(this);\n\n \/\/ prevent window resizing\n this->layout()->setSizeConstraint(QLayout::SetFixedSize);\n\n \/\/ add spinboxes\n QGridLayout *layout = ui->gridLayout;\n layout->addWidget(tileBox, 2, 2, 1, 1);\n layout->addWidget(tilePalBox, 2, 5, 1, 1);\n layout->addWidget(spriteBox, 3, 2, 1, 1);\n layout->addWidget(spritePalBox, 3, 5, 1, 1);\n\n \/\/ add music names to other dropdown\n for (StringMap::const_iterator i = musicNames.begin(); i != musicNames.end(); i++) {\n ui->comboBox_Music->addItem(i->second, i->first);\n }\n\n \/\/ set up signals to automatically apply changes\n QObject::connect(ui->comboBox_TileGFX, SIGNAL(currentIndexChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->tileBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->tilePalBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->spriteBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->spritePalBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(ui->slider_AnimSpeed, SIGNAL(valueChanged(int)),\n this, SLOT(applySpeed(int)));\n QObject::connect(ui->spinBox_Length, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n\n \/\/ set up signals to handle width\/length constraints\n QObject::connect(ui->spinBox_Length, SIGNAL(valueChanged(int)),\n this, SLOT(setMaxLevelWidth(int)));\n QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)),\n this, SLOT(setMaxLevelLength(int)));\n}\n\nPropertiesWindow::~PropertiesWindow()\n{\n delete ui;\n}\n\nvoid PropertiesWindow::setMaxLevelWidth(int length) {\n ui->spinBox_Width->setMaximum(16 \/ length);\n}\n\nvoid PropertiesWindow::setMaxLevelLength(int width) {\n ui->spinBox_Length->setMaximum(16 \/ width);\n}\n\nvoid PropertiesWindow::startEdit(leveldata_t *level) {\n this->level = NULL;\n\n \/\/ add graphics indices to dropdown\n ui->comboBox_TileGFX->clear();\n for (int i = 0; i < 256; i++)\n ui->comboBox_TileGFX->addItem(QString::number(i, 16).rightJustified(2, QLatin1Char('0')).toUpper()\n + \": banks \"\n + QString::number(bankTable[0][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + \", \"\n + QString::number(bankTable[1][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + \", \"\n + QString::number(bankTable[2][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + \"-\"\n + QString::number((bankTable[2][i] + 3) & 0xFF, 16).rightJustified(2, QLatin1Char('0')).toUpper());\n\n\n \/\/ set graphics values\n ui->comboBox_TileGFX->setCurrentIndex(level->header.tileIndex);\n this->tileBox ->setValue(level->tileset);\n this->tileBox ->setMaximum(NUM_TILESETS - 1);\n this->tilePalBox ->setValue(level->header.tilePal);\n this->tilePalBox ->setMaximum(255);\n this->spriteBox ->setValue(level->header.sprIndex);\n this->spriteBox ->setMaximum(255);\n this->spritePalBox ->setValue(level->header.sprPal);\n this->spritePalBox ->setMaximum(255);\n ui->slider_AnimSpeed->setValue(level->header.animSpeed);\n\n \/\/ set height and width values\n ui->spinBox_Length->setValue(level->header.screensV);\n setMaxLevelWidth(level->header.screensH);\n\n ui->spinBox_Width ->setValue(level->header.screensH);\n setMaxLevelLength(level->header.screensV);\n\n \/\/ set music value\n ui->comboBox_Music->setCurrentIndex(std::distance(musicNames.begin(),\n musicNames.find(level->header.music)));\n\n \/\/ save pointer\n this->level = level;\n \/\/ and original data, in case user cancels\n this->header = level->header;\n this->tileset = level->tileset;\n\n this->exec();\n}\n\nvoid PropertiesWindow::applySpeed(int speed) {\n if (speed)\n \/\/ui->label_FrameLength->setText(QString(\"%1 msec\").arg(speed * 16));\n ui->label_FrameLength->setText(QString(\"%1 frame%2\").arg(speed)\n .arg(speed > 1 ? \"s\" : \"\"));\n else\n ui->label_FrameLength->setText(\"none\");\n\n if (level) {\n level->header.animSpeed = speed;\n emit speedChanged(speed);\n }\n}\n\nvoid PropertiesWindow::applyChange() {\n if (!level) return;\n\n level->header.tileIndex = ui->comboBox_TileGFX->currentIndex();\n level->header.tilePal = this->tilePalBox->value();\n level->tileset = this->tileBox->value();\n level->header.sprIndex = this->spriteBox->value();\n level->header.sprPal = this->spritePalBox->value();\n\n \/\/ apply level size\n level->header.screensV = ui->spinBox_Length->value();\n level->header.screensH = ui->spinBox_Width ->value();\n\n \/\/ apply music setting\n level->header.music = ui->comboBox_Music->itemData(ui->comboBox_Music->currentIndex()).toUInt();\n\n emit changed();\n}\n\nvoid PropertiesWindow::accept() {\n level->modified = true;\n level->modifiedRecently = true;\n\n QDialog::accept();\n}\n\n\/\/ discard settings\nvoid PropertiesWindow::reject() {\n \/\/ return to original settings\n level->header = this->header;\n level->tileset = this->tileset;\n\n emit changed();\n QDialog::reject();\n}\nwhoops\/*\n This code is released under the terms of the MIT license.\n See COPYING.txt for details.\n*\/\n\n#include \n#include \n#include \"propertieswindow.h\"\n#include \"ui_propertieswindow.h\"\n#include \"stuff.h\"\n#include \"level.h\"\n#include \"graphics.h\"\n#include \"hexspinbox.h\"\n#include \"tileset.h\"\n\nPropertiesWindow::PropertiesWindow(QWidget *parent) :\n QDialog(parent, Qt::CustomizeWindowHint\n | Qt::WindowTitleHint\n | Qt::WindowCloseButtonHint\n | Qt::MSWindowsFixedSizeDialogHint\n ),\n ui(new Ui::PropertiesWindow),\n tileBox(new HexSpinBox(this, 2)),\n tilePalBox(new HexSpinBox(this, 2)),\n spriteBox(new HexSpinBox(this, 2)),\n spritePalBox(new HexSpinBox(this, 2))\n{\n ui->setupUi(this);\n\n \/\/ prevent window resizing\n this->layout()->setSizeConstraint(QLayout::SetFixedSize);\n\n \/\/ add spinboxes\n QGridLayout *layout = ui->gridLayout;\n layout->addWidget(tileBox, 2, 2, 1, 1);\n layout->addWidget(tilePalBox, 2, 5, 1, 1);\n layout->addWidget(spriteBox, 3, 2, 1, 1);\n layout->addWidget(spritePalBox, 3, 5, 1, 1);\n\n \/\/ add music names to other dropdown\n for (StringMap::const_iterator i = musicNames.begin(); i != musicNames.end(); i++) {\n ui->comboBox_Music->addItem(i->second, i->first);\n }\n\n \/\/ set up signals to automatically apply changes\n QObject::connect(ui->comboBox_TileGFX, SIGNAL(currentIndexChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->tileBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->tilePalBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->spriteBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(this->spritePalBox, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(ui->slider_AnimSpeed, SIGNAL(valueChanged(int)),\n this, SLOT(applySpeed(int)));\n QObject::connect(ui->spinBox_Length, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)),\n this, SLOT(applyChange()));\n\n \/\/ set up signals to handle width\/length constraints\n QObject::connect(ui->spinBox_Length, SIGNAL(valueChanged(int)),\n this, SLOT(setMaxLevelWidth(int)));\n QObject::connect(ui->spinBox_Width, SIGNAL(valueChanged(int)),\n this, SLOT(setMaxLevelLength(int)));\n}\n\nPropertiesWindow::~PropertiesWindow()\n{\n delete ui;\n delete tileBox;\n delete tilePalBox;\n delete spriteBox;\n delete spritePalBox;\n}\n\nvoid PropertiesWindow::setMaxLevelWidth(int length) {\n ui->spinBox_Width->setMaximum(16 \/ length);\n}\n\nvoid PropertiesWindow::setMaxLevelLength(int width) {\n ui->spinBox_Length->setMaximum(16 \/ width);\n}\n\nvoid PropertiesWindow::startEdit(leveldata_t *level) {\n this->level = NULL;\n\n \/\/ add graphics indices to dropdown\n ui->comboBox_TileGFX->clear();\n for (int i = 0; i < 256; i++)\n ui->comboBox_TileGFX->addItem(QString::number(i, 16).rightJustified(2, QLatin1Char('0')).toUpper()\n + \": banks \"\n + QString::number(bankTable[0][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + \", \"\n + QString::number(bankTable[1][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + \", \"\n + QString::number(bankTable[2][i], 16).rightJustified(2, QLatin1Char('0')).toUpper() + \"-\"\n + QString::number((bankTable[2][i] + 3) & 0xFF, 16).rightJustified(2, QLatin1Char('0')).toUpper());\n\n\n \/\/ set graphics values\n ui->comboBox_TileGFX->setCurrentIndex(level->header.tileIndex);\n this->tileBox ->setValue(level->tileset);\n this->tileBox ->setMaximum(NUM_TILESETS - 1);\n this->tilePalBox ->setValue(level->header.tilePal);\n this->tilePalBox ->setMaximum(255);\n this->spriteBox ->setValue(level->header.sprIndex);\n this->spriteBox ->setMaximum(255);\n this->spritePalBox ->setValue(level->header.sprPal);\n this->spritePalBox ->setMaximum(255);\n ui->slider_AnimSpeed->setValue(level->header.animSpeed);\n\n \/\/ set height and width values\n ui->spinBox_Length->setValue(level->header.screensV);\n setMaxLevelWidth(level->header.screensH);\n\n ui->spinBox_Width ->setValue(level->header.screensH);\n setMaxLevelLength(level->header.screensV);\n\n \/\/ set music value\n ui->comboBox_Music->setCurrentIndex(std::distance(musicNames.begin(),\n musicNames.find(level->header.music)));\n\n \/\/ save pointer\n this->level = level;\n \/\/ and original data, in case user cancels\n this->header = level->header;\n this->tileset = level->tileset;\n\n this->exec();\n}\n\nvoid PropertiesWindow::applySpeed(int speed) {\n if (speed)\n \/\/ui->label_FrameLength->setText(QString(\"%1 msec\").arg(speed * 16));\n ui->label_FrameLength->setText(QString(\"%1 frame%2\").arg(speed)\n .arg(speed > 1 ? \"s\" : \"\"));\n else\n ui->label_FrameLength->setText(\"none\");\n\n if (level) {\n level->header.animSpeed = speed;\n emit speedChanged(speed);\n }\n}\n\nvoid PropertiesWindow::applyChange() {\n if (!level) return;\n\n level->header.tileIndex = ui->comboBox_TileGFX->currentIndex();\n level->header.tilePal = this->tilePalBox->value();\n level->tileset = this->tileBox->value();\n level->header.sprIndex = this->spriteBox->value();\n level->header.sprPal = this->spritePalBox->value();\n\n \/\/ apply level size\n level->header.screensV = ui->spinBox_Length->value();\n level->header.screensH = ui->spinBox_Width ->value();\n\n \/\/ apply music setting\n level->header.music = ui->comboBox_Music->itemData(ui->comboBox_Music->currentIndex()).toUInt();\n\n emit changed();\n}\n\nvoid PropertiesWindow::accept() {\n level->modified = true;\n level->modifiedRecently = true;\n\n QDialog::accept();\n}\n\n\/\/ discard settings\nvoid PropertiesWindow::reject() {\n \/\/ return to original settings\n level->header = this->header;\n level->tileset = this->tileset;\n\n emit changed();\n QDialog::reject();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"bitcoin-config.h\"\n#endif\n\n#include \"optionsdialog.h\"\n#include \"ui_optionsdialog.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n#include \"monitoreddatamapper.h\"\n#include \"optionsmodel.h\"\n\n#include \"main.h\" \/\/ for CTransaction::nMinTxFee\n#include \"netbase.h\"\n#include \"txdb.h\" \/\/ for -dbcache defaults\n\n#include \n#include \n#include \n#include \n#include \n\nOptionsDialog::OptionsDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::OptionsDialog),\n model(0),\n mapper(0),\n fProxyIpValid(true)\n{\n ui->setupUi(this);\n GUIUtil::restoreWindowGeometry(\"nOptionsDialogWindow\", this->size(), this);\n\n \/* Main elements init *\/\n ui->databaseCache->setMinimum(nMinDbCache);\n ui->databaseCache->setMaximum(nMaxDbCache);\n\n \/* Network elements init *\/\n#ifndef USE_UPNP\n ui->mapPortUpnp->setEnabled(false);\n#endif\n\n ui->proxyIp->setEnabled(false);\n ui->proxyPort->setEnabled(false);\n ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));\n\n \/** SOCKS version is only selectable for default proxy and is always 5 for IPv6 and Tor *\/\n ui->socksVersion->setEnabled(false);\n ui->socksVersion->addItem(\"5\", 5);\n ui->socksVersion->addItem(\"4\", 4);\n ui->socksVersion->setCurrentIndex(0);\n\n connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));\n connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));\n connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));\n\n ui->proxyIp->installEventFilter(this);\n\n \/* Window elements init *\/\n#ifdef Q_OS_MAC\n \/* remove Window tab on Mac *\/\n ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));\n#endif\n\n \/* Display elements init *\/\n QDir translations(\":translations\");\n ui->lang->addItem(QString(\"(\") + tr(\"default\") + QString(\")\"), QVariant(\"\"));\n foreach(const QString &langStr, translations.entryList())\n {\n QLocale locale(langStr);\n\n \/** check if the locale name consists of 2 parts (language_country) *\/\n if(langStr.contains(\"_\"))\n {\n#if QT_VERSION >= 0x040800\n \/** display language strings as \"native language - native country (locale name)\", e.g. \"Deutsch - Deutschland (de)\" *\/\n ui->lang->addItem(locale.nativeLanguageName() + QString(\" - \") + locale.nativeCountryName() + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#else\n \/** display language strings as \"language - country (locale name)\", e.g. \"German - Germany (de)\" *\/\n ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(\" - \") + QLocale::countryToString(locale.country()) + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#endif\n }\n else\n {\n#if QT_VERSION >= 0x040800\n \/** display language strings as \"native language (locale name)\", e.g. \"Deutsch (de)\" *\/\n ui->lang->addItem(locale.nativeLanguageName() + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#else\n \/** display language strings as \"language (locale name)\", e.g. \"German (de)\" *\/\n ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#endif\n }\n }\n\n ui->unit->setModel(new BitcoinUnits(this));\n ui->transactionFee->setSingleStep(CTransaction::nMinTxFee);\n\n \/* Widget-to-option mapper *\/\n mapper = new MonitoredDataMapper(this);\n mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n mapper->setOrientation(Qt::Vertical);\n\n \/* setup\/change UI elements when proxy IP is invalid\/valid *\/\n connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit *, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit *, int)));\n}\n\nOptionsDialog::~OptionsDialog()\n{\n GUIUtil::saveWindowGeometry(\"nOptionsDialogWindow\", this);\n delete ui;\n}\n\nvoid OptionsDialog::setModel(OptionsModel *model)\n{\n this->model = model;\n\n if(model)\n {\n \/* check if client restart is needed and show persistent message *\/\n if (model->isRestartRequired())\n showRestartWarning(true);\n\n QString strLabel = model->getOverriddenByCommandLine();\n if (strLabel.isEmpty())\n strLabel = tr(\"none\");\n ui->overriddenByCommandLineLabel->setText(strLabel);\n\n connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n mapper->setModel(model);\n setMapper();\n mapper->toFirst();\n }\n\n \/* update the display unit, to not use the default (\"DOGE\") *\/\n updateDisplayUnit();\n\n \/* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) *\/\n\n \/* Main *\/\n connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));\n connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));\n \/* Network *\/\n connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n \/* Display *\/\n connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));\n}\n\nvoid OptionsDialog::setMapper()\n{\n \/* Main *\/\n mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);\n mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);\n mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);\n\n \/* Wallet *\/\n mapper->addMapping(ui->transactionFee, OptionsModel::Fee);\n mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);\n\n \/* Network *\/\n mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);\n\n mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);\n mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);\n mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);\n mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);\n\n \/* Window *\/\n#ifndef Q_OS_MAC\n mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);\n mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);\n#endif\n\n \/* Display *\/\n mapper->addMapping(ui->lang, OptionsModel::Language);\n mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);\n mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);\n mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);\n}\n\nvoid OptionsDialog::enableOkButton()\n{\n \/* prevent enabling of the OK button when data modified, if there is an invalid proxy address present *\/\n if(fProxyIpValid)\n setOkButtonState(true);\n}\n\nvoid OptionsDialog::disableOkButton()\n{\n setOkButtonState(false);\n}\n\nvoid OptionsDialog::setOkButtonState(bool fState)\n{\n ui->okButton->setEnabled(fState);\n}\n\nvoid OptionsDialog::on_resetButton_clicked()\n{\n if(model)\n {\n \/\/ confirmation dialog\n QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr(\"Confirm options reset\"),\n tr(\"Client restart required to activate changes.\") + \"

\" + tr(\"Client will be shutdown, do you want to proceed?\"),\n QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);\n\n if(btnRetVal == QMessageBox::Cancel)\n return;\n\n \/* reset all options and close GUI *\/\n model->Reset();\n QApplication::quit();\n }\n}\n\nvoid OptionsDialog::on_okButton_clicked()\n{\n mapper->submit();\n accept();\n}\n\nvoid OptionsDialog::on_cancelButton_clicked()\n{\n reject();\n}\n\nvoid OptionsDialog::showRestartWarning(bool fPersistent)\n{\n ui->statusLabel->setStyleSheet(\"QLabel { color: red; }\");\n\n if(fPersistent)\n {\n ui->statusLabel->setText(tr(\"Client restart required to activate changes.\"));\n }\n else\n {\n ui->statusLabel->setText(tr(\"This change would require a client restart.\"));\n \/\/ clear non-persistent status label after 10 seconds\n \/\/ Todo: should perhaps be a class attribute, if we extend the use of statusLabel\n QTimer::singleShot(10000, this, SLOT(clearStatusLabel()));\n }\n}\n\nvoid OptionsDialog::clearStatusLabel()\n{\n ui->statusLabel->clear();\n}\n\nvoid OptionsDialog::updateDisplayUnit()\n{\n if(model)\n {\n \/* Update transactionFee with the current unit *\/\n ui->transactionFee->setDisplayUnit(model->getDisplayUnit());\n }\n}\n\nvoid OptionsDialog::doProxyIpChecks(QValidatedLineEdit *pUiProxyIp, int nProxyPort)\n{\n Q_UNUSED(nProxyPort);\n\n const std::string strAddrProxy = pUiProxyIp->text().toStdString();\n CService addrProxy;\n\n \/* Check for a valid IPv4 \/ IPv6 address *\/\n if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy)))\n {\n disableOkButton();\n pUiProxyIp->setValid(false);\n ui->statusLabel->setStyleSheet(\"QLabel { color: red; }\");\n ui->statusLabel->setText(tr(\"The supplied proxy address is invalid.\"));\n }\n else\n {\n enableOkButton();\n ui->statusLabel->clear();\n }\n}\n\nbool OptionsDialog::eventFilter(QObject *object, QEvent *event)\n{\n if(event->type() == QEvent::FocusOut)\n {\n if(object == ui->proxyIp)\n {\n emit proxyIpChecks(ui->proxyIp, ui->proxyPort->text().toInt());\n }\n }\n return QDialog::eventFilter(object, event);\n}\nNotify user about a required restart, when he changes the ZeroConf option.\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"bitcoin-config.h\"\n#endif\n\n#include \"optionsdialog.h\"\n#include \"ui_optionsdialog.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n#include \"monitoreddatamapper.h\"\n#include \"optionsmodel.h\"\n\n#include \"main.h\" \/\/ for CTransaction::nMinTxFee\n#include \"netbase.h\"\n#include \"txdb.h\" \/\/ for -dbcache defaults\n\n#include \n#include \n#include \n#include \n#include \n\nOptionsDialog::OptionsDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::OptionsDialog),\n model(0),\n mapper(0),\n fProxyIpValid(true)\n{\n ui->setupUi(this);\n GUIUtil::restoreWindowGeometry(\"nOptionsDialogWindow\", this->size(), this);\n\n \/* Main elements init *\/\n ui->databaseCache->setMinimum(nMinDbCache);\n ui->databaseCache->setMaximum(nMaxDbCache);\n\n \/* Network elements init *\/\n#ifndef USE_UPNP\n ui->mapPortUpnp->setEnabled(false);\n#endif\n\n ui->proxyIp->setEnabled(false);\n ui->proxyPort->setEnabled(false);\n ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));\n\n \/** SOCKS version is only selectable for default proxy and is always 5 for IPv6 and Tor *\/\n ui->socksVersion->setEnabled(false);\n ui->socksVersion->addItem(\"5\", 5);\n ui->socksVersion->addItem(\"4\", 4);\n ui->socksVersion->setCurrentIndex(0);\n\n connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));\n connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));\n connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));\n\n ui->proxyIp->installEventFilter(this);\n\n \/* Window elements init *\/\n#ifdef Q_OS_MAC\n \/* remove Window tab on Mac *\/\n ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));\n#endif\n\n \/* Display elements init *\/\n QDir translations(\":translations\");\n ui->lang->addItem(QString(\"(\") + tr(\"default\") + QString(\")\"), QVariant(\"\"));\n foreach(const QString &langStr, translations.entryList())\n {\n QLocale locale(langStr);\n\n \/** check if the locale name consists of 2 parts (language_country) *\/\n if(langStr.contains(\"_\"))\n {\n#if QT_VERSION >= 0x040800\n \/** display language strings as \"native language - native country (locale name)\", e.g. \"Deutsch - Deutschland (de)\" *\/\n ui->lang->addItem(locale.nativeLanguageName() + QString(\" - \") + locale.nativeCountryName() + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#else\n \/** display language strings as \"language - country (locale name)\", e.g. \"German - Germany (de)\" *\/\n ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(\" - \") + QLocale::countryToString(locale.country()) + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#endif\n }\n else\n {\n#if QT_VERSION >= 0x040800\n \/** display language strings as \"native language (locale name)\", e.g. \"Deutsch (de)\" *\/\n ui->lang->addItem(locale.nativeLanguageName() + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#else\n \/** display language strings as \"language (locale name)\", e.g. \"German (de)\" *\/\n ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(\" (\") + langStr + QString(\")\"), QVariant(langStr));\n#endif\n }\n }\n\n ui->unit->setModel(new BitcoinUnits(this));\n ui->transactionFee->setSingleStep(CTransaction::nMinTxFee);\n\n \/* Widget-to-option mapper *\/\n mapper = new MonitoredDataMapper(this);\n mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n mapper->setOrientation(Qt::Vertical);\n\n \/* setup\/change UI elements when proxy IP is invalid\/valid *\/\n connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit *, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit *, int)));\n}\n\nOptionsDialog::~OptionsDialog()\n{\n GUIUtil::saveWindowGeometry(\"nOptionsDialogWindow\", this);\n delete ui;\n}\n\nvoid OptionsDialog::setModel(OptionsModel *model)\n{\n this->model = model;\n\n if(model)\n {\n \/* check if client restart is needed and show persistent message *\/\n if (model->isRestartRequired())\n showRestartWarning(true);\n\n QString strLabel = model->getOverriddenByCommandLine();\n if (strLabel.isEmpty())\n strLabel = tr(\"none\");\n ui->overriddenByCommandLineLabel->setText(strLabel);\n\n connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n mapper->setModel(model);\n setMapper();\n mapper->toFirst();\n }\n\n \/* update the display unit, to not use the default (\"DOGE\") *\/\n updateDisplayUnit();\n\n \/* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) *\/\n\n \/* Main *\/\n connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));\n connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));\n \/* Wallet *\/\n connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n \/* Network *\/\n connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));\n \/* Display *\/\n connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));\n}\n\nvoid OptionsDialog::setMapper()\n{\n \/* Main *\/\n mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);\n mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);\n mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);\n\n \/* Wallet *\/\n mapper->addMapping(ui->transactionFee, OptionsModel::Fee);\n mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);\n\n \/* Network *\/\n mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);\n\n mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);\n mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);\n mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);\n mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);\n\n \/* Window *\/\n#ifndef Q_OS_MAC\n mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);\n mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);\n#endif\n\n \/* Display *\/\n mapper->addMapping(ui->lang, OptionsModel::Language);\n mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);\n mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);\n mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);\n}\n\nvoid OptionsDialog::enableOkButton()\n{\n \/* prevent enabling of the OK button when data modified, if there is an invalid proxy address present *\/\n if(fProxyIpValid)\n setOkButtonState(true);\n}\n\nvoid OptionsDialog::disableOkButton()\n{\n setOkButtonState(false);\n}\n\nvoid OptionsDialog::setOkButtonState(bool fState)\n{\n ui->okButton->setEnabled(fState);\n}\n\nvoid OptionsDialog::on_resetButton_clicked()\n{\n if(model)\n {\n \/\/ confirmation dialog\n QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr(\"Confirm options reset\"),\n tr(\"Client restart required to activate changes.\") + \"

\" + tr(\"Client will be shutdown, do you want to proceed?\"),\n QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);\n\n if(btnRetVal == QMessageBox::Cancel)\n return;\n\n \/* reset all options and close GUI *\/\n model->Reset();\n QApplication::quit();\n }\n}\n\nvoid OptionsDialog::on_okButton_clicked()\n{\n mapper->submit();\n accept();\n}\n\nvoid OptionsDialog::on_cancelButton_clicked()\n{\n reject();\n}\n\nvoid OptionsDialog::showRestartWarning(bool fPersistent)\n{\n ui->statusLabel->setStyleSheet(\"QLabel { color: red; }\");\n\n if(fPersistent)\n {\n ui->statusLabel->setText(tr(\"Client restart required to activate changes.\"));\n }\n else\n {\n ui->statusLabel->setText(tr(\"This change would require a client restart.\"));\n \/\/ clear non-persistent status label after 10 seconds\n \/\/ Todo: should perhaps be a class attribute, if we extend the use of statusLabel\n QTimer::singleShot(10000, this, SLOT(clearStatusLabel()));\n }\n}\n\nvoid OptionsDialog::clearStatusLabel()\n{\n ui->statusLabel->clear();\n}\n\nvoid OptionsDialog::updateDisplayUnit()\n{\n if(model)\n {\n \/* Update transactionFee with the current unit *\/\n ui->transactionFee->setDisplayUnit(model->getDisplayUnit());\n }\n}\n\nvoid OptionsDialog::doProxyIpChecks(QValidatedLineEdit *pUiProxyIp, int nProxyPort)\n{\n Q_UNUSED(nProxyPort);\n\n const std::string strAddrProxy = pUiProxyIp->text().toStdString();\n CService addrProxy;\n\n \/* Check for a valid IPv4 \/ IPv6 address *\/\n if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy)))\n {\n disableOkButton();\n pUiProxyIp->setValid(false);\n ui->statusLabel->setStyleSheet(\"QLabel { color: red; }\");\n ui->statusLabel->setText(tr(\"The supplied proxy address is invalid.\"));\n }\n else\n {\n enableOkButton();\n ui->statusLabel->clear();\n }\n}\n\nbool OptionsDialog::eventFilter(QObject *object, QEvent *event)\n{\n if(event->type() == QEvent::FocusOut)\n {\n if(object == ui->proxyIp)\n {\n emit proxyIpChecks(ui->proxyIp, ui->proxyPort->text().toInt());\n }\n }\n return QDialog::eventFilter(object, event);\n}\n<|endoftext|>"} {"text":"\/* This is free and unencumbered software released into the public domain. *\/\n\n#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#include \"serd.h\"\n#include \"..\/quad.h\"\n#include \"..\/term.h\"\n#include \"..\/triple.h\"\n\n#include \/* for assert() *\/\n#include \/* for std::vsnprintf() *\/\n#include \/* for std::fprintf(), std::snprintf() *\/\n#include \/* for std::strrchr() *\/\n#include \/* for std::function *\/\n#include \/* for std::unique_ptr *\/\n#include \/* for std::bad_alloc *\/\n\n#include \/* for serd_*() *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\n struct implementation final : public rdf::reader::implementation {\n public:\n implementation(FILE* stream,\n const char* content_type,\n const char* charset,\n const char* base_uri);\n virtual ~implementation() noexcept override;\n virtual void read_triples(std::function)> callback) override;\n virtual void read_quads(std::function)> callback) override;\n virtual void abort() override;\n\n protected:\n using serd_env_ptr = std::unique_ptr;\n using serd_reader_ptr = std::unique_ptr;\n\n void read();\n static SerdStatus base_sink(void* handle, const SerdNode* uri);\n static SerdStatus prefix_sink(void* handle, const SerdNode* name, const SerdNode* uri);\n static SerdStatus statement_sink(void* handle, SerdStatementFlags flags,\n const SerdNode* graph, const SerdNode* subject, const SerdNode* predicate,\n const SerdNode* object, const SerdNode* object_datatype, const SerdNode* object_lang);\n static SerdStatus end_sink(void* handle, const SerdNode* node);\n static SerdStatus error_sink(void* handle, const SerdError* error);\n static void throw_error(const char* func, SerdStatus status);\n static std::string expand_curie_or_uri(const char* type_label,\n const SerdEnv* env, const SerdNode* curie);\n static std::unique_ptr make_term(const SerdEnv* env,\n const SerdNode* node,\n const SerdNode* node_datatype = nullptr,\n const SerdNode* node_language = nullptr);\n\n private:\n serd_env_ptr _env{nullptr, serd_env_free};\n serd_reader_ptr _reader{nullptr, serd_reader_free};\n std::function)> _triple_callback;\n std::function)> _quad_callback;\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrdf::reader::implementation*\nrdf_reader_for_serd(FILE* const stream,\n const char* const content_type,\n const char* const charset,\n const char* const base_uri) {\n return new implementation(stream, content_type, charset, base_uri);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nimplementation::implementation(FILE* const stream,\n const char* const content_type,\n const char* const charset,\n const char* const base_uri_str) {\n static_cast(content_type); \/* not used *\/\n static_cast(charset); \/* not used *\/\n\n assert(stream);\n\n if (base_uri_str) {\n SerdURI base_uri = SERD_URI_NULL;\n SerdNode base_uri_node = serd_node_new_uri_from_string(\n reinterpret_cast(base_uri_str), nullptr, &base_uri);\n _env.reset(serd_env_new(&base_uri_node));\n serd_node_free(&base_uri_node);\n }\n else {\n _env.reset(serd_env_new(nullptr));\n }\n\n if (!_env) {\n throw std::bad_alloc(); \/* out of memory *\/\n }\n\n _reader.reset(serd_reader_new(SERD_TURTLE, this, nullptr,\n implementation::base_sink,\n implementation::prefix_sink,\n implementation::statement_sink,\n implementation::end_sink));\n\n if (!_reader) {\n throw std::bad_alloc(); \/* out of memory *\/\n }\n\n serd_reader_set_error_sink(_reader.get(), implementation::error_sink, this);\n \/\/serd_reader_set_strict(_reader.get(), true);\n\n SerdStatus status;\n if ((status = serd_reader_start_stream(_reader.get(),\n stream, reinterpret_cast(\"(stream)\"), false)) != SERD_SUCCESS) {\n throw_error(\"serd_reader_start_stream\", status);\n }\n}\n\nimplementation::~implementation() noexcept {\n try { abort(); } catch (...) {}\n}\n\nvoid\nimplementation::read_triples(std::function)> callback) {\n if (!_reader) return;\n\n _triple_callback = callback;\n _quad_callback = nullptr;\n read();\n}\n\nvoid\nimplementation::read_quads(std::function)> callback) {\n if (!_reader) return;\n\n _triple_callback = nullptr;\n _quad_callback = callback;\n read();\n}\n\nvoid\nimplementation::abort() {\n if (!_reader) return;\n\n SerdStatus status;\n if ((status = serd_reader_end_stream(_reader.get())) != SERD_SUCCESS) {\n throw_error(\"serd_reader_end_stream\", status);\n }\n\n _reader.reset();\n}\n\nvoid\nimplementation::read() {\n SerdStatus status = SERD_SUCCESS;\n while (status == SERD_SUCCESS) {\n status = serd_reader_read_chunk(_reader.get());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSerdStatus\nimplementation::base_sink(void* const handle,\n const SerdNode* const uri) {\n if (0) std::fprintf(stderr, \"%s: handle=%p uri=<%s>\\n\", __func__, handle, uri ? uri->buf : nullptr);\n\n assert(handle);\n const implementation& reader = *reinterpret_cast(handle);\n\n return serd_env_set_base_uri(reader._env.get(), uri);\n}\n\nSerdStatus\nimplementation::prefix_sink(void* const handle,\n const SerdNode* const name,\n const SerdNode* const uri) {\n if (0) std::fprintf(stderr, \"%s: handle=%p name='%s' uri=<%s>\\n\", __func__, handle, name ? name->buf : nullptr, uri ? uri->buf : nullptr);\n\n assert(handle);\n const implementation& reader = *reinterpret_cast(handle);\n\n return serd_env_set_prefix(reader._env.get(), name, uri);\n}\n\nSerdStatus\nimplementation::statement_sink(void* const handle,\n const SerdStatementFlags flags,\n const SerdNode* const \/*graph*\/,\n const SerdNode* const subject,\n const SerdNode* const predicate,\n const SerdNode* const object,\n const SerdNode* const object_datatype,\n const SerdNode* const object_lang) {\n if (0) std::fprintf(stderr, \"%s: handle=%p flags=%d subject=%p predicate=%p object=%p object_datatype=%p object_lang=%p\\n\", __func__, handle, flags, subject, predicate, object, object_datatype, object_lang);\n\n assert(handle);\n const implementation& reader = *reinterpret_cast(handle);\n\n std::unique_ptr subject_term{make_term(reader._env.get(), subject)};\n std::unique_ptr predicate_term{make_term(reader._env.get(), predicate)};\n std::unique_ptr object_term{make_term(reader._env.get(), object, object_datatype, object_lang)};\n\n if (reader._quad_callback) {\n std::unique_ptr quad{new rdf::quad{subject_term.release(), predicate_term.release(), object_term.release()}};\n reader._quad_callback(std::move(quad));\n }\n else if (reader._triple_callback) {\n std::unique_ptr triple{new rdf::triple{subject_term.release(), predicate_term.release(), object_term.release()}};\n reader._triple_callback(std::move(triple));\n }\n\n return SERD_SUCCESS;\n}\n\nSerdStatus\nimplementation::end_sink(void* const handle,\n const SerdNode* const node) {\n if (0) std::fprintf(stderr, \"%s: handle=%p node=%s\\n\", __func__, handle, node ? node->buf : nullptr);\n\n return SERD_SUCCESS;\n}\n\nSerdStatus\nimplementation::error_sink(void* const handle,\n const SerdError* const error) {\n if (0) std::fprintf(stderr, \"%s: handle=%p error=%s\\n\", __func__, handle, error ? error->fmt : nullptr);\n\n if (!error) {\n throw rdf::reader_error{\"failed to parse input\"};\n }\n\n switch (error->status) {\n case SERD_SUCCESS: return SERD_SUCCESS;\n case SERD_FAILURE: return SERD_SUCCESS;\n case SERD_ERR_UNKNOWN: break;\n case SERD_ERR_BAD_SYNTAX: break;\n case SERD_ERR_BAD_ARG: break;\n case SERD_ERR_NOT_FOUND: break;\n case SERD_ERR_ID_CLASH: break;\n case SERD_ERR_BAD_CURIE: break;\n case SERD_ERR_INTERNAL: break;\n }\n\n char error_detail[1024];\n std::vsnprintf(error_detail, sizeof(error_detail), error->fmt, *error->args);\n\n \/* Trim the trailing \"\\n\" from the Serd error detail: *\/\n const auto newline_ptr = std::strrchr(error_detail, '\\n');\n if (newline_ptr) *newline_ptr = '\\0';\n\n char error_message[4096];\n std::snprintf(error_message, sizeof(error_message), \"%s: %s on line %u, column %u\",\n error->filename ? reinterpret_cast(error->filename) : \"(stream)\",\n error_detail, error->line, error->col);\n\n throw rdf::reader_error{error_message};\n\n return SERD_SUCCESS; \/* never reached *\/\n}\n\nvoid\nimplementation::throw_error(const char* const symbol,\n const SerdStatus status) {\n const char* status_str = nullptr;\n switch (status) {\n case SERD_SUCCESS: \/* No error *\/\n return;\n case SERD_FAILURE: \/* Non-fatal failure *\/\n status_str = \"SERD_FAILURE\";\n break;\n case SERD_ERR_UNKNOWN: \/* Unknown error *\/\n status_str = \"SERD_ERR_UNKNOWN\";\n break;\n case SERD_ERR_BAD_SYNTAX: \/* Invalid syntax *\/\n status_str = \"SERD_ERR_BAD_SYNTAX\";\n break;\n case SERD_ERR_BAD_ARG: \/* Invalid argument *\/\n status_str = \"SERD_ERR_BAD_ARG\";\n break;\n case SERD_ERR_NOT_FOUND: \/* Not found *\/\n status_str = \"SERD_ERR_NOT_FOUND\";\n break;\n case SERD_ERR_ID_CLASH: \/* Encountered clashing blank node IDs *\/\n status_str = \"SERD_ERR_ID_CLASH\";\n break;\n case SERD_ERR_BAD_CURIE: \/* Invalid CURIE (e.g. prefix does not exist) *\/\n status_str = \"SERD_ERR_BAD_CURIE\";\n break;\n case SERD_ERR_INTERNAL: \/* Unexpected internal error (should not happen) *\/\n status_str = \"SERD_ERR_INTERNAL\";\n break;\n }\n char error_message[256];\n std::snprintf(error_message, sizeof(error_message), \"%s() returned %s\", symbol, status_str);\n throw rdf::reader_error{error_message};\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string\nimplementation::expand_curie_or_uri(const char* const type_label,\n const SerdEnv* const env,\n const SerdNode* const curie_or_uri) {\n SerdNode uri = serd_env_expand_node(env, curie_or_uri);\n\n if (uri.type == SERD_NOTHING) {\n char error_message[256];\n std::snprintf(error_message, sizeof(error_message),\n \"failed to expand the %s node '%s'\", type_label, curie_or_uri->buf);\n throw rdf::reader_error{error_message};\n }\n assert(uri.type == SERD_URI);\n\n std::string uri_string{const_cast(reinterpret_cast(uri.buf))};\n serd_node_free(&uri);\n\n return uri_string;\n}\n\nstd::unique_ptr\nimplementation::make_term(const SerdEnv* const env,\n const SerdNode* const node,\n const SerdNode* const node_datatype,\n const SerdNode* const node_language) {\n std::unique_ptr term;\n if (node) {\n const char* const term_string = reinterpret_cast(node->buf);\n switch (node->type) {\n case SERD_NOTHING: {\n assert(false && \"node->type == SERD_NOTHING\"); \/* should never reach this *\/\n break;\n }\n case SERD_LITERAL: {\n if (node_datatype) {\n std::string term_datatype = expand_curie_or_uri(\n (node_datatype->type == SERD_CURIE) ? \"CURIE\" : \"URI\", env, node_datatype);\n term.reset(new rdf::typed_literal{term_string, term_datatype});\n }\n else if (node_language) {\n const char* const term_language = reinterpret_cast(node_language->buf);\n term.reset(new rdf::plain_literal{term_string, term_language});\n }\n else {\n term.reset(new rdf::plain_literal{term_string});\n }\n break;\n }\n case SERD_URI: {\n term.reset(new rdf::uri_reference{expand_curie_or_uri(\"URI\", env, node)});\n break;\n }\n case SERD_CURIE: {\n term.reset(new rdf::uri_reference{expand_curie_or_uri(\"CURIE\", env, node)});\n break;\n }\n case SERD_BLANK: {\n term.reset(new rdf::blank_node{term_string});\n break;\n }\n }\n }\n return term;\n}\nserd.cc: make calls to expand_curie_or_uri consistent\/* This is free and unencumbered software released into the public domain. *\/\n\n#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#include \"serd.h\"\n#include \"..\/quad.h\"\n#include \"..\/term.h\"\n#include \"..\/triple.h\"\n\n#include \/* for assert() *\/\n#include \/* for std::vsnprintf() *\/\n#include \/* for std::fprintf(), std::snprintf() *\/\n#include \/* for std::strrchr() *\/\n#include \/* for std::function *\/\n#include \/* for std::unique_ptr *\/\n#include \/* for std::bad_alloc *\/\n\n#include \/* for serd_*() *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\n struct implementation final : public rdf::reader::implementation {\n public:\n implementation(FILE* stream,\n const char* content_type,\n const char* charset,\n const char* base_uri);\n virtual ~implementation() noexcept override;\n virtual void read_triples(std::function)> callback) override;\n virtual void read_quads(std::function)> callback) override;\n virtual void abort() override;\n\n protected:\n using serd_env_ptr = std::unique_ptr;\n using serd_reader_ptr = std::unique_ptr;\n\n void read();\n static SerdStatus base_sink(void* handle, const SerdNode* uri);\n static SerdStatus prefix_sink(void* handle, const SerdNode* name, const SerdNode* uri);\n static SerdStatus statement_sink(void* handle, SerdStatementFlags flags,\n const SerdNode* graph, const SerdNode* subject, const SerdNode* predicate,\n const SerdNode* object, const SerdNode* object_datatype, const SerdNode* object_lang);\n static SerdStatus end_sink(void* handle, const SerdNode* node);\n static SerdStatus error_sink(void* handle, const SerdError* error);\n static void throw_error(const char* func, SerdStatus status);\n static std::string expand_curie_or_uri(const char* type_label,\n const SerdEnv* env, const SerdNode* curie);\n static std::unique_ptr make_term(const SerdEnv* env,\n const SerdNode* node,\n const SerdNode* node_datatype = nullptr,\n const SerdNode* node_language = nullptr);\n\n private:\n serd_env_ptr _env{nullptr, serd_env_free};\n serd_reader_ptr _reader{nullptr, serd_reader_free};\n std::function)> _triple_callback;\n std::function)> _quad_callback;\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nrdf::reader::implementation*\nrdf_reader_for_serd(FILE* const stream,\n const char* const content_type,\n const char* const charset,\n const char* const base_uri) {\n return new implementation(stream, content_type, charset, base_uri);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nimplementation::implementation(FILE* const stream,\n const char* const content_type,\n const char* const charset,\n const char* const base_uri_str) {\n static_cast(content_type); \/* not used *\/\n static_cast(charset); \/* not used *\/\n\n assert(stream);\n\n if (base_uri_str) {\n SerdURI base_uri = SERD_URI_NULL;\n SerdNode base_uri_node = serd_node_new_uri_from_string(\n reinterpret_cast(base_uri_str), nullptr, &base_uri);\n _env.reset(serd_env_new(&base_uri_node));\n serd_node_free(&base_uri_node);\n }\n else {\n _env.reset(serd_env_new(nullptr));\n }\n\n if (!_env) {\n throw std::bad_alloc(); \/* out of memory *\/\n }\n\n _reader.reset(serd_reader_new(SERD_TURTLE, this, nullptr,\n implementation::base_sink,\n implementation::prefix_sink,\n implementation::statement_sink,\n implementation::end_sink));\n\n if (!_reader) {\n throw std::bad_alloc(); \/* out of memory *\/\n }\n\n serd_reader_set_error_sink(_reader.get(), implementation::error_sink, this);\n \/\/serd_reader_set_strict(_reader.get(), true);\n\n SerdStatus status;\n if ((status = serd_reader_start_stream(_reader.get(),\n stream, reinterpret_cast(\"(stream)\"), false)) != SERD_SUCCESS) {\n throw_error(\"serd_reader_start_stream\", status);\n }\n}\n\nimplementation::~implementation() noexcept {\n try { abort(); } catch (...) {}\n}\n\nvoid\nimplementation::read_triples(std::function)> callback) {\n if (!_reader) return;\n\n _triple_callback = callback;\n _quad_callback = nullptr;\n read();\n}\n\nvoid\nimplementation::read_quads(std::function)> callback) {\n if (!_reader) return;\n\n _triple_callback = nullptr;\n _quad_callback = callback;\n read();\n}\n\nvoid\nimplementation::abort() {\n if (!_reader) return;\n\n SerdStatus status;\n if ((status = serd_reader_end_stream(_reader.get())) != SERD_SUCCESS) {\n throw_error(\"serd_reader_end_stream\", status);\n }\n\n _reader.reset();\n}\n\nvoid\nimplementation::read() {\n SerdStatus status = SERD_SUCCESS;\n while (status == SERD_SUCCESS) {\n status = serd_reader_read_chunk(_reader.get());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSerdStatus\nimplementation::base_sink(void* const handle,\n const SerdNode* const uri) {\n if (0) std::fprintf(stderr, \"%s: handle=%p uri=<%s>\\n\", __func__, handle, uri ? uri->buf : nullptr);\n\n assert(handle);\n const implementation& reader = *reinterpret_cast(handle);\n\n return serd_env_set_base_uri(reader._env.get(), uri);\n}\n\nSerdStatus\nimplementation::prefix_sink(void* const handle,\n const SerdNode* const name,\n const SerdNode* const uri) {\n if (0) std::fprintf(stderr, \"%s: handle=%p name='%s' uri=<%s>\\n\", __func__, handle, name ? name->buf : nullptr, uri ? uri->buf : nullptr);\n\n assert(handle);\n const implementation& reader = *reinterpret_cast(handle);\n\n return serd_env_set_prefix(reader._env.get(), name, uri);\n}\n\nSerdStatus\nimplementation::statement_sink(void* const handle,\n const SerdStatementFlags flags,\n const SerdNode* const \/*graph*\/,\n const SerdNode* const subject,\n const SerdNode* const predicate,\n const SerdNode* const object,\n const SerdNode* const object_datatype,\n const SerdNode* const object_lang) {\n if (0) std::fprintf(stderr, \"%s: handle=%p flags=%d subject=%p predicate=%p object=%p object_datatype=%p object_lang=%p\\n\", __func__, handle, flags, subject, predicate, object, object_datatype, object_lang);\n\n assert(handle);\n const implementation& reader = *reinterpret_cast(handle);\n\n std::unique_ptr subject_term{make_term(reader._env.get(), subject)};\n std::unique_ptr predicate_term{make_term(reader._env.get(), predicate)};\n std::unique_ptr object_term{make_term(reader._env.get(), object, object_datatype, object_lang)};\n\n if (reader._quad_callback) {\n std::unique_ptr quad{new rdf::quad{subject_term.release(), predicate_term.release(), object_term.release()}};\n reader._quad_callback(std::move(quad));\n }\n else if (reader._triple_callback) {\n std::unique_ptr triple{new rdf::triple{subject_term.release(), predicate_term.release(), object_term.release()}};\n reader._triple_callback(std::move(triple));\n }\n\n return SERD_SUCCESS;\n}\n\nSerdStatus\nimplementation::end_sink(void* const handle,\n const SerdNode* const node) {\n if (0) std::fprintf(stderr, \"%s: handle=%p node=%s\\n\", __func__, handle, node ? node->buf : nullptr);\n\n return SERD_SUCCESS;\n}\n\nSerdStatus\nimplementation::error_sink(void* const handle,\n const SerdError* const error) {\n if (0) std::fprintf(stderr, \"%s: handle=%p error=%s\\n\", __func__, handle, error ? error->fmt : nullptr);\n\n if (!error) {\n throw rdf::reader_error{\"failed to parse input\"};\n }\n\n switch (error->status) {\n case SERD_SUCCESS: return SERD_SUCCESS;\n case SERD_FAILURE: return SERD_SUCCESS;\n case SERD_ERR_UNKNOWN: break;\n case SERD_ERR_BAD_SYNTAX: break;\n case SERD_ERR_BAD_ARG: break;\n case SERD_ERR_NOT_FOUND: break;\n case SERD_ERR_ID_CLASH: break;\n case SERD_ERR_BAD_CURIE: break;\n case SERD_ERR_INTERNAL: break;\n }\n\n char error_detail[1024];\n std::vsnprintf(error_detail, sizeof(error_detail), error->fmt, *error->args);\n\n \/* Trim the trailing \"\\n\" from the Serd error detail: *\/\n const auto newline_ptr = std::strrchr(error_detail, '\\n');\n if (newline_ptr) *newline_ptr = '\\0';\n\n char error_message[4096];\n std::snprintf(error_message, sizeof(error_message), \"%s: %s on line %u, column %u\",\n error->filename ? reinterpret_cast(error->filename) : \"(stream)\",\n error_detail, error->line, error->col);\n\n throw rdf::reader_error{error_message};\n\n return SERD_SUCCESS; \/* never reached *\/\n}\n\nvoid\nimplementation::throw_error(const char* const symbol,\n const SerdStatus status) {\n const char* status_str = nullptr;\n switch (status) {\n case SERD_SUCCESS: \/* No error *\/\n return;\n case SERD_FAILURE: \/* Non-fatal failure *\/\n status_str = \"SERD_FAILURE\";\n break;\n case SERD_ERR_UNKNOWN: \/* Unknown error *\/\n status_str = \"SERD_ERR_UNKNOWN\";\n break;\n case SERD_ERR_BAD_SYNTAX: \/* Invalid syntax *\/\n status_str = \"SERD_ERR_BAD_SYNTAX\";\n break;\n case SERD_ERR_BAD_ARG: \/* Invalid argument *\/\n status_str = \"SERD_ERR_BAD_ARG\";\n break;\n case SERD_ERR_NOT_FOUND: \/* Not found *\/\n status_str = \"SERD_ERR_NOT_FOUND\";\n break;\n case SERD_ERR_ID_CLASH: \/* Encountered clashing blank node IDs *\/\n status_str = \"SERD_ERR_ID_CLASH\";\n break;\n case SERD_ERR_BAD_CURIE: \/* Invalid CURIE (e.g. prefix does not exist) *\/\n status_str = \"SERD_ERR_BAD_CURIE\";\n break;\n case SERD_ERR_INTERNAL: \/* Unexpected internal error (should not happen) *\/\n status_str = \"SERD_ERR_INTERNAL\";\n break;\n }\n char error_message[256];\n std::snprintf(error_message, sizeof(error_message), \"%s() returned %s\", symbol, status_str);\n throw rdf::reader_error{error_message};\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string\nimplementation::expand_curie_or_uri(const char* const type_label,\n const SerdEnv* const env,\n const SerdNode* const curie_or_uri) {\n SerdNode uri = serd_env_expand_node(env, curie_or_uri);\n\n if (uri.type == SERD_NOTHING) {\n char error_message[256];\n std::snprintf(error_message, sizeof(error_message),\n \"failed to expand the %s node '%s'\", type_label, curie_or_uri->buf);\n throw rdf::reader_error{error_message};\n }\n assert(uri.type == SERD_URI);\n\n std::string uri_string{const_cast(reinterpret_cast(uri.buf))};\n serd_node_free(&uri);\n\n return uri_string;\n}\n\nstd::unique_ptr\nimplementation::make_term(const SerdEnv* const env,\n const SerdNode* const node,\n const SerdNode* const node_datatype,\n const SerdNode* const node_language) {\n std::unique_ptr term;\n if (node) {\n const char* const term_string = reinterpret_cast(node->buf);\n switch (node->type) {\n case SERD_NOTHING: {\n assert(false && \"node->type == SERD_NOTHING\"); \/* should never reach this *\/\n break;\n }\n case SERD_LITERAL: {\n if (node_datatype) {\n std::string uri_string = expand_curie_or_uri(\n (node_datatype->type == SERD_CURIE) ? \"CURIE\" : \"URI\", env, node_datatype);\n term.reset(new rdf::typed_literal{term_string, uri_string});\n }\n else if (node_language) {\n const char* const term_language = reinterpret_cast(node_language->buf);\n term.reset(new rdf::plain_literal{term_string, term_language});\n }\n else {\n term.reset(new rdf::plain_literal{term_string});\n }\n break;\n }\n case SERD_URI: {\n std::string uri_string = expand_curie_or_uri(\"URI\", env, node);\n term.reset(new rdf::uri_reference{uri_string});\n break;\n }\n case SERD_CURIE: {\n std::string uri_string = expand_curie_or_uri(\"CURIE\", env, node);\n term.reset(new rdf::uri_reference{uri_string});\n break;\n }\n case SERD_BLANK: {\n term.reset(new rdf::blank_node{term_string});\n break;\n }\n }\n }\n return term;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 Chris Pickel \n\/\/\n\/\/ This file is part of librezin, a free software project. You can redistribute it and\/or modify\n\/\/ it under the terms of the MIT License.\n\n#include \"rezin\/BasicTypes.hpp\"\n\n#include \n#include \n#include \n#include \"rezin\/BitsPiece.hpp\"\n\nusing rgos::Json;\nusing rgos::StringMap;\nusing sfz::Bytes;\nusing sfz::BytesPiece;\nusing sfz::Exception;\nusing sfz::ReadSource;\nusing sfz::format;\nusing sfz::read;\nusing std::vector;\n\nnamespace rezin {\n\nint16_t Rect::width() const {\n return right - left;\n}\n\nint16_t Rect::height() const {\n return bottom - top;\n}\n\nJson Rect::to_json() const {\n StringMap result;\n result[\"top\"] = Json::number(top);\n result[\"left\"] = Json::number(left);\n result[\"bottom\"] = Json::number(bottom);\n result[\"right\"] = Json::number(right);\n return Json::object(result);\n}\n\nvoid read_from(ReadSource in, Rect* out) {\n read(in, &out->top);\n read(in, &out->left);\n read(in, &out->bottom);\n read(in, &out->right);\n}\n\ndouble fixed32_t::to_double() const {\n return int_value \/ 65536.0;\n}\n\nJson fixed32_t::to_json() const {\n return Json::number(to_double());\n}\n\nvoid read_from(ReadSource in, fixed32_t* out) {\n read(in, &out->int_value);\n}\n\nJson PixMap::to_json() const {\n StringMap result;\n result[\"bounds\"] = bounds.to_json();\n return Json::object(result);\n}\n\nvoid PixMap::read_pixels(ReadSource in, vector* out) const {\n size_t size = row_bytes * bounds.height();\n Bytes bytes(size, '\\0');\n in.shift(bytes.mutable_data(), size);\n\n BytesPiece remainder = bytes;\n for (int i = 0; i < bounds.height(); ++i) {\n BitsPiece bits(remainder.substr(0, row_bytes));\n for (int j = 0; j < bounds.width(); ++j) {\n uint8_t value;\n bits.shift(&value, pixel_size);\n out->push_back(value);\n }\n remainder.shift(row_bytes);\n }\n}\n\nvoid read_from(ReadSource in, PixMap* out) {\n read(in, &out->base_addr);\n read(in, &out->row_bytes);\n out->row_bytes &= 0x3fff;\n read(in, &out->bounds);\n read(in, &out->pm_version);\n read(in, &out->pack_type);\n read(in, &out->pack_size);\n read(in, &out->h_res);\n read(in, &out->v_res);\n read(in, &out->pixel_type);\n read(in, &out->pixel_size);\n read(in, &out->cmp_count);\n read(in, &out->cmp_size);\n read(in, &out->plane_bytes);\n read(in, &out->pm_table);\n read(in, &out->pm_reserved);\n\n if ((out->pixel_type != 0) || (out->pack_type != 0) || (out->pack_size != 0)\n || (out->cmp_count != 1) || (out->cmp_size != out->pixel_size)) {\n throw Exception(\"only indexed pixels are supported\");\n }\n switch (out->pixel_size) {\n case 1:\n case 2:\n case 4:\n case 8:\n break;\n\n default:\n throw Exception(format(\"indexed pixels may not have size {0}\", out->pixel_size));\n }\n if (out->plane_bytes != 0) {\n throw Exception(\"PixMap::plane_bytes must be 0\");\n }\n if (out->base_addr != 0) {\n throw Exception(\"PixMap::base_addr must be 0\");\n }\n if (out->pm_table != 0) {\n throw Exception(\"PixMap::pm_table must be 0\");\n }\n if (out->pm_reserved != 0) {\n throw Exception(\"PixMap::pm_reserved must be 0\");\n }\n}\n\nJson BitMap::to_json() const {\n StringMap result;\n result[\"bounds\"] = bounds.to_json();\n return Json::object(result);\n}\n\nvoid BitMap::read_pixels(ReadSource in, vector* out) const {\n size_t size = row_bytes * bounds.height();\n Bytes bytes(size, '\\0');\n in.shift(bytes.mutable_data(), size);\n\n BytesPiece remainder = bytes;\n for (int i = 0; i < bounds.height(); ++i) {\n BitsPiece bits(remainder.substr(0, row_bytes));\n for (int j = 0; j < bounds.width(); ++j) {\n uint8_t value;\n bits.shift(&value, 1);\n out->push_back(value);\n }\n remainder.shift(row_bytes);\n }\n}\n\nvoid read_from(ReadSource in, BitMap* out) {\n read(in, &out->base_addr);\n read(in, &out->row_bytes);\n read(in, &out->bounds);\n\n if (out->base_addr != 0) {\n throw Exception(\"PixMap::base_addr must be 0\");\n }\n}\n\n} \/\/ namespace rezin\nDon't read pixels if row_bytes is 0.\/\/ Copyright (c) 2009 Chris Pickel \n\/\/\n\/\/ This file is part of librezin, a free software project. You can redistribute it and\/or modify\n\/\/ it under the terms of the MIT License.\n\n#include \"rezin\/BasicTypes.hpp\"\n\n#include \n#include \n#include \n#include \"rezin\/BitsPiece.hpp\"\n\nusing rgos::Json;\nusing rgos::StringMap;\nusing sfz::Bytes;\nusing sfz::BytesPiece;\nusing sfz::Exception;\nusing sfz::ReadSource;\nusing sfz::format;\nusing sfz::read;\nusing std::vector;\n\nnamespace rezin {\n\nint16_t Rect::width() const {\n return right - left;\n}\n\nint16_t Rect::height() const {\n return bottom - top;\n}\n\nJson Rect::to_json() const {\n StringMap result;\n result[\"top\"] = Json::number(top);\n result[\"left\"] = Json::number(left);\n result[\"bottom\"] = Json::number(bottom);\n result[\"right\"] = Json::number(right);\n return Json::object(result);\n}\n\nvoid read_from(ReadSource in, Rect* out) {\n read(in, &out->top);\n read(in, &out->left);\n read(in, &out->bottom);\n read(in, &out->right);\n}\n\ndouble fixed32_t::to_double() const {\n return int_value \/ 65536.0;\n}\n\nJson fixed32_t::to_json() const {\n return Json::number(to_double());\n}\n\nvoid read_from(ReadSource in, fixed32_t* out) {\n read(in, &out->int_value);\n}\n\nJson PixMap::to_json() const {\n StringMap result;\n result[\"bounds\"] = bounds.to_json();\n return Json::object(result);\n}\n\nvoid PixMap::read_pixels(ReadSource in, vector* out) const {\n if (row_bytes == 0) {\n return;\n }\n\n size_t size = row_bytes * bounds.height();\n Bytes bytes(size, '\\0');\n in.shift(bytes.mutable_data(), size);\n\n BytesPiece remainder = bytes;\n for (int i = 0; i < bounds.height(); ++i) {\n BitsPiece bits(remainder.substr(0, row_bytes));\n for (int j = 0; j < bounds.width(); ++j) {\n uint8_t value;\n bits.shift(&value, pixel_size);\n out->push_back(value);\n }\n remainder.shift(row_bytes);\n }\n}\n\nvoid read_from(ReadSource in, PixMap* out) {\n read(in, &out->base_addr);\n read(in, &out->row_bytes);\n out->row_bytes &= 0x3fff;\n read(in, &out->bounds);\n read(in, &out->pm_version);\n read(in, &out->pack_type);\n read(in, &out->pack_size);\n read(in, &out->h_res);\n read(in, &out->v_res);\n read(in, &out->pixel_type);\n read(in, &out->pixel_size);\n read(in, &out->cmp_count);\n read(in, &out->cmp_size);\n read(in, &out->plane_bytes);\n read(in, &out->pm_table);\n read(in, &out->pm_reserved);\n\n if ((out->pixel_type != 0) || (out->pack_type != 0) || (out->pack_size != 0)\n || (out->cmp_count != 1) || (out->cmp_size != out->pixel_size)) {\n throw Exception(\"only indexed pixels are supported\");\n }\n switch (out->pixel_size) {\n case 1:\n case 2:\n case 4:\n case 8:\n break;\n\n default:\n throw Exception(format(\"indexed pixels may not have size {0}\", out->pixel_size));\n }\n if (out->plane_bytes != 0) {\n throw Exception(\"PixMap::plane_bytes must be 0\");\n }\n if (out->base_addr != 0) {\n throw Exception(\"PixMap::base_addr must be 0\");\n }\n if (out->pm_table != 0) {\n throw Exception(\"PixMap::pm_table must be 0\");\n }\n if (out->pm_reserved != 0) {\n throw Exception(\"PixMap::pm_reserved must be 0\");\n }\n}\n\nJson BitMap::to_json() const {\n StringMap result;\n result[\"bounds\"] = bounds.to_json();\n return Json::object(result);\n}\n\nvoid BitMap::read_pixels(ReadSource in, vector* out) const {\n if (row_bytes == 0) {\n return;\n }\n\n size_t size = row_bytes * bounds.height();\n Bytes bytes(size, '\\0');\n in.shift(bytes.mutable_data(), size);\n\n BytesPiece remainder = bytes;\n for (int i = 0; i < bounds.height(); ++i) {\n BitsPiece bits(remainder.substr(0, row_bytes));\n for (int j = 0; j < bounds.width(); ++j) {\n uint8_t value;\n bits.shift(&value, 1);\n out->push_back(value);\n }\n remainder.shift(row_bytes);\n }\n}\n\nvoid read_from(ReadSource in, BitMap* out) {\n read(in, &out->base_addr);\n read(in, &out->row_bytes);\n read(in, &out->bounds);\n\n if (out->base_addr != 0) {\n throw Exception(\"PixMap::base_addr must be 0\");\n }\n}\n\n} \/\/ namespace rezin\n<|endoftext|>"} {"text":"#ifndef _SEARCH_CONSTANTS_HPP_\n#define _SEARCH_CONSTANTS_HPP_\n\n\nconst unsigned INITIAL_CLOSED_SET_SIZE = 25000000;\n\n\n#endif \/* !_SEARCH_CONSTANTS_HPP_ *\/\nINITIAL_CLOSED_SET_SIZE changed to 50M#ifndef _SEARCH_CONSTANTS_HPP_\n#define _SEARCH_CONSTANTS_HPP_\n\n\nconst unsigned INITIAL_CLOSED_SET_SIZE = 50000000;\n\n\n#endif \/* !_SEARCH_CONSTANTS_HPP_ *\/\n<|endoftext|>"} {"text":"\/\/Copyright (c) 2017 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"sliceDataStorage.h\"\n\n#include \"FffProcessor.h\" \/\/To create a mesh group with if none is provided.\n#include \"infill\/SubDivCube.h\" \/\/ For the destructor\n\n\nnamespace cura\n{\n\nPolygons& SliceLayerPart::getOwnInfillArea()\n{\n return const_cast(const_cast(this)->getOwnInfillArea());\n}\n\nconst Polygons& SliceLayerPart::getOwnInfillArea() const\n{\n if (infill_area_own)\n {\n return *infill_area_own;\n }\n else\n {\n return infill_area;\n }\n}\n\nbool SliceLayerPart::isUsed(const SettingsBaseVirtual& mesh_settings) const\n{\n if (mesh_settings.getSettingAsCount(\"wall_line_count\") > 0 && insets.size() > 0)\n { \/\/ note that in case wall line count is zero, the outline was pushed onto the insets\n return true;\n }\n if (skin_parts.size() > 0)\n {\n return true;\n }\n if (mesh_settings.getSettingBoolean(\"spaghetti_infill_enabled\"))\n {\n if (spaghetti_infill_volumes.size() > 0)\n {\n return true;\n }\n }\n else if (mesh_settings.getSettingInMicrons(\"infill_line_distance\") > 0)\n {\n for (const std::vector& infill_area_per_combine : infill_area_per_combine_per_density)\n {\n for (const Polygons& area : infill_area_per_combine)\n {\n if (area.size() > 0)\n {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nPolygons SliceLayer::getOutlines(bool external_polys_only) const\n{\n Polygons ret;\n getOutlines(ret, external_polys_only);\n return ret;\n}\n\nvoid SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const\n{\n for (const SliceLayerPart& part : parts)\n {\n if (external_polys_only)\n {\n result.add(part.outline.outerPolygon());\n }\n else \n {\n result.add(part.print_outline);\n }\n }\n}\n\nPolygons SliceLayer::getSecondOrInnermostWalls() const\n{\n Polygons ret;\n getSecondOrInnermostWalls(ret);\n return ret;\n}\n\nvoid SliceLayer::getSecondOrInnermostWalls(Polygons& layer_walls) const\n{\n for (const SliceLayerPart& part : parts)\n {\n \/\/ we want the 2nd inner walls\n if (part.insets.size() >= 2) {\n layer_walls.add(part.insets[1]);\n continue;\n }\n \/\/ but we'll also take the inner wall if the 2nd doesn't exist\n if (part.insets.size() == 1) {\n layer_walls.add(part.insets[0]);\n continue;\n }\n \/\/ offset_from_outlines was so large that it completely destroyed our isle,\n \/\/ so we'll just use the regular outline\n layer_walls.add(part.outline);\n continue;\n }\n}\n\nSliceMeshStorage::~SliceMeshStorage()\n{\n if (base_subdiv_cube)\n {\n delete base_subdiv_cube;\n }\n}\n\nbool SliceMeshStorage::getExtruderIsUsed(int extruder_nr) const\n{\n if (getSettingAsCount(\"wall_line_count\") > 0 && getSettingAsIndex(\"wall_0_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n if (getSettingAsCount(\"wall_line_count\") > 1 && getSettingAsIndex(\"wall_x_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n if (getSettingInMicrons(\"infill_line_distance\") > 0 && getSettingAsIndex(\"infill_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n if (getSettingAsIndex(\"top_bottom_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n return false;\n}\n\nbool SliceMeshStorage::getExtruderIsUsed(int extruder_nr, int layer_nr) const\n{\n if (layer_nr < 0 || layer_nr >= static_cast(layers.size()))\n {\n return false;\n }\n if (getSettingBoolean(\"anti_overhang_mesh\")\n || getSettingBoolean(\"support_mesh\"))\n { \/\/ object is not printed as object, but as support.\n return false;\n }\n const SliceLayer& layer = layers[layer_nr];\n if (getSettingAsCount(\"wall_line_count\") > 0 && getSettingAsIndex(\"wall_0_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.insets.size() > 0 && part.insets[0].size() > 0)\n {\n return true;\n }\n }\n }\n if (getSettingAsCount(\"wall_line_count\") > 1 && getSettingAsIndex(\"wall_x_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.insets.size() > 1 && part.insets[1].size() > 0)\n {\n return true;\n }\n }\n }\n if (getSettingInMicrons(\"infill_line_distance\") > 0 && getSettingAsIndex(\"infill_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.getOwnInfillArea().size() > 0)\n {\n return true;\n }\n }\n }\n if (getSettingAsIndex(\"top_bottom_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (!part.skin_parts.empty())\n {\n return true;\n }\n }\n }\n return false;\n}\n\nstd::vector SliceDataStorage::initializeRetractionConfigs()\n{\n std::vector ret;\n ret.resize(meshgroup->getExtruderCount()); \/\/ initializes with constructor RetractionConfig()\n return ret;\n}\n\nSliceDataStorage::SliceDataStorage(MeshGroup* meshgroup) : SettingsMessenger(meshgroup),\n meshgroup(meshgroup != nullptr ? meshgroup : new MeshGroup(FffProcessor::getInstance())), \/\/If no mesh group is provided, we roll our own.\n print_layer_count(0),\n retraction_config_per_extruder(initializeRetractionConfigs()),\n extruder_switch_retraction_config_per_extruder(initializeRetractionConfigs()),\n max_print_height_second_to_last_extruder(-1),\n primeTower(*this)\n{\n}\n\nPolygons SliceDataStorage::getLayerOutlines(int layer_nr, bool include_helper_parts, bool external_polys_only) const\n{\n if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))\n { \/\/ when processing raft\n if (include_helper_parts)\n {\n if (external_polys_only)\n {\n std::vector parts = raftOutline.splitIntoParts();\n Polygons result;\n for (PolygonsPart& part : parts) \n {\n result.add(part.outerPolygon());\n }\n return result;\n }\n else \n {\n return raftOutline;\n }\n }\n else \n {\n return Polygons();\n }\n }\n else \n {\n Polygons total;\n if (layer_nr >= 0)\n {\n for (const SliceMeshStorage& mesh : meshes)\n {\n if (mesh.getSettingBoolean(\"infill_mesh\") || mesh.getSettingBoolean(\"anti_overhang_mesh\"))\n {\n continue;\n }\n const SliceLayer& layer = mesh.layers[layer_nr];\n layer.getOutlines(total, external_polys_only);\n if (mesh.getSettingAsSurfaceMode(\"magic_mesh_surface_mode\") != ESurfaceMode::NORMAL)\n {\n total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));\n }\n }\n }\n if (include_helper_parts)\n {\n if (support.generated) \n {\n total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_bottom);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_roof);\n }\n if (primeTower.enabled)\n {\n total.add(primeTower.ground_poly);\n }\n }\n return total;\n }\n}\n\nPolygons SliceDataStorage::getLayerSecondOrInnermostWalls(int layer_nr, bool include_helper_parts) const\n{\n if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))\n { \/\/ when processing raft\n if (include_helper_parts)\n {\n return raftOutline;\n }\n else \n {\n return Polygons();\n }\n }\n else \n {\n Polygons total;\n if (layer_nr >= 0)\n {\n for (const SliceMeshStorage& mesh : meshes)\n {\n const SliceLayer& layer = mesh.layers[layer_nr];\n layer.getSecondOrInnermostWalls(total);\n if (mesh.getSettingAsSurfaceMode(\"magic_mesh_surface_mode\") != ESurfaceMode::NORMAL)\n {\n total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));\n }\n }\n }\n if (include_helper_parts)\n {\n if (support.generated) \n {\n total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_bottom);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_roof);\n }\n if (primeTower.enabled)\n {\n total.add(primeTower.ground_poly);\n }\n }\n return total;\n }\n\n}\n\nstd::vector SliceDataStorage::getExtrudersUsed() const\n{\n\n std::vector ret;\n ret.resize(meshgroup->getExtruderCount(), false);\n\n if (getSettingAsPlatformAdhesion(\"adhesion_type\") != EPlatformAdhesion::NONE)\n {\n ret[getSettingAsIndex(\"adhesion_extruder_nr\")] = true;\n { \/\/ process brim\/skirt\n for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)\n {\n if (skirt_brim[extr_nr].size() > 0)\n {\n ret[extr_nr] = true;\n continue;\n }\n }\n }\n }\n\n \/\/ TODO: ooze shield, draft shield ..?\n\n \/\/ support\n \/\/ support is presupposed to be present...\n for (const SliceMeshStorage& mesh : meshes)\n {\n if (mesh.getSettingBoolean(\"support_enable\") || mesh.getSettingBoolean(\"support_mesh\"))\n {\n ret[getSettingAsIndex(\"support_extruder_nr_layer_0\")] = true;\n ret[getSettingAsIndex(\"support_infill_extruder_nr\")] = true;\n if (getSettingBoolean(\"support_roof_enable\"))\n {\n ret[getSettingAsIndex(\"support_roof_extruder_nr\")] = true;\n }\n if (getSettingBoolean(\"support_bottom_enable\"))\n {\n ret[getSettingAsIndex(\"support_bottom_extruder_nr\")] = true;\n }\n }\n }\n\n \/\/ all meshes are presupposed to actually have content\n for (const SliceMeshStorage& mesh : meshes)\n {\n if (!mesh.getSettingBoolean(\"anti_overhang_mesh\")\n && !mesh.getSettingBoolean(\"support_mesh\")\n )\n {\n ret[mesh.getSettingAsIndex(\"extruder_nr\")] = true;\n }\n }\n return ret;\n}\n\nstd::vector SliceDataStorage::getExtrudersUsed(int layer_nr) const\n{\n\n std::vector ret;\n ret.resize(meshgroup->getExtruderCount(), false);\n\n bool include_adhesion = true;\n bool include_helper_parts = true;\n bool include_models = true;\n if (layer_nr < 0)\n {\n include_models = false;\n if (layer_nr < -Raft::getFillerLayerCount(*this))\n {\n include_helper_parts = false;\n }\n else\n {\n layer_nr = 0; \/\/ because the helper parts are copied from the initial layer in the filler layer\n include_adhesion = false;\n }\n }\n else if (layer_nr > 0 || getSettingAsPlatformAdhesion(\"adhesion_type\") == EPlatformAdhesion::RAFT)\n { \/\/ only include adhesion only for layers where platform adhesion actually occurs\n \/\/ i.e. layers < 0 are for raft, layer 0 is for brim\/skirt\n include_adhesion = false;\n }\n if (include_adhesion)\n {\n ret[getSettingAsIndex(\"adhesion_extruder_nr\")] = true;\n { \/\/ process brim\/skirt\n for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)\n {\n if (skirt_brim[extr_nr].size() > 0)\n {\n ret[extr_nr] = true;\n continue;\n }\n }\n }\n }\n\n \/\/ TODO: ooze shield, draft shield ..?\n\n if (include_helper_parts)\n {\n \/\/ support\n if (layer_nr < int(support.supportLayers.size()))\n {\n const SupportLayer& support_layer = support.supportLayers[layer_nr];\n if (layer_nr == 0)\n {\n if (!support_layer.supportAreas.empty())\n {\n ret[getSettingAsIndex(\"support_extruder_nr_layer_0\")] = true;\n }\n }\n else\n {\n if (!support_layer.supportAreas.empty())\n {\n ret[getSettingAsIndex(\"support_infill_extruder_nr\")] = true;\n }\n }\n if (!support_layer.support_bottom.empty())\n {\n ret[getSettingAsIndex(\"support_bottom_extruder_nr\")] = true;\n }\n if (!support_layer.support_roof.empty())\n {\n ret[getSettingAsIndex(\"support_roof_extruder_nr\")] = true;\n }\n }\n }\n\n if (include_models)\n {\n for (const SliceMeshStorage& mesh : meshes)\n {\n if (layer_nr >= int(mesh.layers.size()))\n {\n continue;\n }\n const SliceLayer& layer = mesh.layers[layer_nr];\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.isUsed(mesh))\n {\n ret[mesh.getSettingAsIndex(\"extruder_nr\")] = true;\n break;\n }\n }\n }\n }\n return ret;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n} \/\/ namespace curafix: SliceDataStorage::getExtrudersUsed no longer relies on extruder_nr (CURA-3737)\/\/Copyright (c) 2017 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"sliceDataStorage.h\"\n\n#include \"FffProcessor.h\" \/\/To create a mesh group with if none is provided.\n#include \"infill\/SubDivCube.h\" \/\/ For the destructor\n\n\nnamespace cura\n{\n\nPolygons& SliceLayerPart::getOwnInfillArea()\n{\n return const_cast(const_cast(this)->getOwnInfillArea());\n}\n\nconst Polygons& SliceLayerPart::getOwnInfillArea() const\n{\n if (infill_area_own)\n {\n return *infill_area_own;\n }\n else\n {\n return infill_area;\n }\n}\n\nbool SliceLayerPart::isUsed(const SettingsBaseVirtual& mesh_settings) const\n{\n if (mesh_settings.getSettingAsCount(\"wall_line_count\") > 0 && insets.size() > 0)\n { \/\/ note that in case wall line count is zero, the outline was pushed onto the insets\n return true;\n }\n if (skin_parts.size() > 0)\n {\n return true;\n }\n if (mesh_settings.getSettingBoolean(\"spaghetti_infill_enabled\"))\n {\n if (spaghetti_infill_volumes.size() > 0)\n {\n return true;\n }\n }\n else if (mesh_settings.getSettingInMicrons(\"infill_line_distance\") > 0)\n {\n for (const std::vector& infill_area_per_combine : infill_area_per_combine_per_density)\n {\n for (const Polygons& area : infill_area_per_combine)\n {\n if (area.size() > 0)\n {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nPolygons SliceLayer::getOutlines(bool external_polys_only) const\n{\n Polygons ret;\n getOutlines(ret, external_polys_only);\n return ret;\n}\n\nvoid SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const\n{\n for (const SliceLayerPart& part : parts)\n {\n if (external_polys_only)\n {\n result.add(part.outline.outerPolygon());\n }\n else \n {\n result.add(part.print_outline);\n }\n }\n}\n\nPolygons SliceLayer::getSecondOrInnermostWalls() const\n{\n Polygons ret;\n getSecondOrInnermostWalls(ret);\n return ret;\n}\n\nvoid SliceLayer::getSecondOrInnermostWalls(Polygons& layer_walls) const\n{\n for (const SliceLayerPart& part : parts)\n {\n \/\/ we want the 2nd inner walls\n if (part.insets.size() >= 2) {\n layer_walls.add(part.insets[1]);\n continue;\n }\n \/\/ but we'll also take the inner wall if the 2nd doesn't exist\n if (part.insets.size() == 1) {\n layer_walls.add(part.insets[0]);\n continue;\n }\n \/\/ offset_from_outlines was so large that it completely destroyed our isle,\n \/\/ so we'll just use the regular outline\n layer_walls.add(part.outline);\n continue;\n }\n}\n\nSliceMeshStorage::~SliceMeshStorage()\n{\n if (base_subdiv_cube)\n {\n delete base_subdiv_cube;\n }\n}\n\nbool SliceMeshStorage::getExtruderIsUsed(int extruder_nr) const\n{\n if (getSettingAsCount(\"wall_line_count\") > 0 && getSettingAsIndex(\"wall_0_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n if (getSettingAsCount(\"wall_line_count\") > 1 && getSettingAsIndex(\"wall_x_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n if (getSettingInMicrons(\"infill_line_distance\") > 0 && getSettingAsIndex(\"infill_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n if (getSettingAsIndex(\"top_bottom_extruder_nr\") == extruder_nr)\n {\n return true;\n }\n return false;\n}\n\nbool SliceMeshStorage::getExtruderIsUsed(int extruder_nr, int layer_nr) const\n{\n if (layer_nr < 0 || layer_nr >= static_cast(layers.size()))\n {\n return false;\n }\n if (getSettingBoolean(\"anti_overhang_mesh\")\n || getSettingBoolean(\"support_mesh\"))\n { \/\/ object is not printed as object, but as support.\n return false;\n }\n const SliceLayer& layer = layers[layer_nr];\n if (getSettingAsCount(\"wall_line_count\") > 0 && getSettingAsIndex(\"wall_0_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.insets.size() > 0 && part.insets[0].size() > 0)\n {\n return true;\n }\n }\n }\n if (getSettingAsCount(\"wall_line_count\") > 1 && getSettingAsIndex(\"wall_x_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.insets.size() > 1 && part.insets[1].size() > 0)\n {\n return true;\n }\n }\n }\n if (getSettingInMicrons(\"infill_line_distance\") > 0 && getSettingAsIndex(\"infill_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (part.getOwnInfillArea().size() > 0)\n {\n return true;\n }\n }\n }\n if (getSettingAsIndex(\"top_bottom_extruder_nr\") == extruder_nr)\n {\n for (const SliceLayerPart& part : layer.parts)\n {\n if (!part.skin_parts.empty())\n {\n return true;\n }\n }\n }\n return false;\n}\n\nstd::vector SliceDataStorage::initializeRetractionConfigs()\n{\n std::vector ret;\n ret.resize(meshgroup->getExtruderCount()); \/\/ initializes with constructor RetractionConfig()\n return ret;\n}\n\nSliceDataStorage::SliceDataStorage(MeshGroup* meshgroup) : SettingsMessenger(meshgroup),\n meshgroup(meshgroup != nullptr ? meshgroup : new MeshGroup(FffProcessor::getInstance())), \/\/If no mesh group is provided, we roll our own.\n print_layer_count(0),\n retraction_config_per_extruder(initializeRetractionConfigs()),\n extruder_switch_retraction_config_per_extruder(initializeRetractionConfigs()),\n max_print_height_second_to_last_extruder(-1),\n primeTower(*this)\n{\n}\n\nPolygons SliceDataStorage::getLayerOutlines(int layer_nr, bool include_helper_parts, bool external_polys_only) const\n{\n if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))\n { \/\/ when processing raft\n if (include_helper_parts)\n {\n if (external_polys_only)\n {\n std::vector parts = raftOutline.splitIntoParts();\n Polygons result;\n for (PolygonsPart& part : parts) \n {\n result.add(part.outerPolygon());\n }\n return result;\n }\n else \n {\n return raftOutline;\n }\n }\n else \n {\n return Polygons();\n }\n }\n else \n {\n Polygons total;\n if (layer_nr >= 0)\n {\n for (const SliceMeshStorage& mesh : meshes)\n {\n if (mesh.getSettingBoolean(\"infill_mesh\") || mesh.getSettingBoolean(\"anti_overhang_mesh\"))\n {\n continue;\n }\n const SliceLayer& layer = mesh.layers[layer_nr];\n layer.getOutlines(total, external_polys_only);\n if (mesh.getSettingAsSurfaceMode(\"magic_mesh_surface_mode\") != ESurfaceMode::NORMAL)\n {\n total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));\n }\n }\n }\n if (include_helper_parts)\n {\n if (support.generated) \n {\n total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_bottom);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_roof);\n }\n if (primeTower.enabled)\n {\n total.add(primeTower.ground_poly);\n }\n }\n return total;\n }\n}\n\nPolygons SliceDataStorage::getLayerSecondOrInnermostWalls(int layer_nr, bool include_helper_parts) const\n{\n if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))\n { \/\/ when processing raft\n if (include_helper_parts)\n {\n return raftOutline;\n }\n else \n {\n return Polygons();\n }\n }\n else \n {\n Polygons total;\n if (layer_nr >= 0)\n {\n for (const SliceMeshStorage& mesh : meshes)\n {\n const SliceLayer& layer = mesh.layers[layer_nr];\n layer.getSecondOrInnermostWalls(total);\n if (mesh.getSettingAsSurfaceMode(\"magic_mesh_surface_mode\") != ESurfaceMode::NORMAL)\n {\n total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));\n }\n }\n }\n if (include_helper_parts)\n {\n if (support.generated) \n {\n total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_bottom);\n total.add(support.supportLayers[std::max(0, layer_nr)].support_roof);\n }\n if (primeTower.enabled)\n {\n total.add(primeTower.ground_poly);\n }\n }\n return total;\n }\n\n}\n\nstd::vector SliceDataStorage::getExtrudersUsed() const\n{\n\n std::vector ret;\n ret.resize(meshgroup->getExtruderCount(), false);\n\n if (getSettingAsPlatformAdhesion(\"adhesion_type\") != EPlatformAdhesion::NONE)\n {\n ret[getSettingAsIndex(\"adhesion_extruder_nr\")] = true;\n { \/\/ process brim\/skirt\n for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)\n {\n if (skirt_brim[extr_nr].size() > 0)\n {\n ret[extr_nr] = true;\n continue;\n }\n }\n }\n }\n\n \/\/ TODO: ooze shield, draft shield ..?\n\n \/\/ support\n \/\/ support is presupposed to be present...\n for (const SliceMeshStorage& mesh : meshes)\n {\n if (mesh.getSettingBoolean(\"support_enable\") || mesh.getSettingBoolean(\"support_mesh\"))\n {\n ret[getSettingAsIndex(\"support_extruder_nr_layer_0\")] = true;\n ret[getSettingAsIndex(\"support_infill_extruder_nr\")] = true;\n if (getSettingBoolean(\"support_roof_enable\"))\n {\n ret[getSettingAsIndex(\"support_roof_extruder_nr\")] = true;\n }\n if (getSettingBoolean(\"support_bottom_enable\"))\n {\n ret[getSettingAsIndex(\"support_bottom_extruder_nr\")] = true;\n }\n }\n }\n\n \/\/ all meshes are presupposed to actually have content\n for (const SliceMeshStorage& mesh : meshes)\n {\n for (unsigned int extruder_nr = 0; extruder_nr <= ret.size(); extruder_nr++)\n {\n ret[extruder_nr] = ret[extruder_nr] || mesh.getExtruderIsUsed(extruder_nr);\n }\n }\n return ret;\n}\n\nstd::vector SliceDataStorage::getExtrudersUsed(int layer_nr) const\n{\n\n std::vector ret;\n ret.resize(meshgroup->getExtruderCount(), false);\n\n bool include_adhesion = true;\n bool include_helper_parts = true;\n bool include_models = true;\n if (layer_nr < 0)\n {\n include_models = false;\n if (layer_nr < -Raft::getFillerLayerCount(*this))\n {\n include_helper_parts = false;\n }\n else\n {\n layer_nr = 0; \/\/ because the helper parts are copied from the initial layer in the filler layer\n include_adhesion = false;\n }\n }\n else if (layer_nr > 0 || getSettingAsPlatformAdhesion(\"adhesion_type\") == EPlatformAdhesion::RAFT)\n { \/\/ only include adhesion only for layers where platform adhesion actually occurs\n \/\/ i.e. layers < 0 are for raft, layer 0 is for brim\/skirt\n include_adhesion = false;\n }\n if (include_adhesion)\n {\n ret[getSettingAsIndex(\"adhesion_extruder_nr\")] = true;\n { \/\/ process brim\/skirt\n for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)\n {\n if (skirt_brim[extr_nr].size() > 0)\n {\n ret[extr_nr] = true;\n continue;\n }\n }\n }\n }\n\n \/\/ TODO: ooze shield, draft shield ..?\n\n if (include_helper_parts)\n {\n \/\/ support\n if (layer_nr < int(support.supportLayers.size()))\n {\n const SupportLayer& support_layer = support.supportLayers[layer_nr];\n if (layer_nr == 0)\n {\n if (!support_layer.supportAreas.empty())\n {\n ret[getSettingAsIndex(\"support_extruder_nr_layer_0\")] = true;\n }\n }\n else\n {\n if (!support_layer.supportAreas.empty())\n {\n ret[getSettingAsIndex(\"support_infill_extruder_nr\")] = true;\n }\n }\n if (!support_layer.support_bottom.empty())\n {\n ret[getSettingAsIndex(\"support_bottom_extruder_nr\")] = true;\n }\n if (!support_layer.support_roof.empty())\n {\n ret[getSettingAsIndex(\"support_roof_extruder_nr\")] = true;\n }\n }\n }\n\n if (include_models)\n {\n for (const SliceMeshStorage& mesh : meshes)\n {\n for (unsigned int extruder_nr = 0; extruder_nr <= ret.size(); extruder_nr++)\n {\n ret[extruder_nr] = ret[extruder_nr] || mesh.getExtruderIsUsed(extruder_nr, layer_nr);\n }\n }\n }\n return ret;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n} \/\/ namespace cura<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sort_file.h\"\n#include \"logging.h\"\n#include \"common\/filesystem.h\"\n#include \"common\/tools_util.h\"\n#include \"thread_pool.h\"\n#include \"mutex.h\"\n\nDEFINE_int32(total, 0, \"total numbers of map tasks\");\nDEFINE_int32(reduce_no, 0, \"the reduce number of this reduce task\");\nDEFINE_string(work_dir, \"\/tmp\", \"the shuffle work dir\");\nDEFINE_int32(batch, 500, \"merge how many maps output at the same time\");\nDEFINE_int32(attempt_id, 0, \"the attempt_id of this reduce task\");\nDEFINE_string(dfs_host, \"\", \"host name of dfs master\");\nDEFINE_string(dfs_port, \"\", \"port of dfs master\");\nDEFINE_string(dfs_user, \"\", \"user name of dfs master\");\nDEFINE_string(dfs_password, \"\", \"password of dfs master\");\nDEFINE_string(pipe, \"streaming\", \"pipe style: streaming\/bistreaming\");\nDEFINE_bool(skip_merge, false, \"whether skip merge phase\");\n\nusing baidu::common::Log;\nusing baidu::common::FATAL;\nusing baidu::common::INFO;\nusing baidu::common::WARNING;\nusing namespace baidu;\nusing namespace baidu::shuttle;\n\nstd::set g_merged;\nint32_t g_file_no(0);\nFileSystem* g_fs(NULL);\nMutex g_mu;\n\nvoid FillParam(FileSystem::Param& param) {\n if (!FLAGS_dfs_user.empty()) {\n param[\"user\"] = FLAGS_dfs_user;\n }\n if (!FLAGS_dfs_password.empty()) {\n param[\"password\"] = FLAGS_dfs_password;\n }\n if (!FLAGS_dfs_host.empty()) {\n param[\"host\"] = FLAGS_dfs_host;\n }\n if (!FLAGS_dfs_port.empty()) {\n param[\"port\"] = FLAGS_dfs_port;\n }\n}\n\nvoid CollectFilesToMerge(std::vector* maps_to_merge) {\n assert(maps_to_merge);\n for (int i = 0; i < FLAGS_total; i++) {\n std::stringstream ss;\n ss << FLAGS_work_dir << \"\/map_\" << i;\n std::string map_dir = ss.str();\n if (g_merged.find(map_dir) != g_merged.end()) {\n continue;\n }\n if (g_fs->Exist(map_dir)) {\n LOG(INFO, \"maps_to_merge: %s\", map_dir.c_str());\n maps_to_merge->push_back(map_dir);\n }\n if (maps_to_merge->size() >= (size_t)FLAGS_batch) {\n break;\n }\n }\n}\n\nvoid AddSortFiles(const std::string map_dir, std::vector* file_names) {\n assert(file_names);\n std::vector sort_files;\n if (g_fs->List(map_dir, &sort_files)) {\n std::vector::iterator jt;\n for (jt = sort_files.begin(); jt != sort_files.end(); jt++) {\n const std::string& file_name = jt->name;\n if (boost::ends_with(file_name, \".sort\")) {\n MutexLock lock(&g_mu);\n file_names->push_back(file_name);\n }\n }\n } else {\n LOG(FATAL, \"fail to list %s\", map_dir.c_str());\n }\n}\n\nvoid MergeMapOutput(const std::vector& maps_to_merge) {\n std::vector * file_names = new std::vector();\n boost::scoped_ptr > file_names_guard(file_names);\n std::vector::const_iterator it;\n std::vector real_merged_maps;\n ThreadPool pool;\n int map_ct = 0;\n for (it = maps_to_merge.begin(); it != maps_to_merge.end(); it++) {\n const std::string& map_dir = *it;\n pool.AddTask(boost::bind(&AddSortFiles, map_dir, file_names));\n map_ct++;\n real_merged_maps.push_back(map_dir);\n if (map_ct >= FLAGS_batch){\n break;\n }\n }\n LOG(INFO, \"wait for list done\");\n pool.Stop(true);\n if (file_names->empty()) {\n LOG(WARNING, \"not map output found\");\n return;\n }\n LOG(INFO, \"list #%d *.sort files\", file_names->size());\n MergeFileReader reader;\n FileSystem::Param param;\n FillParam(param);\n Status status = reader.Open(*file_names, param, kHdfsFile);\n if (status != kOk) {\n LOG(FATAL, \"fail to open: %s\", reader.GetErrorFile().c_str());\n }\n char s_reduce_no[256];\n snprintf(s_reduce_no, sizeof(s_reduce_no), \"%05d\", FLAGS_reduce_no);\n std::string s_reduce_key(s_reduce_no);\n\n SortFileReader::Iterator* scan_it = reader.Scan(s_reduce_key, \n s_reduce_key + \"\\xff\");\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n }\n\n char output_file[4096];\n snprintf(output_file, sizeof(output_file), \"%s\/reduce_%d_%d\/%d.sort\",\n FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id,\n g_file_no++);\n SortFileWriter * writer = SortFileWriter::Create(kHdfsFile, &status);\n if (status != kOk) {\n LOG(FATAL, \"fail to create writer\");\n }\n FileSystem::Param param_write;\n FillParam(param_write);\n param_write[\"replica\"] = \"2\";\n status = writer->Open(output_file, param_write);\n if (status != kOk) {\n LOG(FATAL, \"fail to open %s for write\", output_file);\n }\n while (!scan_it->Done()) {\n status = writer->Put(scan_it->Key(), scan_it->Value());\n if (status != kOk) {\n LOG(FATAL, \"fail to put: %s\", output_file); \n }\n scan_it->Next();\n }\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n } \n status = writer->Close();\n if (status != kOk) {\n LOG(FATAL, \"fail to close writer: %s\", output_file);\n }\n delete scan_it;\n status = reader.Close();\n if (status != kOk) {\n LOG(FATAL, \"fail to close reader: %s\", reader.GetErrorFile().c_str());\n }\n delete writer;\n for (it = real_merged_maps.begin(); it != real_merged_maps.end(); it++) {\n LOG(INFO, \"g_merged insert: %s\", it->c_str());\n g_merged.insert(*it); \n }\n}\n\nvoid MergeAndPrint() {\n char reduce_merge_dir[4096];\n snprintf(reduce_merge_dir, sizeof(reduce_merge_dir), \n \"%s\/reduce_%d_%d\",\n FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id);\n std::vector children;\n if (!g_fs->List(reduce_merge_dir, &children)) {\n LOG(FATAL, \"fail to list: %s\", reduce_merge_dir);\n }\n std::vector file_names;\n std::vector::iterator it;\n for (it = children.begin(); it != children.end(); it++) {\n const std::string& file_name = it->name;\n if (boost::ends_with(file_name, \".sort\")) {\n file_names.push_back(file_name);\n }\n }\n if (file_names.empty()) {\n LOG(WARNING, \"no data for this reduce task\");\n return;\n }\n MergeFileReader reader;\n FileSystem::Param param;\n FillParam(param);\n Status status = reader.Open(file_names, param, kHdfsFile);\n if (status != kOk) {\n LOG(FATAL, \"fail to open: %s\", reader.GetErrorFile().c_str());\n }\n SortFileReader::Iterator* scan_it = reader.Scan(\"\", \"\");\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n }\n while (!scan_it->Done()) {\n if (FLAGS_pipe == \"streaming\") {\n std::cout << scan_it->Value() << std::endl;\n } else {\n std::cout << scan_it->Value();\n }\n scan_it->Next();\n }\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n }\n reader.Close();\n}\n\nint main(int argc, char* argv[]) {\n baidu::common::SetLogFile(GetLogName(\".\/shuffle_tool.log\").c_str());\n baidu::common::SetWarningFile(GetLogName(\".\/shuffle_tool.log.wf\").c_str());\n google::ParseCommandLineFlags(&argc, &argv, true);\n FileSystem::Param param;\n FillParam(param);\n g_fs = FileSystem::CreateInfHdfs(param);\n if (FLAGS_total == 0 ) {\n LOG(FATAL, \"invalid map task total\");\n } \n while (!FLAGS_skip_merge && (int32_t)g_merged.size() < FLAGS_total) {\n std::vector maps_to_merge;\n CollectFilesToMerge(&maps_to_merge);\n if (maps_to_merge.empty()) {\n LOG(INFO, \"map output is empty, wait 10 seconds and try...\");\n sleep(10);\n continue;\n }\n if (maps_to_merge.size() >= (size_t)FLAGS_batch || \n maps_to_merge.size() + g_merged.size() >= (size_t)FLAGS_total) {\n LOG(INFO, \"try merge %d maps\", maps_to_merge.size());\n std::random_shuffle(maps_to_merge.begin(), maps_to_merge.end());\n MergeMapOutput(maps_to_merge);\n } else {\n LOG(INFO, \"merged: %d, wait-for merge: %d\", g_merged.size(), maps_to_merge.size());\n LOG(INFO, \"wait for enough map-output to merge, sleep 5 second\");\n sleep(5);\n }\n LOG(INFO, \"merge progress: < %d\/%d > \", g_merged.size(), FLAGS_total);\n }\n LOG(INFO, \"merge and print out\");\n MergeAndPrint();\n return 0;\n}\nbigger batch merge size#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sort_file.h\"\n#include \"logging.h\"\n#include \"common\/filesystem.h\"\n#include \"common\/tools_util.h\"\n#include \"thread_pool.h\"\n#include \"mutex.h\"\n\nDEFINE_int32(total, 0, \"total numbers of map tasks\");\nDEFINE_int32(reduce_no, 0, \"the reduce number of this reduce task\");\nDEFINE_string(work_dir, \"\/tmp\", \"the shuffle work dir\");\nDEFINE_int32(batch, 800, \"merge how many maps output at the same time\");\nDEFINE_int32(attempt_id, 0, \"the attempt_id of this reduce task\");\nDEFINE_string(dfs_host, \"\", \"host name of dfs master\");\nDEFINE_string(dfs_port, \"\", \"port of dfs master\");\nDEFINE_string(dfs_user, \"\", \"user name of dfs master\");\nDEFINE_string(dfs_password, \"\", \"password of dfs master\");\nDEFINE_string(pipe, \"streaming\", \"pipe style: streaming\/bistreaming\");\nDEFINE_bool(skip_merge, false, \"whether skip merge phase\");\n\nusing baidu::common::Log;\nusing baidu::common::FATAL;\nusing baidu::common::INFO;\nusing baidu::common::WARNING;\nusing namespace baidu;\nusing namespace baidu::shuttle;\n\nstd::set g_merged;\nint32_t g_file_no(0);\nFileSystem* g_fs(NULL);\nMutex g_mu;\n\nvoid FillParam(FileSystem::Param& param) {\n if (!FLAGS_dfs_user.empty()) {\n param[\"user\"] = FLAGS_dfs_user;\n }\n if (!FLAGS_dfs_password.empty()) {\n param[\"password\"] = FLAGS_dfs_password;\n }\n if (!FLAGS_dfs_host.empty()) {\n param[\"host\"] = FLAGS_dfs_host;\n }\n if (!FLAGS_dfs_port.empty()) {\n param[\"port\"] = FLAGS_dfs_port;\n }\n}\n\nvoid CollectFilesToMerge(std::vector* maps_to_merge) {\n assert(maps_to_merge);\n for (int i = 0; i < FLAGS_total; i++) {\n std::stringstream ss;\n ss << FLAGS_work_dir << \"\/map_\" << i;\n std::string map_dir = ss.str();\n if (g_merged.find(map_dir) != g_merged.end()) {\n continue;\n }\n if (g_fs->Exist(map_dir)) {\n LOG(INFO, \"maps_to_merge: %s\", map_dir.c_str());\n maps_to_merge->push_back(map_dir);\n }\n if (maps_to_merge->size() >= (size_t)FLAGS_batch) {\n break;\n }\n }\n}\n\nvoid AddSortFiles(const std::string map_dir, std::vector* file_names) {\n assert(file_names);\n std::vector sort_files;\n if (g_fs->List(map_dir, &sort_files)) {\n std::vector::iterator jt;\n for (jt = sort_files.begin(); jt != sort_files.end(); jt++) {\n const std::string& file_name = jt->name;\n if (boost::ends_with(file_name, \".sort\")) {\n MutexLock lock(&g_mu);\n file_names->push_back(file_name);\n }\n }\n } else {\n LOG(FATAL, \"fail to list %s\", map_dir.c_str());\n }\n}\n\nvoid MergeMapOutput(const std::vector& maps_to_merge) {\n std::vector * file_names = new std::vector();\n boost::scoped_ptr > file_names_guard(file_names);\n std::vector::const_iterator it;\n std::vector real_merged_maps;\n ThreadPool pool;\n int map_ct = 0;\n for (it = maps_to_merge.begin(); it != maps_to_merge.end(); it++) {\n const std::string& map_dir = *it;\n pool.AddTask(boost::bind(&AddSortFiles, map_dir, file_names));\n map_ct++;\n real_merged_maps.push_back(map_dir);\n if (map_ct >= FLAGS_batch){\n break;\n }\n }\n LOG(INFO, \"wait for list done\");\n pool.Stop(true);\n if (file_names->empty()) {\n LOG(WARNING, \"not map output found\");\n return;\n }\n LOG(INFO, \"list #%d *.sort files\", file_names->size());\n MergeFileReader reader;\n FileSystem::Param param;\n FillParam(param);\n Status status = reader.Open(*file_names, param, kHdfsFile);\n if (status != kOk) {\n LOG(FATAL, \"fail to open: %s\", reader.GetErrorFile().c_str());\n }\n char s_reduce_no[256];\n snprintf(s_reduce_no, sizeof(s_reduce_no), \"%05d\", FLAGS_reduce_no);\n std::string s_reduce_key(s_reduce_no);\n\n SortFileReader::Iterator* scan_it = reader.Scan(s_reduce_key, \n s_reduce_key + \"\\xff\");\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n }\n\n char output_file[4096];\n snprintf(output_file, sizeof(output_file), \"%s\/reduce_%d_%d\/%d.sort\",\n FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id,\n g_file_no++);\n SortFileWriter * writer = SortFileWriter::Create(kHdfsFile, &status);\n if (status != kOk) {\n LOG(FATAL, \"fail to create writer\");\n }\n FileSystem::Param param_write;\n FillParam(param_write);\n param_write[\"replica\"] = \"2\";\n status = writer->Open(output_file, param_write);\n if (status != kOk) {\n LOG(FATAL, \"fail to open %s for write\", output_file);\n }\n while (!scan_it->Done()) {\n status = writer->Put(scan_it->Key(), scan_it->Value());\n if (status != kOk) {\n LOG(FATAL, \"fail to put: %s\", output_file); \n }\n scan_it->Next();\n }\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n } \n status = writer->Close();\n if (status != kOk) {\n LOG(FATAL, \"fail to close writer: %s\", output_file);\n }\n delete scan_it;\n status = reader.Close();\n if (status != kOk) {\n LOG(FATAL, \"fail to close reader: %s\", reader.GetErrorFile().c_str());\n }\n delete writer;\n for (it = real_merged_maps.begin(); it != real_merged_maps.end(); it++) {\n LOG(INFO, \"g_merged insert: %s\", it->c_str());\n g_merged.insert(*it); \n }\n}\n\nvoid MergeAndPrint() {\n char reduce_merge_dir[4096];\n snprintf(reduce_merge_dir, sizeof(reduce_merge_dir), \n \"%s\/reduce_%d_%d\",\n FLAGS_work_dir.c_str(), FLAGS_reduce_no, FLAGS_attempt_id);\n std::vector children;\n if (!g_fs->List(reduce_merge_dir, &children)) {\n LOG(FATAL, \"fail to list: %s\", reduce_merge_dir);\n }\n std::vector file_names;\n std::vector::iterator it;\n for (it = children.begin(); it != children.end(); it++) {\n const std::string& file_name = it->name;\n if (boost::ends_with(file_name, \".sort\")) {\n file_names.push_back(file_name);\n }\n }\n if (file_names.empty()) {\n LOG(WARNING, \"no data for this reduce task\");\n return;\n }\n MergeFileReader reader;\n FileSystem::Param param;\n FillParam(param);\n Status status = reader.Open(file_names, param, kHdfsFile);\n if (status != kOk) {\n LOG(FATAL, \"fail to open: %s\", reader.GetErrorFile().c_str());\n }\n SortFileReader::Iterator* scan_it = reader.Scan(\"\", \"\");\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n }\n while (!scan_it->Done()) {\n if (FLAGS_pipe == \"streaming\") {\n std::cout << scan_it->Value() << std::endl;\n } else {\n std::cout << scan_it->Value();\n }\n scan_it->Next();\n }\n if (scan_it->Error() != kOk && scan_it->Error() != kNoMore) {\n LOG(FATAL, \"fail to scan: %s\", reader.GetErrorFile().c_str());\n }\n reader.Close();\n}\n\nint main(int argc, char* argv[]) {\n baidu::common::SetLogFile(GetLogName(\".\/shuffle_tool.log\").c_str());\n baidu::common::SetWarningFile(GetLogName(\".\/shuffle_tool.log.wf\").c_str());\n google::ParseCommandLineFlags(&argc, &argv, true);\n FileSystem::Param param;\n FillParam(param);\n g_fs = FileSystem::CreateInfHdfs(param);\n if (FLAGS_total == 0 ) {\n LOG(FATAL, \"invalid map task total\");\n } \n while (!FLAGS_skip_merge && (int32_t)g_merged.size() < FLAGS_total) {\n std::vector maps_to_merge;\n CollectFilesToMerge(&maps_to_merge);\n if (maps_to_merge.empty()) {\n LOG(INFO, \"map output is empty, wait 10 seconds and try...\");\n sleep(10);\n continue;\n }\n if (maps_to_merge.size() >= (size_t)FLAGS_batch || \n maps_to_merge.size() + g_merged.size() >= (size_t)FLAGS_total) {\n LOG(INFO, \"try merge %d maps\", maps_to_merge.size());\n std::random_shuffle(maps_to_merge.begin(), maps_to_merge.end());\n MergeMapOutput(maps_to_merge);\n } else {\n LOG(INFO, \"merged: %d, wait-for merge: %d\", g_merged.size(), maps_to_merge.size());\n LOG(INFO, \"wait for enough map-output to merge, sleep 5 second\");\n sleep(5);\n }\n LOG(INFO, \"merge progress: < %d\/%d > \", g_merged.size(), FLAGS_total);\n }\n LOG(INFO, \"merge and print out\");\n MergeAndPrint();\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"game_state.hpp\"\n\n#include \"start_game_state.hpp\"\n#include \"imove.hpp\"\n#include \"walk_move.hpp\"\n#include \"wall_move.hpp\"\n#include \"logger.hpp\"\n#include \"exception.hpp\"\n\n\nstatic boost::log::sources::severity_logger lg;\n\nnamespace Quoridor {\n\nstatic std::vector colors = {\"red\", \"green\", \"blue\", \"yellow\"};\nstd::string GameState::name_(\"Start Game\");\n\nGameState::GameState(std::shared_ptr stm,\n const std::vector &player_types) : stm_(stm),\n board_(new Board(9)), pf_(), players_(), pawn_list_(), cur_pawn_(),\n repr_(), is_running_(true)\n{\n CEGUI::ImageManager::getSingleton().loadImageset(\"pawn.imageset\");\n win_ = std::shared_ptr(\n CEGUI::WindowManager::getSingleton().\n loadLayoutFromFile(\"game.layout\"),\n [=](CEGUI::Window *w) {\n BOOST_LOG_SEV(lg, boost::log::trivial::debug) << \"removing window \" << w;\n CEGUI::WindowManager::getSingleton().destroyWindow(w);\n }\n );\n\n subscribe_for_events_();\n\n if ((player_types.size() != 2) && (player_types.size() != 4)) {\n throw Exception(\"Invalid number of players\");\n }\n\n set_pawns_(player_types);\n\n int i = 0;\n for (auto player_type : player_types) {\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"adding player \"\n << player_type;\n std::shared_ptr pawn(new Pawn(colors[i]));\n board_->add_pawn(pawn);\n players_[pawn] = pf_.make_player(player_type, board_, pawn);\n pawn_list_.push_back(pawn);\n ++i;\n }\n\n cur_pawn_ = pawn_list_[0];\n\n init_board_repr();\n}\n\nGameState::~GameState()\n{\n}\n\nvoid GameState::update()\n{\n IMove *move;\n\n if (!is_running_) {\n return;\n }\n\n \/\/ if (!players_[cur_pawn_]->is_interactive()) {\n move = players_[cur_pawn_]->get_move();\n \/\/ }\n if (move != NULL) {\n Pos cur_node = board_->pawn_node(cur_pawn_);\n int rc;\n\n if (WalkMove *walk_move = dynamic_cast(move)) {\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()\n << \" move: \" << walk_move->node().row() << \":\"\n << walk_move->node().col();\n rc = board_->make_walking_move(cur_pawn_, walk_move->node());\n if (rc == 0) {\n Pos goal_node = board_->pawn_node(cur_pawn_);\n redraw_pawn(cur_pawn_->color()[0], cur_node, goal_node);\n }\n }\n else if (WallMove *wall_move = dynamic_cast(move)) {\n const Wall &wall = wall_move->wall();\n rc = board_->add_wall(wall);\n if (rc == 0) {\n draw_wall(wall);\n }\n }\n\n if (board_->is_at_goal_node(cur_pawn_)) {\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()\n << \" win\";\n is_running_ = false;\n }\n else if (rc == 0) {\n cur_pawn_ = next_pawn();\n }\n }\n}\n\nstd::shared_ptr GameState::window() const\n{\n return win_;\n}\n\nconst std::string &GameState::name() const\n{\n return name_;\n}\n\nvoid GameState::set_pawns_(const std::vector &player_types)\n{\n auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_0_4\")->addChild(w1);\n auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_8_4\")->addChild(w2);\n\n if (player_types.size() == 4) {\n auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_4_0\")->addChild(w1);\n auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_4_8\")->addChild(w2);\n }\n}\n\nvoid GameState::subscribe_for_events_()\n{\n win_->getChild(\"back\")->subscribeEvent(\n CEGUI::Window::EventMouseClick,\n CEGUI::Event::Subscriber(\n &GameState::handle_back_, this\n )\n );\n for (int i = 0; i < 9; ++i) {\n for (int j = 0; j < 9; ++j) {\n std::string field_name = \"boardWindow\/field_\" + std::to_string(i) + \"_\"\n + std::to_string(j);\n win_->getChild(field_name)->subscribeEvent(\n CEGUI::Window::EventDragDropItemDropped,\n CEGUI::Event::Subscriber(\n &GameState::handle_fields_, this\n )\n );\n }\n }\n}\n\nbool GameState::handle_back_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"returning to start game menu\";\n stm_->change_state(std::shared_ptr(new StartGameState(stm_)));\n return true;\n}\n\nbool GameState::handle_fields_(const CEGUI::EventArgs &e)\n{\n const CEGUI::DragDropEventArgs &dde = static_cast(e);\n if (!dde.window->getChildCount()) {\n dde.window->addChild(dde.dragDropItem);\n \/\/ dde.dragDropItem->setPosition(CEGUI::UVector2(CEGUI::UDim(0.05, 0), CEGUI::UDim(0.05, 0)));\n }\n return true;\n}\n\nvoid GameState::init_board_repr() const\n{\n repr_.resize(19);\n for (int i = 0; i < 19; ++i) {\n repr_[i].resize(19);\n for (int j = 0; j < 19; ++j) {\n if (i % 2 == 1) {\n repr_[i][j] = (j % 2 == 0 ? '|' : ' ');\n }\n else {\n repr_[i][j] = (j % 2 == 0 ? ' ' : '_');\n }\n }\n }\n\n for (auto pawn : pawn_list_) {\n Pos pos = board_->pawn_node(pawn);\n repr_[pos.row() * 2 + 1][pos.col() * 2 + 1] = pawn->color()[0];\n }\n}\n\nvoid GameState::redraw_pawn(char p, const Pos &old_pos, const Pos &new_pos) const\n{\n repr_[old_pos.row() * 2 + 1][old_pos.col() * 2 + 1] = ' ';\n repr_[new_pos.row() * 2 + 1][new_pos.col() * 2 + 1] = p;\n}\n\nvoid GameState::draw_wall(const Wall &wall) const\n{\n if (wall.orientation() == 0) {\n for (int i = 0; i < wall.cnt(); ++i) {\n repr_[wall.line() * 2 + 2][(wall.start_pos() + i) * 2 + 1] = '=';\n }\n }\n else {\n for (int i = 0; i < wall.cnt(); ++i) {\n repr_[(wall.start_pos() + i) * 2 + 1][wall.line() * 2 + 2] = '$';\n }\n }\n}\n\nstd::shared_ptr GameState::next_pawn() const\n{\n auto it = pawn_list_.begin();\n for (;it != pawn_list_.end(); ++it) {\n if (*it == cur_pawn_) {\n break;\n }\n }\n if (++it == pawn_list_.end()) {\n return pawn_list_[0];\n }\n else {\n return *it;\n }\n}\n\n} \/* namespace Quoridor *\/\nChange pawn position on player moves#include \"game_state.hpp\"\n\n#include \"start_game_state.hpp\"\n#include \"imove.hpp\"\n#include \"walk_move.hpp\"\n#include \"wall_move.hpp\"\n#include \"logger.hpp\"\n#include \"exception.hpp\"\n\n\nstatic boost::log::sources::severity_logger lg;\n\nnamespace Quoridor {\n\nstatic std::vector colors = {\"red\", \"green\", \"blue\", \"yellow\"};\nstd::string GameState::name_(\"Start Game\");\n\nGameState::GameState(std::shared_ptr stm,\n const std::vector &player_types) : stm_(stm),\n board_(new Board(9)), pf_(), players_(), pawn_list_(), cur_pawn_(),\n repr_(), is_running_(true)\n{\n CEGUI::ImageManager::getSingleton().loadImageset(\"pawn.imageset\");\n win_ = std::shared_ptr(\n CEGUI::WindowManager::getSingleton().\n loadLayoutFromFile(\"game.layout\"),\n [=](CEGUI::Window *w) {\n BOOST_LOG_SEV(lg, boost::log::trivial::debug) << \"removing window \" << w;\n CEGUI::WindowManager::getSingleton().destroyWindow(w);\n }\n );\n\n subscribe_for_events_();\n\n if ((player_types.size() != 2) && (player_types.size() != 4)) {\n throw Exception(\"Invalid number of players\");\n }\n\n set_pawns_(player_types);\n\n int i = 0;\n for (auto player_type : player_types) {\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"adding player \"\n << player_type;\n std::shared_ptr pawn(new Pawn(colors[i]));\n board_->add_pawn(pawn);\n players_[pawn] = pf_.make_player(player_type, board_, pawn);\n pawn_list_.push_back(pawn);\n ++i;\n }\n\n cur_pawn_ = pawn_list_[0];\n\n init_board_repr();\n}\n\nGameState::~GameState()\n{\n}\n\nvoid GameState::update()\n{\n IMove *move;\n\n if (!is_running_) {\n return;\n }\n\n \/\/ if (!players_[cur_pawn_]->is_interactive()) {\n move = players_[cur_pawn_]->get_move();\n \/\/ }\n if (move != NULL) {\n Pos cur_node = board_->pawn_node(cur_pawn_);\n int rc;\n\n if (WalkMove *walk_move = dynamic_cast(move)) {\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()\n << \" move: \" << walk_move->node().row() << \":\"\n << walk_move->node().col() << \" -> \" << cur_node.row() << \":\"\n << cur_node.col();\n rc = board_->make_walking_move(cur_pawn_, walk_move->node());\n if (rc == 0) {\n Pos goal_node = board_->pawn_node(cur_pawn_);\n redraw_pawn(cur_pawn_->color()[0], cur_node, goal_node);\n }\n }\n else if (WallMove *wall_move = dynamic_cast(move)) {\n const Wall &wall = wall_move->wall();\n rc = board_->add_wall(wall);\n if (rc == 0) {\n draw_wall(wall);\n }\n }\n\n if (board_->is_at_goal_node(cur_pawn_)) {\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << cur_pawn_->color()\n << \" win\";\n is_running_ = false;\n }\n else if (rc == 0) {\n cur_pawn_ = next_pawn();\n }\n }\n}\n\nstd::shared_ptr GameState::window() const\n{\n return win_;\n}\n\nconst std::string &GameState::name() const\n{\n return name_;\n}\n\nvoid GameState::set_pawns_(const std::vector &player_types)\n{\n auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_0_4\")->addChild(w1);\n auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_8_4\")->addChild(w2);\n\n if (player_types.size() == 4) {\n auto w1 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_4_0\")->addChild(w1);\n auto w2 = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n win_->getChild(\"boardWindow\/field_4_8\")->addChild(w2);\n }\n}\n\nvoid GameState::subscribe_for_events_()\n{\n win_->getChild(\"back\")->subscribeEvent(\n CEGUI::Window::EventMouseClick,\n CEGUI::Event::Subscriber(\n &GameState::handle_back_, this\n )\n );\n for (int i = 0; i < 9; ++i) {\n for (int j = 0; j < 9; ++j) {\n std::string field_name = \"boardWindow\/field_\" + std::to_string(i) + \"_\"\n + std::to_string(j);\n win_->getChild(field_name)->subscribeEvent(\n CEGUI::Window::EventDragDropItemDropped,\n CEGUI::Event::Subscriber(\n &GameState::handle_fields_, this\n )\n );\n }\n }\n}\n\nbool GameState::handle_back_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"returning to start game menu\";\n stm_->change_state(std::shared_ptr(new StartGameState(stm_)));\n return true;\n}\n\nbool GameState::handle_fields_(const CEGUI::EventArgs &e)\n{\n const CEGUI::DragDropEventArgs &dde = static_cast(e);\n if (!dde.window->getChildCount()) {\n dde.window->addChild(dde.dragDropItem);\n \/\/ dde.dragDropItem->setPosition(CEGUI::UVector2(CEGUI::UDim(0.05, 0), CEGUI::UDim(0.05, 0)));\n }\n return true;\n}\n\nvoid GameState::init_board_repr() const\n{\n repr_.resize(19);\n for (int i = 0; i < 19; ++i) {\n repr_[i].resize(19);\n for (int j = 0; j < 19; ++j) {\n if (i % 2 == 1) {\n repr_[i][j] = (j % 2 == 0 ? '|' : ' ');\n }\n else {\n repr_[i][j] = (j % 2 == 0 ? ' ' : '_');\n }\n }\n }\n\n for (auto pawn : pawn_list_) {\n Pos pos = board_->pawn_node(pawn);\n repr_[pos.row() * 2 + 1][pos.col() * 2 + 1] = pawn->color()[0];\n }\n}\n\nvoid GameState::redraw_pawn(char p, const Pos &old_pos, const Pos &new_pos) const\n{\n std::string old_pos_field = \"boardWindow\/field_\"\n + std::to_string(old_pos.row()) + \"_\"\n + std::to_string(old_pos.col());\n std::string new_pos_field = \"boardWindow\/field_\"\n + std::to_string(new_pos.row()) + \"_\"\n + std::to_string(new_pos.col());\n\n auto pawn_win = win_->getChild(old_pos_field)->getChild(\"pawn\");\n win_->getChild(old_pos_field)->removeChild(pawn_win);\n win_->getChild(new_pos_field)->addChild(pawn_win);\n\n repr_[old_pos.row() * 2 + 1][old_pos.col() * 2 + 1] = ' ';\n repr_[new_pos.row() * 2 + 1][new_pos.col() * 2 + 1] = p;\n}\n\nvoid GameState::draw_wall(const Wall &wall) const\n{\n if (wall.orientation() == 0) {\n for (int i = 0; i < wall.cnt(); ++i) {\n repr_[wall.line() * 2 + 2][(wall.start_pos() + i) * 2 + 1] = '=';\n }\n }\n else {\n for (int i = 0; i < wall.cnt(); ++i) {\n repr_[(wall.start_pos() + i) * 2 + 1][wall.line() * 2 + 2] = '$';\n }\n }\n}\n\nstd::shared_ptr GameState::next_pawn() const\n{\n auto it = pawn_list_.begin();\n for (;it != pawn_list_.end(); ++it) {\n if (*it == cur_pawn_) {\n break;\n }\n }\n if (++it == pawn_list_.end()) {\n return pawn_list_[0];\n }\n else {\n return *it;\n }\n}\n\n} \/* namespace Quoridor *\/\n<|endoftext|>"} {"text":"#include \"resource.h\"\n\nint main(int argc, char **argv)\n{\n\t\/\/initializing allegro\n al_init();\n al_init_image_addon();\n al_init_primitives_addon();\n al_init_font_addon();\n al_init_ttf_addon();\n al_get_display_mode(al_get_num_display_modes()-1, &disp_data);\n \/\/al_set_new_display_flags(ALLEGRO_FULLSCREEN);\n al_set_new_display_flags(ALLEGRO_WINDOWED);\n al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);\n disp_data.width*=0.8;\n disp_data.height*=0.8;\n display=al_create_display(disp_data.width, disp_data.height);\n\tif(!display)\n {\n return -1;\n }\n\tal_clear_to_color(al_map_rgb(0, 0, 0));\n al_flip_display();\n al_install_keyboard();\n al_install_mouse();\n al_install_audio();\n al_init_acodec_addon();\n al_reserve_samples(5);\n al_set_target_bitmap(al_get_backbuffer(display));\n \/\/ allegro initialization\n\n\t\/\/ initializing lua\n\tlua_state = luaL_newstate();\n\t\/\/ opening libraries for lua, otherwise functions dont work\n\tluaL_openlibs(lua_state);\n\t\/\/ lua initialization\n\n\t\/\/ initializing box2d\n\tworld.SetGravity(b2Vec2(0, -9.8));\n\tContactListener worldContactListener;\n\tworld.SetContactListener(&worldContactListener);\n\tconst int tlx=0, tly=0, brx=10000, bry=disp_data.height;\n Box ground(tlx, bry-10, brx, bry);\n Box ceiling(tlx, tly, brx, 10);\n Box leftWall(tlx, tly, 10, bry);\n Box rightWall(brx-10, 0, brx, bry);\n Chain chn;\n chn.getResource()->registerChainShape(&chn, b2Vec2(0, 0),\n 0, -PX_TO_M(bry)\/3,\n PX_TO_M(brx)*1\/10, -PX_TO_M(bry)*3\/9,\n PX_TO_M(brx)*2\/10, -PX_TO_M(bry)*5\/9,\n PX_TO_M(brx)*3\/10, -PX_TO_M(bry)*9\/9,\n PX_TO_M(brx)*4\/10, -PX_TO_M(bry)*6\/9,\n PX_TO_M(brx)*5\/10, -PX_TO_M(bry)*5\/9,\n PX_TO_M(brx)*6\/10, -PX_TO_M(bry)*3\/9,\n PX_TO_M(brx)*7\/10, -PX_TO_M(bry)*5\/9,\n PX_TO_M(brx)*8\/10, -PX_TO_M(bry)*8\/9,\n PX_TO_M(brx)*9\/10, -PX_TO_M(bry)*9\/9,\n PX_TO_M(brx)*10\/10, -PX_TO_M(bry)*7\/9\n );\n\t\/\/ box2d initialization\n\n resource.initialize();\n sysGC.initialize();\n\n \/*\n Lexer lex;\n Parser psr;\n auto ret=lex.generateTokens(\"\\\n if(y>-0.2 && x<=11)\\n\\\n {\\n\\\n if(x<0.2)\\n\\\n {\\n\\\n activeBullet.move(0.4, 0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(0.4, 0)\\n\\\n }\\n\\\n }\\n\\\n else if(x>11 && y>=-8.2)\\n\\\n {\\n\\\n if(y>-0.2)\\n\\\n {\\n\\\n activeBullet.move(0.4, -0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(0, -0.4)\\n\\\n }\\n\\\n }\\n\\\n else if(y<-8.2 && x>=0.2)\\n\\\n {\\n\\\n if(x>11)\\n\\\n {\\n\\\n activeBullet.move(-0.4, -0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(-0.4, 0)\\n\\\n }\\n\\\n }\\n\\\n else if(x<0.2 && y<=-0.2)\\n\\\n {\\n\\\n if(y<-8.2)\\n\\\n {\\n\\\n activeBullet.move(-0.4, 0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(0, 0.4)\\n\\\n }\\n\\\n }\\n\\\n \");\n std::cout<<\"Errors: \"<push(obj->getCamera()->midground);\n return 0;\n });\n lua_prepmfunctions(lua_state, \"__game\", \"FrameMT\", Frame, &game);\n\n lua_regmfunctions(lua_state, \"RobotMT\");\n lua_makemfunction(lua_state, \"shoot\", \"RobotMT\", Robot,\n {\n obj->shootProjectile(b2Vec2(0, 0), luaL_checknumber(l, 1), luaL_checknumber(l, 2));\n return 0;\n });\n lua_prepmfunctions(lua_state, \"the_robot\", \"RobotMT\", Robot, &rob);\n\n lua_regmfunctions(lua_state, \"BulletMT\");\n lua_makemfunction(lua_state, \"move\", \"BulletMT\", Projectile*,\n {\n (*obj)->move(b2Vec2(luaL_checknumber(l, 1), luaL_checknumber(l, 2)));\n return 0;\n });\n lua_prepmfunctions(lua_state, \"activeBullet\", \"BulletMT\", Projectile*, activeBullet);\n\n\n lua_regmfunctions(lua_state, \"BatbotMT\");\n lua_makemfunction(lua_state, \"x\", \"BatbotMT\", Batbot*,\n {\n lua_pushnumber(l, (*obj)->getX());\n return 1;\n });\n lua_makemfunction(lua_state, \"y\", \"BatbotMT\", Batbot*,\n {\n lua_pushnumber(l, (*obj)->getY());\n return 1;\n });\n lua_makemfunction(lua_state, \"mass\", \"BatbotMT\", Batbot*,\n {\n lua_pushnumber(l, (*obj)->getMass());\n return 1;\n });\n lua_makemfunction(lua_state, \"move\", \"BatbotMT\", Batbot*,\n {\n (*obj)->move(luaL_checknumber(l, 1), luaL_checknumber(l, 2));\n return 0;\n });\n lua_prepmfunctions(lua_state, \"batbot\", \"BatbotMT\", Batbot*, activeBatbot);\n\n lua_makelfunction(lua_state, \"luascripts\/updatelua.lua\", \"updatelua\");\n lua_reglfunction(lua_state, \"luascripts\/userscript.lua\");\n lua_reglfunction(lua_state, \"luascripts\/updatebullet.lua\");\n lua_reglfunction(lua_state, \"luascripts\/updatebatbot.lua\");\n \/*\n luaE_beginmfunctions(lua_state, \"RobotMT\");\n luaE_regmfunctions();\n luaE_makemfunction(\"press\", Robot,\n {\n obj->onKeyPress(luaL_checkint(l, 1), ALLEGRO_KEY_RIGHT, luaL_checkint(l, 2));\n return 0;\n });\n luaE_prepmfunctions(\"the_robot\", Robot, &rob);\n luaE_endmfunctions();\n *\/\n rob.push(game.getCamera()->midground);\n \/\/bat->push(game.getCamera()->midground);\n chn.push(game.getCamera()->background);\n ground.push(game.getCamera()->background);\n ceiling.push(game.getCamera()->background);\n leftWall.push(game.getCamera()->background);\n rightWall.push(game.getCamera()->background);\n game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){rob.push(game.getCamera()->midground);});\n \/\/game.addOnRestart([](FRAMETYPE){return true;}, [&bat, &game](){bat->push(game.getCamera()->midground);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&chn, &game](){chn.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&ground, &game](){ground.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&ceiling, &game](){ceiling.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&leftWall, &game](){leftWall.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&rightWall, &game](){rightWall.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){game.addObserver(&rob);});\n game.getCamera()->setCustomTranslate([&rob](Camera *camera_arg)\n {\n camera_arg->postset().postTranslate(b2Vec2(-rob.getPosition().x+PX_TO_M(disp_data.width)\/2, 0\/*-rob.getPosition().y-PX_TO_M(disp_data.height)*2\/3*\/));\n }\n );\n game.addObserver(&rob);\n game.start(FRAMETYPE::STARTSCREEN);\n std::chrono::steady_clock::time_point current_time;\n current_time=std::chrono::steady_clock::now();\n while(game)\n {\n \/\/menu flickering caused by unlimited framerate?\n sysEvents[EVENTTYPE::COLLECTGARBAGE].fire();\n \/\/lua_runlfunction(lua_state, \"updatelua\");\n game.delayTime(std::chrono::duration_cast>(std::chrono::steady_clock::now()-current_time).count());\n current_time=std::chrono::steady_clock::now();\n game.update();\n game.render();\n lua_runlfunction(lua_state, \"userscript\");\n al_flip_display();\n }\n rob.pull();\n delete activeBatbot;\n delete activeBullet;\n \/*\n \/\/ Events example\n EventHandler *evHandler=new EventHandler([]()\n {\n std::cout<<\"Goodbye, World!\\n\";\n });\n sysEvents.addEventHandler(evHandler);\n evHandler->push(sysEvents[EVENTTYPE::INVALID]);\n evHandler->add(EVENTTYPE::INVALID);\n sysEvents[EVENTTYPE::INVALID].fire();\n *\/\n lua_close(lua_state);\n resource.cleanup();\n sysGC.cleanup();\n game.end();\n game.destroy();\n al_destroy_display(display);\n printf(\"End\\n\");\n\n return 0;\n}\nmore spacing fixes#include \"resource.h\"\n\nint main(int argc, char **argv)\n{\n\t\/\/initializing allegro\n al_init();\n al_init_image_addon();\n al_init_primitives_addon();\n al_init_font_addon();\n al_init_ttf_addon();\n al_get_display_mode(al_get_num_display_modes()-1, &disp_data);\n \/\/al_set_new_display_flags(ALLEGRO_FULLSCREEN);\n al_set_new_display_flags(ALLEGRO_WINDOWED);\n al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);\n disp_data.width*=0.8;\n disp_data.height*=0.8;\n display=al_create_display(disp_data.width, disp_data.height);\n\tif(!display)\n {\n return -1;\n }\n\tal_clear_to_color(al_map_rgb(0, 0, 0));\n al_flip_display();\n al_install_keyboard();\n al_install_mouse();\n al_install_audio();\n al_init_acodec_addon();\n al_reserve_samples(5);\n al_set_target_bitmap(al_get_backbuffer(display));\n \/\/ allegro initialization\n\n\t\/\/ initializing lua\n\tlua_state = luaL_newstate();\n\t\/\/ opening libraries for lua, otherwise functions dont work\n\tluaL_openlibs(lua_state);\n\t\/\/ lua initialization\n\n\t\/\/ initializing box2d\n\tworld.SetGravity(b2Vec2(0, -9.8));\n\tContactListener worldContactListener;\n\tworld.SetContactListener(&worldContactListener);\n\tconst int tlx=0, tly=0, brx=10000, bry=disp_data.height;\n Box ground(tlx, bry-10, brx, bry);\n Box ceiling(tlx, tly, brx, 10);\n Box leftWall(tlx, tly, 10, bry);\n Box rightWall(brx-10, 0, brx, bry);\n Chain chn;\n chn.getResource()->registerChainShape(&chn, b2Vec2(0, 0),\n 0, -PX_TO_M(bry)\/3,\n PX_TO_M(brx)*1\/10, -PX_TO_M(bry)*3\/9,\n PX_TO_M(brx)*2\/10, -PX_TO_M(bry)*5\/9,\n PX_TO_M(brx)*3\/10, -PX_TO_M(bry)*9\/9,\n PX_TO_M(brx)*4\/10, -PX_TO_M(bry)*6\/9,\n PX_TO_M(brx)*5\/10, -PX_TO_M(bry)*5\/9,\n PX_TO_M(brx)*6\/10, -PX_TO_M(bry)*3\/9,\n PX_TO_M(brx)*7\/10, -PX_TO_M(bry)*5\/9,\n PX_TO_M(brx)*8\/10, -PX_TO_M(bry)*8\/9,\n PX_TO_M(brx)*9\/10, -PX_TO_M(bry)*9\/9,\n PX_TO_M(brx)*10\/10, -PX_TO_M(bry)*7\/9\n );\n\t\/\/ box2d initialization\n\n resource.initialize();\n sysGC.initialize();\n\n \/*\n Lexer lex;\n Parser psr;\n auto ret=lex.generateTokens(\"\\\n if(y>-0.2 && x<=11)\\n\\\n {\\n\\\n if(x<0.2)\\n\\\n {\\n\\\n activeBullet.move(0.4, 0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(0.4, 0)\\n\\\n }\\n\\\n }\\n\\\n else if(x>11 && y>=-8.2)\\n\\\n {\\n\\\n if(y>-0.2)\\n\\\n {\\n\\\n activeBullet.move(0.4, -0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(0, -0.4)\\n\\\n }\\n\\\n }\\n\\\n else if(y<-8.2 && x>=0.2)\\n\\\n {\\n\\\n if(x>11)\\n\\\n {\\n\\\n activeBullet.move(-0.4, -0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(-0.4, 0)\\n\\\n }\\n\\\n }\\n\\\n else if(x<0.2 && y<=-0.2)\\n\\\n {\\n\\\n if(y<-8.2)\\n\\\n {\\n\\\n activeBullet.move(-0.4, 0.4)\\n\\\n }\\n\\\n else\\n\\\n {\\n\\\n activeBullet.move(0, 0.4)\\n\\\n }\\n\\\n }\\n\\\n \");\n std::cout<<\"Errors: \"<push(obj->getCamera()->midground);\n return 0;\n });\n lua_prepmfunctions(lua_state, \"__game\", \"FrameMT\", Frame, &game);\n\n lua_regmfunctions(lua_state, \"RobotMT\");\n lua_makemfunction(lua_state, \"shoot\", \"RobotMT\", Robot,\n {\n obj->shootProjectile(b2Vec2(0, 0), luaL_checknumber(l, 1), luaL_checknumber(l, 2));\n return 0;\n });\n lua_prepmfunctions(lua_state, \"the_robot\", \"RobotMT\", Robot, &rob);\n\n lua_regmfunctions(lua_state, \"BulletMT\");\n lua_makemfunction(lua_state, \"move\", \"BulletMT\", Projectile*,\n {\n (*obj)->move(b2Vec2(luaL_checknumber(l, 1), luaL_checknumber(l, 2)));\n return 0;\n });\n lua_prepmfunctions(lua_state, \"activeBullet\", \"BulletMT\", Projectile*, activeBullet);\n\n\n lua_regmfunctions(lua_state, \"BatbotMT\");\n lua_makemfunction(lua_state, \"x\", \"BatbotMT\", Batbot*,\n {\n lua_pushnumber(l, (*obj)->getX());\n return 1;\n });\n lua_makemfunction(lua_state, \"y\", \"BatbotMT\", Batbot*,\n {\n lua_pushnumber(l, (*obj)->getY());\n return 1;\n });\n lua_makemfunction(lua_state, \"mass\", \"BatbotMT\", Batbot*,\n {\n lua_pushnumber(l, (*obj)->getMass());\n return 1;\n });\n lua_makemfunction(lua_state, \"move\", \"BatbotMT\", Batbot*,\n {\n (*obj)->move(luaL_checknumber(l, 1), luaL_checknumber(l, 2));\n return 0;\n });\n lua_prepmfunctions(lua_state, \"batbot\", \"BatbotMT\", Batbot*, activeBatbot);\n\n lua_makelfunction(lua_state, \"luascripts\/updatelua.lua\", \"updatelua\");\n lua_reglfunction(lua_state, \"luascripts\/userscript.lua\");\n lua_reglfunction(lua_state, \"luascripts\/updatebullet.lua\");\n lua_reglfunction(lua_state, \"luascripts\/updatebatbot.lua\");\n \/*\n luaE_beginmfunctions(lua_state, \"RobotMT\");\n luaE_regmfunctions();\n luaE_makemfunction(\"press\", Robot,\n {\n obj->onKeyPress(luaL_checkint(l, 1), ALLEGRO_KEY_RIGHT, luaL_checkint(l, 2));\n return 0;\n });\n luaE_prepmfunctions(\"the_robot\", Robot, &rob);\n luaE_endmfunctions();\n *\/\n rob.push(game.getCamera()->midground);\n chn.push(game.getCamera()->background);\n ground.push(game.getCamera()->background);\n ceiling.push(game.getCamera()->background);\n leftWall.push(game.getCamera()->background);\n rightWall.push(game.getCamera()->background);\n game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){rob.push(game.getCamera()->midground);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&chn, &game](){chn.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&ground, &game](){ground.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&ceiling, &game](){ceiling.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&leftWall, &game](){leftWall.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&rightWall, &game](){rightWall.push(game.getCamera()->background);});\n game.addOnRestart([](FRAMETYPE){return true;}, [&rob, &game](){game.addObserver(&rob);});\n game.getCamera()->setCustomTranslate([&rob](Camera *camera_arg)\n {\n camera_arg->postset().postTranslate(b2Vec2(-rob.getPosition().x+PX_TO_M(disp_data.width)\/2, 0\/*-rob.getPosition().y-PX_TO_M(disp_data.height)*2\/3*\/));\n }\n );\n game.addObserver(&rob);\n game.start(FRAMETYPE::STARTSCREEN);\n std::chrono::steady_clock::time_point current_time;\n current_time=std::chrono::steady_clock::now();\n while(game)\n {\n \/\/menu flickering caused by unlimited framerate?\n sysEvents[EVENTTYPE::COLLECTGARBAGE].fire();\n \/\/lua_runlfunction(lua_state, \"updatelua\");\n game.delayTime(std::chrono::duration_cast>(std::chrono::steady_clock::now()-current_time).count());\n current_time=std::chrono::steady_clock::now();\n game.update();\n game.render();\n lua_runlfunction(lua_state, \"userscript\");\n al_flip_display();\n }\n rob.pull();\n delete activeBatbot;\n delete activeBullet;\n lua_close(lua_state);\n resource.cleanup();\n sysGC.cleanup();\n game.end();\n game.destroy();\n al_destroy_display(display);\n printf(\"End\\n\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2010, Rice University\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Rice University nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Ioan Sucan *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ob = ompl::base;\nnamespace oc = ompl::control;\n\n\/\/ a decomposition is only needed for SyclopRRT and SyclopEST\nclass MyDecomposition : public oc::GridDecomposition\n{\npublic:\n MyDecomposition(const int length, const ob::RealVectorBounds& bounds)\n : GridDecomposition(length, 2, bounds)\n {\n }\n void project(const ob::State* s, std::vector& coord) const override\n {\n coord.resize(2);\n coord[0] = s->as()->getX();\n coord[1] = s->as()->getY();\n }\n\n void sampleFullState(const ob::StateSamplerPtr& sampler, const std::vector& coord, ob::State* s) const override\n {\n sampler->sampleUniform(s);\n s->as()->setXY(coord[0], coord[1]);\n }\n};\n\nbool isStateValid(const oc::SpaceInformation *si, const ob::State *state)\n{\n \/\/ ob::ScopedState\n \/\/ cast the abstract state type to the type we expect\n const auto *se2state = state->as();\n\n \/\/ extract the first component of the state and cast it to what we expect\n const auto *pos = se2state->as(0);\n\n \/\/ extract the second component of the state and cast it to what we expect\n const auto *rot = se2state->as(1);\n\n \/\/ check validity of state defined by pos & rot\n\n\n \/\/ return a value that is always true but uses the two variables we define, so we avoid compiler warnings\n return si->satisfiesBounds(state) && (const void*)rot != (const void*)pos;\n}\n\nvoid propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result)\n{\n const auto *se2state = start->as();\n const double* pos = se2state->as(0)->values;\n const double rot = se2state->as(1)->value;\n const double* ctrl = control->as()->values;\n\n result->as()->setXY(\n pos[0] + ctrl[0] * duration * cos(rot),\n pos[1] + ctrl[0] * duration * sin(rot));\n result->as()->setYaw(\n rot + ctrl[1] * duration);\n}\n\nvoid plan()\n{\n\n \/\/ construct the state space we are planning in\n auto space(std::make_shared());\n\n \/\/ set the bounds for the R^2 part of SE(2)\n ob::RealVectorBounds bounds(2);\n bounds.setLow(-1);\n bounds.setHigh(1);\n\n space->setBounds(bounds);\n\n \/\/ create a control space\n auto cspace(std::make_shared(space, 2));\n\n \/\/ set the bounds for the control space\n ob::RealVectorBounds cbounds(2);\n cbounds.setLow(-0.3);\n cbounds.setHigh(0.3);\n\n cspace->setBounds(cbounds);\n\n \/\/ construct an instance of space information from this control space\n auto si(std::make_shared(space, cspace));\n\n \/\/ set state validity checking for this space\n si->setStateValidityChecker(\n [&si](const ob::State *state) { return isStateValid(si.get(), state); });\n\n \/\/ set the state propagation routine\n si->setStatePropagator(propagate);\n\n \/\/ create a start state\n ob::ScopedState start(space);\n start->setX(-0.5);\n start->setY(0.0);\n start->setYaw(0.0);\n\n \/\/ create a goal state\n ob::ScopedState goal(start);\n goal->setX(0.5);\n\n \/\/ create a problem instance\n auto pdef(std::make_shared(si));\n\n \/\/ set the start and goal states\n pdef->setStartAndGoalStates(start, goal, 0.1);\n\n \/\/ create a planner for the defined space\n \/\/auto planner(std::make_shared(si));\n \/\/auto planner(std::make_shared(si));\n \/\/auto planner(std::make_shared(si));\n auto decomp(std::make_shared(32, bounds));\n auto planner(std::make_shared(si, decomp));\n \/\/auto planner(std::make_shared(si, decomp));\n\n \/\/ set the problem we are trying to solve for the planner\n planner->setProblemDefinition(pdef);\n\n \/\/ perform setup steps for the planner\n planner->setup();\n\n\n \/\/ print the settings for this space\n si->printSettings(std::cout);\n\n \/\/ print the problem settings\n pdef->print(std::cout);\n\n \/\/ attempt to solve the problem within one second of planning time\n ob::PlannerStatus solved = planner->ob::Planner::solve(10.0);\n\n if (solved)\n {\n \/\/ get the goal representation from the problem definition (not the same as the goal state)\n \/\/ and inquire about the found path\n ob::PathPtr path = pdef->getSolutionPath();\n std::cout << \"Found solution:\" << std::endl;\n\n \/\/ print the path to screen\n path->print(std::cout);\n }\n else\n std::cout << \"No solution found\" << std::endl;\n}\n\n\nvoid planWithSimpleSetup()\n{\n \/\/ construct the state space we are planning in\n auto space(std::make_shared());\n\n \/\/ set the bounds for the R^2 part of SE(2)\n ob::RealVectorBounds bounds(2);\n bounds.setLow(-1);\n bounds.setHigh(1);\n\n space->setBounds(bounds);\n\n \/\/ create a control space\n auto cspace(std::make_shared(space, 2));\n\n \/\/ set the bounds for the control space\n ob::RealVectorBounds cbounds(2);\n cbounds.setLow(-0.3);\n cbounds.setHigh(0.3);\n\n cspace->setBounds(cbounds);\n\n \/\/ define a simple setup class\n oc::SimpleSetup ss(cspace);\n\n \/\/ set the state propagation routine\n ss.setStatePropagator(propagate);\n\n \/\/ set state validity checking for this space\n ss.setStateValidityChecker(\n [&ss](const ob::State *state) { return isStateValid(ss.getSpaceInformation().get(), state); });\n\n \/\/ create a start state\n ob::ScopedState start(space);\n start->setX(-0.5);\n start->setY(0.0);\n start->setYaw(0.0);\n\n \/\/ create a goal state; use the hard way to set the elements\n ob::ScopedState goal(space);\n (*goal)[0]->as()->values[0] = 0.0;\n (*goal)[0]->as()->values[1] = 0.5;\n (*goal)[1]->as()->value = 0.0;\n\n\n \/\/ set the start and goal states\n ss.setStartAndGoalStates(start, goal, 0.05);\n\n \/\/ ss.setPlanner(std::make_shared(ss.getSpaceInformation()));\n \/\/ ss.getSpaceInformation()->setMinMaxControlDuration(1,100);\n \/\/ attempt to solve the problem within one second of planning time\n ob::PlannerStatus solved = ss.solve(10.0);\n\n if (solved)\n {\n std::cout << \"Found solution:\" << std::endl;\n \/\/ print the path to screen\n\n ss.getSolutionPath().printAsMatrix(std::cout);\n }\n else\n std::cout << \"No solution found\" << std::endl;\n}\n\nint main(int \/*argc*\/, char ** \/*argv*\/)\n{\n std::cout << \"OMPL version: \" << OMPL_VERSION << std::endl;\n\n \/\/ plan();\n \/\/\n \/\/ std::cout << std::endl << std::endl;\n \/\/\n planWithSimpleSetup();\n\n return 0;\n}\nfixed comment about seconds.\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2010, Rice University\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Rice University nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Ioan Sucan *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ob = ompl::base;\nnamespace oc = ompl::control;\n\n\/\/ a decomposition is only needed for SyclopRRT and SyclopEST\nclass MyDecomposition : public oc::GridDecomposition\n{\npublic:\n MyDecomposition(const int length, const ob::RealVectorBounds& bounds)\n : GridDecomposition(length, 2, bounds)\n {\n }\n void project(const ob::State* s, std::vector& coord) const override\n {\n coord.resize(2);\n coord[0] = s->as()->getX();\n coord[1] = s->as()->getY();\n }\n\n void sampleFullState(const ob::StateSamplerPtr& sampler, const std::vector& coord, ob::State* s) const override\n {\n sampler->sampleUniform(s);\n s->as()->setXY(coord[0], coord[1]);\n }\n};\n\nbool isStateValid(const oc::SpaceInformation *si, const ob::State *state)\n{\n \/\/ ob::ScopedState\n \/\/ cast the abstract state type to the type we expect\n const auto *se2state = state->as();\n\n \/\/ extract the first component of the state and cast it to what we expect\n const auto *pos = se2state->as(0);\n\n \/\/ extract the second component of the state and cast it to what we expect\n const auto *rot = se2state->as(1);\n\n \/\/ check validity of state defined by pos & rot\n\n\n \/\/ return a value that is always true but uses the two variables we define, so we avoid compiler warnings\n return si->satisfiesBounds(state) && (const void*)rot != (const void*)pos;\n}\n\nvoid propagate(const ob::State *start, const oc::Control *control, const double duration, ob::State *result)\n{\n const auto *se2state = start->as();\n const double* pos = se2state->as(0)->values;\n const double rot = se2state->as(1)->value;\n const double* ctrl = control->as()->values;\n\n result->as()->setXY(\n pos[0] + ctrl[0] * duration * cos(rot),\n pos[1] + ctrl[0] * duration * sin(rot));\n result->as()->setYaw(\n rot + ctrl[1] * duration);\n}\n\nvoid plan()\n{\n\n \/\/ construct the state space we are planning in\n auto space(std::make_shared());\n\n \/\/ set the bounds for the R^2 part of SE(2)\n ob::RealVectorBounds bounds(2);\n bounds.setLow(-1);\n bounds.setHigh(1);\n\n space->setBounds(bounds);\n\n \/\/ create a control space\n auto cspace(std::make_shared(space, 2));\n\n \/\/ set the bounds for the control space\n ob::RealVectorBounds cbounds(2);\n cbounds.setLow(-0.3);\n cbounds.setHigh(0.3);\n\n cspace->setBounds(cbounds);\n\n \/\/ construct an instance of space information from this control space\n auto si(std::make_shared(space, cspace));\n\n \/\/ set state validity checking for this space\n si->setStateValidityChecker(\n [&si](const ob::State *state) { return isStateValid(si.get(), state); });\n\n \/\/ set the state propagation routine\n si->setStatePropagator(propagate);\n\n \/\/ create a start state\n ob::ScopedState start(space);\n start->setX(-0.5);\n start->setY(0.0);\n start->setYaw(0.0);\n\n \/\/ create a goal state\n ob::ScopedState goal(start);\n goal->setX(0.5);\n\n \/\/ create a problem instance\n auto pdef(std::make_shared(si));\n\n \/\/ set the start and goal states\n pdef->setStartAndGoalStates(start, goal, 0.1);\n\n \/\/ create a planner for the defined space\n \/\/auto planner(std::make_shared(si));\n \/\/auto planner(std::make_shared(si));\n \/\/auto planner(std::make_shared(si));\n auto decomp(std::make_shared(32, bounds));\n auto planner(std::make_shared(si, decomp));\n \/\/auto planner(std::make_shared(si, decomp));\n\n \/\/ set the problem we are trying to solve for the planner\n planner->setProblemDefinition(pdef);\n\n \/\/ perform setup steps for the planner\n planner->setup();\n\n\n \/\/ print the settings for this space\n si->printSettings(std::cout);\n\n \/\/ print the problem settings\n pdef->print(std::cout);\n\n \/\/ attempt to solve the problem within ten seconds of planning time\n ob::PlannerStatus solved = planner->ob::Planner::solve(10.0);\n\n if (solved)\n {\n \/\/ get the goal representation from the problem definition (not the same as the goal state)\n \/\/ and inquire about the found path\n ob::PathPtr path = pdef->getSolutionPath();\n std::cout << \"Found solution:\" << std::endl;\n\n \/\/ print the path to screen\n path->print(std::cout);\n }\n else\n std::cout << \"No solution found\" << std::endl;\n}\n\n\nvoid planWithSimpleSetup()\n{\n \/\/ construct the state space we are planning in\n auto space(std::make_shared());\n\n \/\/ set the bounds for the R^2 part of SE(2)\n ob::RealVectorBounds bounds(2);\n bounds.setLow(-1);\n bounds.setHigh(1);\n\n space->setBounds(bounds);\n\n \/\/ create a control space\n auto cspace(std::make_shared(space, 2));\n\n \/\/ set the bounds for the control space\n ob::RealVectorBounds cbounds(2);\n cbounds.setLow(-0.3);\n cbounds.setHigh(0.3);\n\n cspace->setBounds(cbounds);\n\n \/\/ define a simple setup class\n oc::SimpleSetup ss(cspace);\n\n \/\/ set the state propagation routine\n ss.setStatePropagator(propagate);\n\n \/\/ set state validity checking for this space\n ss.setStateValidityChecker(\n [&ss](const ob::State *state) { return isStateValid(ss.getSpaceInformation().get(), state); });\n\n \/\/ create a start state\n ob::ScopedState start(space);\n start->setX(-0.5);\n start->setY(0.0);\n start->setYaw(0.0);\n\n \/\/ create a goal state; use the hard way to set the elements\n ob::ScopedState goal(space);\n (*goal)[0]->as()->values[0] = 0.0;\n (*goal)[0]->as()->values[1] = 0.5;\n (*goal)[1]->as()->value = 0.0;\n\n\n \/\/ set the start and goal states\n ss.setStartAndGoalStates(start, goal, 0.05);\n\n \/\/ ss.setPlanner(std::make_shared(ss.getSpaceInformation()));\n \/\/ ss.getSpaceInformation()->setMinMaxControlDuration(1,100);\n \/\/ attempt to solve the problem within one second of planning time\n ob::PlannerStatus solved = ss.solve(10.0);\n\n if (solved)\n {\n std::cout << \"Found solution:\" << std::endl;\n \/\/ print the path to screen\n\n ss.getSolutionPath().printAsMatrix(std::cout);\n }\n else\n std::cout << \"No solution found\" << std::endl;\n}\n\nint main(int \/*argc*\/, char ** \/*argv*\/)\n{\n std::cout << \"OMPL version: \" << OMPL_VERSION << std::endl;\n\n \/\/ plan();\n \/\/\n \/\/ std::cout << std::endl << std::endl;\n \/\/\n planWithSimpleSetup();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: segmentedname.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 14:42:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ARY_SEGMENTEDNAME_HXX\n#define ARY_SEGMENTEDNAME_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ OTHER\n\n\n\nnamespace ary\n{\nnamespace sn \/\/ segmented name\n{\n\n\/** One segment in a name like \"::global::abc::def\".\n A segment being the part between \"::\"s.\n\n @collab implements ->SegmentedName\n*\/\nclass NameSegment\n{\n public:\n explicit NameSegment(\n const char * i_name );\n explicit NameSegment(\n const String & i_name );\n explicit NameSegment(\n const NameSegment & i_segment );\n ~NameSegment();\n \/\/ OPERATORS\n NameSegment & operator=(\n const NameSegment & i_other );\n bool operator<(\n const NameSegment & i_other ) const;\n \/\/ OPERATIONS\n String & Make_Template();\n\n \/\/ INQUIRY\n const String & Name() const;\n const String * TemplateArguments() const;\n\n void Get_Text(\n StreamStr & o_out ) const;\n private:\n \/\/ DATA\n String sName;\n Dyn pTemplateArguments;\n};\n\n\n\ntypedef std::vector NameChain;\n\n} \/\/ namespace sn\n\n\n\/** A name of the form \"::global::abc::def\".\n*\/\nclass SegmentedName\n{\n public:\n explicit SegmentedName(\n const char * i_text );\n explicit SegmentedName(\n const String & i_text );\n ~SegmentedName();\n \/\/ OPERATIONS\n bool operator<(\n const SegmentedName &\n i_other ) const;\n\n \/\/ INQUIRY\n bool IsAbsolute() const;\n const sn::NameChain &\n Sequence() const;\n\n void Get_Text(\n StreamStr & o_out ) const;\n private:\n void Interpret_Text(\n const char * i_text ); \/\/\/ [valid C++ or IDL name].\n\n \/\/ DATA\n sn::NameChain aSegments;\n bool bIsAbsolute;\n};\n\n\n\/\/ IMPLEMENTATION\nnamespace sn\n{\n\ninline const String &\nNameSegment::Name() const\n{\n return sName;\n}\n\ninline const String *\nNameSegment::TemplateArguments() const\n{\n return pTemplateArguments.Ptr();\n}\n\n} \/\/ namespace sn\n\ninline bool\nSegmentedName::IsAbsolute() const\n{\n return bIsAbsolute;\n}\n\ninline const sn::NameChain &\nSegmentedName::Sequence() const\n{\n return aSegments;\n}\n\n\n\n} \/\/ namespace ary\n#endif\nINTEGRATION: CWS cmcfixes39 (1.2.4); FILE MERGED 2007\/11\/20 09:48:25 cmc 1.2.4.1: #i83486# stlportism -> stl\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: segmentedname.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2007-12-12 14:56:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ARY_SEGMENTEDNAME_HXX\n#define ARY_SEGMENTEDNAME_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ OTHER\n\n\n\nnamespace ary\n{\nnamespace sn \/\/ segmented name\n{\n\n\/** One segment in a name like \"::global::abc::def\".\n A segment being the part between \"::\"s.\n\n @collab implements ->SegmentedName\n*\/\nclass NameSegment\n{\n public:\n explicit NameSegment(\n const char * i_name );\n explicit NameSegment(\n const String & i_name );\n NameSegment(\n const NameSegment & i_segment );\n ~NameSegment();\n \/\/ OPERATORS\n NameSegment & operator=(\n const NameSegment & i_other );\n bool operator<(\n const NameSegment & i_other ) const;\n \/\/ OPERATIONS\n String & Make_Template();\n\n \/\/ INQUIRY\n const String & Name() const;\n const String * TemplateArguments() const;\n\n void Get_Text(\n StreamStr & o_out ) const;\n private:\n \/\/ DATA\n String sName;\n Dyn pTemplateArguments;\n};\n\n\n\ntypedef std::vector NameChain;\n\n} \/\/ namespace sn\n\n\n\/** A name of the form \"::global::abc::def\".\n*\/\nclass SegmentedName\n{\n public:\n explicit SegmentedName(\n const char * i_text );\n explicit SegmentedName(\n const String & i_text );\n ~SegmentedName();\n \/\/ OPERATIONS\n bool operator<(\n const SegmentedName &\n i_other ) const;\n\n \/\/ INQUIRY\n bool IsAbsolute() const;\n const sn::NameChain &\n Sequence() const;\n\n void Get_Text(\n StreamStr & o_out ) const;\n private:\n void Interpret_Text(\n const char * i_text ); \/\/\/ [valid C++ or IDL name].\n\n \/\/ DATA\n sn::NameChain aSegments;\n bool bIsAbsolute;\n};\n\n\n\/\/ IMPLEMENTATION\nnamespace sn\n{\n\ninline const String &\nNameSegment::Name() const\n{\n return sName;\n}\n\ninline const String *\nNameSegment::TemplateArguments() const\n{\n return pTemplateArguments.Ptr();\n}\n\n} \/\/ namespace sn\n\ninline bool\nSegmentedName::IsAbsolute() const\n{\n return bIsAbsolute;\n}\n\ninline const sn::NameChain &\nSegmentedName::Sequence() const\n{\n return aSegments;\n}\n\n\n\n} \/\/ namespace ary\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2003-2010 Rony Shapiro .\n * All rights reserved. Use of the code is allowed under the\n * Artistic License 2.0 terms, as specified in the LICENSE file\n * distributed with this code, or available from\n * http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n *\/\n\n\/** \\file safecombinationentry.cpp\n* \n*\/\n\/\/ Generated by DialogBlocks, Sun 18 Jan 2009 09:22:13 PM IST\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n\/\/\/\/@begin includes\n\/\/\/\/@end includes\n\n#include \"safecombinationentry.h\"\n#include \"safecombinationsetup.h\"\n#include \"version.h\"\n#include \"corelib\/corelib.h\"\n#include \"corelib\/PWSdirs.h\"\n#include \"os\/file.h\"\n\/\/\/\/@begin XPM images\n#include \"..\/graphics\/wxWidgets\/cpane.xpm\"\n#include \"..\/graphics\/wxWidgets\/psafetxt.xpm\"\n\/\/\/\/@end XPM images\n#include \"pwsafeapp.h\"\n#include \"SafeCombinationCtrl.h\"\n\n\/*!\n * CSafeCombinationEntry type definition\n *\/\n\nIMPLEMENT_CLASS( CSafeCombinationEntry, wxDialog )\n\n\n\/*!\n * CSafeCombinationEntry event table definition\n *\/\n\nBEGIN_EVENT_TABLE( CSafeCombinationEntry, wxDialog )\n\n\/\/\/\/@begin CSafeCombinationEntry event table entries\n EVT_BUTTON( ID_ELLIPSIS, CSafeCombinationEntry::OnEllipsisClick )\n\n EVT_BUTTON( ID_NEWDB, CSafeCombinationEntry::OnNewDbClick )\n\n EVT_BUTTON( wxID_OK, CSafeCombinationEntry::OnOk )\n\n EVT_BUTTON( wxID_CANCEL, CSafeCombinationEntry::OnCancel )\n\/\/\/\/@end CSafeCombinationEntry event table entries\n\nEND_EVENT_TABLE()\n\n\n\/*!\n * CSafeCombinationEntry constructors\n *\/\n\nCSafeCombinationEntry::CSafeCombinationEntry(PWScore &core)\n: m_core(core), m_tries(0)\n{\n Init();\n}\n\nCSafeCombinationEntry::CSafeCombinationEntry(wxWindow* parent, PWScore &core,\n wxWindowID id,\n const wxString& caption,\n const wxPoint& pos,\n const wxSize& size, long style)\n : m_core(core), m_tries(0)\n{\n Init();\n Create(parent, id, caption, pos, size, style);\n}\n\n\n\/*!\n * CSafeCombinationEntry creator\n *\/\n\nbool CSafeCombinationEntry::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )\n{\n\/\/\/\/@begin CSafeCombinationEntry creation\n SetExtraStyle(wxWS_EX_BLOCK_EVENTS);\n wxDialog::Create( parent, id, caption, pos, size, style );\n\n CreateControls();\n if (GetSizer())\n {\n GetSizer()->SetSizeHints(this);\n }\n Centre();\n\/\/\/\/@end CSafeCombinationEntry creation\n return true;\n}\n\n\n\/*!\n * CSafeCombinationEntry destructor\n *\/\n\nCSafeCombinationEntry::~CSafeCombinationEntry()\n{\n\/\/\/\/@begin CSafeCombinationEntry destruction\n\/\/\/\/@end CSafeCombinationEntry destruction\n}\n\n\n\/*!\n * Member initialisation\n *\/\n\nvoid CSafeCombinationEntry::Init()\n{\n m_readOnly = m_core.IsReadOnly();\n m_filename = m_core.GetCurFile().c_str();\n\/\/\/\/@begin CSafeCombinationEntry member initialisation\n m_version = NULL;\n m_filenameCB = NULL;\n\/\/\/\/@end CSafeCombinationEntry member initialisation\n}\n\n\n\/*!\n * Control creation for CSafeCombinationEntry\n *\/\n\nvoid CSafeCombinationEntry::CreateControls()\n{ \n\/\/\/\/@begin CSafeCombinationEntry content construction\n CSafeCombinationEntry* itemDialog1 = this;\n\n wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxHORIZONTAL);\n itemDialog1->SetSizer(itemBoxSizer2);\n\n wxStaticBitmap* itemStaticBitmap3 = new wxStaticBitmap( itemDialog1, wxID_STATIC, itemDialog1->GetBitmapResource(wxT(\"..\/graphics\/wxWidgets\/cpane.xpm\")), wxDefaultPosition, itemDialog1->ConvertDialogToPixels(wxSize(49, 46)), 0 );\n itemBoxSizer2->Add(itemStaticBitmap3, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxVERTICAL);\n itemBoxSizer2->Add(itemBoxSizer4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL);\n itemBoxSizer4->Add(itemBoxSizer5, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);\n\n wxStaticBitmap* itemStaticBitmap6 = new wxStaticBitmap( itemDialog1, wxID_STATIC, itemDialog1->GetBitmapResource(wxT(\"..\/graphics\/wxWidgets\/psafetxt.xpm\")), wxDefaultPosition, itemDialog1->ConvertDialogToPixels(wxSize(111, 16)), 0 );\n itemBoxSizer5->Add(itemStaticBitmap6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n m_version = new wxStaticText( itemDialog1, wxID_STATIC, _(\"VX.YY\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemBoxSizer5->Add(m_version, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxStaticText* itemStaticText8 = new wxStaticText( itemDialog1, wxID_STATIC, _(\"Open Password Database:\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemBoxSizer4->Add(itemStaticText8, 0, wxALIGN_LEFT|wxALL, 3);\n\n wxBoxSizer* itemBoxSizer9 = new wxBoxSizer(wxHORIZONTAL);\n itemBoxSizer4->Add(itemBoxSizer9, 50, wxGROW|wxALL, 5);\n\n wxArrayString m_filenameCBStrings;\n m_filenameCB = new wxComboBox( itemDialog1, ID_DBASECOMBOBOX, wxEmptyString, wxDefaultPosition, wxSize(itemDialog1->ConvertDialogToPixels(wxSize(140, -1)).x, -1), m_filenameCBStrings, wxCB_DROPDOWN );\n itemBoxSizer9->Add(m_filenameCB, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT|wxBOTTOM, 0);\n\n wxButton* itemButton11 = new wxButton( itemDialog1, ID_ELLIPSIS, _(\"...\"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );\n itemBoxSizer9->Add(itemButton11, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxStaticText* itemStaticText12 = new wxStaticText( itemDialog1, wxID_STATIC, _(\"Safe Combination:\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemBoxSizer4->Add(itemStaticText12, 0, wxALIGN_LEFT|wxALL, 3);\n\n CSafeCombinationCtrl* combinationEntry = new CSafeCombinationCtrl(itemDialog1, ID_COMBINATION);\n itemBoxSizer4->Add(combinationEntry, 0, wxGROW|wxRIGHT|wxTOP|wxBOTTOM, 5);\n\n wxBoxSizer* itemBoxSizer14 = new wxBoxSizer(wxHORIZONTAL);\n itemBoxSizer4->Add(itemBoxSizer14, 0, wxGROW|wxALL, 5);\n\n wxCheckBox* itemCheckBox15 = new wxCheckBox( itemDialog1, ID_READONLY, _(\"Open as read-only\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemCheckBox15->SetValue(false);\n itemBoxSizer14->Add(itemCheckBox15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0);\n\n itemBoxSizer14->Add(120, 10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxButton* itemButton17 = new wxButton( itemDialog1, ID_NEWDB, _(\"New\\nDatabase\"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );\n itemBoxSizer14->Add(itemButton17, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, 5);\n\n wxStdDialogButtonSizer* itemStdDialogButtonSizer18 = new wxStdDialogButtonSizer;\n\n itemBoxSizer4->Add(itemStdDialogButtonSizer18, 0, wxGROW|wxALL, 0);\n wxButton* itemButton19 = new wxButton( itemDialog1, wxID_OK, _(\"OK\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemButton19->SetDefault();\n itemStdDialogButtonSizer18->AddButton(itemButton19);\n\n wxButton* itemButton20 = new wxButton( itemDialog1, wxID_CANCEL, _(\"Cancel\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemStdDialogButtonSizer18->AddButton(itemButton20);\n\n wxButton* itemButton21 = new wxButton( itemDialog1, wxID_HELP, _(\"&Help\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemStdDialogButtonSizer18->AddButton(itemButton21);\n\n itemStdDialogButtonSizer18->Realize();\n\n \/\/ Set validators\n m_filenameCB->SetValidator( wxGenericValidator(& m_filename) );\n combinationEntry->textCtrl->SetValidator( wxGenericValidator(& m_password) );\n itemCheckBox15->SetValidator( wxGenericValidator(& m_readOnly) );\n\/\/\/\/@end CSafeCombinationEntry content construction\n#if (REVISION == 0)\n m_version->SetLabel(wxString::Format(_(\"V%d.%02d %s\"),\n MAJORVERSION, MINORVERSION, SPECIALBUILD));\n#else\n m_version->SetLabel(wxString::Format(_(\"V%d.%02d.%d %s\"),\n MAJORVERSION, MINORVERSION,\n REVISION, SPECIALBUILD));\n#endif\n wxArrayString recentFiles;\n wxGetApp().recentDatabases().GetAll(recentFiles);\n m_filenameCB->Append(recentFiles);\n \/\/ if m_readOnly, then don't allow user to change it\n itemCheckBox15->Enable(!m_readOnly);\n \/\/ if filename field not empty, set focus to password:\n if (!m_filename.empty()) {\n FindWindow(ID_COMBINATION)->SetFocus();\n }\n}\n\n\n\/*!\n * Should we show tooltips?\n *\/\n\nbool CSafeCombinationEntry::ShowToolTips()\n{\n return true;\n}\n\n\/*!\n * Get bitmap resources\n *\/\n\nwxBitmap CSafeCombinationEntry::GetBitmapResource( const wxString& name )\n{\n \/\/ Bitmap retrieval\n\/\/\/\/@begin CSafeCombinationEntry bitmap retrieval\n wxUnusedVar(name);\n if (name == _T(\"..\/graphics\/wxWidgets\/cpane.xpm\"))\n {\n wxBitmap bitmap(cpane_xpm);\n return bitmap;\n }\n else if (name == _T(\"..\/graphics\/wxWidgets\/psafetxt.xpm\"))\n {\n wxBitmap bitmap(psafetxt_xpm);\n return bitmap;\n }\n return wxNullBitmap;\n\/\/\/\/@end CSafeCombinationEntry bitmap retrieval\n}\n\n\/*!\n * Get icon resources\n *\/\n\nwxIcon CSafeCombinationEntry::GetIconResource( const wxString& name )\n{\n \/\/ Icon retrieval\n\/\/\/\/@begin CSafeCombinationEntry icon retrieval\n wxUnusedVar(name);\n return wxNullIcon;\n\/\/\/\/@end CSafeCombinationEntry icon retrieval\n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_OK\n *\/\n\nvoid CSafeCombinationEntry::OnOk( wxCommandEvent& )\n{\n if (Validate() && TransferDataFromWindow()) {\n if (m_password.empty()) {\n wxMessageDialog err(this, _(\"The combination cannot be blank.\"),\n _(\"Error\"), wxOK | wxICON_EXCLAMATION);\n err.ShowModal();\n return;\n }\n if (!pws_os::FileExists(m_filename.c_str())) {\n wxMessageDialog err(this, _(\"File or path not found.\"),\n _(\"Error\"), wxOK | wxICON_EXCLAMATION);\n err.ShowModal();\n return;\n }\n int status = m_core.CheckPasskey(m_filename.c_str(), m_password.c_str());\n wxString errmess;\n switch (status) {\n case PWScore::SUCCESS:\n m_core.SetReadOnly(m_readOnly);\n m_core.SetCurFile(m_filename.c_str());\n wxGetApp().recentDatabases().AddFileToHistory(m_filename);\n EndModal(wxID_OK);\n return;\n case PWScore::CANT_OPEN_FILE:\n { stringT str;\n LoadAString(str, IDSC_FILE_UNREADABLE);\n errmess = str.c_str();\n }\n break;\n case PWScore::WRONG_PASSWORD:\n default:\n if (m_tries >= 2) {\n errmess = _(\"Three strikes - yer out!\");\n } else {\n m_tries++;\n errmess = _(\"Incorrect passkey, not a PasswordSafe database, or a corrupt database. (Backup database has same name as original, ending with '~')\");\n }\n break;\n } \/\/ switch (status)\n \/\/ here iff CheckPasskey failed.\n wxMessageDialog err(this, errmess,\n _(\"Error\"), wxOK | wxICON_EXCLAMATION);\n err.ShowModal();\n wxTextCtrl *txt = (wxTextCtrl *)FindWindow(ID_COMBINATION);\n txt->SetSelection(-1,-1);\n txt->SetFocus();\n } \/\/ Validate && TransferDataFromWindow\n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL\n *\/\n\nvoid CSafeCombinationEntry::OnCancel( wxCommandEvent& event )\n{\n\/\/\/\/@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationEntry.\n \/\/ Before editing this code, remove the block markers.\n event.Skip();\n\/\/\/\/@end wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationEntry. \n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ELLIPSIS\n *\/\n\nvoid CSafeCombinationEntry::OnEllipsisClick( wxCommandEvent& \/* evt *\/ )\n{\n wxFileDialog fd(this, _(\"Please Choose a Database to Open:\"),\n wxT(\"\"), wxT(\"\"),\n _(\"Password Safe Databases (*.psafe3; *.dat)|*.psafe3;*.dat| All files (*.*; *)|*.*;*\"),\n (wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR));\n \n if (fd.ShowModal() == wxID_OK) {\n m_filename = fd.GetPath();\n wxComboBox *cb = (wxComboBox *)FindWindow(ID_DBASECOMBOBOX);\n cb->SetValue(m_filename);\n }\n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_NEWDB\n *\/\n\nvoid CSafeCombinationEntry::OnNewDbClick( wxCommandEvent& \/* evt *\/ )\n{\n \/\/ 1. Get a filename from a file dialog box\n \/\/ 2. Get a password\n \/\/ 3. Set m_filespec && m_passkey to returned value!\n wxString newfile;\n wxString cs_msg, cs_title, cs_temp;\n\n wxString cf(_(\"pwsafe\")); \/\/ reasonable default for first time user\n stringT v3FileName = PWSUtil::GetNewFileName(cf.c_str(), _(\"psafe3\"));\n stringT dir = PWSdirs::GetSafeDir();\n\n while (1) {\n wxFileDialog fd(this, _(\"Please choose a name for the new database\"),\n dir.c_str(), v3FileName.c_str(),\n _(\"Password Safe Databases (*.psafe3; *.dat)|*.psafe3;*.dat| All files (*.*; *)|*.*;*\"),\n (wxFD_SAVE | wxFD_OVERWRITE_PROMPT| wxFD_CHANGE_DIR));\n int rc = fd.ShowModal();\n if (rc == wxID_OK) {\n newfile = fd.GetPath();\n break;\n } else\n return;\n }\n \/\/ 2. Get a password\n CSafeCombinationSetup pksetup(this);\n int rc = pksetup.ShowModal();\n\n if (rc != wxID_OK)\n return; \/\/User cancelled password entry\n\n \/\/ 3. Set m_filespec && m_passkey to returned value!\n m_core.SetCurFile(newfile.c_str());\n m_core.SetPassKey(pksetup.GetPassword().c_str());\n wxGetApp().recentDatabases().AddFileToHistory(newfile);\n EndModal(wxID_OK);\n}\n\nUse CreateStdDialogButtonSizer instead of manually adding buttons to wxStdDialogButtonSizer\/*\n * Copyright (c) 2003-2010 Rony Shapiro .\n * All rights reserved. Use of the code is allowed under the\n * Artistic License 2.0 terms, as specified in the LICENSE file\n * distributed with this code, or available from\n * http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n *\/\n\n\/** \\file safecombinationentry.cpp\n* \n*\/\n\/\/ Generated by DialogBlocks, Sun 18 Jan 2009 09:22:13 PM IST\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \"wx\/wx.h\"\n#endif\n\n\/\/\/\/@begin includes\n\/\/\/\/@end includes\n\n#include \"safecombinationentry.h\"\n#include \"safecombinationsetup.h\"\n#include \"version.h\"\n#include \"corelib\/corelib.h\"\n#include \"corelib\/PWSdirs.h\"\n#include \"os\/file.h\"\n\/\/\/\/@begin XPM images\n#include \"..\/graphics\/wxWidgets\/cpane.xpm\"\n#include \"..\/graphics\/wxWidgets\/psafetxt.xpm\"\n\/\/\/\/@end XPM images\n#include \"pwsafeapp.h\"\n#include \"SafeCombinationCtrl.h\"\n\n\/*!\n * CSafeCombinationEntry type definition\n *\/\n\nIMPLEMENT_CLASS( CSafeCombinationEntry, wxDialog )\n\n\n\/*!\n * CSafeCombinationEntry event table definition\n *\/\n\nBEGIN_EVENT_TABLE( CSafeCombinationEntry, wxDialog )\n\n\/\/\/\/@begin CSafeCombinationEntry event table entries\n EVT_BUTTON( ID_ELLIPSIS, CSafeCombinationEntry::OnEllipsisClick )\n\n EVT_BUTTON( ID_NEWDB, CSafeCombinationEntry::OnNewDbClick )\n\n EVT_BUTTON( wxID_OK, CSafeCombinationEntry::OnOk )\n\n EVT_BUTTON( wxID_CANCEL, CSafeCombinationEntry::OnCancel )\n\/\/\/\/@end CSafeCombinationEntry event table entries\n\nEND_EVENT_TABLE()\n\n\n\/*!\n * CSafeCombinationEntry constructors\n *\/\n\nCSafeCombinationEntry::CSafeCombinationEntry(PWScore &core)\n: m_core(core), m_tries(0)\n{\n Init();\n}\n\nCSafeCombinationEntry::CSafeCombinationEntry(wxWindow* parent, PWScore &core,\n wxWindowID id,\n const wxString& caption,\n const wxPoint& pos,\n const wxSize& size, long style)\n : m_core(core), m_tries(0)\n{\n Init();\n Create(parent, id, caption, pos, size, style);\n}\n\n\n\/*!\n * CSafeCombinationEntry creator\n *\/\n\nbool CSafeCombinationEntry::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )\n{\n\/\/\/\/@begin CSafeCombinationEntry creation\n SetExtraStyle(wxWS_EX_BLOCK_EVENTS);\n wxDialog::Create( parent, id, caption, pos, size, style );\n\n CreateControls();\n if (GetSizer())\n {\n GetSizer()->SetSizeHints(this);\n }\n Centre();\n\/\/\/\/@end CSafeCombinationEntry creation\n return true;\n}\n\n\n\/*!\n * CSafeCombinationEntry destructor\n *\/\n\nCSafeCombinationEntry::~CSafeCombinationEntry()\n{\n\/\/\/\/@begin CSafeCombinationEntry destruction\n\/\/\/\/@end CSafeCombinationEntry destruction\n}\n\n\n\/*!\n * Member initialisation\n *\/\n\nvoid CSafeCombinationEntry::Init()\n{\n m_readOnly = m_core.IsReadOnly();\n m_filename = m_core.GetCurFile().c_str();\n\/\/\/\/@begin CSafeCombinationEntry member initialisation\n m_version = NULL;\n m_filenameCB = NULL;\n\/\/\/\/@end CSafeCombinationEntry member initialisation\n}\n\n\n\/*!\n * Control creation for CSafeCombinationEntry\n *\/\n\nvoid CSafeCombinationEntry::CreateControls()\n{ \n\/\/\/\/@begin CSafeCombinationEntry content construction\n CSafeCombinationEntry* itemDialog1 = this;\n\n wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxHORIZONTAL);\n itemDialog1->SetSizer(itemBoxSizer2);\n\n wxStaticBitmap* itemStaticBitmap3 = new wxStaticBitmap( itemDialog1, wxID_STATIC, itemDialog1->GetBitmapResource(wxT(\"..\/graphics\/wxWidgets\/cpane.xpm\")), wxDefaultPosition, itemDialog1->ConvertDialogToPixels(wxSize(49, 46)), 0 );\n itemBoxSizer2->Add(itemStaticBitmap3, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxVERTICAL);\n itemBoxSizer2->Add(itemBoxSizer4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL);\n itemBoxSizer4->Add(itemBoxSizer5, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);\n\n wxStaticBitmap* itemStaticBitmap6 = new wxStaticBitmap( itemDialog1, wxID_STATIC, itemDialog1->GetBitmapResource(wxT(\"..\/graphics\/wxWidgets\/psafetxt.xpm\")), wxDefaultPosition, itemDialog1->ConvertDialogToPixels(wxSize(111, 16)), 0 );\n itemBoxSizer5->Add(itemStaticBitmap6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n m_version = new wxStaticText( itemDialog1, wxID_STATIC, _(\"VX.YY\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemBoxSizer5->Add(m_version, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxStaticText* itemStaticText8 = new wxStaticText( itemDialog1, wxID_STATIC, _(\"Open Password Database:\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemBoxSizer4->Add(itemStaticText8, 0, wxALIGN_LEFT|wxALL, 3);\n\n wxBoxSizer* itemBoxSizer9 = new wxBoxSizer(wxHORIZONTAL);\n itemBoxSizer4->Add(itemBoxSizer9, 50, wxGROW|wxALL, 5);\n\n wxArrayString m_filenameCBStrings;\n m_filenameCB = new wxComboBox( itemDialog1, ID_DBASECOMBOBOX, wxEmptyString, wxDefaultPosition, wxSize(itemDialog1->ConvertDialogToPixels(wxSize(140, -1)).x, -1), m_filenameCBStrings, wxCB_DROPDOWN );\n itemBoxSizer9->Add(m_filenameCB, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT|wxBOTTOM, 0);\n\n wxButton* itemButton11 = new wxButton( itemDialog1, ID_ELLIPSIS, _(\"...\"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );\n itemBoxSizer9->Add(itemButton11, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxStaticText* itemStaticText12 = new wxStaticText( itemDialog1, wxID_STATIC, _(\"Safe Combination:\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemBoxSizer4->Add(itemStaticText12, 0, wxALIGN_LEFT|wxALL, 3);\n\n CSafeCombinationCtrl* combinationEntry = new CSafeCombinationCtrl(itemDialog1, ID_COMBINATION);\n itemBoxSizer4->Add(combinationEntry, 0, wxGROW|wxRIGHT|wxTOP|wxBOTTOM, 5);\n\n wxBoxSizer* itemBoxSizer14 = new wxBoxSizer(wxHORIZONTAL);\n itemBoxSizer4->Add(itemBoxSizer14, 0, wxGROW|wxALL, 5);\n\n wxCheckBox* itemCheckBox15 = new wxCheckBox( itemDialog1, ID_READONLY, _(\"Open as read-only\"), wxDefaultPosition, wxDefaultSize, 0 );\n itemCheckBox15->SetValue(false);\n itemBoxSizer14->Add(itemCheckBox15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0);\n\n itemBoxSizer14->Add(120, 10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);\n\n wxButton* itemButton17 = new wxButton( itemDialog1, ID_NEWDB, _(\"New\\nDatabase\"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );\n itemBoxSizer14->Add(itemButton17, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxTOP|wxBOTTOM, 5);\n\n itemBoxSizer4->Add(CreateStdDialogButtonSizer(wxOK|wxCANCEL|wxHELP), 0, wxGROW|wxALL, 0);\n\n \/\/ Set validators\n m_filenameCB->SetValidator( wxGenericValidator(& m_filename) );\n combinationEntry->textCtrl->SetValidator( wxGenericValidator(& m_password) );\n itemCheckBox15->SetValidator( wxGenericValidator(& m_readOnly) );\n\/\/\/\/@end CSafeCombinationEntry content construction\n#if (REVISION == 0)\n m_version->SetLabel(wxString::Format(_(\"V%d.%02d %s\"),\n MAJORVERSION, MINORVERSION, SPECIALBUILD));\n#else\n m_version->SetLabel(wxString::Format(_(\"V%d.%02d.%d %s\"),\n MAJORVERSION, MINORVERSION,\n REVISION, SPECIALBUILD));\n#endif\n wxArrayString recentFiles;\n wxGetApp().recentDatabases().GetAll(recentFiles);\n m_filenameCB->Append(recentFiles);\n \/\/ if m_readOnly, then don't allow user to change it\n itemCheckBox15->Enable(!m_readOnly);\n \/\/ if filename field not empty, set focus to password:\n if (!m_filename.empty()) {\n FindWindow(ID_COMBINATION)->SetFocus();\n }\n}\n\n\n\/*!\n * Should we show tooltips?\n *\/\n\nbool CSafeCombinationEntry::ShowToolTips()\n{\n return true;\n}\n\n\/*!\n * Get bitmap resources\n *\/\n\nwxBitmap CSafeCombinationEntry::GetBitmapResource( const wxString& name )\n{\n \/\/ Bitmap retrieval\n\/\/\/\/@begin CSafeCombinationEntry bitmap retrieval\n wxUnusedVar(name);\n if (name == _T(\"..\/graphics\/wxWidgets\/cpane.xpm\"))\n {\n wxBitmap bitmap(cpane_xpm);\n return bitmap;\n }\n else if (name == _T(\"..\/graphics\/wxWidgets\/psafetxt.xpm\"))\n {\n wxBitmap bitmap(psafetxt_xpm);\n return bitmap;\n }\n return wxNullBitmap;\n\/\/\/\/@end CSafeCombinationEntry bitmap retrieval\n}\n\n\/*!\n * Get icon resources\n *\/\n\nwxIcon CSafeCombinationEntry::GetIconResource( const wxString& name )\n{\n \/\/ Icon retrieval\n\/\/\/\/@begin CSafeCombinationEntry icon retrieval\n wxUnusedVar(name);\n return wxNullIcon;\n\/\/\/\/@end CSafeCombinationEntry icon retrieval\n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_OK\n *\/\n\nvoid CSafeCombinationEntry::OnOk( wxCommandEvent& )\n{\n if (Validate() && TransferDataFromWindow()) {\n if (m_password.empty()) {\n wxMessageDialog err(this, _(\"The combination cannot be blank.\"),\n _(\"Error\"), wxOK | wxICON_EXCLAMATION);\n err.ShowModal();\n return;\n }\n if (!pws_os::FileExists(m_filename.c_str())) {\n wxMessageDialog err(this, _(\"File or path not found.\"),\n _(\"Error\"), wxOK | wxICON_EXCLAMATION);\n err.ShowModal();\n return;\n }\n int status = m_core.CheckPasskey(m_filename.c_str(), m_password.c_str());\n wxString errmess;\n switch (status) {\n case PWScore::SUCCESS:\n m_core.SetReadOnly(m_readOnly);\n m_core.SetCurFile(m_filename.c_str());\n wxGetApp().recentDatabases().AddFileToHistory(m_filename);\n EndModal(wxID_OK);\n return;\n case PWScore::CANT_OPEN_FILE:\n { stringT str;\n LoadAString(str, IDSC_FILE_UNREADABLE);\n errmess = str.c_str();\n }\n break;\n case PWScore::WRONG_PASSWORD:\n default:\n if (m_tries >= 2) {\n errmess = _(\"Three strikes - yer out!\");\n } else {\n m_tries++;\n errmess = _(\"Incorrect passkey, not a PasswordSafe database, or a corrupt database. (Backup database has same name as original, ending with '~')\");\n }\n break;\n } \/\/ switch (status)\n \/\/ here iff CheckPasskey failed.\n wxMessageDialog err(this, errmess,\n _(\"Error\"), wxOK | wxICON_EXCLAMATION);\n err.ShowModal();\n wxTextCtrl *txt = (wxTextCtrl *)FindWindow(ID_COMBINATION);\n txt->SetSelection(-1,-1);\n txt->SetFocus();\n } \/\/ Validate && TransferDataFromWindow\n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL\n *\/\n\nvoid CSafeCombinationEntry::OnCancel( wxCommandEvent& event )\n{\n\/\/\/\/@begin wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationEntry.\n \/\/ Before editing this code, remove the block markers.\n event.Skip();\n\/\/\/\/@end wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CANCEL in CSafeCombinationEntry. \n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_ELLIPSIS\n *\/\n\nvoid CSafeCombinationEntry::OnEllipsisClick( wxCommandEvent& \/* evt *\/ )\n{\n wxFileDialog fd(this, _(\"Please Choose a Database to Open:\"),\n wxT(\"\"), wxT(\"\"),\n _(\"Password Safe Databases (*.psafe3; *.dat)|*.psafe3;*.dat| All files (*.*; *)|*.*;*\"),\n (wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR));\n \n if (fd.ShowModal() == wxID_OK) {\n m_filename = fd.GetPath();\n wxComboBox *cb = (wxComboBox *)FindWindow(ID_DBASECOMBOBOX);\n cb->SetValue(m_filename);\n }\n}\n\n\n\/*!\n * wxEVT_COMMAND_BUTTON_CLICKED event handler for ID_NEWDB\n *\/\n\nvoid CSafeCombinationEntry::OnNewDbClick( wxCommandEvent& \/* evt *\/ )\n{\n \/\/ 1. Get a filename from a file dialog box\n \/\/ 2. Get a password\n \/\/ 3. Set m_filespec && m_passkey to returned value!\n wxString newfile;\n wxString cs_msg, cs_title, cs_temp;\n\n wxString cf(_(\"pwsafe\")); \/\/ reasonable default for first time user\n stringT v3FileName = PWSUtil::GetNewFileName(cf.c_str(), _(\"psafe3\"));\n stringT dir = PWSdirs::GetSafeDir();\n\n while (1) {\n wxFileDialog fd(this, _(\"Please choose a name for the new database\"),\n dir.c_str(), v3FileName.c_str(),\n _(\"Password Safe Databases (*.psafe3; *.dat)|*.psafe3;*.dat| All files (*.*; *)|*.*;*\"),\n (wxFD_SAVE | wxFD_OVERWRITE_PROMPT| wxFD_CHANGE_DIR));\n int rc = fd.ShowModal();\n if (rc == wxID_OK) {\n newfile = fd.GetPath();\n break;\n } else\n return;\n }\n \/\/ 2. Get a password\n CSafeCombinationSetup pksetup(this);\n int rc = pksetup.ShowModal();\n\n if (rc != wxID_OK)\n return; \/\/User cancelled password entry\n\n \/\/ 3. Set m_filespec && m_passkey to returned value!\n m_core.SetCurFile(newfile.c_str());\n m_core.SetPassKey(pksetup.GetPassword().c_str());\n wxGetApp().recentDatabases().AddFileToHistory(newfile);\n EndModal(wxID_OK);\n}\n\n<|endoftext|>"} {"text":"#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ uint32_t etc.\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \n#endif\n\n#ifndef WINDOW_WIDTH\n#define WINDOW_WIDTH (1600.0f)\n#endif\n\n#ifndef WINDOW_HEIGHT\n#define WINDOW_HEIGHT (900.0f)\n#endif\n\n#ifndef ASPECT_RATIO\n#define ASPECT_RATIO (WINDOW_WIDTH \/ WINDOW_HEIGHT)\n#endif\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\n#ifndef EARTH_RADIUS\n#define EARTH_RADIUS 6371000.0f\n#endif\n\n#ifndef TEXT_SIZE\n#define TEXT_SIZE 40\n#endif\n\n#ifndef FONT_SIZE\n#define FONT_SIZE 16\n#endif\n\n#ifndef MAX_FPS\n#define MAX_FPS 60\n#endif\n\nextern glm::vec3 position;\nextern GLfloat gravity;\nextern bool inFlightmode;\nextern GLfloat fallSpeed;\nextern double horizontalAngle;\nextern double verticalAngle;\nextern GLfloat initialFoV;\nextern double earth_radius;\nextern bool hasMouseEverMoved;\nextern bool is_invert_mouse_in_use;\nextern bool is_key_I_released;\nextern bool is_world_loaded; \/\/ no more than one world object can be loaded. TODO: check that no more than one world is loaded!\nextern bool is_world_spherical;\n\ntypedef struct\n{\n void *world_pointer = NULL; \/\/ pointer to the world (draw list).\n std::string vertex_shader; \/\/ filename of vertex shader.\n std::string fragment_shader; \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct\n{\n void *shader_pointer = NULL; \/\/ pointer to the shader.\n std::string texture_file_format; \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n std::string texture_filename; \/\/ filename of the model file.\n std::string image_path;\n} TextureStruct;\n\ntypedef struct\n{\n GLuint nodeID;\n void *graph_pointer = NULL;\n glm::vec3 coordinate_vector;\n std::vector neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct\n{\n glm::vec3 coordinate_vector; \/\/ coordinate vector.\n GLfloat rotate_angle = NAN; \/\/ rotate angle.\n glm::vec3 rotate_vector; \/\/ rotate vector.\n glm::vec3 translate_vector; \/\/ translate vector.\n glm::mat4 model_matrix; \/\/ model matrix.\n glm::mat4 MVP_matrix; \/\/ model view projection matrix.\n void *species_pointer = NULL; \/\/ pointer to the species.\n} ObjectStruct;\n\ntypedef struct\n{\n \/\/ used for all files (for all species).\n void *texture_pointer = NULL; \/\/ pointer to the texture object.\n std::string model_file_format; \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n \/\/ TODO: add support for `\"SRTM\"`.\n std::string vertex_shader; \/\/ filename of vertex shader.\n std::string fragment_shader; \/\/ filename of fragment shader.\n glm::vec3 lightPos; \/\/ light position.\n std::vector object_vector; \/\/ vector of individual objects of this species.\n bool is_world; \/\/ worlds currently do not rotate nor translate.\n std::string coordinate_system; \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n double world_radius; \/\/ radius of sea level in meters. used only for worlds.\n\n \/\/ for `\"bmp\"` model files.\n std::string model_filename; \/\/ filename of the model file.\n std::string color_channel; \/\/ color channel to use for altitude data.\n} SpeciesStruct;\n\ntypedef struct\n{\n GLuint screen_width;\n GLuint screen_height;\n GLuint x;\n GLuint y;\n GLuint text_size;\n GLuint font_size;\n const char *text;\n const char *char_font_texture_file_format;\n const char *horizontal_alignment;\n const char *vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n double rho;\n double theta;\n double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct\n{\n double southern_latitude;\n double northern_latitude;\n double western_longitude;\n double eastern_longitude;\n} SphericalWorldStruct;\n\nextern SphericalCoordinatesStruct spherical_position;\n\n#endif\n`typedef struct {` ... `} SpeciesStruct`: Muuttuja `is_world`.#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ uint32_t etc.\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \n#endif\n\n#ifndef WINDOW_WIDTH\n#define WINDOW_WIDTH (1600.0f)\n#endif\n\n#ifndef WINDOW_HEIGHT\n#define WINDOW_HEIGHT (900.0f)\n#endif\n\n#ifndef ASPECT_RATIO\n#define ASPECT_RATIO (WINDOW_WIDTH \/ WINDOW_HEIGHT)\n#endif\n\n#ifndef PI\n#define PI 3.14159265359f\n#endif\n\n#ifndef EARTH_RADIUS\n#define EARTH_RADIUS 6371000.0f\n#endif\n\n#ifndef TEXT_SIZE\n#define TEXT_SIZE 40\n#endif\n\n#ifndef FONT_SIZE\n#define FONT_SIZE 16\n#endif\n\n#ifndef MAX_FPS\n#define MAX_FPS 60\n#endif\n\nextern glm::vec3 position;\nextern GLfloat gravity;\nextern bool inFlightmode;\nextern GLfloat fallSpeed;\nextern double horizontalAngle;\nextern double verticalAngle;\nextern GLfloat initialFoV;\nextern double earth_radius;\nextern bool hasMouseEverMoved;\nextern bool is_invert_mouse_in_use;\nextern bool is_key_I_released;\nextern bool is_world_loaded; \/\/ no more than one world object can be loaded. TODO: check that no more than one world is loaded!\nextern bool is_world_spherical;\n\ntypedef struct\n{\n void *world_pointer = NULL; \/\/ pointer to the world (draw list).\n std::string vertex_shader; \/\/ filename of vertex shader.\n std::string fragment_shader; \/\/ filename of fragment shader.\n} ShaderStruct;\n\ntypedef struct\n{\n void *shader_pointer = NULL; \/\/ pointer to the shader.\n std::string texture_file_format; \/\/ type of the texture file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"dds\"`\/`\"DDS\"`.\n std::string texture_filename; \/\/ filename of the model file.\n std::string image_path;\n} TextureStruct;\n\ntypedef struct\n{\n GLuint nodeID;\n void *graph_pointer = NULL;\n glm::vec3 coordinate_vector;\n std::vector neighbor_nodeIDs;\n} NodeStruct;\n\ntypedef struct\n{\n glm::vec3 coordinate_vector; \/\/ coordinate vector.\n GLfloat rotate_angle = NAN; \/\/ rotate angle.\n glm::vec3 rotate_vector; \/\/ rotate vector.\n glm::vec3 translate_vector; \/\/ translate vector.\n glm::mat4 model_matrix; \/\/ model matrix.\n glm::mat4 MVP_matrix; \/\/ model view projection matrix.\n void *species_pointer = NULL; \/\/ pointer to the species.\n} ObjectStruct;\n\ntypedef struct\n{\n \/\/ used for all files (for all species).\n void *texture_pointer = NULL; \/\/ pointer to the texture object.\n std::string model_file_format; \/\/ type of the model file. supported file formats so far: `\"bmp\"`\/`\"BMP\"`, `\"obj\"`\/`\"OBJ\"`.\n \/\/ TODO: add support for `\"SRTM\"`.\n std::string vertex_shader; \/\/ filename of vertex shader.\n std::string fragment_shader; \/\/ filename of fragment shader.\n glm::vec3 lightPos; \/\/ light position.\n std::vector object_vector; \/\/ vector of individual objects of this species.\n bool is_world = false; \/\/ worlds currently do not rotate nor translate.\n std::string coordinate_system; \/\/ used only for worlds (`is_world` == `true`). valid values: `\"cartesian\"`.\n \/\/ TODO: add support for `\"spherical\"`. `\"spherical\"` is used eg. in SRTM heightmaps.\n double world_radius; \/\/ radius of sea level in meters. used only for worlds.\n\n \/\/ for `\"bmp\"` model files.\n std::string model_filename; \/\/ filename of the model file.\n std::string color_channel; \/\/ color channel to use for altitude data.\n} SpeciesStruct;\n\ntypedef struct\n{\n GLuint screen_width;\n GLuint screen_height;\n GLuint x;\n GLuint y;\n GLuint text_size;\n GLuint font_size;\n const char *text;\n const char *char_font_texture_file_format;\n const char *horizontal_alignment;\n const char *vertical_alignment;\n} PrintingStruct;\n\ntypedef struct\n{\n double rho;\n double theta;\n double phi;\n} SphericalCoordinatesStruct;\n\ntypedef struct\n{\n double southern_latitude;\n double northern_latitude;\n double western_longitude;\n double eastern_longitude;\n} SphericalWorldStruct;\n\nextern SphericalCoordinatesStruct spherical_position;\n\n#endif\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2015 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"nwchemjson.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace Avogadro {\nnamespace QuantumIO {\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nusing Json::Value;\nusing Json::Reader;\nusing Json::StyledStreamWriter;\n\nusing Core::Array;\nusing Core::Atom;\nusing Core::BasisSet;\nusing Core::Bond;\nusing Core::CrystalTools;\nusing Core::Elements;\nusing Core::GaussianSet;\nusing Core::Molecule;\nusing Core::Variant;\nusing Core::split;\n\nNWChemJson::NWChemJson()\n{\n}\n\nNWChemJson::~NWChemJson()\n{\n}\n\nbool NWChemJson::read(std::istream &file, Molecule &molecule)\n{\n Value root;\n Reader reader;\n bool ok = reader.parse(file, root);\n if (!ok) {\n appendError(\"Error parsing JSON: \" + reader.getFormatedErrorMessages());\n return false;\n }\n\n if (!root.isObject()) {\n appendError(\"Error: Input is not a JSON object.\");\n return false;\n }\n\n Value simulation = root[\"simulation\"];\n if (simulation.empty()) {\n appendError(\"Error: no \\\"simulation\\\" key found.\");\n return false;\n }\n\n \/\/ Scan the calculations array for calculationSetup.molecule objects.\n Value calculations = simulation[\"calculations\"];\n if (calculations.empty() || !calculations.isArray()) {\n appendError(\"Error: no \\\"calculations\\\" array found.\");\n return false;\n }\n\n \/\/ Iterate through the objects in the array, and print out any molecules.\n Value moleculeArray(Json::arrayValue);\n Value basisSetArray(Json::arrayValue);\n Value calculationVib;\n Value molecularOrbitals;\n int numberOfElectrons = 0;\n for (size_t i = 0; i < calculations.size(); ++i) {\n Value calcObj = calculations.get(i, \"\");\n if (calcObj.isObject()) {\n string calcType = calcObj[\"calculationType\"].asString();\n \/\/ Store the last vibrational frequencies calculation object.\n if (calcType == \"vibrationalModes\")\n calculationVib = calcObj;\n Value calcSetup = calcObj[\"calculationSetup\"];\n Value calcMol = calcSetup[\"molecule\"];\n numberOfElectrons = calcSetup[\"numberOfElectrons\"].asInt();\n if (!calcMol.isNull() && calcMol.isObject())\n moleculeArray.append(calcMol);\n Value basisSet = calcSetup[\"basisSet\"];\n if (!basisSet.isNull() && basisSet.isObject())\n basisSetArray.append(basisSet);\n\n Value calcResults = calcObj[\"calculationResults\"];\n calcMol = calcResults[\"molecule\"];\n if (!calcMol.isNull() && calcMol.isObject())\n moleculeArray.append(calcMol);\n \/\/ There is currently one id for all, just get the last one we find.\n if (!calcResults[\"molecularOrbitals\"].isNull()\n && calcResults[\"molecularOrbitals\"].isObject())\n molecularOrbitals = calcResults[\"molecularOrbitals\"];\n }\n }\n\n \/\/ For now, we are just grabbing the \"last\" molecule, and using that. This\n \/\/ needs more complex logic to step through the file and do it properly.\n Value finalMol = moleculeArray.get(moleculeArray.size() - 1, 0);\n Value atoms = finalMol[\"atoms\"];\n if (atoms.isArray()) {\n for (size_t i = 0; i < atoms.size(); ++i) {\n Value jsonAtom = atoms.get(i, 0);\n if (jsonAtom.isNull() || !jsonAtom.isObject())\n continue;\n Atom a =\n molecule.addAtom(static_cast(jsonAtom[\"elementNumber\"]\n .asInt()));\n Value pos = jsonAtom[\"cartesianCoordinates\"][\"value\"];\n Vector3 position(pos.get(Json::Value::ArrayIndex(0), 0.0).asDouble(),\n pos.get(Json::Value::ArrayIndex(1), 0.0).asDouble(),\n pos.get(Json::Value::ArrayIndex(2), 0.0).asDouble());\n string units = jsonAtom[\"cartesianCoordinates\"][\"units\"].asString();\n if (units == \"bohr\")\n position *= BOHR_TO_ANGSTROM_D;\n a.setPosition3d(position);\n }\n }\n \/\/ Perceive bonds for the molecule.\n molecule.perceiveBondsSimple();\n\n \/\/ Add in the electronic structure information if available.\n if (molecularOrbitals.isObject()\n && molecularOrbitals[\"atomicOrbitalDescriptions\"].isArray()) {\n Value basisSet = basisSetArray.get(basisSetArray.size() - 1, 0);\n Value orbDesc = molecularOrbitals[\"atomicOrbitalDescriptions\"];\n\n \/\/ Figure out the mapping of basis set to molecular orbitals.\n Array atomNumber;\n Array atomSymbol;\n for (size_t i = 0; i < orbDesc.size(); ++i) {\n string desc = orbDesc.get(i, 0).asString();\n vector parts = split(desc, ' ');\n assert(parts.size() == 3);\n int num = Core::lexicalCast(parts[0]);\n if (atomNumber.size() > 0 && atomNumber.back() == num)\n continue;\n atomNumber.push_back(num);\n atomSymbol.push_back(parts[1]);\n }\n\n \/\/ Now create the structure, and expand out the orbitals.\n GaussianSet *basis = new GaussianSet;\n basis->setMolecule(&molecule);\n for (size_t i = 0; i < atomSymbol.size(); ++i) {\n string symbol = atomSymbol[i];\n Value basisFunctions = basisSet[\"basisFunctions\"];\n Value currentFunction;\n for (size_t j = 0; j < basisFunctions.size(); ++j) {\n currentFunction = basisFunctions.get(j, 0);\n\n string elementType;\n if (currentFunction.isMember(\"elementLabel\"))\n elementType = currentFunction[\"elementLabel\"].asString();\n else if (currentFunction.isMember(\"elementType\"))\n elementType = currentFunction[\"elementType\"].asString();\n\n if (elementType == symbol)\n break;\n\n currentFunction = Json::nullValue;\n }\n\n if (currentFunction.isNull())\n break;\n\n Value contraction = currentFunction[\"basisSetContraction\"];\n bool spherical = currentFunction[\"basisSetHarmonicType\"].asString()\n == \"spherical\";\n for (size_t j = 0; j < contraction.size(); ++j) {\n Value contractionShell = contraction.get(j, Json::nullValue);\n string shellType;\n if (contractionShell.isMember(\"basisSetShell\"))\n shellType = contractionShell[\"basisSetShell\"].asString();\n else if (contractionShell.isMember(\"basisSetShellType\"))\n shellType = contractionShell[\"basisSetShellType\"].asString();\n Value exponent = contractionShell[\"basisSetExponent\"];\n Value coefficient = contractionShell[\"basisSetCoefficient\"];\n assert(exponent.size() == coefficient.size());\n GaussianSet::orbital type = GaussianSet::UU;\n if (shellType == \"s\")\n type = GaussianSet::S;\n else if (shellType == \"p\")\n type = GaussianSet::P;\n else if (shellType == \"d\" && spherical)\n type = GaussianSet::D5;\n else if (shellType == \"d\")\n type = GaussianSet::D;\n else if (shellType == \"f\" && spherical)\n type = GaussianSet::F7;\n else if (shellType == \"f\")\n type == GaussianSet::F;\n\n if (type != GaussianSet::UU) {\n int b = basis->addBasis(i, type);\n for (size_t k = 0; k < exponent.size(); ++k) {\n basis->addGto(b, coefficient.get(k, 0).asDouble(),\n exponent.get(k, 0).asDouble());\n }\n }\n }\n }\n \/\/ Now to add the molecular orbital coefficients.\n Value moCoeffs = molecularOrbitals[\"molecularOrbital\"];\n vector coeffArray;\n for (size_t i = 0; i < moCoeffs.size(); ++i) {\n Value coeff = moCoeffs.get(i, Json::nullValue)[\"moCoefficients\"];\n for (size_t j = 0; j < coeff.size(); ++j)\n coeffArray.push_back(coeff.get(j, 0).asDouble());\n }\n basis->setMolecularOrbitals(coeffArray);\n basis->setElectronCount(numberOfElectrons);\n molecule.setBasisSet(basis);\n }\n\n \/\/ Now to see if there was a vibrational frequencies calculation.\n if (!calculationVib.isNull() && calculationVib.isObject()) {\n Value normalModes = calculationVib[\"calculationResults\"][\"normalModes\"];\n if (!normalModes.isNull() && normalModes.isArray()) {\n Array frequencies;\n Array intensities;\n Array< Array > Lx;\n for (size_t i = 0; i < normalModes.size(); ++i) {\n Value mode = normalModes.get(i, \"\");\n frequencies.push_back(mode[\"normalModeFrequency\"][\"value\"].asDouble());\n intensities.push_back(mode[\"normalModeInfraRedIntensity\"][\"value\"].asDouble());\n Value lx = mode[\"normalModeVector\"][\"value\"];\n if (!lx.empty() && lx.isArray()) {\n Array modeLx;\n modeLx.resize(lx.size() \/ 3);\n for (size_t k = 0; k < lx.size(); ++k)\n modeLx[k \/ 3][k % 3] = lx.get(k, 0).asDouble();\n Lx.push_back(modeLx);\n }\n }\n molecule.setVibrationFrequencies(frequencies);\n molecule.setVibrationIntensities(intensities);\n molecule.setVibrationLx(Lx);\n }\n }\n\n return true;\n}\n\nbool NWChemJson::write(std::ostream &file, const Molecule &molecule)\n{\n return false;\n}\n\nvector NWChemJson::fileExtensions() const\n{\n vector ext;\n ext.push_back(\"json\");\n ext.push_back(\"nwjson\");\n return ext;\n}\n\nvector NWChemJson::mimeTypes() const\n{\n vector mime;\n mime.push_back(\"chemical\/x-nwjson\");\n return mime;\n}\n\n} \/\/ end QuantumIO namespace\n} \/\/ end Avogadro namespace\nRead in additional MO data when available\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2015 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"nwchemjson.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace Avogadro {\nnamespace QuantumIO {\n\nusing std::string;\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\nusing Json::Value;\nusing Json::Reader;\nusing Json::StyledStreamWriter;\n\nusing Core::Array;\nusing Core::Atom;\nusing Core::BasisSet;\nusing Core::Bond;\nusing Core::CrystalTools;\nusing Core::Elements;\nusing Core::GaussianSet;\nusing Core::Molecule;\nusing Core::Variant;\nusing Core::split;\n\nNWChemJson::NWChemJson()\n{\n}\n\nNWChemJson::~NWChemJson()\n{\n}\n\nbool NWChemJson::read(std::istream &file, Molecule &molecule)\n{\n Value root;\n Reader reader;\n bool ok = reader.parse(file, root);\n if (!ok) {\n appendError(\"Error parsing JSON: \" + reader.getFormatedErrorMessages());\n return false;\n }\n\n if (!root.isObject()) {\n appendError(\"Error: Input is not a JSON object.\");\n return false;\n }\n\n Value simulation = root[\"simulation\"];\n if (simulation.empty()) {\n appendError(\"Error: no \\\"simulation\\\" key found.\");\n return false;\n }\n\n \/\/ Scan the calculations array for calculationSetup.molecule objects.\n Value calculations = simulation[\"calculations\"];\n if (calculations.empty() || !calculations.isArray()) {\n appendError(\"Error: no \\\"calculations\\\" array found.\");\n return false;\n }\n\n \/\/ Iterate through the objects in the array, and print out any molecules.\n Value moleculeArray(Json::arrayValue);\n Value basisSetArray(Json::arrayValue);\n Value calculationVib;\n Value molecularOrbitals;\n int numberOfElectrons = 0;\n for (size_t i = 0; i < calculations.size(); ++i) {\n Value calcObj = calculations.get(i, \"\");\n if (calcObj.isObject()) {\n string calcType = calcObj[\"calculationType\"].asString();\n \/\/ Store the last vibrational frequencies calculation object.\n if (calcType == \"vibrationalModes\")\n calculationVib = calcObj;\n Value calcSetup = calcObj[\"calculationSetup\"];\n Value calcMol = calcSetup[\"molecule\"];\n numberOfElectrons = calcSetup[\"numberOfElectrons\"].asInt();\n if (!calcMol.isNull() && calcMol.isObject())\n moleculeArray.append(calcMol);\n Value basisSet = calcSetup[\"basisSet\"];\n if (!basisSet.isNull() && basisSet.isObject())\n basisSetArray.append(basisSet);\n\n Value calcResults = calcObj[\"calculationResults\"];\n calcMol = calcResults[\"molecule\"];\n if (!calcMol.isNull() && calcMol.isObject())\n moleculeArray.append(calcMol);\n \/\/ There is currently one id for all, just get the last one we find.\n if (!calcResults[\"molecularOrbitals\"].isNull()\n && calcResults[\"molecularOrbitals\"].isObject())\n molecularOrbitals = calcResults[\"molecularOrbitals\"];\n }\n }\n\n \/\/ For now, we are just grabbing the \"last\" molecule, and using that. This\n \/\/ needs more complex logic to step through the file and do it properly.\n Value finalMol = moleculeArray.get(moleculeArray.size() - 1, 0);\n Value atoms = finalMol[\"atoms\"];\n if (atoms.isArray()) {\n for (size_t i = 0; i < atoms.size(); ++i) {\n Value jsonAtom = atoms.get(i, 0);\n if (jsonAtom.isNull() || !jsonAtom.isObject())\n continue;\n Atom a =\n molecule.addAtom(static_cast(jsonAtom[\"elementNumber\"]\n .asInt()));\n Value pos = jsonAtom[\"cartesianCoordinates\"][\"value\"];\n Vector3 position(pos.get(Json::Value::ArrayIndex(0), 0.0).asDouble(),\n pos.get(Json::Value::ArrayIndex(1), 0.0).asDouble(),\n pos.get(Json::Value::ArrayIndex(2), 0.0).asDouble());\n string units = jsonAtom[\"cartesianCoordinates\"][\"units\"].asString();\n if (units == \"bohr\")\n position *= BOHR_TO_ANGSTROM_D;\n a.setPosition3d(position);\n }\n }\n \/\/ Perceive bonds for the molecule.\n molecule.perceiveBondsSimple();\n\n \/\/ Add in the electronic structure information if available.\n if (molecularOrbitals.isObject()\n && molecularOrbitals[\"atomicOrbitalDescriptions\"].isArray()) {\n Value basisSet = basisSetArray.get(basisSetArray.size() - 1, 0);\n Value orbDesc = molecularOrbitals[\"atomicOrbitalDescriptions\"];\n\n \/\/ Figure out the mapping of basis set to molecular orbitals.\n Array atomNumber;\n Array atomSymbol;\n for (size_t i = 0; i < orbDesc.size(); ++i) {\n string desc = orbDesc.get(i, 0).asString();\n vector parts = split(desc, ' ');\n assert(parts.size() == 3);\n int num = Core::lexicalCast(parts[0]);\n if (atomNumber.size() > 0 && atomNumber.back() == num)\n continue;\n atomNumber.push_back(num);\n atomSymbol.push_back(parts[1]);\n }\n\n \/\/ Now create the structure, and expand out the orbitals.\n GaussianSet *basis = new GaussianSet;\n basis->setMolecule(&molecule);\n for (size_t i = 0; i < atomSymbol.size(); ++i) {\n string symbol = atomSymbol[i];\n Value basisFunctions = basisSet[\"basisFunctions\"];\n Value currentFunction;\n for (size_t j = 0; j < basisFunctions.size(); ++j) {\n currentFunction = basisFunctions.get(j, 0);\n\n string elementType;\n if (currentFunction.isMember(\"elementLabel\"))\n elementType = currentFunction[\"elementLabel\"].asString();\n else if (currentFunction.isMember(\"elementType\"))\n elementType = currentFunction[\"elementType\"].asString();\n\n if (elementType == symbol)\n break;\n\n currentFunction = Json::nullValue;\n }\n\n if (currentFunction.isNull())\n break;\n\n Value contraction = currentFunction[\"basisSetContraction\"];\n bool spherical = currentFunction[\"basisSetHarmonicType\"].asString()\n == \"spherical\";\n for (size_t j = 0; j < contraction.size(); ++j) {\n Value contractionShell = contraction.get(j, Json::nullValue);\n string shellType;\n if (contractionShell.isMember(\"basisSetShell\"))\n shellType = contractionShell[\"basisSetShell\"].asString();\n else if (contractionShell.isMember(\"basisSetShellType\"))\n shellType = contractionShell[\"basisSetShellType\"].asString();\n Value exponent = contractionShell[\"basisSetExponent\"];\n Value coefficient = contractionShell[\"basisSetCoefficient\"];\n assert(exponent.size() == coefficient.size());\n GaussianSet::orbital type = GaussianSet::UU;\n if (shellType == \"s\")\n type = GaussianSet::S;\n else if (shellType == \"p\")\n type = GaussianSet::P;\n else if (shellType == \"d\" && spherical)\n type = GaussianSet::D5;\n else if (shellType == \"d\")\n type = GaussianSet::D;\n else if (shellType == \"f\" && spherical)\n type = GaussianSet::F7;\n else if (shellType == \"f\")\n type == GaussianSet::F;\n\n if (type != GaussianSet::UU) {\n int b = basis->addBasis(i, type);\n for (size_t k = 0; k < exponent.size(); ++k) {\n basis->addGto(b, coefficient.get(k, 0).asDouble(),\n exponent.get(k, 0).asDouble());\n }\n }\n }\n }\n \/\/ Now to add the molecular orbital coefficients.\n Value moCoeffs = molecularOrbitals[\"molecularOrbital\"];\n vector coeffArray;\n vector energyArray;\n vector occArray;\n vector numArray;\n for (size_t i = 0; i < moCoeffs.size(); ++i) {\n Value currentMO = moCoeffs.get(i, Json::nullValue);\n Value coeff = currentMO[\"moCoefficients\"];\n for (size_t j = 0; j < coeff.size(); ++j)\n coeffArray.push_back(coeff.get(j, 0).asDouble());\n if (currentMO.isMember(\"orbitalEnergy\"))\n energyArray.push_back(currentMO[\"orbitalEnergy\"][\"value\"].asDouble());\n if (currentMO.isMember(\"orbitalOccupancy\"))\n occArray.push_back(static_cast(currentMO[\"orbitalOccupancy\"].asInt()));\n if (currentMO.isMember(\"orbitalNumber\"))\n numArray.push_back(static_cast(currentMO[\"orbitalNumber\"].asInt()));\n }\n basis->setMolecularOrbitals(coeffArray);\n basis->setMolecularOrbtitalEnergy(energyArray);\n basis->setMolecularOrbtitalOccupancy(occArray);\n basis->setMolecularOrbtitalNumber(numArray);\n basis->setElectronCount(numberOfElectrons);\n molecule.setBasisSet(basis);\n }\n\n \/\/ Now to see if there was a vibrational frequencies calculation.\n if (!calculationVib.isNull() && calculationVib.isObject()) {\n Value normalModes = calculationVib[\"calculationResults\"][\"normalModes\"];\n if (!normalModes.isNull() && normalModes.isArray()) {\n Array frequencies;\n Array intensities;\n Array< Array > Lx;\n for (size_t i = 0; i < normalModes.size(); ++i) {\n Value mode = normalModes.get(i, \"\");\n frequencies.push_back(mode[\"normalModeFrequency\"][\"value\"].asDouble());\n intensities.push_back(mode[\"normalModeInfraRedIntensity\"][\"value\"].asDouble());\n Value lx = mode[\"normalModeVector\"][\"value\"];\n if (!lx.empty() && lx.isArray()) {\n Array modeLx;\n modeLx.resize(lx.size() \/ 3);\n for (size_t k = 0; k < lx.size(); ++k)\n modeLx[k \/ 3][k % 3] = lx.get(k, 0).asDouble();\n Lx.push_back(modeLx);\n }\n }\n molecule.setVibrationFrequencies(frequencies);\n molecule.setVibrationIntensities(intensities);\n molecule.setVibrationLx(Lx);\n }\n }\n\n return true;\n}\n\nbool NWChemJson::write(std::ostream &file, const Molecule &molecule)\n{\n return false;\n}\n\nvector NWChemJson::fileExtensions() const\n{\n vector ext;\n ext.push_back(\"json\");\n ext.push_back(\"nwjson\");\n return ext;\n}\n\nvector NWChemJson::mimeTypes() const\n{\n vector mime;\n mime.push_back(\"chemical\/x-nwjson\");\n return mime;\n}\n\n} \/\/ end QuantumIO namespace\n} \/\/ end Avogadro namespace\n<|endoftext|>"} {"text":"\/***************************************************************************\n * common\/version.cpp\n *\n * Part of the STXXL. See http:\/\/stxxl.sourceforge.net\n *\n * Copyright (C) 2007, 2008, 2011 Andreas Beckmann \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n **************************************************************************\/\n\n#include \n\n#ifdef STXXL_BOOST_CONFIG\n#include \n#endif\n\n#define stringify(x) #x\n#define STXXL_VERSION_STRING_MA_MI_PL stringify(STXXL_VERSION_MAJOR) \".\" stringify(STXXL_VERSION_MINOR) \".\" stringify(STXXL_VERSION_PATCHLEVEL)\n\n\/\/ version.defs gets created if a snapshot\/beta\/rc\/release is done\n#ifdef HAVE_VERSION_DEFS\n#include \"version.defs\"\n#endif\n\n\/\/ version_svn.defs gets created if stxxl is built from SVN\n#ifdef HAVE_VERSION_SVN_DEFS\n#include \"version_svn.defs\"\n#endif\n\n\n__STXXL_BEGIN_NAMESPACE\n\nint version_major()\n{\n return STXXL_VERSION_MAJOR;\n};\n\nint version_minor()\n{\n return STXXL_VERSION_MINOR;\n}\n\nint version_patchlevel()\n{\n return STXXL_VERSION_PATCHLEVEL;\n}\n\n\/\/ FIXME: this currently only works for GNU-like systems,\n\/\/ there are no details available on windows platform\n\nconst char * get_version_string()\n{\n return \"STXXL\"\n#ifdef STXXL_VERSION_STRING_SVN_BRANCH\n \" (branch: \" STXXL_VERSION_STRING_SVN_BRANCH \")\"\n#endif\n \" v\"\n STXXL_VERSION_STRING_MA_MI_PL\n#ifdef STXXL_VERSION_STRING_DATE\n \"-\" STXXL_VERSION_STRING_DATE\n#endif\n#ifdef STXXL_VERSION_STRING_SVN_REVISION\n \" (SVN r\" STXXL_VERSION_STRING_SVN_REVISION \")\"\n#endif\n#ifdef STXXL_VERSION_STRING_PHASE\n \" (\" STXXL_VERSION_STRING_PHASE \")\"\n#else\n \" (prerelease)\"\n#endif\n#ifdef STXXL_VERSION_STRING_COMMENT\n \" (\" STXXL_VERSION_STRING_COMMENT \")\"\n#endif\n#ifdef __MCSTL__\n \" + MCSTL\"\n#ifdef MCSTL_VERSION_STRING_DATE\n \" \" MCSTL_VERSION_STRING_DATE\n#endif\n#ifdef MCSTL_VERSION_STRING_SVN_REVISION\n \" (SVN r\" MCSTL_VERSION_STRING_SVN_REVISION \")\"\n#endif\n#endif\n#ifdef STXXL_BOOST_CONFIG\n \" + Boost \"\n#define Y(x) # x\n#define X(x) Y(x)\n X(BOOST_VERSION)\n#undef X\n#undef Y\n#endif\n ;\n}\n\n__STXXL_END_NAMESPACE\n\n\/\/ vim: et:ts=4:sw=4\nfix stringify() macro, needs to be nested\/***************************************************************************\n * common\/version.cpp\n *\n * Part of the STXXL. See http:\/\/stxxl.sourceforge.net\n *\n * Copyright (C) 2007, 2008, 2011 Andreas Beckmann \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n **************************************************************************\/\n\n#include \n\n#ifdef STXXL_BOOST_CONFIG\n#include \n#endif\n\n#define stringify_(x) #x\n#define stringify(x) stringify_(x)\n#define STXXL_VERSION_STRING_MA_MI_PL stringify(STXXL_VERSION_MAJOR) \".\" stringify(STXXL_VERSION_MINOR) \".\" stringify(STXXL_VERSION_PATCHLEVEL)\n\n\/\/ version.defs gets created if a snapshot\/beta\/rc\/release is done\n#ifdef HAVE_VERSION_DEFS\n#include \"version.defs\"\n#endif\n\n\/\/ version_svn.defs gets created if stxxl is built from SVN\n#ifdef HAVE_VERSION_SVN_DEFS\n#include \"version_svn.defs\"\n#endif\n\n\n__STXXL_BEGIN_NAMESPACE\n\nint version_major()\n{\n return STXXL_VERSION_MAJOR;\n};\n\nint version_minor()\n{\n return STXXL_VERSION_MINOR;\n}\n\nint version_patchlevel()\n{\n return STXXL_VERSION_PATCHLEVEL;\n}\n\n\/\/ FIXME: this currently only works for GNU-like systems,\n\/\/ there are no details available on windows platform\n\nconst char * get_version_string()\n{\n return \"STXXL\"\n#ifdef STXXL_VERSION_STRING_SVN_BRANCH\n \" (branch: \" STXXL_VERSION_STRING_SVN_BRANCH \")\"\n#endif\n \" v\"\n STXXL_VERSION_STRING_MA_MI_PL\n#ifdef STXXL_VERSION_STRING_DATE\n \"-\" STXXL_VERSION_STRING_DATE\n#endif\n#ifdef STXXL_VERSION_STRING_SVN_REVISION\n \" (SVN r\" STXXL_VERSION_STRING_SVN_REVISION \")\"\n#endif\n#ifdef STXXL_VERSION_STRING_PHASE\n \" (\" STXXL_VERSION_STRING_PHASE \")\"\n#else\n \" (prerelease)\"\n#endif\n#ifdef STXXL_VERSION_STRING_COMMENT\n \" (\" STXXL_VERSION_STRING_COMMENT \")\"\n#endif\n#ifdef __MCSTL__\n \" + MCSTL\"\n#ifdef MCSTL_VERSION_STRING_DATE\n \" \" MCSTL_VERSION_STRING_DATE\n#endif\n#ifdef MCSTL_VERSION_STRING_SVN_REVISION\n \" (SVN r\" MCSTL_VERSION_STRING_SVN_REVISION \")\"\n#endif\n#endif\n#ifdef STXXL_BOOST_CONFIG\n \" + Boost \"\n#define Y(x) # x\n#define X(x) Y(x)\n X(BOOST_VERSION)\n#undef X\n#undef Y\n#endif\n ;\n}\n\n__STXXL_END_NAMESPACE\n\n\/\/ vim: et:ts=4:sw=4\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCell.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkCell.h\"\n\n\/\/ Construct cell.\nvtkCell::vtkCell()\n{\n this->Points = vtkPoints::New();\n this->PointIds = vtkIdList::New();\n} \n\nvtkCell::~vtkCell()\n{\n this->Points->Delete();\n this->PointIds->Delete();\n}\n\n\n\/\/\n\/\/ Instantiate cell from outside\n\/\/\nvoid vtkCell::Initialize(int npts, int *pts, vtkPoints *p)\n{\n this->PointIds->Reset();\n this->Points->Reset();\n\n for (int i=0; iPointIds->InsertId(i,pts[i]);\n this->Points->InsertPoint(i,p->GetPoint(pts[i]));\n }\n}\n \nvoid vtkCell::ShallowCopy(vtkCell *c)\n{\n this->Points->ShallowCopy(c->Points);\n this->PointIds->ShallowCopy(c->PointIds);\n}\n\nvoid vtkCell::DeepCopy(vtkCell *c)\n{\n this->Points->DeepCopy(c->Points);\n this->PointIds->DeepCopy(c->PointIds);\n}\n\n#define VTK_RIGHT 0\n#define VTK_LEFT 1\n#define VTK_MIDDLE 2\n\n\/\/ Bounding box intersection modified from Graphics Gems Vol I.\n\/\/ Note: the intersection ray is assumed normalized, such that\n\/\/ valid intersections can only occur between [0,1]. Method returns non-zero\n\/\/ value if bounding box is hit. Origin[3] starts the ray, dir[3] is the \n\/\/ components of the ray in the x-y-z directions, coord[3] is the location \n\/\/ of hit, and t is the parametric coordinate along line.\nchar vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3], \n float coord[3], float& t)\n{\n char inside=1;\n char quadrant[3];\n int i, whichPlane=0;\n float maxT[3], candidatePlane[3];\n\/\/\n\/\/ First find closest planes\n\/\/\n for (i=0; i<3; i++) \n {\n if ( origin[i] < bounds[2*i] ) \n {\n quadrant[i] = VTK_LEFT;\n candidatePlane[i] = bounds[2*i];\n inside = 0;\n }\n else if ( origin[i] > bounds[2*i+1] ) \n {\n quadrant[i] = VTK_RIGHT;\n candidatePlane[i] = bounds[2*i+1];\n inside = 0;\n }\n else \n {\n quadrant[i] = VTK_MIDDLE;\n }\n }\n\/\/\n\/\/ Check whether origin of ray is inside bbox\n\/\/\n if (inside) \n {\n coord[0] = origin[0];\n coord[1] = origin[1];\n coord[2] = origin[2];\n t = 0;\n return 1;\n }\n \n\/\/\n\/\/ Calculate parametric distances to plane\n\/\/\n for (i=0; i<3; i++)\n {\n if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 )\n {\n maxT[i] = (candidatePlane[i]-origin[i]) \/ dir[i];\n }\n else\n {\n maxT[i] = -1.0;\n }\n }\n\/\/\n\/\/ Find the largest parametric value of intersection\n\/\/\n for (i=0; i<3; i++)\n {\n if ( maxT[whichPlane] < maxT[i] )\n {\n whichPlane = i;\n }\n }\n\/\/\n\/\/ Check for valid intersection along line\n\/\/\n if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 )\n {\n return 0;\n }\n else\n {\n t = maxT[whichPlane];\n }\n\/\/\n\/\/ Intersection point along line is okay. Check bbox.\n\/\/\n for (i=0; i<3; i++) \n {\n if (whichPlane != i) \n {\n coord[i] = origin[i] + maxT[whichPlane]*dir[i];\n if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] )\n\t{\n return 0;\n\t}\n } \n else \n {\n coord[i] = candidatePlane[i];\n }\n }\n\n return 1;\n}\n\n\/\/ Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer\n\/\/ to array of six float values.\nfloat *vtkCell::GetBounds ()\n{\n float *x;\n int i, numPts=this->Points->GetNumberOfPoints();\n\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;\n\n for (i=0; iPoints->GetPoint(i);\n\n this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]);\n this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]);\n this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]);\n this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]);\n this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]);\n this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]);\n \n }\n return this->Bounds;\n}\n\n\/\/ Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into\n\/\/ user provided array.\nvoid vtkCell::GetBounds(float bounds[6])\n{\n this->GetBounds();\n for (int i=0; i < 6; i++)\n {\n bounds[i] = this->Bounds[i];\n }\n}\n\n\/\/ Compute Length squared of cell (i.e., bounding box diagonal squared).\nfloat vtkCell::GetLength2 ()\n{\n float diff, l=0.0;\n int i;\n\n this->GetBounds();\n for (i=0; i<3; i++)\n {\n diff = this->Bounds[2*i+1] - this->Bounds[2*i];\n l += diff * diff;\n }\n \n return l;\n}\n\n\/\/ Return center of the cell in parametric coordinates.\n\/\/ Note that the parametric center is not always located \n\/\/ at (0.5,0.5,0.5). The return value is the subId that\n\/\/ the center is in (if a composite cell). If you want the\n\/\/ center in x-y-z space, invoke the EvaluateLocation() method.\nint vtkCell::GetParametricCenter(float pcoords[3])\n{\n pcoords[0] = pcoords[1] = pcoords[2] = 0.5;\n return 0;\n}\n\nvoid vtkCell::PrintSelf(ostream& os, vtkIndent indent)\n{\n int numIds=this->PointIds->GetNumberOfIds();\n\n vtkObject::PrintSelf(os,indent);\n\n os << indent << \"Number Of Points: \" << numIds << \"\\n\";\n\n if ( numIds > 0 )\n {\n float *bounds=this->GetBounds();\n\n os << indent << \"Bounds: \\n\";\n os << indent << \" Xmin,Xmax: (\" << bounds[0] << \", \" << bounds[1] << \")\\n\";\n os << indent << \" Ymin,Ymax: (\" << bounds[2] << \", \" << bounds[3] << \")\\n\";\n os << indent << \" Zmin,Zmax: (\" << bounds[4] << \", \" << bounds[5] << \")\\n\";\n\n os << indent << \" Point ids are: \";\n for (int i=0; i < numIds; i++)\n {\n os << this->PointIds->GetId(i);\n if ( i && !(i % 12) )\n\t{\n\tos << \"\\n\\t\";\n\t}\n else\n\t{\n\tif ( i != (numIds-1) )\n\t {\n\t os << \", \";\n\t }\n\t}\n }\n os << indent << \"\\n\";\n }\n}\nENH:Improved IdList performance\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCell.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkCell.h\"\n\n\/\/ Construct cell.\nvtkCell::vtkCell()\n{\n this->Points = vtkPoints::New();\n this->PointIds = vtkIdList::New();\n} \n\nvtkCell::~vtkCell()\n{\n this->Points->Delete();\n this->PointIds->Delete();\n}\n\n\n\/\/\n\/\/ Instantiate cell from outside\n\/\/\nvoid vtkCell::Initialize(int npts, int *pts, vtkPoints *p)\n{\n this->PointIds->Reset();\n this->Points->Reset();\n\n for (int i=0; iPointIds->InsertId(i,pts[i]);\n this->Points->InsertPoint(i,p->GetPoint(pts[i]));\n }\n}\n \nvoid vtkCell::ShallowCopy(vtkCell *c)\n{\n this->Points->ShallowCopy(c->Points);\n this->PointIds->DeepCopy(c->PointIds);\n}\n\nvoid vtkCell::DeepCopy(vtkCell *c)\n{\n this->Points->DeepCopy(c->Points);\n this->PointIds->DeepCopy(c->PointIds);\n}\n\n#define VTK_RIGHT 0\n#define VTK_LEFT 1\n#define VTK_MIDDLE 2\n\n\/\/ Bounding box intersection modified from Graphics Gems Vol I.\n\/\/ Note: the intersection ray is assumed normalized, such that\n\/\/ valid intersections can only occur between [0,1]. Method returns non-zero\n\/\/ value if bounding box is hit. Origin[3] starts the ray, dir[3] is the \n\/\/ components of the ray in the x-y-z directions, coord[3] is the location \n\/\/ of hit, and t is the parametric coordinate along line.\nchar vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3], \n float coord[3], float& t)\n{\n char inside=1;\n char quadrant[3];\n int i, whichPlane=0;\n float maxT[3], candidatePlane[3];\n\/\/\n\/\/ First find closest planes\n\/\/\n for (i=0; i<3; i++) \n {\n if ( origin[i] < bounds[2*i] ) \n {\n quadrant[i] = VTK_LEFT;\n candidatePlane[i] = bounds[2*i];\n inside = 0;\n }\n else if ( origin[i] > bounds[2*i+1] ) \n {\n quadrant[i] = VTK_RIGHT;\n candidatePlane[i] = bounds[2*i+1];\n inside = 0;\n }\n else \n {\n quadrant[i] = VTK_MIDDLE;\n }\n }\n\/\/\n\/\/ Check whether origin of ray is inside bbox\n\/\/\n if (inside) \n {\n coord[0] = origin[0];\n coord[1] = origin[1];\n coord[2] = origin[2];\n t = 0;\n return 1;\n }\n \n\/\/\n\/\/ Calculate parametric distances to plane\n\/\/\n for (i=0; i<3; i++)\n {\n if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 )\n {\n maxT[i] = (candidatePlane[i]-origin[i]) \/ dir[i];\n }\n else\n {\n maxT[i] = -1.0;\n }\n }\n\/\/\n\/\/ Find the largest parametric value of intersection\n\/\/\n for (i=0; i<3; i++)\n {\n if ( maxT[whichPlane] < maxT[i] )\n {\n whichPlane = i;\n }\n }\n\/\/\n\/\/ Check for valid intersection along line\n\/\/\n if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 )\n {\n return 0;\n }\n else\n {\n t = maxT[whichPlane];\n }\n\/\/\n\/\/ Intersection point along line is okay. Check bbox.\n\/\/\n for (i=0; i<3; i++) \n {\n if (whichPlane != i) \n {\n coord[i] = origin[i] + maxT[whichPlane]*dir[i];\n if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] )\n\t{\n return 0;\n\t}\n } \n else \n {\n coord[i] = candidatePlane[i];\n }\n }\n\n return 1;\n}\n\n\/\/ Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer\n\/\/ to array of six float values.\nfloat *vtkCell::GetBounds ()\n{\n float *x;\n int i, numPts=this->Points->GetNumberOfPoints();\n\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;\n\n for (i=0; iPoints->GetPoint(i);\n\n this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]);\n this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]);\n this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]);\n this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]);\n this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]);\n this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]);\n \n }\n return this->Bounds;\n}\n\n\/\/ Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into\n\/\/ user provided array.\nvoid vtkCell::GetBounds(float bounds[6])\n{\n this->GetBounds();\n for (int i=0; i < 6; i++)\n {\n bounds[i] = this->Bounds[i];\n }\n}\n\n\/\/ Compute Length squared of cell (i.e., bounding box diagonal squared).\nfloat vtkCell::GetLength2 ()\n{\n float diff, l=0.0;\n int i;\n\n this->GetBounds();\n for (i=0; i<3; i++)\n {\n diff = this->Bounds[2*i+1] - this->Bounds[2*i];\n l += diff * diff;\n }\n \n return l;\n}\n\n\/\/ Return center of the cell in parametric coordinates.\n\/\/ Note that the parametric center is not always located \n\/\/ at (0.5,0.5,0.5). The return value is the subId that\n\/\/ the center is in (if a composite cell). If you want the\n\/\/ center in x-y-z space, invoke the EvaluateLocation() method.\nint vtkCell::GetParametricCenter(float pcoords[3])\n{\n pcoords[0] = pcoords[1] = pcoords[2] = 0.5;\n return 0;\n}\n\nvoid vtkCell::PrintSelf(ostream& os, vtkIndent indent)\n{\n int numIds=this->PointIds->GetNumberOfIds();\n\n vtkObject::PrintSelf(os,indent);\n\n os << indent << \"Number Of Points: \" << numIds << \"\\n\";\n\n if ( numIds > 0 )\n {\n float *bounds=this->GetBounds();\n\n os << indent << \"Bounds: \\n\";\n os << indent << \" Xmin,Xmax: (\" << bounds[0] << \", \" << bounds[1] << \")\\n\";\n os << indent << \" Ymin,Ymax: (\" << bounds[2] << \", \" << bounds[3] << \")\\n\";\n os << indent << \" Zmin,Zmax: (\" << bounds[4] << \", \" << bounds[5] << \")\\n\";\n\n os << indent << \" Point ids are: \";\n for (int i=0; i < numIds; i++)\n {\n os << this->PointIds->GetId(i);\n if ( i && !(i % 12) )\n\t{\n\tos << \"\\n\\t\";\n\t}\n else\n\t{\n\tif ( i != (numIds-1) )\n\t {\n\t os << \", \";\n\t }\n\t}\n }\n os << indent << \"\\n\";\n }\n}\n<|endoftext|>"} {"text":"#include \"console.h\"\n\n#include \n#include \n#include \n\n#include \"defs.h\"\n#include \"command.h\"\n\n\nConsole::Console(){\n\n\tshell = new Shell();\n\thandler = new Handler(shell);\n}\n\nConsole::~Console(){\n\n\tdelete handler;\n\tdelete shell;\n}\n\nbool Console::start(){\n\n\twhile(!handler->isTerminated()){\n\n\t\t\/\/ getting the current path\n\t\tconst char* cur_path = shell->getPath();\n\t\t\/\/ printing the prompt\n\t\tstd::cout << PROMPT1 << cur_path << PROMPT2;\n\n\t\t\/\/ reading the line\n\t\tchar line[LINE_SIZE];\n\t\tstd::cin.getline(line, LINE_SIZE);\n\n\t\t\/\/ creating new Command object\n\t\t\/\/ TODO make static?\n\t\t\/\/Command* command = new Command(line);\t\t\n\t\t\/\/handler->execute(*command);\n\t\t\n\t\tCommand command(line);\n\t\t\n\t\t\/\/have handler object to execute the command\n\t\thandler->execute(command);\n\n\t}\n\n\treturn true;\n}using GNU readline and the arrows work as in bash (command history)#include \"console.h\"\n\n#include \n#include \n#include \n\n#include \"defs.h\"\n#include \"command.h\"\n\n\nConsole::Console(){\n\n\tshell = new Shell();\n\thandler = new Handler(shell);\n}\n\nConsole::~Console(){\n\n\tdelete handler;\n\tdelete shell;\n}\n\nbool Console::start(){\n\n\twhile(!handler->isTerminated()){\n\n\t\t\/\/ getting the current path\n\t\tconst char* cur_path = shell->getPath();\n\t\t\/\/ printing the prompt\n\t\tstd::cout << PROMPT1 << cur_path << PROMPT2;\n\n\t\t\n\t\tchar *line=(char*)NULL;\n\t\t\n\t\t\/***using GNU readline***\/\n\t\t\n\t\t\/\/checking if line is empty and if it is not it frees it and reallocates memory\n\t\tif (line){\n \tdelete line;\n \t\tline = (char *)NULL;\n \t}\n\t\t\/\/getting the line\n \t\tline = readline (\"\");\n\n \t\t\/\/adding it to history (you can use the arrows to navigate through history)\n \t if (line && *line){\n \t\tadd_history (line);\n\t\t}\n\t\t\n\t\t\/\/ creating new Command object\n\t\tCommand command(line);\n\t\t\n\t\t\/\/have handler object to execute the command\n\t\thandler->execute(command);\n\n\t}\n\n\treturn true;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : ABC085B_.cpp\n * Author : Kazune Takahashi\n * Created : 2020\/1\/31 21:37:45\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n int N;\n cin >> N;\n vector d(N);\n for (auto i = 0; i < N; ++i)\n {\n cin >> d[i];\n }\n sort(d.begin(), d.end());\n unique(d.begin(), d.end());\n cout << d.size() << endl;\n}\nsubmit ABC085B_.cpp to 'ABC085B - Kagami Mochi' (language-test-202001) [C++ (GCC 9.2.1)]#define DEBUG 1\n\/**\n * File : ABC085B_.cpp\n * Author : Kazune Takahashi\n * Created : 2020\/1\/31 21:37:45\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate \nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, const Mint &rhs)\n{\n return rhs + lhs;\n}\ntemplate \nMint operator-(ll lhs, const Mint &rhs)\n{\n return -rhs + lhs;\n}\ntemplate \nMint operator*(ll lhs, const Mint &rhs)\n{\n return rhs * lhs;\n}\ntemplate \nMint operator\/(ll lhs, const Mint &rhs)\n{\n return Mint{lhs} \/ rhs;\n}\ntemplate \nistream &operator>>(istream &stream, Mint &a)\n{\n return stream >> a.x;\n}\ntemplate \nostream &operator<<(ostream &stream, const Mint &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++17 -----\ntemplate \nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nint main()\n{\n int N;\n cin >> N;\n vector d(N);\n for (auto i = 0; i < N; ++i)\n {\n cin >> d[i];\n }\n sort(d.begin(), d.end());\n d.erase(unique(d.begin(), d.end()), d.end());\n cout << d.size() << endl;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"macros.h\"\n#include \"database.h\"\n#include \"statement.h\"\n\nusing namespace node_sqlite3;\n\nPersistent Database::constructor_template;\n\nvoid Database::Init(Handle target) {\n HandleScope scope;\n\n Local t = FunctionTemplate::New(New);\n\n constructor_template = Persistent::New(t);\n constructor_template->Inherit(EventEmitter::constructor_template);\n constructor_template->InstanceTemplate()->SetInternalFieldCount(1);\n constructor_template->SetClassName(String::NewSymbol(\"Database\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"close\", Close);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"exec\", Exec);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"serialize\", Serialize);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"parallelize\", Parallelize);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"configure\", Configure);\n\n target->Set(String::NewSymbol(\"Database\"),\n constructor_template->GetFunction());\n}\n\nvoid Database::Process() {\n if (!open && locked && !queue.empty()) {\n EXCEPTION(String::New(\"Database handle is closed\"), SQLITE_MISUSE, exception);\n Local argv[] = { exception };\n bool called = false;\n\n \/\/ Call all callbacks with the error object.\n while (!queue.empty()) {\n Call* call = queue.front();\n if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) {\n TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv);\n called = true;\n }\n queue.pop();\n \/\/ We don't call the actual callback, so we have to make sure that\n \/\/ the baton gets destroyed.\n delete call->baton;\n delete call;\n }\n\n \/\/ When we couldn't call a callback function, emit an error on the\n \/\/ Database object.\n if (!called) {\n Local args[] = { String::NewSymbol(\"error\"), exception };\n EMIT_EVENT(handle_, 2, args);\n }\n return;\n }\n\n while (open && (!locked || pending == 0) && !queue.empty()) {\n Call* call = queue.front();\n\n if (call->exclusive && pending > 0) {\n break;\n }\n\n queue.pop();\n locked = call->exclusive;\n call->callback(call->baton);\n delete call;\n\n if (locked) break;\n }\n}\n\nvoid Database::Schedule(EIO_Callback callback, Baton* baton, bool exclusive) {\n if (!open && locked) {\n EXCEPTION(String::New(\"Database is closed\"), SQLITE_MISUSE, exception);\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n Local argv[] = { exception };\n TRY_CATCH_CALL(handle_, baton->callback, 1, argv);\n }\n else {\n Local argv[] = { String::NewSymbol(\"error\"), exception };\n EMIT_EVENT(handle_, 2, argv);\n }\n return;\n }\n\n if (!open || ((locked || exclusive || serialize) && pending > 0)) {\n queue.push(new Call(callback, baton, exclusive || serialize));\n }\n else {\n locked = exclusive;\n callback(baton);\n }\n}\n\nHandle Database::New(const Arguments& args) {\n HandleScope scope;\n\n if (!Database::HasInstance(args.This())) {\n return ThrowException(Exception::TypeError(\n String::New(\"Use the new operator to create new Database objects\"))\n );\n }\n\n REQUIRE_ARGUMENT_STRING(0, filename);\n int pos = 1;\n\n int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;\n if (args.Length() >= pos && args[pos]->IsInt32()) {\n mode = args[pos++]->Int32Value();\n }\n\n Local callback;\n if (args.Length() >= pos && args[pos]->IsFunction()) {\n callback = Local::Cast(args[pos++]);\n }\n\n Database* db = new Database();\n db->Wrap(args.This());\n\n args.This()->Set(String::NewSymbol(\"filename\"), args[0]->ToString(), ReadOnly);\n args.This()->Set(String::NewSymbol(\"mode\"), Integer::New(mode), ReadOnly);\n\n \/\/ Start opening the database.\n OpenBaton* baton = new OpenBaton(db, callback, *filename, SQLITE_OPEN_FULLMUTEX | mode);\n EIO_BeginOpen(baton);\n\n return args.This();\n}\n\nvoid Database::EIO_BeginOpen(Baton* baton) {\n eio_custom(EIO_Open, EIO_PRI_DEFAULT, EIO_AfterOpen, baton);\n}\n\nint Database::EIO_Open(eio_req *req) {\n OpenBaton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n baton->status = sqlite3_open_v2(\n baton->filename.c_str(),\n &db->handle,\n baton->mode,\n NULL\n );\n\n if (baton->status != SQLITE_OK) {\n baton->message = std::string(sqlite3_errmsg(db->handle));\n sqlite3_close(db->handle);\n db->handle = NULL;\n }\n\n return 0;\n}\n\nint Database::EIO_AfterOpen(eio_req *req) {\n HandleScope scope;\n OpenBaton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n Local argv[1];\n if (baton->status != SQLITE_OK) {\n EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);\n argv[0] = exception;\n }\n else {\n db->open = true;\n argv[0] = Local::New(Null());\n }\n\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n else if (!db->open) {\n Local args[] = { String::NewSymbol(\"error\"), argv[0] };\n EMIT_EVENT(db->handle_, 2, args);\n }\n\n if (db->open) {\n Local args[] = { String::NewSymbol(\"open\") };\n EMIT_EVENT(db->handle_, 1, args);\n db->Process();\n }\n\n delete baton;\n return 0;\n}\n\nHandle Database::Close(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n OPTIONAL_ARGUMENT_FUNCTION(0, callback);\n\n Baton* baton = new Baton(db, callback);\n db->Schedule(EIO_BeginClose, baton, true);\n\n return args.This();\n}\n\nvoid Database::EIO_BeginClose(Baton* baton) {\n assert(baton->db->locked);\n assert(baton->db->open);\n assert(baton->db->handle);\n assert(baton->db->pending == 0);\n eio_custom(EIO_Close, EIO_PRI_DEFAULT, EIO_AfterClose, baton);\n}\n\nint Database::EIO_Close(eio_req *req) {\n Baton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n baton->status = sqlite3_close(db->handle);\n\n if (baton->status != SQLITE_OK) {\n baton->message = std::string(sqlite3_errmsg(db->handle));\n }\n else {\n db->handle = NULL;\n }\n return 0;\n}\n\nint Database::EIO_AfterClose(eio_req *req) {\n HandleScope scope;\n Baton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n Local argv[1];\n if (baton->status != SQLITE_OK) {\n EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);\n argv[0] = exception;\n }\n else {\n db->open = false;\n \/\/ Leave db->locked to indicate that this db object has reached\n \/\/ the end of its life.\n argv[0] = Local::New(Null());\n }\n\n \/\/ Fire callbacks.\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n else if (db->open) {\n Local args[] = { String::NewSymbol(\"error\"), argv[0] };\n EMIT_EVENT(db->handle_, 2, args);\n }\n\n assert(baton->db->locked);\n assert(!baton->db->open);\n assert(!baton->db->handle);\n assert(baton->db->pending == 0);\n\n if (!db->open) {\n Local args[] = { String::NewSymbol(\"close\"), argv[0] };\n EMIT_EVENT(db->handle_, 1, args);\n db->Process();\n }\n\n delete baton;\n return 0;\n}\n\nHandle Database::Serialize(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n OPTIONAL_ARGUMENT_FUNCTION(0, callback);\n\n bool before = db->serialize;\n db->serialize = true;\n\n if (!callback.IsEmpty() && callback->IsFunction()) {\n TRY_CATCH_CALL(args.This(), callback, 0, NULL);\n db->serialize = before;\n }\n\n db->Process();\n\n return args.This();\n}\n\nHandle Database::Parallelize(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n OPTIONAL_ARGUMENT_FUNCTION(0, callback);\n\n bool before = db->serialize;\n db->serialize = false;\n\n if (!callback.IsEmpty() && callback->IsFunction()) {\n TRY_CATCH_CALL(args.This(), callback, 0, NULL);\n db->serialize = before;\n }\n\n db->Process();\n\n return args.This();\n}\n\nHandle Database::Configure(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n\n REQUIRE_ARGUMENTS(2);\n\n if (args[0]->Equals(String::NewSymbol(\"trace\"))) {\n Local handle;\n Baton* baton = new Baton(db, handle);\n db->Schedule(RegisterTraceCallback, baton);\n }\n else {\n ThrowException(Exception::Error(String::Concat(\n args[0]->ToString(),\n String::NewSymbol(\" is not a valid configuration option\")\n )));\n }\n\n return args.This();\n}\n\nvoid Database::RegisterTraceCallback(Baton* baton) {\n assert(baton->db->open);\n assert(baton->db->handle);\n Database* db = baton->db;\n\n if (db->debug_trace == NULL) {\n \/\/ Add it.\n db->debug_trace = new AsyncTrace(db, TraceCallback);\n sqlite3_trace(db->handle, TraceCallback, db);\n }\n else {\n \/\/ Remove it.\n sqlite3_trace(db->handle, NULL, NULL);\n delete db->debug_trace;\n db->debug_trace = NULL;\n }\n\n delete baton;\n}\n\nvoid Database::TraceCallback(void* db, const char* sql) {\n \/\/ Note: This function is called in the thread pool.\n \/\/ Note: Some queries, such as \"EXPLAIN\" queries, are not sent through this.\n static_cast(db)->debug_trace->send(std::string(sql));\n}\n\nvoid Database::TraceCallback(EV_P_ ev_async *w, int revents) {\n \/\/ Note: This function is called in the main V8 thread.\n HandleScope scope;\n AsyncTrace* async = static_cast(w->data);\n\n std::vector queries = async->get();\n for (int i = 0; i < queries.size(); i++) {\n Local argv[] = {\n String::NewSymbol(\"trace\"),\n String::New(queries[i].c_str())\n };\n EMIT_EVENT(async->parent->handle_, 2, argv);\n }\n queries.clear();\n}\n\nHandle Database::Exec(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n\n REQUIRE_ARGUMENT_STRING(0, sql);\n OPTIONAL_ARGUMENT_FUNCTION(1, callback);\n\n Baton* baton = new ExecBaton(db, callback, *sql);\n db->Schedule(EIO_BeginExec, baton, true);\n\n return args.This();\n}\n\nvoid Database::EIO_BeginExec(Baton* baton) {\n assert(baton->db->locked);\n assert(baton->db->open);\n assert(baton->db->handle);\n assert(baton->db->pending == 0);\n eio_custom(EIO_Exec, EIO_PRI_DEFAULT, EIO_AfterExec, baton);\n}\n\nint Database::EIO_Exec(eio_req *req) {\n ExecBaton* baton = static_cast(req->data);\n\n char* message = NULL;\n baton->status = sqlite3_exec(\n baton->db->handle,\n baton->sql.c_str(),\n NULL,\n NULL,\n &message\n );\n\n if (baton->status != SQLITE_OK && message != NULL) {\n baton->message = std::string(message);\n sqlite3_free(message);\n }\n\n return 0;\n}\n\nint Database::EIO_AfterExec(eio_req *req) {\n HandleScope scope;\n ExecBaton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n\n if (baton->status != SQLITE_OK) {\n EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);\n\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n Local argv[] = { exception };\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n else {\n Local args[] = { String::NewSymbol(\"error\"), exception };\n EMIT_EVENT(db->handle_, 2, args);\n }\n }\n else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n Local argv[] = { Local::New(Null()) };\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n\n db->Process();\n\n delete baton;\n return 0;\n}\n\n\/**\n * Override this so that we can properly close the database when this object\n * gets garbage collected.\n *\/\nvoid Database::Wrap(Handle handle) {\n assert(handle_.IsEmpty());\n assert(handle->InternalFieldCount() > 0);\n handle_ = Persistent::New(handle);\n handle_->SetPointerInInternalField(0, this);\n handle_.MakeWeak(this, Destruct);\n}\n\ninline void Database::MakeWeak (void) {\n handle_.MakeWeak(this, Destruct);\n}\n\nvoid Database::Unref() {\n assert(!handle_.IsEmpty());\n assert(!handle_.IsWeak());\n assert(refs_ > 0);\n if (--refs_ == 0) { MakeWeak(); }\n}\n\nvoid Database::Destruct(Persistent value, void *data) {\n Database* db = static_cast(data);\n if (db->handle) {\n eio_custom(EIO_Destruct, EIO_PRI_DEFAULT, EIO_AfterDestruct, db);\n ev_ref(EV_DEFAULT_UC);\n }\n else {\n delete db;\n }\n}\n\nint Database::EIO_Destruct(eio_req *req) {\n Database* db = static_cast(req->data);\n\n sqlite3_close(db->handle);\n db->handle = NULL;\n\n return 0;\n}\n\nint Database::EIO_AfterDestruct(eio_req *req) {\n Database* db = static_cast(req->data);\n ev_unref(EV_DEFAULT_UC);\n delete db;\n return 0;\n}\nmake sure that the async handler is properly stopped when the database is closed or destructed#include \n#include \n#include \n#include \n\n#include \"macros.h\"\n#include \"database.h\"\n#include \"statement.h\"\n\nusing namespace node_sqlite3;\n\nPersistent Database::constructor_template;\n\nvoid Database::Init(Handle target) {\n HandleScope scope;\n\n Local t = FunctionTemplate::New(New);\n\n constructor_template = Persistent::New(t);\n constructor_template->Inherit(EventEmitter::constructor_template);\n constructor_template->InstanceTemplate()->SetInternalFieldCount(1);\n constructor_template->SetClassName(String::NewSymbol(\"Database\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"close\", Close);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"exec\", Exec);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"serialize\", Serialize);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"parallelize\", Parallelize);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"configure\", Configure);\n\n target->Set(String::NewSymbol(\"Database\"),\n constructor_template->GetFunction());\n}\n\nvoid Database::Process() {\n if (!open && locked && !queue.empty()) {\n EXCEPTION(String::New(\"Database handle is closed\"), SQLITE_MISUSE, exception);\n Local argv[] = { exception };\n bool called = false;\n\n \/\/ Call all callbacks with the error object.\n while (!queue.empty()) {\n Call* call = queue.front();\n if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) {\n TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv);\n called = true;\n }\n queue.pop();\n \/\/ We don't call the actual callback, so we have to make sure that\n \/\/ the baton gets destroyed.\n delete call->baton;\n delete call;\n }\n\n \/\/ When we couldn't call a callback function, emit an error on the\n \/\/ Database object.\n if (!called) {\n Local args[] = { String::NewSymbol(\"error\"), exception };\n EMIT_EVENT(handle_, 2, args);\n }\n return;\n }\n\n while (open && (!locked || pending == 0) && !queue.empty()) {\n Call* call = queue.front();\n\n if (call->exclusive && pending > 0) {\n break;\n }\n\n queue.pop();\n locked = call->exclusive;\n call->callback(call->baton);\n delete call;\n\n if (locked) break;\n }\n}\n\nvoid Database::Schedule(EIO_Callback callback, Baton* baton, bool exclusive) {\n if (!open && locked) {\n EXCEPTION(String::New(\"Database is closed\"), SQLITE_MISUSE, exception);\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n Local argv[] = { exception };\n TRY_CATCH_CALL(handle_, baton->callback, 1, argv);\n }\n else {\n Local argv[] = { String::NewSymbol(\"error\"), exception };\n EMIT_EVENT(handle_, 2, argv);\n }\n return;\n }\n\n if (!open || ((locked || exclusive || serialize) && pending > 0)) {\n queue.push(new Call(callback, baton, exclusive || serialize));\n }\n else {\n locked = exclusive;\n callback(baton);\n }\n}\n\nHandle Database::New(const Arguments& args) {\n HandleScope scope;\n\n if (!Database::HasInstance(args.This())) {\n return ThrowException(Exception::TypeError(\n String::New(\"Use the new operator to create new Database objects\"))\n );\n }\n\n REQUIRE_ARGUMENT_STRING(0, filename);\n int pos = 1;\n\n int mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;\n if (args.Length() >= pos && args[pos]->IsInt32()) {\n mode = args[pos++]->Int32Value();\n }\n\n Local callback;\n if (args.Length() >= pos && args[pos]->IsFunction()) {\n callback = Local::Cast(args[pos++]);\n }\n\n Database* db = new Database();\n db->Wrap(args.This());\n\n args.This()->Set(String::NewSymbol(\"filename\"), args[0]->ToString(), ReadOnly);\n args.This()->Set(String::NewSymbol(\"mode\"), Integer::New(mode), ReadOnly);\n\n \/\/ Start opening the database.\n OpenBaton* baton = new OpenBaton(db, callback, *filename, SQLITE_OPEN_FULLMUTEX | mode);\n EIO_BeginOpen(baton);\n\n return args.This();\n}\n\nvoid Database::EIO_BeginOpen(Baton* baton) {\n eio_custom(EIO_Open, EIO_PRI_DEFAULT, EIO_AfterOpen, baton);\n}\n\nint Database::EIO_Open(eio_req *req) {\n OpenBaton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n baton->status = sqlite3_open_v2(\n baton->filename.c_str(),\n &db->handle,\n baton->mode,\n NULL\n );\n\n if (baton->status != SQLITE_OK) {\n baton->message = std::string(sqlite3_errmsg(db->handle));\n sqlite3_close(db->handle);\n db->handle = NULL;\n }\n\n return 0;\n}\n\nint Database::EIO_AfterOpen(eio_req *req) {\n HandleScope scope;\n OpenBaton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n Local argv[1];\n if (baton->status != SQLITE_OK) {\n EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);\n argv[0] = exception;\n }\n else {\n db->open = true;\n argv[0] = Local::New(Null());\n }\n\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n else if (!db->open) {\n Local args[] = { String::NewSymbol(\"error\"), argv[0] };\n EMIT_EVENT(db->handle_, 2, args);\n }\n\n if (db->open) {\n Local args[] = { String::NewSymbol(\"open\") };\n EMIT_EVENT(db->handle_, 1, args);\n db->Process();\n }\n\n delete baton;\n return 0;\n}\n\nHandle Database::Close(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n OPTIONAL_ARGUMENT_FUNCTION(0, callback);\n\n Baton* baton = new Baton(db, callback);\n db->Schedule(EIO_BeginClose, baton, true);\n\n return args.This();\n}\n\nvoid Database::EIO_BeginClose(Baton* baton) {\n assert(baton->db->locked);\n assert(baton->db->open);\n assert(baton->db->handle);\n assert(baton->db->pending == 0);\n eio_custom(EIO_Close, EIO_PRI_DEFAULT, EIO_AfterClose, baton);\n}\n\nint Database::EIO_Close(eio_req *req) {\n Baton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n if (db->debug_trace) {\n delete db->debug_trace;\n db->debug_trace = NULL;\n }\n\n baton->status = sqlite3_close(db->handle);\n\n if (baton->status != SQLITE_OK) {\n baton->message = std::string(sqlite3_errmsg(db->handle));\n }\n else {\n db->handle = NULL;\n }\n return 0;\n}\n\nint Database::EIO_AfterClose(eio_req *req) {\n HandleScope scope;\n Baton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n Local argv[1];\n if (baton->status != SQLITE_OK) {\n EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);\n argv[0] = exception;\n }\n else {\n db->open = false;\n \/\/ Leave db->locked to indicate that this db object has reached\n \/\/ the end of its life.\n argv[0] = Local::New(Null());\n }\n\n \/\/ Fire callbacks.\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n else if (db->open) {\n Local args[] = { String::NewSymbol(\"error\"), argv[0] };\n EMIT_EVENT(db->handle_, 2, args);\n }\n\n assert(baton->db->locked);\n assert(!baton->db->open);\n assert(!baton->db->handle);\n assert(baton->db->pending == 0);\n\n if (!db->open) {\n Local args[] = { String::NewSymbol(\"close\"), argv[0] };\n EMIT_EVENT(db->handle_, 1, args);\n db->Process();\n }\n\n delete baton;\n return 0;\n}\n\nHandle Database::Serialize(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n OPTIONAL_ARGUMENT_FUNCTION(0, callback);\n\n bool before = db->serialize;\n db->serialize = true;\n\n if (!callback.IsEmpty() && callback->IsFunction()) {\n TRY_CATCH_CALL(args.This(), callback, 0, NULL);\n db->serialize = before;\n }\n\n db->Process();\n\n return args.This();\n}\n\nHandle Database::Parallelize(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n OPTIONAL_ARGUMENT_FUNCTION(0, callback);\n\n bool before = db->serialize;\n db->serialize = false;\n\n if (!callback.IsEmpty() && callback->IsFunction()) {\n TRY_CATCH_CALL(args.This(), callback, 0, NULL);\n db->serialize = before;\n }\n\n db->Process();\n\n return args.This();\n}\n\nHandle Database::Configure(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n\n REQUIRE_ARGUMENTS(2);\n\n if (args[0]->Equals(String::NewSymbol(\"trace\"))) {\n Local handle;\n Baton* baton = new Baton(db, handle);\n db->Schedule(RegisterTraceCallback, baton);\n }\n else {\n ThrowException(Exception::Error(String::Concat(\n args[0]->ToString(),\n String::NewSymbol(\" is not a valid configuration option\")\n )));\n }\n\n return args.This();\n}\n\nvoid Database::RegisterTraceCallback(Baton* baton) {\n assert(baton->db->open);\n assert(baton->db->handle);\n Database* db = baton->db;\n\n if (db->debug_trace == NULL) {\n \/\/ Add it.\n db->debug_trace = new AsyncTrace(db, TraceCallback);\n sqlite3_trace(db->handle, TraceCallback, db);\n }\n else {\n \/\/ Remove it.\n sqlite3_trace(db->handle, NULL, NULL);\n delete db->debug_trace;\n db->debug_trace = NULL;\n }\n\n delete baton;\n}\n\nvoid Database::TraceCallback(void* db, const char* sql) {\n \/\/ Note: This function is called in the thread pool.\n \/\/ Note: Some queries, such as \"EXPLAIN\" queries, are not sent through this.\n static_cast(db)->debug_trace->send(std::string(sql));\n}\n\nvoid Database::TraceCallback(EV_P_ ev_async *w, int revents) {\n \/\/ Note: This function is called in the main V8 thread.\n HandleScope scope;\n AsyncTrace* async = static_cast(w->data);\n\n std::vector queries = async->get();\n for (int i = 0; i < queries.size(); i++) {\n Local argv[] = {\n String::NewSymbol(\"trace\"),\n String::New(queries[i].c_str())\n };\n EMIT_EVENT(async->parent->handle_, 2, argv);\n }\n queries.clear();\n}\n\nHandle Database::Exec(const Arguments& args) {\n HandleScope scope;\n Database* db = ObjectWrap::Unwrap(args.This());\n\n REQUIRE_ARGUMENT_STRING(0, sql);\n OPTIONAL_ARGUMENT_FUNCTION(1, callback);\n\n Baton* baton = new ExecBaton(db, callback, *sql);\n db->Schedule(EIO_BeginExec, baton, true);\n\n return args.This();\n}\n\nvoid Database::EIO_BeginExec(Baton* baton) {\n assert(baton->db->locked);\n assert(baton->db->open);\n assert(baton->db->handle);\n assert(baton->db->pending == 0);\n eio_custom(EIO_Exec, EIO_PRI_DEFAULT, EIO_AfterExec, baton);\n}\n\nint Database::EIO_Exec(eio_req *req) {\n ExecBaton* baton = static_cast(req->data);\n\n char* message = NULL;\n baton->status = sqlite3_exec(\n baton->db->handle,\n baton->sql.c_str(),\n NULL,\n NULL,\n &message\n );\n\n if (baton->status != SQLITE_OK && message != NULL) {\n baton->message = std::string(message);\n sqlite3_free(message);\n }\n\n return 0;\n}\n\nint Database::EIO_AfterExec(eio_req *req) {\n HandleScope scope;\n ExecBaton* baton = static_cast(req->data);\n Database* db = baton->db;\n\n\n if (baton->status != SQLITE_OK) {\n EXCEPTION(String::New(baton->message.c_str()), baton->status, exception);\n\n if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n Local argv[] = { exception };\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n else {\n Local args[] = { String::NewSymbol(\"error\"), exception };\n EMIT_EVENT(db->handle_, 2, args);\n }\n }\n else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) {\n Local argv[] = { Local::New(Null()) };\n TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv);\n }\n\n db->Process();\n\n delete baton;\n return 0;\n}\n\n\/**\n * Override this so that we can properly close the database when this object\n * gets garbage collected.\n *\/\nvoid Database::Wrap(Handle handle) {\n assert(handle_.IsEmpty());\n assert(handle->InternalFieldCount() > 0);\n handle_ = Persistent::New(handle);\n handle_->SetPointerInInternalField(0, this);\n handle_.MakeWeak(this, Destruct);\n}\n\ninline void Database::MakeWeak (void) {\n handle_.MakeWeak(this, Destruct);\n}\n\nvoid Database::Unref() {\n assert(!handle_.IsEmpty());\n assert(!handle_.IsWeak());\n assert(refs_ > 0);\n if (--refs_ == 0) { MakeWeak(); }\n}\n\nvoid Database::Destruct(Persistent value, void *data) {\n Database* db = static_cast(data);\n if (db->handle) {\n eio_custom(EIO_Destruct, EIO_PRI_DEFAULT, EIO_AfterDestruct, db);\n ev_ref(EV_DEFAULT_UC);\n }\n else {\n delete db;\n }\n}\n\nint Database::EIO_Destruct(eio_req *req) {\n Database* db = static_cast(req->data);\n\n if (db->debug_trace) {\n delete db->debug_trace;\n db->debug_trace = NULL;\n }\n\n sqlite3_close(db->handle);\n db->handle = NULL;\n\n return 0;\n}\n\nint Database::EIO_AfterDestruct(eio_req *req) {\n Database* db = static_cast(req->data);\n ev_unref(EV_DEFAULT_UC);\n delete db;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ Licensed under the MIT License.\n\n#include \"gtest\/gtest.h\"\n#include \"core\/eager\/ort_kernel_invoker.h\"\n#include \"core\/common\/logging\/sinks\/clog_sink.h\"\n#include \"core\/providers\/cpu\/cpu_execution_provider.h\"\n#include \"test\/framework\/test_utils.h\"\n\nnamespace onnxruntime {\nnamespace test {\n\nTEST(InvokerTest, Basic) {\n std::unique_ptr cpu_execution_provider = onnxruntime::make_unique(CPUExecutionProviderInfo(false));\n const std::string logger_id{\"InvokerTest\"};\n auto logging_manager = onnxruntime::make_unique(\n std::unique_ptr{new logging::CLogSink{}},\n logging::Severity::kVERBOSE, false,\n logging::LoggingManager::InstanceType::Default,\n &logger_id); \n std::unique_ptr env;\n Environment::Create(std::move(logging_manager), env);\n ORTInvoker kernel_invoker(std::move(cpu_execution_provider), env->GetLoggingManager()->DefaultLogger());\n\n std::vector dims_mul_x = {3, 2};\n std::vector values_mul_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};\n OrtValue A, B;\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &A);\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &B);\n std::vector result(1);\n auto status = kernel_invoker.Invoke(\"Add\", {A, B}, result, nullptr);\n ASSERT_TRUE(status.IsOK());\n const Tensor& C = result.back().Get();\n auto& c_shape = C.Shape();\n EXPECT_EQ(c_shape.GetDims(), dims_mul_x);\n\n std::vector expected_result = {2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f};\n auto* c_data = C.Data();\n for (auto i = 0; i < c_shape.Size(); ++i) {\n EXPECT_EQ(c_data[i], expected_result[i]);\n }\n}\n\nTEST(InvokerTest, Inplace) {\n std::unique_ptr cpu_execution_provider = onnxruntime::make_unique(CPUExecutionProviderInfo(false));\n const std::string logger_id{\"InvokerTest\"};\n auto logging_manager = onnxruntime::make_unique(\n std::unique_ptr{new logging::CLogSink{}},\n logging::Severity::kVERBOSE, false,\n logging::LoggingManager::InstanceType::Default,\n &logger_id); \n std::unique_ptr env;\n Environment::Create(std::move(logging_manager), env);\n ORTInvoker kernel_invoker(std::move(cpu_execution_provider), env->GetLoggingManager()->DefaultLogger());\n\n std::vector dims_mul_x = {3, 2};\n std::vector values_mul_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};\n OrtValue A, B;\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &A);\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &B);\n std::vector result;\n result.push_back(A);\n auto status = kernel_invoker.Invoke(\"Add\", {A, B}, result, nullptr);\n\n std::vector expected_result = {2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f};\n auto* a_data = A.Get().Data();\n for (size_t i = 0; i < expected_result.size(); ++i) {\n EXPECT_EQ(a_data[i], expected_result[i]);\n }\n}\n\n} \/\/ namespace test\n} \/\/ namespace onnxruntime\nfix broken tests (#7909)\/\/ Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ Licensed under the MIT License.\n\n#include \"gtest\/gtest.h\"\n#include \"core\/eager\/ort_kernel_invoker.h\"\n#include \"core\/common\/logging\/sinks\/clog_sink.h\"\n#include \"core\/providers\/cpu\/cpu_execution_provider.h\"\n#include \"test\/framework\/test_utils.h\"\n\nnamespace onnxruntime {\nnamespace test {\n\nTEST(InvokerTest, Basic) {\n std::unique_ptr cpu_execution_provider = std::make_unique(CPUExecutionProviderInfo(false));\n const std::string logger_id{\"InvokerTest\"};\n auto logging_manager = std::make_unique(\n std::unique_ptr{new logging::CLogSink{}},\n logging::Severity::kVERBOSE, false,\n logging::LoggingManager::InstanceType::Default,\n &logger_id); \n std::unique_ptr env;\n Environment::Create(std::move(logging_manager), env);\n ORTInvoker kernel_invoker(std::move(cpu_execution_provider), env->GetLoggingManager()->DefaultLogger());\n\n std::vector dims_mul_x = {3, 2};\n std::vector values_mul_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};\n OrtValue A, B;\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &A);\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &B);\n std::vector result(1);\n auto status = kernel_invoker.Invoke(\"Add\", {A, B}, result, nullptr);\n ASSERT_TRUE(status.IsOK());\n const Tensor& C = result.back().Get();\n auto& c_shape = C.Shape();\n EXPECT_EQ(c_shape.GetDims(), dims_mul_x);\n\n std::vector expected_result = {2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f};\n auto* c_data = C.Data();\n for (auto i = 0; i < c_shape.Size(); ++i) {\n EXPECT_EQ(c_data[i], expected_result[i]);\n }\n}\n\nTEST(InvokerTest, Inplace) {\n std::unique_ptr cpu_execution_provider = std::make_unique(CPUExecutionProviderInfo(false));\n const std::string logger_id{\"InvokerTest\"};\n auto logging_manager = std::make_unique(\n std::unique_ptr{new logging::CLogSink{}},\n logging::Severity::kVERBOSE, false,\n logging::LoggingManager::InstanceType::Default,\n &logger_id); \n std::unique_ptr env;\n Environment::Create(std::move(logging_manager), env);\n ORTInvoker kernel_invoker(std::move(cpu_execution_provider), env->GetLoggingManager()->DefaultLogger());\n\n std::vector dims_mul_x = {3, 2};\n std::vector values_mul_x = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f};\n OrtValue A, B;\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &A);\n CreateMLValue(kernel_invoker.GetCurrentExecutionProvider().GetAllocator(0, OrtMemTypeDefault), dims_mul_x, values_mul_x,\n &B);\n std::vector result;\n result.push_back(A);\n auto status = kernel_invoker.Invoke(\"Add\", {A, B}, result, nullptr);\n\n std::vector expected_result = {2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f};\n auto* a_data = A.Get().Data();\n for (size_t i = 0; i < expected_result.size(); ++i) {\n EXPECT_EQ(a_data[i], expected_result[i]);\n }\n}\n\n} \/\/ namespace test\n} \/\/ namespace onnxruntime\n<|endoftext|>"} {"text":"\/*\n * Copyright 1999-2004 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680)\n#define XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include \n\n\n\n#include \n\n#include \n\n#include \n\n#include \n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\n\/\/ We're using our own auto_ptr-like class due to wide\n\/\/ variations amongst the varous platforms we have to\n\/\/ support\ntemplate<\tclass\tType, \n\t\t\tbool\ttoCallDestructor = true>\nclass XalanMemMgrAutoPtr\n{\npublic:\n\n\ttypedef XALAN_STD_QUALIFIER pair AutoPtrPairType;\n\n\tclass MemMgrAutoPtrData : public AutoPtrPairType\n\t{\n\tpublic:\n\t\tMemMgrAutoPtrData():\n\t\t\tAutoPtrPairType(0,0)\n\t\t{\n\t\t}\n\n\t\tMemMgrAutoPtrData(\t\n\t\t\tMemoryManagerType* memoryManager,\n\t\t\tType* dataPointer): \n\t\t\tAutoPtrPairType(memoryManager, dataPointer)\n\t\t{\n\t\t\tinvariants();\n\t\t}\n\t\t\n\t\n\t\tbool\n\t\tisInitilized()const\n\t\t{\n\t\t\treturn ( (this->first != 0) && (this->second != 0) )? true : false;\n\t\t}\n\t\n\t\tvoid\n\t\tdeallocate()\n\t\t{\n\t\t\tinvariants();\n\n\t\t\tif ( isInitilized() )\n\t\t\t{\t\t\n\t\t\t\tif ( toCallDestructor ) \n\t\t\t\t{\n\t\t\t\t\tthis->second->~Type();\n\t\t\t\t}\n\n\t\t\t\tthis->first->deallocate(this->second);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid \n\t\treset(\tMemoryManagerType* m_memoryManager ,\n\t\t\t\tType*\tm_dataPointer )\n\t\t{\t\n\t\t\tinvariants();\n\n\t\t\tthis->first = m_memoryManager;\n\t\t\t\n\t\t\tthis->second = m_dataPointer;\n\n\t\t\tinvariants();\n\t\t}\t\n\tprivate:\n\t\tvoid\n\t\tinvariants()const\n\t\t{\n\t\t\tassert( isInitilized() ||\n\t\t\t\t\t( (this->first == 0) && (this->second ==0) ) );\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tXalanMemMgrAutoPtr(\n\t\t\tMemoryManagerType& theManager, \n\t\t\tType* ptr ) : \n\t\tm_pointerInfo(&theManager, ptr)\n\t{\n\t}\t\n\n\tXalanMemMgrAutoPtr() :\n\t\tm_pointerInfo()\n\t{\n\t}\n\t\n\tXalanMemMgrAutoPtr(const XalanMemMgrAutoPtr&\ttheSource) :\n\t\tm_pointerInfo(((XalanMemMgrAutoPtr&)theSource).release())\n\t{\n\t}\n\n\tXalanMemMgrAutoPtr&\n\toperator=(XalanMemMgrAutoPtr&\ttheRHS)\n\t{\t\t\n\t\tif (this != &theRHS)\n\t\t{\n\t\t\tm_pointerInfo.deallocate();\n\n\t\t\tm_pointerInfo = theRHS.release();\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t~XalanMemMgrAutoPtr()\n\t{\n\t\tm_pointerInfo.deallocate();\n\t}\n\n\tType&\n\toperator*() const\n\t{\n\t\treturn *m_pointerInfo.second;\n\t}\n\n\tType*\n\toperator->() const\n\t{\n\t\treturn m_pointerInfo.second;\n\t}\n\n\tType*\n\tget() const\n\t{\n\t\treturn m_pointerInfo.second;\n\t}\n\n\tMemMgrAutoPtrData\n\trelease()\n\t{\t\t\n\t\tMemMgrAutoPtrData tmp = m_pointerInfo;\n\t\n\t\tm_pointerInfo.reset( 0 , 0 ); \n\t\t\n\t\treturn MemMgrAutoPtrData(tmp);\n\t}\n\t\n\tType*\n\treleasePtr()\n\t{\t\t\n\t\tMemMgrAutoPtrData tmp = release();\n\t\n\t\treturn tmp.second;\n\t}\t\n\t\n\tvoid\n\treset(\tMemoryManagerType* theManager = 0,\n\t\t\tType*\t\tthePointer = 0 )\n\t{\t\t\n\t\tm_pointerInfo.deallocate();\n\n\t\tm_pointerInfo.reset ( theManager , thePointer );\n\t}\n\nprivate:\n\n\n\/\/ data member\n\tMemMgrAutoPtrData m_pointerInfo;\n};\n\n\n\n\ntemplate<\tclass Type>\nclass XalanMemMgrAutoPtrArray\n{\npublic:\n\n\ttypedef unsigned int size_type;\n\n\tclass MemMgrAutoPtrArrayData \n\t{\n\tpublic:\n\t\tMemMgrAutoPtrArrayData():\n\t\t\tm_memoryManager(0),\n\t\t\tm_dataArray(0),\n\t\t\tm_size(0)\n\t\t{\n\t\t}\n\n\t\tMemMgrAutoPtrArrayData(\t\n\t\t\t\tMemoryManagerType*\tmemoryManager,\n\t\t\t\tType*\t\t\t\tdataPointer,\n\t\t\t\tsize_type\t\t\t\tsize): \n\t\t\tm_memoryManager(memoryManager),\n\t\t\tm_dataArray(dataPointer),\n\t\t\tm_size(size)\n\t\t{\n\t\t\tinvariants();\n\t\t}\n\t\t\n\t\n\t\tbool\n\t\tisInitilized()const\n\t\t{\n\t\t\treturn ( (m_memoryManager != 0) && (m_dataArray != 0) && (m_size != 0) )? true : false;\n\t\t}\n\t\n\t\tvoid\n\t\tdeallocate()\n\t\t{\n\t\t\tinvariants();\n\n\t\t\tif ( isInitilized() )\n\t\t\t{\t\t\t\n\t\t\t\tassert ( m_dataArray != 0 );\n\n\t\t\t\tfor ( size_type i = 0; i < m_size ; ++i )\n\t\t\t\t{\n\t\t\t\t\tm_dataArray[i].~Type();\n\t\t\t\t}\n\t\t\t\tm_memoryManager->deallocate ( m_dataArray);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid \n\t\treset(\tMemoryManagerType*\tmemoryManager ,\n\t\t\t\tType*\t\t\t\tdataPointer,\n\t\t\t\tsize_type\t\t\t\tsize)\n\t\t{\t\n\t\t\tinvariants();\n\n\t\t\tm_memoryManager = memoryManager;\n\t\t\t\n\t\t\tm_dataArray =\tdataPointer;\n\n\t\t\tm_size = size;\n\n\t\t\tinvariants();\n\t\t}\t\n\n\n\t\tMemoryManagerType*\t\tm_memoryManager;\n\t\tType*\t\t\t\t\tm_dataArray;\n\t\tsize_type\t\t\t\t\tm_size;\n\n\tprivate:\n\t\tvoid\n\t\tinvariants()const\n\t\t{\n\t\t\tassert( isInitilized() ||\n\t\t\t\t\t( (m_memoryManager == 0) && (m_dataArray ==0) && (m_size == 0)) );\n\t\t}\t\t\n\t};\n\t\n\tXalanMemMgrAutoPtrArray(\n\t\t\tMemoryManagerType& theManager, \n\t\t\tType*\t\t\t\tptr,\n\t\t\tsize_type\t\t\tsize) : \n\t\tm_pointerInfo(&theManager, ptr, size)\n\t{\n\t}\t\n\n\tXalanMemMgrAutoPtrArray() :\n\t\tm_pointerInfo()\n\t{\n\t}\n\t\n\tXalanMemMgrAutoPtrArray(const XalanMemMgrAutoPtrArray&\ttheSource) :\n\t\tm_pointerInfo(((XalanMemMgrAutoPtr&)theSource).release())\n\t{\n\t}\n\n\n\tXalanMemMgrAutoPtrArray&\n\toperator=(XalanMemMgrAutoPtrArray&\ttheRHS)\n\t{\t\t\n\t\tif (this != &theRHS)\n\t\t{\n\t\t\tm_pointerInfo.deallocate();\n\n\t\t\tm_pointerInfo = theRHS.release();\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t~XalanMemMgrAutoPtrArray()\n\t{\n\t\tm_pointerInfo.deallocate();\n\t}\n\n\tType&\n\toperator*() const\n\t{\n\t\treturn *m_pointerInfo.m_dataArray;\n\t}\n\n\tType*\n\toperator->() const\n\t{\n\t\treturn m_pointerInfo.m_dataArray;\n\t}\n\n\tType*\n\tget() const\n\t{\n\t\treturn m_pointerInfo.m_dataArray;\n\t}\n\n\tsize_type\n\tgetSize()const\n\t{\n\t\treturn m_pointerInfo.m_size;\n\t}\n\n\tXalanMemMgrAutoPtrArray&\n\toperator++ ()\n\t{\n\t\t++m_pointerInfo.m_size;\n\n\t\treturn *this;\n\t}\n\n\tXalanMemMgrAutoPtrArray\n\toperator++ (int)\n\t{\n\t\tXalanMemMgrAutoPtrArray temp = *this;\n\t\t++*this;\n\n\t\treturn temp;\n\t}\n\n\tMemMgrAutoPtrArrayData\n\trelease()\n\t{\t\t\n\t\tMemMgrAutoPtrArrayData tmp = m_pointerInfo;\n\t\n\t\tm_pointerInfo.reset( 0 , 0 , 0); \n\t\t\n\t\treturn MemMgrAutoPtrArrayData(tmp);\n\t}\n\n\tType*\n\treleasePtr()\n\t{\t\t\n\t\tMemMgrAutoPtrArrayData tmp = release();\n\t\n\t\t\n\t\treturn tmp.dataPointer;\n\t}\n\t\n\tvoid\n\treset(\tMemoryManagerType* theManager = 0,\n\t\t\tType*\t\t\t\tthePointer = 0 ,\n\t\t\tsize_type\t\t\t\tsize = 0)\n\t{\t\t\n\t\tm_pointerInfo.deallocate();\n\n\t\tm_pointerInfo.reset ( theManager , thePointer , size );\n\t}\n\t\n\tType&\n\toperator[](size_type\tindex) const\n\t{\n\t\treturn m_pointerInfo.m_dataArray[index];\n\t}\n\t\nprivate:\n\n\n\t\/\/ data member\n\tMemMgrAutoPtrArrayData m_pointerInfo;\n};\n\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680)\nAdded accessors to get to memory managers and commented out questionable post-increment operator.\/*\n * Copyright 1999-2004 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680)\n#define XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include \n\n\n\n#include \n\n#include \n\n#include \n\n#include \n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\n\/\/ We're using our own auto_ptr-like class due to wide\n\/\/ variations amongst the varous platforms we have to\n\/\/ support\ntemplate<\tclass\tType, \n\t\t\tbool\ttoCallDestructor = true>\nclass XalanMemMgrAutoPtr\n{\npublic:\n\n\ttypedef XALAN_STD_QUALIFIER pair AutoPtrPairType;\n\n\tclass MemMgrAutoPtrData : public AutoPtrPairType\n\t{\n\tpublic:\n\t\tMemMgrAutoPtrData():\n\t\t\tAutoPtrPairType(0,0)\n\t\t{\n\t\t}\n\n\t\tMemMgrAutoPtrData(\t\n\t\t\tMemoryManagerType* memoryManager,\n\t\t\tType* dataPointer): \n\t\t\tAutoPtrPairType(memoryManager, dataPointer)\n\t\t{\n\t\t\tinvariants();\n\t\t}\n\t\t\n\t\n\t\tbool\n\t\tisInitilized()const\n\t\t{\n\t\t\treturn ( (this->first != 0) && (this->second != 0) )? true : false;\n\t\t}\n\t\n\t\tvoid\n\t\tdeallocate()\n\t\t{\n\t\t\tinvariants();\n\n\t\t\tif ( isInitilized() )\n\t\t\t{\t\t\n\t\t\t\tif ( toCallDestructor ) \n\t\t\t\t{\n\t\t\t\t\tthis->second->~Type();\n\t\t\t\t}\n\n\t\t\t\tthis->first->deallocate(this->second);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid \n\t\treset(\tMemoryManagerType* m_memoryManager ,\n\t\t\t\tType*\tm_dataPointer )\n\t\t{\t\n\t\t\tinvariants();\n\n\t\t\tthis->first = m_memoryManager;\n\t\t\t\n\t\t\tthis->second = m_dataPointer;\n\n\t\t\tinvariants();\n\t\t}\t\n\tprivate:\n\t\tvoid\n\t\tinvariants()const\n\t\t{\n\t\t\tassert( isInitilized() ||\n\t\t\t\t\t( (this->first == 0) && (this->second ==0) ) );\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tXalanMemMgrAutoPtr(\n\t\t\tMemoryManagerType& theManager, \n\t\t\tType* ptr ) : \n\t\tm_pointerInfo(&theManager, ptr)\n\t{\n\t}\t\n\n\tXalanMemMgrAutoPtr() :\n\t\tm_pointerInfo()\n\t{\n\t}\n\t\n\tXalanMemMgrAutoPtr(const XalanMemMgrAutoPtr&\ttheSource) :\n\t\tm_pointerInfo(((XalanMemMgrAutoPtr&)theSource).release())\n\t{\n\t}\n\n\tXalanMemMgrAutoPtr&\n\toperator=(XalanMemMgrAutoPtr&\ttheRHS)\n\t{\t\t\n\t\tif (this != &theRHS)\n\t\t{\n\t\t\tm_pointerInfo.deallocate();\n\n\t\t\tm_pointerInfo = theRHS.release();\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t~XalanMemMgrAutoPtr()\n\t{\n\t\tm_pointerInfo.deallocate();\n\t}\n\n\tType&\n\toperator*() const\n\t{\n\t\treturn *m_pointerInfo.second;\n\t}\n\n\tType*\n\toperator->() const\n\t{\n\t\treturn m_pointerInfo.second;\n\t}\n\n\tType*\n\tget() const\n\t{\n\t\treturn m_pointerInfo.second;\n\t}\n\n MemoryManagerType*\n getMemoryManager()\n {\n return m_pointerInfo.first;\n }\n\n const MemoryManagerType*\n getMemoryManager() const\n {\n return m_pointerInfo.first;\n }\n\n\tMemMgrAutoPtrData\n\trelease()\n\t{\t\t\n\t\tMemMgrAutoPtrData tmp = m_pointerInfo;\n\t\n\t\tm_pointerInfo.reset( 0 , 0 ); \n\t\t\n\t\treturn MemMgrAutoPtrData(tmp);\n\t}\n\n\tType*\n\treleasePtr()\n\t{\t\t\n\t\tMemMgrAutoPtrData tmp = release();\n\t\n\t\treturn tmp.second;\n\t}\t\n\t\n\tvoid\n\treset(\tMemoryManagerType* theManager = 0,\n\t\t\tType*\t\tthePointer = 0 )\n\t{\t\t\n\t\tm_pointerInfo.deallocate();\n\n\t\tm_pointerInfo.reset ( theManager , thePointer );\n\t}\n\nprivate:\n\n\n\/\/ data member\n\tMemMgrAutoPtrData m_pointerInfo;\n};\n\n\n\n\ntemplate<\tclass Type>\nclass XalanMemMgrAutoPtrArray\n{\npublic:\n\n\ttypedef unsigned int size_type;\n\n\tclass MemMgrAutoPtrArrayData \n\t{\n\tpublic:\n\t\tMemMgrAutoPtrArrayData():\n\t\t\tm_memoryManager(0),\n\t\t\tm_dataArray(0),\n\t\t\tm_size(0)\n\t\t{\n\t\t}\n\n\t\tMemMgrAutoPtrArrayData(\t\n\t\t\t\tMemoryManagerType*\tmemoryManager,\n\t\t\t\tType*\t\t\t\tdataPointer,\n\t\t\t\tsize_type\t\t\t\tsize): \n\t\t\tm_memoryManager(memoryManager),\n\t\t\tm_dataArray(dataPointer),\n\t\t\tm_size(size)\n\t\t{\n\t\t\tinvariants();\n\t\t}\n\t\t\n\t\n\t\tbool\n\t\tisInitilized()const\n\t\t{\n\t\t\treturn ( (m_memoryManager != 0) && (m_dataArray != 0) && (m_size != 0) )? true : false;\n\t\t}\n\t\n\t\tvoid\n\t\tdeallocate()\n\t\t{\n\t\t\tinvariants();\n\n\t\t\tif ( isInitilized() )\n\t\t\t{\t\t\t\n\t\t\t\tassert ( m_dataArray != 0 );\n\n\t\t\t\tfor ( size_type i = 0; i < m_size ; ++i )\n\t\t\t\t{\n\t\t\t\t\tm_dataArray[i].~Type();\n\t\t\t\t}\n\t\t\t\tm_memoryManager->deallocate ( m_dataArray);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid \n\t\treset(\tMemoryManagerType*\tmemoryManager ,\n\t\t\t\tType*\t\t\t\tdataPointer,\n\t\t\t\tsize_type\t\t\t\tsize)\n\t\t{\t\n\t\t\tinvariants();\n\n\t\t\tm_memoryManager = memoryManager;\n\t\t\t\n\t\t\tm_dataArray =\tdataPointer;\n\n\t\t\tm_size = size;\n\n\t\t\tinvariants();\n\t\t}\t\n\n\n\t\tMemoryManagerType*\t\tm_memoryManager;\n\t\tType*\t\t\t\t\tm_dataArray;\n\t\tsize_type\t\t\t\t\tm_size;\n\n\tprivate:\n\t\tvoid\n\t\tinvariants()const\n\t\t{\n\t\t\tassert( isInitilized() ||\n\t\t\t\t\t( (m_memoryManager == 0) && (m_dataArray ==0) && (m_size == 0)) );\n\t\t}\t\t\n\t};\n\t\n\tXalanMemMgrAutoPtrArray(\n\t\t\tMemoryManagerType& theManager, \n\t\t\tType*\t\t\t\tptr,\n\t\t\tsize_type\t\t\tsize) : \n\t\tm_pointerInfo(&theManager, ptr, size)\n\t{\n\t}\t\n\n\tXalanMemMgrAutoPtrArray() :\n\t\tm_pointerInfo()\n\t{\n\t}\n\t\n\tXalanMemMgrAutoPtrArray(const XalanMemMgrAutoPtrArray&\ttheSource) :\n\t\tm_pointerInfo(((XalanMemMgrAutoPtr&)theSource).release())\n\t{\n\t}\n\n\n\tXalanMemMgrAutoPtrArray&\n\toperator=(XalanMemMgrAutoPtrArray&\ttheRHS)\n\t{\t\t\n\t\tif (this != &theRHS)\n\t\t{\n\t\t\tm_pointerInfo.deallocate();\n\n\t\t\tm_pointerInfo = theRHS.release();\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t~XalanMemMgrAutoPtrArray()\n\t{\n\t\tm_pointerInfo.deallocate();\n\t}\n\n\tType&\n\toperator*() const\n\t{\n\t\treturn *m_pointerInfo.m_dataArray;\n\t}\n\n\tType*\n\toperator->() const\n\t{\n\t\treturn m_pointerInfo.m_dataArray;\n\t}\n\n\tType*\n\tget() const\n\t{\n\t\treturn m_pointerInfo.m_dataArray;\n\t}\n\n\tsize_type\n\tgetSize()const\n\t{\n\t\treturn m_pointerInfo.m_size;\n\t}\n\n MemoryManagerType*\n getMemoryManager()\n {\n return m_pointerInfo.m_memoryManager;\n }\n\n const MemoryManagerType*\n getMemoryManager() const\n {\n return m_pointerInfo.m_memoryManager;\n }\n\n\tXalanMemMgrAutoPtrArray&\n\toperator++ ()\n\t{\n\t\t++m_pointerInfo.m_size;\n\n\t\treturn *this;\n\t}\n\n \/* Since this class is not reference-counted, I don't see how this\n could work, since the destruction of the temporary will free\n the controlled pointer.\n\tXalanMemMgrAutoPtrArray\n\toperator++ (int)\n\t{\n\t\tXalanMemMgrAutoPtrArray temp = *this;\n\t\t++*this;\n\n\t\treturn temp;\n\t}\n *\/\n\n\tMemMgrAutoPtrArrayData\n\trelease()\n\t{\t\t\n\t\tMemMgrAutoPtrArrayData tmp = m_pointerInfo;\n\t\n\t\tm_pointerInfo.reset( 0 , 0 , 0); \n\t\t\n\t\treturn MemMgrAutoPtrArrayData(tmp);\n\t}\n\n\tType*\n\treleasePtr()\n\t{\t\t\n\t\tMemMgrAutoPtrArrayData tmp = release();\n\t\n\t\t\n\t\treturn tmp.dataPointer;\n\t}\n\t\n\tvoid\n\treset(\tMemoryManagerType* theManager = 0,\n\t\t\tType*\t\t\t\tthePointer = 0 ,\n\t\t\tsize_type\t\t\t\tsize = 0)\n\t{\t\t\n\t\tm_pointerInfo.deallocate();\n\n\t\tm_pointerInfo.reset ( theManager , thePointer , size );\n\t}\n\t\n\tType&\n\toperator[](size_type\tindex) const\n\t{\n\t\treturn m_pointerInfo.m_dataArray[index];\n\t}\n\t\nprivate:\n\n\n\t\/\/ data member\n\tMemMgrAutoPtrArrayData m_pointerInfo;\n};\n\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ if !defined(XALANMEMMGRAUTOPTR_HEADER_GUARD_1357924680)\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\n\/\/ void print(const int it, const double energy);\n\ntemplate\nstd::string to_string(const T& t)\n{\n std::ostringstream strs;\n strs << std::scientific << std::setprecision(3) << t;\n return strs.str();\n}\n\ntemplate\nstd::string red(const T& t)\n{\n return \"\\033[31m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string green(const T& t)\n{\n return \"\\033[32m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string yellow(const T& t)\n{\n return \"\\033[33m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string blue(const T& t)\n{\n return \"\\033[34m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string white(const T& t)\n{\n return \"\\033[37m\" + to_string(t) + \"\\033[0m\";\n}\n\nstd::string red(const std::string& s);\nstd::string green(const std::string& s);\nstd::string yellow(const std::string& s);\nstd::string blue(const std::string& s);\nstd::string white(const std::string& s);\n\nvoid bar();\n\n\/\/ template\n\/\/ template\n\/\/ template\n\/\/ void print(\n\/\/ const Solver& s\n\/\/ \/\/ , const Color& c\n\/\/ )\n\/\/ {\n\/\/ std::cout << Color(s.current_it) << \"\\t\";\n\/\/ std::cout << Color(s.current_temperature) << \"\\t\";\n\/\/ std::cout << Color(s.current_temperature - s.temperature(s.current_temperature)) << \"\\t\";\n\/\/ std::cout << Color(s.current_energy) << \"\\t\";\n\/\/ \/\/ \/\/ std::cout << s.d_energy << \"\\t\";\n\/\/ std::cout << std::endl;\n\/\/ }\n\nstruct Accepted{};\nstruct Rejected{};\n\ntemplate\nvoid print(\n const Solver& s\n , Accepted\n )\n{\n \/\/ std::cout << green(s.current_it) << \"\\t\";\n std::cout << green(s.current_temperature) << \"\\t\";\n std::cout << green(s.current_temperature - s.temperature()) << \"\\t\";\n std::cout << green(s.current_energy) << \"\\t\";\n \/\/ \/\/ std::cout << s.d_energy << \"\\t\";\n std::cout << std::endl;\n}\n\ntemplate\nvoid print(\n const Solver& s\n , Rejected\n )\n{\n \/\/ std::cout << red(s.current_it) << \"\\t\";\n std::cout << red(s.current_temperature) << \"\\t\";\n std::cout << red(s.current_temperature - s.temperature()) << \"\\t\";\n std::cout << red(s.current_energy) << \"\\t\";\n \/\/ \/\/ std::cout << s.d_energy << \"\\t\";\n\n \/\/ std::cout << std::string(60, '\\b');\n std::cout << std::endl;\n}\n\ntemplate\nvoid final_print(const Solver& s)\n{\n std::cout << std::endl;\n std::cout << \"Final temperature: \" << s.current_temperature << \"\\n\";\n std::cout << \"Final energy: \" << s.current_energy << \"\\n\";\n std::cout << std::endl;\n}\n[display] display is now on one line#pragma once\n\n#include \n#include \n#include \n\n\/\/ void print(const int it, const double energy);\n\ntemplate\nstd::string to_string(const T& t)\n{\n std::ostringstream strs;\n strs << std::scientific << std::setprecision(3) << t;\n return strs.str();\n}\n\ntemplate\nstd::string red(const T& t)\n{\n return \"\\033[31m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string green(const T& t)\n{\n return \"\\033[32m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string yellow(const T& t)\n{\n return \"\\033[33m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string blue(const T& t)\n{\n return \"\\033[34m\" + to_string(t) + \"\\033[0m\";\n}\n\ntemplate\nstd::string white(const T& t)\n{\n return \"\\033[37m\" + to_string(t) + \"\\033[0m\";\n}\n\nstd::string red(const std::string& s);\nstd::string green(const std::string& s);\nstd::string yellow(const std::string& s);\nstd::string blue(const std::string& s);\nstd::string white(const std::string& s);\n\nvoid bar();\n\n\/\/ template\n\/\/ template\n\/\/ template\n\/\/ void print(\n\/\/ const Solver& s\n\/\/ \/\/ , const Color& c\n\/\/ )\n\/\/ {\n\/\/ std::cout << Color(s.current_it) << \"\\t\";\n\/\/ std::cout << Color(s.current_temperature) << \"\\t\";\n\/\/ std::cout << Color(s.current_temperature - s.temperature(s.current_temperature)) << \"\\t\";\n\/\/ std::cout << Color(s.current_energy) << \"\\t\";\n\/\/ \/\/ \/\/ std::cout << s.d_energy << \"\\t\";\n\/\/ std::cout << std::endl;\n\/\/ }\n\nstruct Accepted{};\nstruct Rejected{};\n\ntemplate\nvoid print(\n const Solver& s\n , Accepted\n )\n{\n \/\/ std::cout << green(s.current_it) << \"\\t\";\n std::cout << green(s.current_temperature) << \"\\t\";\n std::cout << green(s.current_temperature - s.temperature()) << \"\\t\";\n std::cout << green(s.current_energy) << \"\\t\";\n \/\/ \/\/ std::cout << s.d_energy << \"\\t\";\n\n std::cout << \"\\n\\r\\e[A\";\n std::cout << std::string(100, ' ');\n std::cout << \"\\r\";\n\n \/\/ std::cout << \"\\n\\r\\e[A\";\n}\n\ntemplate\nvoid print(\n const Solver& s\n , Rejected\n )\n{\n \/\/ std::cout << red(s.current_it) << \"\\t\";\n std::cout << red(s.current_temperature) << \"\\t\";\n std::cout << red(s.current_temperature - s.temperature()) << \"\\t\";\n std::cout << red(s.current_energy) << \"\\t\";\n \/\/ \/\/ std::cout << s.d_energy << \"\\t\";\n\n std::cout << \"\\n\\r\\e[A\";\n std::cout << std::string(100, ' ');\n std::cout << \"\\r\";\n}\n\ntemplate\nvoid final_print(const Solver& s)\n{\n std::cout << std::endl;\n std::cout << \"Final temperature: \" << s.current_temperature << \"\\n\";\n std::cout << \"Final energy: \" << s.current_energy << \"\\n\";\n std::cout << std::endl;\n}\n<|endoftext|>"} {"text":"\/***********************************************\n * Author: Jun Jiang - jiangjun4@sina.com\n * Create: 2017-08-19 18:50\n * Last modified : 2017-08-19 18:50\n * Filename : DNN.cpp\n * Description : \n **********************************************\/\n#include \"dnn\/DNN.h\"\n#include \"dnn\/Layer.h\"\n#include \"utils\/Log.h\"\n#include \"utils\/Shuffler.h\"\n#include \n\n\nnamespace abcdl{\nnamespace dnn{\n\nvoid DNN::train(const abcdl::algebra::Mat& train_data,\n const abcdl::algebra::Mat& train_label,\n const abcdl::algebra::Mat& test_data,\n const abcdl::algebra::Mat& test_label){\n LOG(INFO) << \"dnn start training...\";\n\n size_t layer_size = _layers.size();\n size_t num_train_data = train_data.rows();\n\n CHECK(num_train_data == train_label.rows());\n CHECK(train_data.cols() == _layers[0]->get_input_dim());\n CHECK(train_label.cols() == _layers[_layers.size() -1]->get_output_dim());\n\n abcdl::utils::Shuffler shuffler(num_train_data);\n abcdl::algebra::Mat data;\n abcdl::algebra::Mat label;\n\n for(size_t i = 0; i != _epoch; i++){\n shuffler.shuffle();\n for(size_t j = 0; j != num_train_data; j++){\n train_data.get_row(&data, shuffler.get_row(j));\n train_label.get_row(&label, shuffler.get_row(j));\n\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n\n for(size_t k = layer_size - 1; k > 0; k--){\n if(k == layer_size - 1){\n ((OutputLayer*)_layers[k])->set_y(label);\n _layers[k]->backward(_layers[k-1], nullptr);\n }else{\n _layers[k]->backward(_layers[k-1], _layers[k+1]);\n }\n \n \/\/mini_batch_update\n if(j % _batch_size == _batch_size - 1 || j == num_train_data - 1){\n _layers[k]->update_gradient(j % _batch_size + 1, _alpha, _lamda);\n }\n }\n\n if(j % 100 == 0){\n printf(\"Epoch[%ld\/%ld] Train[%ld\/%ld]\\r\", i + 1, _epoch, j, num_train_data);\n }\n }\n\n if(test_data.rows() > 0){\n size_t num = evaluate(test_data, test_label);\n printf(\"Epoch[%ld][%ld\/%ld] rate[%f]\\n\", i + 1, num, test_data.rows(), num\/(real)test_data.rows());\n }\n }\n}\n\nsize_t DNN::evaluate(const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){\n CHECK(test_data.cols() == _layers[0]->get_input_dim());\n CHECK(test_data.rows() == test_label.rows());\n CHECK(test_label.cols() == _layers[_layers.size() - 1]->get_output_dim());\n\n size_t rows = test_data.rows();\n size_t predict_num = 0;\n abcdl::algebra::Mat mat;\n\n for(size_t i = 0; i != rows; i++){\n predict(mat, test_data.get_row(i));\n if(mat.argmax() == test_label.get_row(i).argmax()){\n ++predict_num;\n }\n }\n return predict_num;\n}\n\nvoid DNN::predict(abcdl::algebra::Mat& result, const abcdl::algebra::Mat& predict_data){\n CHECK(predict_data.cols() == _layers[0]->get_input_dim());\n size_t layer_size = _layers.size();\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(predict_data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n result = _layers[layer_size - 1]->get_activate_data();\n}\n\nbool DNN::load_model(const std::string& path){\n std::vector models;\n if(!model_loader.read(path, &models, \"DNNMODEL\") || models.size() % 2 != 0){\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return false;\n }\n\n for(auto& layer : _layers){\n delete layer;\n }\n _layers.clear();\n\n for(size_t i = 0; i != models.size() \/ 2; i++){\n if(i == 0){\n _layers.push_back(new InputLayer(models[0]->rows()));\n }\n if(i == models.size() \/ 2 - 1){\n _layers.push_back(new OutputLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), new CrossEntropyCost(), *models[i * 2], *models[i * 2 + 1]));\n }else{\n _layers.push_back(new FullConnLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), *models[i * 2], *models[i * 2 + 1]));\n }\n }\n\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return true;\n}\nbool DNN::write_model(const std::string& path){\n std::vector models;\n for(size_t i = 1; i != _layers.size(); i++){\n models.push_back(&_layers[i]->get_weight());\n models.push_back(&_layers[i]->get_bias());\n }\n return model_loader.write(models, path, \"DNNMODEL\", false);\n}\n\n}\/\/namespace dnn\n}\/\/namespace abcdl\ninitialized\/***********************************************\n * Author: Jun Jiang - jiangjun4@sina.com\n * Create: 2017-08-19 18:50\n * Last modified : 2017-08-19 18:50\n * Filename : DNN.cpp\n * Description : \n **********************************************\/\n#include \"dnn\/DNN.h\"\n#include \"dnn\/Layer.h\"\n#include \"utils\/Log.h\"\n#include \"utils\/Shuffler.h\"\n#include \n\n\nnamespace abcdl{\nnamespace dnn{\n\nvoid DNN::train(const abcdl::algebra::Mat& train_data,\n const abcdl::algebra::Mat& train_label,\n const abcdl::algebra::Mat& test_data,\n const abcdl::algebra::Mat& test_label){\n LOG(INFO) << \"dnn start training...\";\n\n size_t layer_size = _layers.size();\n size_t num_train_data = train_data.rows();\n\n CHECK(num_train_data == train_label.rows());\n CHECK(train_data.cols() == _layers[0]->get_input_dim());\n CHECK(train_label.cols() == _layers[_layers.size() -1]->get_output_dim());\n\n abcdl::utils::Shuffler shuffler(num_train_data);\n abcdl::algebra::Mat data;\n abcdl::algebra::Mat label;\n\n for(size_t i = 0; i != _epoch; i++){\n shuffler.shuffle();\n for(size_t j = 0; j != num_train_data; j++){\n train_data.get_row(&data, shuffler.get_row(j));\n train_label.get_row(&label, shuffler.get_row(j));\n\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n\n for(size_t k = layer_size - 1; k > 0; k--){\n if(k == layer_size - 1){\n ((OutputLayer*)_layers[k])->set_y(label);\n _layers[k]->backward(_layers[k-1], nullptr);\n }else{\n _layers[k]->backward(_layers[k-1], _layers[k+1]);\n }\n \n \/\/mini_batch_update\n if(j % _batch_size == _batch_size - 1 || j == num_train_data - 1){\n _layers[k]->update_gradient(j % _batch_size + 1, _alpha, _lamda);\n }\n }\n\n if(j % 100 == 0){\n printf(\"Epoch[%ld\/%ld] Train[%ld\/%ld]\\r\", i + 1, _epoch, j, num_train_data);\n }\n }\n\n if(test_data.rows() > 0){\n size_t num = evaluate(test_data, test_label);\n printf(\"Epoch[%ld][%ld\/%ld] rate[%f]\\n\", i + 1, num, test_data.rows(), num\/(real)test_data.rows());\n }\n }\n}\n\nsize_t DNN::evaluate(const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){\n CHECK(test_data.cols() == _layers[0]->get_input_dim());\n CHECK(test_data.rows() == test_label.rows());\n CHECK(test_label.cols() == _layers[_layers.size() - 1]->get_output_dim());\n\n size_t rows = test_data.rows();\n size_t predict_num = 0;\n abcdl::algebra::Mat mat;\n\n for(size_t i = 0; i != rows; i++){\n predict(mat, test_data.get_row(i));\n if(mat.argmax() == test_label.get_row(i).argmax()){\n ++predict_num;\n }\n }\n return predict_num;\n}\n\nvoid DNN::predict(abcdl::algebra::Mat& result, const abcdl::algebra::Mat& predict_data){\n CHECK(predict_data.cols() == _layers[0]->get_input_dim());\n size_t layer_size = _layers.size();\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(predict_data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n result = _layers[layer_size - 1]->get_activate_data();\n}\n\nbool DNN::load_model(const std::string& path){\n std::vector models;\n if(!_model_loader.read(path, &models, \"DNNMODEL\") || models.size() % 2 != 0){\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return false;\n }\n\n for(auto& layer : _layers){\n delete layer;\n }\n _layers.clear();\n\n for(size_t i = 0; i != models.size() \/ 2; i++){\n if(i == 0){\n _layers.push_back(new InputLayer(models[0]->rows()));\n }\n if(i == models.size() \/ 2 - 1){\n _layers.push_back(new OutputLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), new CrossEntropyCost(), *models[i * 2], *models[i * 2 + 1]));\n }else{\n _layers.push_back(new FullConnLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), *models[i * 2], *models[i * 2 + 1]));\n }\n }\n\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return true;\n}\nbool DNN::write_model(const std::string& path){\n std::vector models;\n for(size_t i = 1; i != _layers.size(); i++){\n models.push_back(&_layers[i]->get_weight());\n models.push_back(&_layers[i]->get_bias());\n }\n return _model_loader.write(models, path, \"DNNMODEL\", false);\n}\n\n}\/\/namespace dnn\n}\/\/namespace abcdl\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2015 - The CM Authors \n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/SHA1.h\"\n#include \"stx\/http\/HTTPSSEResponseHandler.h\"\n#include \"zbase\/mapreduce\/tasks\/MapTableTask.h\"\n#include \"zbase\/mapreduce\/MapReduceScheduler.h\"\n#include \n\nusing namespace stx;\n\nnamespace zbase {\n\nMapTableTask::MapTableTask(\n const AnalyticsSession& session,\n const TSDBTableRef& table_ref,\n const String& map_function,\n const String& globals,\n const String& params,\n MapReduceShardList* shards,\n AnalyticsAuth* auth,\n zbase::PartitionMap* pmap,\n zbase::ReplicationScheme* repl) :\n session_(session),\n table_ref_(table_ref),\n map_function_(map_function),\n globals_(globals),\n params_(params),\n auth_(auth),\n pmap_(pmap),\n repl_(repl) {\n auto table = pmap_->findTable(session_.customer(), table_ref_.table_key);\n if (table.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_ref_.table_key);\n }\n\n auto partitioner = table.get()->partitioner();\n auto partitions = partitioner->listPartitions();\n\n for (const auto& partition : partitions) {\n auto shard = mkRef(new MapTableTaskShard());\n shard->task = this;\n shard->table_ref = table_ref_;\n shard->table_ref.partition_key = partition;\n\n addShard(shard.get(), shards);\n }\n}\n\nOption MapTableTask::execute(\n RefPtr shard_base,\n RefPtr job) {\n auto shard = shard_base.asInstanceOf();\n\n Vector errors;\n auto hosts = repl_->replicasFor(shard->table_ref.partition_key.get());\n for (const auto& host : hosts) {\n try {\n return executeRemote(shard, job, host);\n } catch (const StandardException& e) {\n logError(\n \"z1.mapreduce\",\n e,\n \"MapTableTask::execute failed\");\n\n errors.emplace_back(e.what());\n }\n }\n\n RAISEF(\n kRuntimeError,\n \"MapTableTask::execute failed: $0\",\n StringUtil::join(errors, \", \"));\n}\n\nOption MapTableTask::executeRemote(\n RefPtr shard,\n RefPtr job,\n const ReplicaRef& host) {\n logDebug(\n \"z1.mapreduce\",\n \"Executing map table shard on $0\/$1\/$2 on $3\",\n session_.customer(),\n shard->table_ref.table_key,\n shard->table_ref.partition_key.get().toString(),\n host.addr.hostAndPort());\n\n auto url = StringUtil::format(\n \"http:\/\/$0\/api\/v1\/mapreduce\/tasks\/map_partition\",\n host.addr.ipAndPort());\n\n auto params = StringUtil::format(\n \"table=$0&partition=$1&map_function=$2&globals=$3¶ms=$4\",\n URI::urlEncode(shard->table_ref.table_key),\n shard->table_ref.partition_key.get().toString(),\n URI::urlEncode(map_function_),\n URI::urlEncode(globals_),\n URI::urlEncode(params_));\n\n auto api_token = auth_->encodeAuthToken(session_);\n\n Option result;\n Vector errors;\n auto event_handler = [&] (const http::HTTPSSEEvent& ev) {\n if (ev.name.isEmpty()) {\n return;\n }\n\n if (ev.name.get() == \"result_id\") {\n result = Some(MapReduceShardResult {\n .host = host,\n .result_id = SHA1Hash::fromHexString(ev.data)\n });\n }\n\n else if (ev.name.get() == \"log\") {\n job->sendLogline(URI::urlDecode(ev.data));\n }\n\n else if (ev.name.get() == \"error\") {\n errors.emplace_back(ev.data);\n }\n };\n\n http::HTTPMessage::HeaderList auth_headers;\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", api_token));\n\n http::HTTPClient http_client(&z1stats()->http_client_stats);\n auto req = http::HTTPRequest::mkPost(url, params, auth_headers);\n auto res = http_client.executeRequest(\n req,\n http::HTTPSSEResponseHandler::getFactory(event_handler));\n\n if (!errors.empty()) {\n RAISE(kRuntimeError, StringUtil::join(errors, \"; \"));\n }\n\n if (res.statusCode() != 200) {\n RAISEF(kRuntimeError, \"HTTP Error: $0\", url);\n }\n\n return result;\n}\n\n} \/\/ namespace zbase\n\nfix partition list w\/o constraints in MapTableTask\/**\n * Copyright (c) 2015 - The CM Authors \n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/SHA1.h\"\n#include \"stx\/http\/HTTPSSEResponseHandler.h\"\n#include \"zbase\/mapreduce\/tasks\/MapTableTask.h\"\n#include \"zbase\/mapreduce\/MapReduceScheduler.h\"\n#include \n\nusing namespace stx;\n\nnamespace zbase {\n\nMapTableTask::MapTableTask(\n const AnalyticsSession& session,\n const TSDBTableRef& table_ref,\n const String& map_function,\n const String& globals,\n const String& params,\n MapReduceShardList* shards,\n AnalyticsAuth* auth,\n zbase::PartitionMap* pmap,\n zbase::ReplicationScheme* repl) :\n session_(session),\n table_ref_(table_ref),\n map_function_(map_function),\n globals_(globals),\n params_(params),\n auth_(auth),\n pmap_(pmap),\n repl_(repl) {\n auto table = pmap_->findTable(session_.customer(), table_ref_.table_key);\n if (table.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_ref_.table_key);\n }\n\n Vector constraints;\n if (!table_ref.timerange_begin.isEmpty()) {\n csql::ScanConstraint constraint;\n constraint.column_name = \"time\";\n constraint.type = csql::ScanConstraintType::GREATER_THAN_OR_EQUAL_TO;\n constraint.value = csql::SValue(csql::SValue::IntegerType(\n table_ref.timerange_begin.get().unixMicros()));\n constraints.emplace_back(constraint);\n }\n\n if (!table_ref.timerange_limit.isEmpty()) {\n csql::ScanConstraint constraint;\n constraint.column_name = \"time\";\n constraint.type = csql::ScanConstraintType::GREATER_THAN_OR_EQUAL_TO;\n constraint.value = csql::SValue(csql::SValue::IntegerType(\n table_ref.timerange_limit.get().unixMicros()));\n constraints.emplace_back(constraint);\n }\n\n auto partitioner = table.get()->partitioner();\n auto partitions = partitioner->listPartitions(constraints);\n\n for (const auto& partition : partitions) {\n auto shard = mkRef(new MapTableTaskShard());\n shard->task = this;\n shard->table_ref = table_ref_;\n shard->table_ref.partition_key = partition;\n\n addShard(shard.get(), shards);\n }\n}\n\nOption MapTableTask::execute(\n RefPtr shard_base,\n RefPtr job) {\n auto shard = shard_base.asInstanceOf();\n\n Vector errors;\n auto hosts = repl_->replicasFor(shard->table_ref.partition_key.get());\n for (const auto& host : hosts) {\n try {\n return executeRemote(shard, job, host);\n } catch (const StandardException& e) {\n logError(\n \"z1.mapreduce\",\n e,\n \"MapTableTask::execute failed\");\n\n errors.emplace_back(e.what());\n }\n }\n\n RAISEF(\n kRuntimeError,\n \"MapTableTask::execute failed: $0\",\n StringUtil::join(errors, \", \"));\n}\n\nOption MapTableTask::executeRemote(\n RefPtr shard,\n RefPtr job,\n const ReplicaRef& host) {\n logDebug(\n \"z1.mapreduce\",\n \"Executing map table shard on $0\/$1\/$2 on $3\",\n session_.customer(),\n shard->table_ref.table_key,\n shard->table_ref.partition_key.get().toString(),\n host.addr.hostAndPort());\n\n auto url = StringUtil::format(\n \"http:\/\/$0\/api\/v1\/mapreduce\/tasks\/map_partition\",\n host.addr.ipAndPort());\n\n auto params = StringUtil::format(\n \"table=$0&partition=$1&map_function=$2&globals=$3¶ms=$4\",\n URI::urlEncode(shard->table_ref.table_key),\n shard->table_ref.partition_key.get().toString(),\n URI::urlEncode(map_function_),\n URI::urlEncode(globals_),\n URI::urlEncode(params_));\n\n auto api_token = auth_->encodeAuthToken(session_);\n\n Option result;\n Vector errors;\n auto event_handler = [&] (const http::HTTPSSEEvent& ev) {\n if (ev.name.isEmpty()) {\n return;\n }\n\n if (ev.name.get() == \"result_id\") {\n result = Some(MapReduceShardResult {\n .host = host,\n .result_id = SHA1Hash::fromHexString(ev.data)\n });\n }\n\n else if (ev.name.get() == \"log\") {\n job->sendLogline(URI::urlDecode(ev.data));\n }\n\n else if (ev.name.get() == \"error\") {\n errors.emplace_back(ev.data);\n }\n };\n\n http::HTTPMessage::HeaderList auth_headers;\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", api_token));\n\n http::HTTPClient http_client(&z1stats()->http_client_stats);\n auto req = http::HTTPRequest::mkPost(url, params, auth_headers);\n auto res = http_client.executeRequest(\n req,\n http::HTTPSSEResponseHandler::getFactory(event_handler));\n\n if (!errors.empty()) {\n RAISE(kRuntimeError, StringUtil::join(errors, \"; \"));\n }\n\n if (res.statusCode() != 200) {\n RAISEF(kRuntimeError, \"HTTP Error: $0\", url);\n }\n\n return result;\n}\n\n} \/\/ namespace zbase\n\n<|endoftext|>"} {"text":"#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\n#include\n#include\n\n\n\/\/#define DEVC \"\/dev\/i2c-1\" <-- this is the real I2C device you need with the scale model\n#define DEVC \"\/dev\/simudrv\"\nusing namespace std;\n\nint main() {\nint file=open(DEVC, O_RDWR);\n\nioctl(file, I2C_SLAVE, 0x08);\n\n\/\/ declare writeBuffer\nint writeBuffer[10];\nwriteBuffer[0]=0xCC;\nint readBuffer[10];\nwrite(file, writeBuffer, 1);\n\nread(file, readBuffer, 1);\nint output = readBuffer[0];\n\ncout << output << endl;\nclose(file);\n\nreturn 0;\n}\n\nduplicated file<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright NumFOCUS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkGaussianImageSource.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkKullbackLeiblerCompareHistogramImageToImageMetric.h\"\n#include \"itkTranslationTransform.h\"\n\n\/** This test uses two 2D-Gaussians (standard deviation RegionSize\/2).\n This test computes the mutual information between the two images.\n*\/\nint\nitkCompareHistogramImageToImageMetricTest(int, char *[])\n{\n try\n {\n \/\/ Create two simple images.\n constexpr unsigned int ImageDimension = 2;\n using PixelType = double;\n using CoordinateRepresentationType = double;\n\n \/\/ Allocate Images\n using MovingImageType = itk::Image;\n using FixedImageType = itk::Image;\n\n \/\/ Declare Gaussian Sources\n using MovingImageSourceType = itk::GaussianImageSource;\n using FixedImageSourceType = itk::GaussianImageSource;\n\n \/\/ Note: the following declarations are classical arrays\n FixedImageType::SizeValueType fixedImageSize[] = { 100, 100 };\n MovingImageType::SizeValueType movingImageSize[] = { 100, 100 };\n\n FixedImageType::SpacingValueType fixedImageSpacing[] = { 1.0f, 1.0f };\n MovingImageType::SpacingValueType movingImageSpacing[] = { 1.0f, 1.0f };\n\n FixedImageType::PointValueType fixedImageOrigin[] = { 0.0f, 0.0f };\n MovingImageType::PointValueType movingImageOrigin[] = { 0.0f, 0.0f };\n\n MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New();\n FixedImageSourceType::Pointer fixedImageSource = FixedImageSourceType::New();\n\n movingImageSource->SetSize(movingImageSize);\n movingImageSource->SetOrigin(movingImageOrigin);\n movingImageSource->SetSpacing(movingImageSpacing);\n movingImageSource->SetNormalized(false);\n movingImageSource->SetScale(250.0f);\n\n fixedImageSource->SetSize(fixedImageSize);\n fixedImageSource->SetOrigin(fixedImageOrigin);\n fixedImageSource->SetSpacing(fixedImageSpacing);\n fixedImageSource->SetNormalized(false);\n fixedImageSource->SetScale(250.0f);\n\n movingImageSource->Update(); \/\/ Force the filter to run\n fixedImageSource->Update(); \/\/ Force the filter to run\n\n MovingImageType::Pointer movingImage = movingImageSource->GetOutput();\n FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput();\n\n \/\/ Set up the metric.\n using MetricType = itk::KullbackLeiblerCompareHistogramImageToImageMetric;\n using TransformBaseType = MetricType::TransformType;\n using ScalesType = MetricType::ScalesType;\n using ParametersType = TransformBaseType::ParametersType;\n\n MetricType::Pointer metric = MetricType::New();\n\n unsigned int nBins = 256;\n MetricType::HistogramType::SizeType histSize;\n\n histSize.SetSize(2);\n\n histSize[0] = nBins;\n histSize[1] = nBins;\n metric->SetHistogramSize(histSize);\n\n \/\/ Plug the images into the metric.\n metric->SetFixedImage(fixedImage);\n metric->SetMovingImage(movingImage);\n\n \/\/ Set up a transform.\n using TransformType = itk::TranslationTransform;\n\n TransformType::Pointer transform = TransformType::New();\n metric->SetTransform(transform);\n\n \/\/ Set up an interpolator.\n using InterpolatorType = itk::LinearInterpolateImageFunction;\n\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n interpolator->SetInputImage(movingImage);\n metric->SetInterpolator(interpolator);\n\n \/\/ Define the region over which the metric will be computed.\n metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());\n\n \/\/ Set up transform parameters.\n ParametersType parameters(transform->GetNumberOfParameters());\n\n for (unsigned int k = 0; k < ImageDimension; ++k)\n parameters[k] = 0.0f;\n\n \/\/ Set scales for derivative calculation.\n ScalesType scales(transform->GetNumberOfParameters());\n\n for (unsigned int k = 0; k < transform->GetNumberOfParameters(); ++k)\n scales[k] = 1;\n\n metric->SetDerivativeStepLengthScales(scales);\n\n \/\/ Now set up the Training Stuff\n metric->SetTrainingTransform(transform);\n metric->SetTrainingFixedImage(fixedImage);\n metric->SetTrainingFixedImageRegion(fixedImage->GetBufferedRegion());\n metric->SetTrainingMovingImage(movingImage);\n metric->SetTrainingInterpolator(interpolator);\n\n \/\/ Initialize the metric.\n metric->Initialize();\n\n \/\/ Print out metric value and derivative.\n MetricType::MeasureType measure = metric->GetValue(parameters);\n MetricType::DerivativeType derivative;\n metric->GetDerivative(parameters, derivative);\n\n std::cout << \"Metric value = \" << measure << std::endl << \"Derivative = \" << derivative << std::endl;\n\n \/\/ Exercise Print() method.\n metric->Print(std::cout);\n\n std::cout << \"Test passed.\" << std::endl;\n }\n catch (const itk::ExceptionObject & ex)\n {\n std::cerr << \"Exception caught!\" << std::endl;\n std::cerr << ex << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\nENH: Improve KLCompareHistogramImageToImageMetric coverage\/*=========================================================================\n *\n * Copyright NumFOCUS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkGaussianImageSource.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkKullbackLeiblerCompareHistogramImageToImageMetric.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkTestingMacros.h\"\n\n\/** This test uses two 2D-Gaussians (standard deviation RegionSize\/2).\n This test computes the mutual information between the two images.\n*\/\nint\nitkCompareHistogramImageToImageMetricTest(int, char *[])\n{\n\n \/\/ Create two simple images.\n constexpr unsigned int ImageDimension = 2;\n using PixelType = double;\n using CoordinateRepresentationType = double;\n\n \/\/ Allocate Images\n using MovingImageType = itk::Image;\n using FixedImageType = itk::Image;\n\n \/\/ Declare Gaussian Sources\n using MovingImageSourceType = itk::GaussianImageSource;\n using FixedImageSourceType = itk::GaussianImageSource;\n\n \/\/ Note: the following declarations are classical arrays\n FixedImageType::SizeValueType fixedImageSize[] = { 100, 100 };\n MovingImageType::SizeValueType movingImageSize[] = { 100, 100 };\n\n FixedImageType::SpacingValueType fixedImageSpacing[] = { 1.0f, 1.0f };\n MovingImageType::SpacingValueType movingImageSpacing[] = { 1.0f, 1.0f };\n\n FixedImageType::PointValueType fixedImageOrigin[] = { 0.0f, 0.0f };\n MovingImageType::PointValueType movingImageOrigin[] = { 0.0f, 0.0f };\n\n MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New();\n FixedImageSourceType::Pointer fixedImageSource = FixedImageSourceType::New();\n\n movingImageSource->SetSize(movingImageSize);\n movingImageSource->SetOrigin(movingImageOrigin);\n movingImageSource->SetSpacing(movingImageSpacing);\n movingImageSource->SetNormalized(false);\n movingImageSource->SetScale(250.0f);\n\n fixedImageSource->SetSize(fixedImageSize);\n fixedImageSource->SetOrigin(fixedImageOrigin);\n fixedImageSource->SetSpacing(fixedImageSpacing);\n fixedImageSource->SetNormalized(false);\n fixedImageSource->SetScale(250.0f);\n\n ITK_TRY_EXPECT_NO_EXCEPTION(movingImageSource->Update()); \/\/ Force the filter to run\n ITK_TRY_EXPECT_NO_EXCEPTION(fixedImageSource->Update()); \/\/ Force the filter to run\n\n MovingImageType::Pointer movingImage = movingImageSource->GetOutput();\n FixedImageType::Pointer fixedImage = fixedImageSource->GetOutput();\n\n \/\/ Set up the metric.\n using MetricType = itk::KullbackLeiblerCompareHistogramImageToImageMetric;\n using TransformBaseType = MetricType::TransformType;\n using ScalesType = MetricType::ScalesType;\n using ParametersType = TransformBaseType::ParametersType;\n\n MetricType::Pointer metric = MetricType::New();\n\n ITK_EXERCISE_BASIC_OBJECT_METHODS(\n metric, KullbackLeiblerCompareHistogramImageToImageMetric, CompareHistogramImageToImageMetric);\n\n\n auto epsilon = 1e-12;\n ITK_TEST_SET_GET_VALUE(epsilon, metric->GetEpsilon());\n\n unsigned int nBins = 256;\n MetricType::HistogramType::SizeType histSize;\n\n histSize.SetSize(2);\n\n histSize[0] = nBins;\n histSize[1] = nBins;\n metric->SetHistogramSize(histSize);\n\n \/\/ Plug the images into the metric.\n metric->SetFixedImage(fixedImage);\n metric->SetMovingImage(movingImage);\n\n \/\/ Set up a transform.\n using TransformType = itk::TranslationTransform;\n\n TransformType::Pointer transform = TransformType::New();\n metric->SetTransform(transform);\n\n \/\/ Set up an interpolator.\n using InterpolatorType = itk::LinearInterpolateImageFunction;\n\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n interpolator->SetInputImage(movingImage);\n metric->SetInterpolator(interpolator);\n\n \/\/ Define the region over which the metric will be computed.\n metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());\n\n \/\/ Set up transform parameters.\n ParametersType parameters(transform->GetNumberOfParameters());\n\n for (unsigned int k = 0; k < ImageDimension; ++k)\n {\n parameters[k] = 0.0f;\n }\n\n \/\/ Set scales for derivative calculation.\n ScalesType scales(transform->GetNumberOfParameters());\n\n for (unsigned int k = 0; k < transform->GetNumberOfParameters(); ++k)\n {\n scales[k] = 1;\n }\n\n metric->SetDerivativeStepLengthScales(scales);\n\n \/\/ Now set up the Training Stuff\n metric->SetTrainingTransform(transform);\n metric->SetTrainingFixedImage(fixedImage);\n metric->SetTrainingFixedImageRegion(fixedImage->GetBufferedRegion());\n metric->SetTrainingMovingImage(movingImage);\n metric->SetTrainingInterpolator(interpolator);\n\n \/\/ Initialize the metric.\n metric->Initialize();\n\n \/\/ Print out metric value and derivative.\n MetricType::MeasureType measure = metric->GetValue(parameters);\n MetricType::DerivativeType derivative;\n metric->GetDerivative(parameters, derivative);\n\n std::cout << \"Metric value = \" << measure << std::endl << \"Derivative = \" << derivative << std::endl;\n\n\n std::cout << \"Test finished.\" << std::endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ example.hpp\n\/\/ ***********\n\/\/\n\/\/ Copyright (c) 2019 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace example_bot\n{\n\nusing json = nlohmann::json;\nusing namespace aegis;\nusing namespace aegis::gateway::events;\n\nclass example\n{\npublic:\n example(core & bot) : bot(bot) {};\n ~example() = default;\n\n core & bot;\n\n template\n void split(const std::string &s, char delim, Out result)\n {\n std::stringstream ss;\n ss.str(s);\n std::string item;\n while (std::getline(ss, item, delim))\n {\n if (!item.empty())\n *(result++) = item;\n }\n }\n\n const json make_info_obj(aegis::core & bot, aegis::shards::shard * _shard);\n\n std::vector split(const std::string &s, char delim)\n {\n std::vector elems;\n split(s, delim, std::back_inserter(elems));\n return elems;\n }\n\n \/\/ Messages you want to process\n void attach()\n {\n bot.set_on_message_create(std::bind(&example::MessageCreate, this, std::placeholders::_1));\n }\n\n snowflake get_snowflake(const std::string name, aegis::guild & _guild) const noexcept\n {\n if (name.empty())\n return 0;\n try\n {\n if (name[0] == '<')\n {\n \/\/mention param\n\n std::string::size_type pos = name.find_first_of('>');\n if (pos == std::string::npos)\n return { 0 };\n if (name[2] == '!')\/\/mobile mention. strip <@!\n return std::stoull(std::string{ name.substr(3, pos - 1) });\n else if (name[2] == '&')\/\/role mention. strip <@&\n return std::stoull(std::string{ name.substr(3, pos - 1) });\n else if (name[1] == '#')\/\/channel mention. strip <#\n return std::stoull(std::string{ name.substr(2, pos - 1) });\n else\/\/regular mention. strip <@\n return std::stoull(std::string{ name.substr(2, pos - 1) });\n }\n else if (std::isdigit(name[0]))\n {\n \/\/snowflake param\n return std::stoull(std::string{ name });\n }\n else\n {\n \/\/most likely username#discriminator param\n std::string::size_type n = name.find('#');\n if (n != std::string::npos)\n {\n \/\/found # separator\n for (auto & m : _guild.get_members())\n if (m.second->get_full_name() == name)\n return { m.second->get_id() };\n return 0;\n }\n return 0;\/\/# not found. unknown parameter. unicode may trigger this.\n }\n }\n catch (std::invalid_argument &)\n {\n return 0;\n }\n }\n\n const snowflake bot_owner_id = 171000788183678976LL;\n\n std::string prefix = \"?\";\n\n \/\/ All the hooks in the websocket stream\n void TypingStart(typing_start obj);\n\n void MessageCreate(message_create msg);\n\n void MessageCreateDM(message_create msg);\n\n void MessageUpdate(message_update obj);\n\n void MessageDelete(message_delete obj);\n\n void MessageDeleteBulk(message_delete_bulk obj);\n\n void GuildCreate(guild_create);\n\n void GuildUpdate(guild_update obj);\n\n void GuildDelete(guild_delete obj);\n\n void UserUpdate(user_update obj);\n\n void Ready(ready obj);\n\n void Resumed(resumed obj);\n\n void ChannelCreate(channel_create obj);\n\n void ChannelUpdate(channel_update obj);\n\n void ChannelDelete(channel_delete obj);\n\n void GuildBanAdd(guild_ban_add obj);\n\n void GuildBanRemove(guild_ban_remove obj);\n\n void GuildEmojisUpdate(guild_emojis_update obj);\n\n void GuildIntegrationsUpdate(guild_integrations_update obj);\n\n void GuildMemberAdd(guild_member_add obj);\n\n void GuildMemberRemove(guild_member_remove obj);\n\n void GuildMemberUpdate(guild_member_update obj);\n\n void GuildMemberChunk(guild_members_chunk obj);\n\n void GuildRoleCreate(guild_role_create obj);\n\n void GuildRoleUpdate(guild_role_update obj);\n\n void GuildRoleDelete(guild_role_delete obj);\n\n void PresenceUpdate(presence_update obj);\n\n void VoiceStateUpdate(voice_state_update obj);\n\n void VoiceServerUpdate(voice_server_update obj);\n\n const json make_info_obj(shard * _shard, core * bot);\n};\n\n}\nExample fix\/\/\n\/\/ example.hpp\n\/\/ ***********\n\/\/\n\/\/ Copyright (c) 2019 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace example_bot\n{\n\nusing json = nlohmann::json;\nusing namespace aegis;\nusing namespace aegis::gateway::events;\n\nclass example\n{\npublic:\n example(core & bot) : bot(bot) {};\n ~example() = default;\n\n core & bot;\n\n template\n void split(const std::string &s, char delim, Out result)\n {\n std::stringstream ss;\n ss.str(s);\n std::string item;\n while (std::getline(ss, item, delim))\n {\n if (!item.empty())\n *(result++) = item;\n }\n }\n\n const json make_info_obj(aegis::core & bot, aegis::shards::shard * _shard);\n\n std::vector split(const std::string &s, char delim)\n {\n std::vector elems;\n split(s, delim, std::back_inserter(elems));\n return elems;\n }\n\n \/\/ Messages you want to process\n void attach()\n {\n bot.set_on_message_create(std::bind(&example::MessageCreate, this, std::placeholders::_1));\n }\n\n snowflake get_snowflake(const std::string name, aegis::guild & _guild) const noexcept\n {\n if (name.empty())\n return 0;\n try\n {\n if (name[0] == '<')\n {\n \/\/mention param\n\n std::string::size_type pos = name.find_first_of('>');\n if (pos == std::string::npos)\n return 0;\n if (name[2] == '!')\/\/mobile mention. strip <@!\n return std::stoull(std::string{ name.substr(3, pos - 1) });\n else if (name[2] == '&')\/\/role mention. strip <@&\n return std::stoull(std::string{ name.substr(3, pos - 1) });\n else if (name[1] == '#')\/\/channel mention. strip <#\n return std::stoull(std::string{ name.substr(2, pos - 1) });\n else\/\/regular mention. strip <@\n return std::stoull(std::string{ name.substr(2, pos - 1) });\n }\n else if (std::isdigit(name[0]))\n {\n \/\/snowflake param\n return std::stoull(std::string{ name });\n }\n else\n {\n \/\/most likely username#discriminator param\n std::string::size_type n = name.find('#');\n if (n != std::string::npos)\n {\n \/\/found # separator\n for (auto & m : _guild.get_members())\n if (m.second->get_full_name() == name)\n return { m.second->get_id() };\n return 0;\n }\n return 0;\/\/# not found. unknown parameter. unicode may trigger this.\n }\n }\n catch (std::invalid_argument &)\n {\n return 0;\n }\n }\n\n const snowflake bot_owner_id = 171000788183678976LL;\n\n std::string prefix = \"?\";\n\n \/\/ All the hooks in the websocket stream\n void TypingStart(typing_start obj);\n\n void MessageCreate(message_create msg);\n\n void MessageCreateDM(message_create msg);\n\n void MessageUpdate(message_update obj);\n\n void MessageDelete(message_delete obj);\n\n void MessageDeleteBulk(message_delete_bulk obj);\n\n void GuildCreate(guild_create);\n\n void GuildUpdate(guild_update obj);\n\n void GuildDelete(guild_delete obj);\n\n void UserUpdate(user_update obj);\n\n void Ready(ready obj);\n\n void Resumed(resumed obj);\n\n void ChannelCreate(channel_create obj);\n\n void ChannelUpdate(channel_update obj);\n\n void ChannelDelete(channel_delete obj);\n\n void GuildBanAdd(guild_ban_add obj);\n\n void GuildBanRemove(guild_ban_remove obj);\n\n void GuildEmojisUpdate(guild_emojis_update obj);\n\n void GuildIntegrationsUpdate(guild_integrations_update obj);\n\n void GuildMemberAdd(guild_member_add obj);\n\n void GuildMemberRemove(guild_member_remove obj);\n\n void GuildMemberUpdate(guild_member_update obj);\n\n void GuildMemberChunk(guild_members_chunk obj);\n\n void GuildRoleCreate(guild_role_create obj);\n\n void GuildRoleUpdate(guild_role_update obj);\n\n void GuildRoleDelete(guild_role_delete obj);\n\n void PresenceUpdate(presence_update obj);\n\n void VoiceStateUpdate(voice_state_update obj);\n\n void VoiceServerUpdate(voice_server_update obj);\n\n const json make_info_obj(shard * _shard, core * bot);\n};\n\n}\n<|endoftext|>"} {"text":"\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n\t\\file\t\tTextfileOut.cpp\r\n\t\\author\t\tJens Krueger\r\n\t\t\t\tSCI Institute\r\n\t\t\t\tUniversity of Utah\r\n\t\\version\t1.0\r\n\t\\date\t\tAugust 2008\r\n*\/\r\n\r\n#include \"TextfileOut.h\"\r\n\r\n#ifdef WIN32\r\n\t#include \r\n#endif\r\n\r\n#include \r\nusing namespace std;\r\n\r\nTextfileOut::TextfileOut(std::string strFilename) :\r\n\tm_strFilename(strFilename)\r\n{\r\n\tthis->printf(\"MESSAGE (TextfileOut::~TextfileOut:): Starting up\");\r\n}\r\n\r\nTextfileOut::~TextfileOut() {\r\n\tthis->printf(\"MESSAGE (TextfileOut::~TextfileOut:): Shutting down\\n\\n\\n\");\r\n}\r\n\r\nvoid TextfileOut::printf(const char* format, ...)\r\n{\r\n\tif (!m_bShowOther) return;\r\n\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\r\n\tofstream fs;\r\n\tfs.open(m_strFilename.c_str(), ios_base::app);\r\n\tif (fs.fail()) return;\r\n\tfs << buff << endl;\r\n\tfs.close();\r\n}\r\n\r\nvoid TextfileOut::Message(const char* source, const char* format, ...) {\r\n\tif (!m_bShowMessages) return;\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\tthis->printf(\"MESSAGE (%s): %s\",source, buff);\r\n}\r\n\r\nvoid TextfileOut::Warning(const char* source, const char* format, ...) {\r\n\tif (!m_bShowWarnings) return;\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\tthis->printf(\"WARNING (%s): %s\",source, buff);\r\n}\r\n\r\nvoid TextfileOut::Error(const char* source, const char* format, ...) {\r\n\tif (!m_bShowErrors) return;\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\tthis->printf(\"ERROR (%s): %s\",source, buff);\r\n}\r\n\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n\t\\file\t\tTextfileOut.cpp\r\n\t\\author\t\tJens Krueger\r\n\t\t\t\tSCI Institute\r\n\t\t\t\tUniversity of Utah\r\n\t\\version\t1.0\r\n\t\\date\t\tAugust 2008\r\n*\/\r\n\r\n#include \"TextfileOut.h\"\r\n\r\n#ifdef WIN32\r\n\t#include \r\n#endif\r\n\r\n#include \r\n\r\n#include \r\nusing namespace std;\r\n\r\nTextfileOut::TextfileOut(std::string strFilename) :\r\n\tm_strFilename(strFilename)\r\n{\r\n\tthis->printf(\"MESSAGE (TextfileOut::~TextfileOut:): Starting up\");\r\n}\r\n\r\nTextfileOut::~TextfileOut() {\r\n\tthis->printf(\"MESSAGE (TextfileOut::~TextfileOut:): Shutting down\\n\\n\\n\");\r\n}\r\n\r\nvoid TextfileOut::printf(const char* format, ...)\r\n{\r\n\tif (!m_bShowOther) return;\r\n\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\r\n\tofstream fs;\r\n\tfs.open(m_strFilename.c_str(), ios_base::app);\r\n\tif (fs.fail()) return;\r\n\tfs << buff << endl;\r\n\tfs.close();\r\n}\r\n\r\nvoid TextfileOut::Message(const char* source, const char* format, ...) {\r\n\tif (!m_bShowMessages) return;\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\tthis->printf(\"MESSAGE (%s): %s\",source, buff);\r\n}\r\n\r\nvoid TextfileOut::Warning(const char* source, const char* format, ...) {\r\n\tif (!m_bShowWarnings) return;\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\tthis->printf(\"WARNING (%s): %s\",source, buff);\r\n}\r\n\r\nvoid TextfileOut::Error(const char* source, const char* format, ...) {\r\n\tif (!m_bShowErrors) return;\r\n\tchar buff[16384];\r\n\tva_list args;\r\n\tva_start(args, format);\r\n#ifdef WIN32\r\n\t_vsnprintf_s( buff, 16384, sizeof(buff), format, args);\r\n#else\r\n\tvsnprintf( buff, sizeof(buff), format, args);\r\n#endif\r\n\tthis->printf(\"ERROR (%s): %s\",source, buff);\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"tinyworld.h\"\n#include \"mylogger.h\"\n#include \"mydb.h\"\n\n#include \"object2db.h\"\n#include \"object2bin.h\"\n\n#include \"player.h\"\n#include \"player.db.h\"\n#include \"player.pb.h\"\n#include \"player.bin.h\"\n\nLoggerPtr logger(Logger::getLogger(\"test\"));\n\nvoid dumpPlayer(const Player& p)\n{\n std::cout << \"Player:\"\n << p.id << \"\\t\"\n << p.name << \"\\t\"\n << p.bin.size() << \"\\t\"\n << p.score << std::endl;\n}\n\ntypedef Object2DB PlayerDB;\ntypedef Object2Bin PlayerBin;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid test_bin()\n{\n\/\/ bin::Player player;\n\/\/ player.set_id(10);\n\/\/ player.set_score(45.0);\n\/\/ player.set_name(\"david\");\n\/\/ player.set_v_bool(true);\n\/\/ std::cout << player.DebugString() << std::endl;\n\n Player p;\n p.id = 1;\n strncpy(p.name, \"name\", sizeof(p.name)-1);\n p.bin =\"binary.....\";\n\n std::string bin;\n\n PlayerBin pb(p);\n pb.serialize(bin);\n std::cout << pb.debugString() << std::endl;\n\n PlayerBin pb2;\n pb2.deserialize(bin);\n std::cout << pb2.debugString() << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid test_db()\n{\n Player p;\n p.id = 1;\n strncpy(p.name, \"name\", sizeof(p.name)-1);\n p.bin =\"binary.....\";\n\n mysqlpp::Query query(NULL);\n PlayerDBDescriptor pd;\n\n pd.makeInsertQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeReplaceQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeUpdateQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeDeleteQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeSelectFromQuery(query, \"WHERE `ID`=100\");\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeDeleteFromQuery(query, \"WHERE `ID`=100\");\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeCreateQuery(query);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeAddFieldQuery(query, \"`ID`\");\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n}\n\nstruct DummyData\n{\n int int_ = 0x123456;\n float float_value = 3.1415;\n char char_ = 'A';\n\n void dump()\n {\n LOG4CXX_DEBUG(logger, \"DUMMY DATA:\" << int_ << \",\" << float_value << \",\" << char_);\n }\n};\n\nvoid test_create()\n{\n PlayerDB::createTable();\n}\n\nvoid test_drop()\n{\n PlayerDB::dropTable();\n}\n\nvoid test_update()\n{\n PlayerDB::updateTable();\n}\n\nvoid test_insertDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n Player p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player:%u\", i);\n\n DummyData data;\n data.float_value *= i;\n p.bin.assign((char*)&data, sizeof(data));\n\n\n PlayerDB pdb2;\n PlayerDB pdb(p);\n\/\/ dumpPlayer(pdb);\n pdb.insertDB();\n }\n}\n\nvoid test_replaceDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player-replace:%u\", i);\n p.replaceDB();\n }\n}\n\nvoid test_updateDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player-update:%u\", i);\n p.updateDB();\n }\n}\n\nvoid test_deleteDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player-update:%u\", i);\n p.deleteDB();\n }\n}\n\nvoid test_selectDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.selectDB();\n dumpPlayer(p);\n }\n}\n\nvoid test_loadFromDB()\n{\n PlayerDB::Records players;\n PlayerDB::loadFromDB(players, \"\");\n\n std::for_each(players.begin(), players.end(), dumpPlayer);\n}\n\nvoid test_deleteFromDB()\n{\n PlayerDB::deleteFromDB(\"\");\n}\n\n\nint main(int argc, const char* argv[])\n{\n if (argc < 2)\n {\n std::cout << \"Usage:\" << argv[0]\n << \" create | drop | update\" << std::endl;\n return 1;\n }\n\n BasicConfigurator::configure();\n\n LOG4CXX_DEBUG(logger, \"dataserver 启动\")\n\n MySqlConnectionPool::instance()->setServerAddress(\"mysql:\/\/david:123456@127.0.0.1\/tinyworld?maxconn=5\");\n MySqlConnectionPool::instance()->createAll();\n\n std::string op = argv[1];\n if (\"create\" == op)\n test_create();\n else if (\"drop\" == op)\n test_drop();\n else if (\"updatetable\" == op)\n test_update();\n else if (\"test\" == op)\n test_db();\n else if (\"insertDB\" == op)\n test_insertDB();\n else if (\"replaceDB\" == op)\n test_replaceDB();\n else if (\"updateDB\" == op)\n test_updateDB();\n else if (\"deleteDB\" == op)\n test_deleteDB();\n else if (\"selectDB\" == op)\n test_selectDB();\n else if (\"loadFromDB\" == op)\n test_loadFromDB();\n else if (\"deleteFromDB\" == op)\n test_deleteFromDB();\n else if (\"testbin\" == op)\n test_bin();\n\n return 0;\n}\nYAML生成SuperObject#include \n#include \n#include \n#include \n#include \n\n#include \"tinyworld.h\"\n#include \"mylogger.h\"\n#include \"mydb.h\"\n\n#include \"object2db.h\"\n#include \"object2bin.h\"\n\n#include \"player.h\"\n#include \"player.db.h\"\n#include \"player.pb.h\"\n#include \"player.bin.h\"\n\nLoggerPtr logger(Logger::getLogger(\"test\"));\n\nvoid dumpPlayer(const Player& p)\n{\n std::cout << \"Player:\"\n << p.id << \"\\t\"\n << p.name << \"\\t\"\n << p.bin.size() << \"\\t\"\n << p.score << std::endl;\n}\n\ntemplate \nstruct SuperObject\n{\n typedef Object2Bin BinType;\n typedef Object2DB DBType;\n typedef Object2DB Type;\n};\n\ntypedef Object2DB PlayerDB;\ntypedef Object2Bin PlayerBin;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntypedef SuperObject::Type SuperPlayer;\n\/\/typedef Object2DB, PlayerDBDescriptor> SuperPlayer;\n\nvoid test_super()\n{\n SuperPlayer p;\n p.id = 2;\n p.selectDB();\n\n std::cout << p.debugString() << std::endl;\n\n std::string bin;\n p.serialize(bin);\n\n SuperPlayer p2;\n p2.deserialize(bin);\n\n std::cout << p2.debugString() << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid test_bin()\n{\n\/\/ bin::Player player;\n\/\/ player.set_id(10);\n\/\/ player.set_score(45.0);\n\/\/ player.set_name(\"david\");\n\/\/ player.set_v_bool(true);\n\/\/ std::cout << player.DebugString() << std::endl;\n\n Player p;\n p.id = 1;\n strncpy(p.name, \"name\", sizeof(p.name)-1);\n p.bin =\"binary.....\";\n\n std::string bin;\n\n PlayerBin pb(p);\n pb.serialize(bin);\n std::cout << pb.debugString() << std::endl;\n\n PlayerBin pb2;\n pb2.deserialize(bin);\n std::cout << pb2.debugString() << std::endl;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid test_db()\n{\n Player p;\n p.id = 1;\n strncpy(p.name, \"name\", sizeof(p.name)-1);\n p.bin =\"binary.....\";\n\n mysqlpp::Query query(NULL);\n PlayerDBDescriptor pd;\n\n pd.makeInsertQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeReplaceQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeUpdateQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeDeleteQuery(query, p);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeSelectFromQuery(query, \"WHERE `ID`=100\");\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeDeleteFromQuery(query, \"WHERE `ID`=100\");\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeCreateQuery(query);\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n\n pd.makeAddFieldQuery(query, \"`ID`\");\n std::cout << \"SQL:\" << query.str() << std::endl;\n query.reset();\n}\n\nstruct DummyData\n{\n int int_ = 0x123456;\n float float_value = 3.1415;\n char char_ = 'A';\n\n void dump()\n {\n LOG4CXX_DEBUG(logger, \"DUMMY DATA:\" << int_ << \",\" << float_value << \",\" << char_);\n }\n};\n\nvoid test_create()\n{\n PlayerDB::createTable();\n}\n\nvoid test_drop()\n{\n PlayerDB::dropTable();\n}\n\nvoid test_update()\n{\n PlayerDB::updateTable();\n}\n\nvoid test_insertDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n Player p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player:%u\", i);\n\n DummyData data;\n data.float_value *= i;\n p.bin.assign((char*)&data, sizeof(data));\n\n\n PlayerDB pdb2;\n PlayerDB pdb(p);\n\/\/ dumpPlayer(pdb);\n pdb.insertDB();\n }\n}\n\nvoid test_replaceDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player-replace:%u\", i);\n p.replaceDB();\n }\n}\n\nvoid test_updateDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player-update:%u\", i);\n p.updateDB();\n }\n}\n\nvoid test_deleteDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.score = 1.1f * i;\n snprintf(p.name, sizeof(p.name), \"player-update:%u\", i);\n p.deleteDB();\n }\n}\n\nvoid test_selectDB()\n{\n for (unsigned int i = 1; i <= 10; ++i )\n {\n PlayerDB p;\n p.id = i;\n p.selectDB();\n dumpPlayer(p);\n }\n}\n\nvoid test_loadFromDB()\n{\n PlayerDB::Records players;\n PlayerDB::loadFromDB(players, \"\");\n\n std::for_each(players.begin(), players.end(), dumpPlayer);\n}\n\nvoid test_deleteFromDB()\n{\n PlayerDB::deleteFromDB(\"\");\n}\n\n\nint main(int argc, const char* argv[])\n{\n if (argc < 2)\n {\n std::cout << \"Usage:\" << argv[0]\n << \" create | drop | update\" << std::endl;\n return 1;\n }\n\n BasicConfigurator::configure();\n\n LOG4CXX_DEBUG(logger, \"dataserver 启动\")\n\n MySqlConnectionPool::instance()->setServerAddress(\"mysql:\/\/david:123456@127.0.0.1\/tinyworld?maxconn=5\");\n MySqlConnectionPool::instance()->createAll();\n\n std::string op = argv[1];\n if (\"create\" == op)\n test_create();\n else if (\"drop\" == op)\n test_drop();\n else if (\"updatetable\" == op)\n test_update();\n else if (\"test\" == op)\n test_db();\n else if (\"insertDB\" == op)\n test_insertDB();\n else if (\"replaceDB\" == op)\n test_replaceDB();\n else if (\"updateDB\" == op)\n test_updateDB();\n else if (\"deleteDB\" == op)\n test_deleteDB();\n else if (\"selectDB\" == op)\n test_selectDB();\n else if (\"loadFromDB\" == op)\n test_loadFromDB();\n else if (\"deleteFromDB\" == op)\n test_deleteFromDB();\n else if (\"testbin\" == op)\n test_bin();\n else if (\"testsuper\" == op)\n test_super();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"mem\/Compiler.hpp\"\n\n\nint main (int argc, char** argv)\n{\n opt::Options opts;\n opts.addStrOpt(\"--dump-ast-xml\", \"\",\n \"Dump the Abstract Syntax Tree as XML\");\n opts.addStrOpt(\"--emit-llvm-bc\", \"\",\n \"Emit LLVM bytecode\");\n opts.addStrOpt(\"--log-formatter\", \"\",\n \"Set the log formatter\");\n opts.addIntEnumOpt(\"--log-level\", \"\",\n \"Set the minimum log level\")\n ->bind(\"unknown\", log::UNKNOWN)\n ->bind(\"debug\", log::DEBUG)\n ->bind(\"info\", log::INFO)\n ->bind(\"warning\", log::WARNING)\n ->bind(\"error\", log::ERROR)\n ->bind(\"fatal-error\", log::FATAL_ERROR);\n opts.addBoolOpt(\"--help\", \"\",\n \"Show help\");\n opts.addStrOpt(\"--output\", \"\",\n \"Path to the output file\");\n opts.addBoolOpt(\"--version\", \"\",\n \"Show version\");\n opts.addStrOpt(\"--dump-st-xml\", \"\",\n \"Dump the Symbol Table as XML\");\n opts.parse(argc, argv);\n\n Compiler memc;\n memc.setOptions(&opts);\n memc.run();\n\n return 0;\n}\nChange exit code to 1 if build unsuccessful#include \"mem\/Compiler.hpp\"\n\n\nint main (int argc, char** argv)\n{\n opt::Options opts;\n opts.addStrOpt(\"--dump-ast-xml\", \"\",\n \"Dump the Abstract Syntax Tree as XML\");\n opts.addStrOpt(\"--emit-llvm-bc\", \"\",\n \"Emit LLVM bytecode\");\n opts.addStrOpt(\"--log-formatter\", \"\",\n \"Set the log formatter\");\n opts.addIntEnumOpt(\"--log-level\", \"\",\n \"Set the minimum log level\")\n ->bind(\"unknown\", log::UNKNOWN)\n ->bind(\"debug\", log::DEBUG)\n ->bind(\"info\", log::INFO)\n ->bind(\"warning\", log::WARNING)\n ->bind(\"error\", log::ERROR)\n ->bind(\"fatal-error\", log::FATAL_ERROR);\n opts.addBoolOpt(\"--help\", \"\",\n \"Show help\");\n opts.addStrOpt(\"--output\", \"\",\n \"Path to the output file\");\n opts.addBoolOpt(\"--version\", \"\",\n \"Show version\");\n opts.addStrOpt(\"--dump-st-xml\", \"\",\n \"Dump the Symbol Table as XML\");\n opts.parse(argc, argv);\n\n Compiler memc;\n memc.setOptions(&opts);\n memc.run();\n\n return memc.isBuildSuccessful() ? 0 : 1;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\n#include \"db\/db_impl.h\"\n#include \"rocksdb\/db.h\"\n#include \"rocksdb\/env.h\"\n#include \"table\/meta_blocks.h\"\n#include \"table\/cuckoo_table_factory.h\"\n#include \"table\/cuckoo_table_reader.h\"\n#include \"util\/testharness.h\"\n#include \"util\/testutil.h\"\n\nnamespace rocksdb {\n\nclass CuckooTableDBTest {\n private:\n std::string dbname_;\n Env* env_;\n DB* db_;\n\n public:\n CuckooTableDBTest() : env_(Env::Default()) {\n dbname_ = test::TmpDir() + \"\/cuckoo_table_db_test\";\n ASSERT_OK(DestroyDB(dbname_, Options()));\n db_ = nullptr;\n Reopen();\n }\n\n ~CuckooTableDBTest() {\n delete db_;\n ASSERT_OK(DestroyDB(dbname_, Options()));\n }\n\n Options CurrentOptions() {\n Options options;\n options.table_factory.reset(NewCuckooTableFactory());\n options.memtable_factory.reset(NewHashLinkListRepFactory(4, 0, 3, true));\n options.allow_mmap_reads = true;\n options.create_if_missing = true;\n options.max_mem_compaction_level = 0;\n return options;\n }\n\n DBImpl* dbfull() {\n return reinterpret_cast(db_);\n }\n\n \/\/ The following util methods are copied from plain_table_db_test.\n void Reopen(Options* options = nullptr) {\n delete db_;\n db_ = nullptr;\n Options opts;\n if (options != nullptr) {\n opts = *options;\n } else {\n opts = CurrentOptions();\n opts.create_if_missing = true;\n }\n ASSERT_OK(DB::Open(opts, dbname_, &db_));\n }\n\n Status Put(const Slice& k, const Slice& v) {\n return db_->Put(WriteOptions(), k, v);\n }\n\n Status Delete(const std::string& k) {\n return db_->Delete(WriteOptions(), k);\n }\n\n std::string Get(const std::string& k) {\n ReadOptions options;\n std::string result;\n Status s = db_->Get(options, k, &result);\n if (s.IsNotFound()) {\n result = \"NOT_FOUND\";\n } else if (!s.ok()) {\n result = s.ToString();\n }\n return result;\n }\n\n int NumTableFilesAtLevel(int level) {\n std::string property;\n ASSERT_TRUE(\n db_->GetProperty(\"rocksdb.num-files-at-level\" + NumberToString(level),\n &property));\n return atoi(property.c_str());\n }\n\n \/\/ Return spread of files per level\n std::string FilesPerLevel() {\n std::string result;\n int last_non_zero_offset = 0;\n for (int level = 0; level < db_->NumberLevels(); level++) {\n int f = NumTableFilesAtLevel(level);\n char buf[100];\n snprintf(buf, sizeof(buf), \"%s%d\", (level ? \",\" : \"\"), f);\n result += buf;\n if (f > 0) {\n last_non_zero_offset = result.size();\n }\n }\n result.resize(last_non_zero_offset);\n return result;\n }\n};\n\nTEST(CuckooTableDBTest, Flush) {\n \/\/ Try with empty DB first.\n ASSERT_TRUE(dbfull() != nullptr);\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key2\"));\n\n \/\/ Add some values to db.\n Options options = CurrentOptions();\n Reopen(&options);\n\n ASSERT_OK(Put(\"key1\", \"v1\"));\n ASSERT_OK(Put(\"key2\", \"v2\"));\n ASSERT_OK(Put(\"key3\", \"v3\"));\n dbfull()->TEST_FlushMemTable();\n\n TablePropertiesCollection ptc;\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(1U, ptc.size());\n ASSERT_EQ(3U, ptc.begin()->second->num_entries);\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n ASSERT_EQ(\"v1\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key4\"));\n\n \/\/ Now add more keys and flush.\n ASSERT_OK(Put(\"key4\", \"v4\"));\n ASSERT_OK(Put(\"key5\", \"v5\"));\n ASSERT_OK(Put(\"key6\", \"v6\"));\n dbfull()->TEST_FlushMemTable();\n\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(2U, ptc.size());\n auto row = ptc.begin();\n ASSERT_EQ(3U, row->second->num_entries);\n ASSERT_EQ(3U, (++row)->second->num_entries);\n ASSERT_EQ(\"2\", FilesPerLevel());\n ASSERT_EQ(\"v1\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"v4\", Get(\"key4\"));\n ASSERT_EQ(\"v5\", Get(\"key5\"));\n ASSERT_EQ(\"v6\", Get(\"key6\"));\n\n ASSERT_OK(Delete(\"key6\"));\n ASSERT_OK(Delete(\"key5\"));\n ASSERT_OK(Delete(\"key4\"));\n dbfull()->TEST_FlushMemTable();\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(3U, ptc.size());\n row = ptc.begin();\n ASSERT_EQ(3U, row->second->num_entries);\n ASSERT_EQ(3U, (++row)->second->num_entries);\n ASSERT_EQ(3U, (++row)->second->num_entries);\n ASSERT_EQ(\"3\", FilesPerLevel());\n ASSERT_EQ(\"v1\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key4\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key5\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key6\"));\n}\n\nTEST(CuckooTableDBTest, FlushWithDuplicateKeys) {\n Options options = CurrentOptions();\n Reopen(&options);\n ASSERT_OK(Put(\"key1\", \"v1\"));\n ASSERT_OK(Put(\"key2\", \"v2\"));\n ASSERT_OK(Put(\"key1\", \"v3\")); \/\/ Duplicate\n dbfull()->TEST_FlushMemTable();\n\n TablePropertiesCollection ptc;\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(1U, ptc.size());\n ASSERT_EQ(2U, ptc.begin()->second->num_entries);\n ASSERT_EQ(\"1\", FilesPerLevel());\n ASSERT_EQ(\"v3\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n}\n\nnamespace {\nstatic std::string Key(int i) {\n char buf[100];\n snprintf(buf, sizeof(buf), \"key_______%06d\", i);\n return std::string(buf);\n}\nstatic std::string Uint64Key(uint64_t i) {\n std::string str;\n str.resize(8);\n memcpy(&str[0], static_cast(&i), 8);\n return str;\n}\n} \/\/ namespace.\n\nTEST(CuckooTableDBTest, Uint64Comparator) {\n Options options = CurrentOptions();\n options.comparator = test::Uint64Comparator();\n Reopen(&options);\n\n ASSERT_OK(Put(Uint64Key(1), \"v1\"));\n ASSERT_OK(Put(Uint64Key(2), \"v2\"));\n ASSERT_OK(Put(Uint64Key(3), \"v3\"));\n dbfull()->TEST_FlushMemTable();\n\n ASSERT_EQ(\"v1\", Get(Uint64Key(1)));\n ASSERT_EQ(\"v2\", Get(Uint64Key(2)));\n ASSERT_EQ(\"v3\", Get(Uint64Key(3)));\n ASSERT_EQ(\"NOT_FOUND\", Get(Uint64Key(4)));\n\n \/\/ Add more keys.\n ASSERT_OK(Delete(Uint64Key(2))); \/\/ Delete.\n ASSERT_OK(Put(Uint64Key(3), \"v0\")); \/\/ Update.\n ASSERT_OK(Put(Uint64Key(4), \"v4\"));\n dbfull()->TEST_FlushMemTable();\n ASSERT_EQ(\"v1\", Get(Uint64Key(1)));\n ASSERT_EQ(\"NOT_FOUND\", Get(Uint64Key(2)));\n ASSERT_EQ(\"v0\", Get(Uint64Key(3)));\n ASSERT_EQ(\"v4\", Get(Uint64Key(4)));\n}\n\nTEST(CuckooTableDBTest, CompactionTrigger) {\n Options options = CurrentOptions();\n options.write_buffer_size = 100 << 10; \/\/ 100KB\n options.level0_file_num_compaction_trigger = 2;\n Reopen(&options);\n\n \/\/ Write 11 values, each 10016 B\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n \/\/ Generate one more file in level-0, and should trigger level-0 compaction\n for (int idx = 11; idx < 22; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"2\", FilesPerLevel());\n\n dbfull()->TEST_CompactRange(0, nullptr, nullptr);\n ASSERT_EQ(\"0,2\", FilesPerLevel());\n for (int idx = 0; idx < 22; ++idx) {\n ASSERT_EQ(std::string(10000, 'a' + idx), Get(Key(idx)));\n }\n}\n\nTEST(CuckooTableDBTest, CompactionIntoMultipleFiles) {\n \/\/ Create a big L0 file and check it compacts into multiple files in L1.\n Options options = CurrentOptions();\n options.write_buffer_size = 270 << 10;\n \/\/ Two SST files should be created, each containing 14 keys.\n \/\/ Number of buckets will be 16. Total size ~156 KB.\n options.target_file_size_base = 160 << 10;\n Reopen(&options);\n\n \/\/ Write 28 values, each 10016 B ~ 10KB\n for (int idx = 0; idx < 28; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n dbfull()->TEST_CompactRange(0, nullptr, nullptr);\n ASSERT_EQ(\"0,2\", FilesPerLevel());\n for (int idx = 0; idx < 28; ++idx) {\n ASSERT_EQ(std::string(10000, 'a' + idx), Get(Key(idx)));\n }\n}\n\nTEST(CuckooTableDBTest, SameKeyInsertedInTwoDifferentFilesAndCompacted) {\n \/\/ Insert same key twice so that they go to different SST files. Then wait for\n \/\/ compaction and check if the latest value is stored and old value removed.\n Options options = CurrentOptions();\n options.write_buffer_size = 100 << 10; \/\/ 100KB\n options.level0_file_num_compaction_trigger = 2;\n Reopen(&options);\n\n \/\/ Write 11 values, each 10016 B\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a')));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n \/\/ Generate one more file in level-0, and should trigger level-0 compaction\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n dbfull()->TEST_CompactRange(0, nullptr, nullptr);\n\n ASSERT_EQ(\"0,1\", FilesPerLevel());\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_EQ(std::string(10000, 'a' + idx), Get(Key(idx)));\n }\n}\n\nTEST(CuckooTableDBTest, AdaptiveTable) {\n Options options = CurrentOptions();\n\n \/\/ Write some keys using cuckoo table.\n options.table_factory.reset(NewCuckooTableFactory());\n Reopen(&options);\n\n ASSERT_OK(Put(\"key1\", \"v1\"));\n ASSERT_OK(Put(\"key2\", \"v2\"));\n ASSERT_OK(Put(\"key3\", \"v3\"));\n dbfull()->TEST_FlushMemTable();\n\n \/\/ Write some keys using plain table.\n options.create_if_missing = false;\n options.table_factory.reset(NewPlainTableFactory());\n Reopen(&options);\n ASSERT_OK(Put(\"key4\", \"v4\"));\n ASSERT_OK(Put(\"key1\", \"v5\"));\n dbfull()->TEST_FlushMemTable();\n\n \/\/ Write some keys using block based table.\n std::shared_ptr block_based_factory(\n NewBlockBasedTableFactory());\n options.table_factory.reset(NewAdaptiveTableFactory(block_based_factory));\n Reopen(&options);\n ASSERT_OK(Put(\"key5\", \"v6\"));\n ASSERT_OK(Put(\"key2\", \"v7\"));\n dbfull()->TEST_FlushMemTable();\n\n ASSERT_EQ(\"v5\", Get(\"key1\"));\n ASSERT_EQ(\"v7\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"v4\", Get(\"key4\"));\n ASSERT_EQ(\"v6\", Get(\"key5\"));\n}\n} \/\/ namespace rocksdb\n\nint main(int argc, char** argv) { return rocksdb::test::RunAllTests(); }\ncuckoo_table_db_test.cc: add flush after delete\/\/ Copyright (c) 2014, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\n#include \"db\/db_impl.h\"\n#include \"rocksdb\/db.h\"\n#include \"rocksdb\/env.h\"\n#include \"table\/meta_blocks.h\"\n#include \"table\/cuckoo_table_factory.h\"\n#include \"table\/cuckoo_table_reader.h\"\n#include \"util\/testharness.h\"\n#include \"util\/testutil.h\"\n\nnamespace rocksdb {\n\nclass CuckooTableDBTest {\n private:\n std::string dbname_;\n Env* env_;\n DB* db_;\n\n public:\n CuckooTableDBTest() : env_(Env::Default()) {\n dbname_ = test::TmpDir() + \"\/cuckoo_table_db_test\";\n ASSERT_OK(DestroyDB(dbname_, Options()));\n db_ = nullptr;\n Reopen();\n }\n\n ~CuckooTableDBTest() {\n delete db_;\n ASSERT_OK(DestroyDB(dbname_, Options()));\n }\n\n Options CurrentOptions() {\n Options options;\n options.table_factory.reset(NewCuckooTableFactory());\n options.memtable_factory.reset(NewHashLinkListRepFactory(4, 0, 3, true));\n options.allow_mmap_reads = true;\n options.create_if_missing = true;\n options.max_mem_compaction_level = 0;\n return options;\n }\n\n DBImpl* dbfull() {\n return reinterpret_cast(db_);\n }\n\n \/\/ The following util methods are copied from plain_table_db_test.\n void Reopen(Options* options = nullptr) {\n delete db_;\n db_ = nullptr;\n Options opts;\n if (options != nullptr) {\n opts = *options;\n } else {\n opts = CurrentOptions();\n opts.create_if_missing = true;\n }\n ASSERT_OK(DB::Open(opts, dbname_, &db_));\n }\n\n Status Put(const Slice& k, const Slice& v) {\n return db_->Put(WriteOptions(), k, v);\n }\n\n Status Delete(const std::string& k) {\n return db_->Delete(WriteOptions(), k);\n }\n\n std::string Get(const std::string& k) {\n ReadOptions options;\n std::string result;\n Status s = db_->Get(options, k, &result);\n if (s.IsNotFound()) {\n result = \"NOT_FOUND\";\n } else if (!s.ok()) {\n result = s.ToString();\n }\n return result;\n }\n\n int NumTableFilesAtLevel(int level) {\n std::string property;\n ASSERT_TRUE(\n db_->GetProperty(\"rocksdb.num-files-at-level\" + NumberToString(level),\n &property));\n return atoi(property.c_str());\n }\n\n \/\/ Return spread of files per level\n std::string FilesPerLevel() {\n std::string result;\n int last_non_zero_offset = 0;\n for (int level = 0; level < db_->NumberLevels(); level++) {\n int f = NumTableFilesAtLevel(level);\n char buf[100];\n snprintf(buf, sizeof(buf), \"%s%d\", (level ? \",\" : \"\"), f);\n result += buf;\n if (f > 0) {\n last_non_zero_offset = result.size();\n }\n }\n result.resize(last_non_zero_offset);\n return result;\n }\n};\n\nTEST(CuckooTableDBTest, Flush) {\n \/\/ Try with empty DB first.\n ASSERT_TRUE(dbfull() != nullptr);\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key2\"));\n\n \/\/ Add some values to db.\n Options options = CurrentOptions();\n Reopen(&options);\n\n ASSERT_OK(Put(\"key1\", \"v1\"));\n ASSERT_OK(Put(\"key2\", \"v2\"));\n ASSERT_OK(Put(\"key3\", \"v3\"));\n dbfull()->TEST_FlushMemTable();\n\n TablePropertiesCollection ptc;\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(1U, ptc.size());\n ASSERT_EQ(3U, ptc.begin()->second->num_entries);\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n ASSERT_EQ(\"v1\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key4\"));\n\n \/\/ Now add more keys and flush.\n ASSERT_OK(Put(\"key4\", \"v4\"));\n ASSERT_OK(Put(\"key5\", \"v5\"));\n ASSERT_OK(Put(\"key6\", \"v6\"));\n dbfull()->TEST_FlushMemTable();\n\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(2U, ptc.size());\n auto row = ptc.begin();\n ASSERT_EQ(3U, row->second->num_entries);\n ASSERT_EQ(3U, (++row)->second->num_entries);\n ASSERT_EQ(\"2\", FilesPerLevel());\n ASSERT_EQ(\"v1\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"v4\", Get(\"key4\"));\n ASSERT_EQ(\"v5\", Get(\"key5\"));\n ASSERT_EQ(\"v6\", Get(\"key6\"));\n\n ASSERT_OK(Delete(\"key6\"));\n ASSERT_OK(Delete(\"key5\"));\n ASSERT_OK(Delete(\"key4\"));\n dbfull()->TEST_FlushMemTable();\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(3U, ptc.size());\n row = ptc.begin();\n ASSERT_EQ(3U, row->second->num_entries);\n ASSERT_EQ(3U, (++row)->second->num_entries);\n ASSERT_EQ(3U, (++row)->second->num_entries);\n ASSERT_EQ(\"3\", FilesPerLevel());\n ASSERT_EQ(\"v1\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key4\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key5\"));\n ASSERT_EQ(\"NOT_FOUND\", Get(\"key6\"));\n}\n\nTEST(CuckooTableDBTest, FlushWithDuplicateKeys) {\n Options options = CurrentOptions();\n Reopen(&options);\n ASSERT_OK(Put(\"key1\", \"v1\"));\n ASSERT_OK(Put(\"key2\", \"v2\"));\n ASSERT_OK(Put(\"key1\", \"v3\")); \/\/ Duplicate\n dbfull()->TEST_FlushMemTable();\n\n TablePropertiesCollection ptc;\n reinterpret_cast(dbfull())->GetPropertiesOfAllTables(&ptc);\n ASSERT_EQ(1U, ptc.size());\n ASSERT_EQ(2U, ptc.begin()->second->num_entries);\n ASSERT_EQ(\"1\", FilesPerLevel());\n ASSERT_EQ(\"v3\", Get(\"key1\"));\n ASSERT_EQ(\"v2\", Get(\"key2\"));\n}\n\nnamespace {\nstatic std::string Key(int i) {\n char buf[100];\n snprintf(buf, sizeof(buf), \"key_______%06d\", i);\n return std::string(buf);\n}\nstatic std::string Uint64Key(uint64_t i) {\n std::string str;\n str.resize(8);\n memcpy(&str[0], static_cast(&i), 8);\n return str;\n}\n} \/\/ namespace.\n\nTEST(CuckooTableDBTest, Uint64Comparator) {\n Options options = CurrentOptions();\n options.comparator = test::Uint64Comparator();\n Reopen(&options);\n\n ASSERT_OK(Put(Uint64Key(1), \"v1\"));\n ASSERT_OK(Put(Uint64Key(2), \"v2\"));\n ASSERT_OK(Put(Uint64Key(3), \"v3\"));\n dbfull()->TEST_FlushMemTable();\n\n ASSERT_EQ(\"v1\", Get(Uint64Key(1)));\n ASSERT_EQ(\"v2\", Get(Uint64Key(2)));\n ASSERT_EQ(\"v3\", Get(Uint64Key(3)));\n ASSERT_EQ(\"NOT_FOUND\", Get(Uint64Key(4)));\n\n \/\/ Add more keys.\n ASSERT_OK(Delete(Uint64Key(2))); \/\/ Delete.\n dbfull()->TEST_FlushMemTable();\n ASSERT_OK(Put(Uint64Key(3), \"v0\")); \/\/ Update.\n ASSERT_OK(Put(Uint64Key(4), \"v4\"));\n dbfull()->TEST_FlushMemTable();\n ASSERT_EQ(\"v1\", Get(Uint64Key(1)));\n ASSERT_EQ(\"NOT_FOUND\", Get(Uint64Key(2)));\n ASSERT_EQ(\"v0\", Get(Uint64Key(3)));\n ASSERT_EQ(\"v4\", Get(Uint64Key(4)));\n}\n\nTEST(CuckooTableDBTest, CompactionTrigger) {\n Options options = CurrentOptions();\n options.write_buffer_size = 100 << 10; \/\/ 100KB\n options.level0_file_num_compaction_trigger = 2;\n Reopen(&options);\n\n \/\/ Write 11 values, each 10016 B\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n \/\/ Generate one more file in level-0, and should trigger level-0 compaction\n for (int idx = 11; idx < 22; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"2\", FilesPerLevel());\n\n dbfull()->TEST_CompactRange(0, nullptr, nullptr);\n ASSERT_EQ(\"0,2\", FilesPerLevel());\n for (int idx = 0; idx < 22; ++idx) {\n ASSERT_EQ(std::string(10000, 'a' + idx), Get(Key(idx)));\n }\n}\n\nTEST(CuckooTableDBTest, CompactionIntoMultipleFiles) {\n \/\/ Create a big L0 file and check it compacts into multiple files in L1.\n Options options = CurrentOptions();\n options.write_buffer_size = 270 << 10;\n \/\/ Two SST files should be created, each containing 14 keys.\n \/\/ Number of buckets will be 16. Total size ~156 KB.\n options.target_file_size_base = 160 << 10;\n Reopen(&options);\n\n \/\/ Write 28 values, each 10016 B ~ 10KB\n for (int idx = 0; idx < 28; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n dbfull()->TEST_CompactRange(0, nullptr, nullptr);\n ASSERT_EQ(\"0,2\", FilesPerLevel());\n for (int idx = 0; idx < 28; ++idx) {\n ASSERT_EQ(std::string(10000, 'a' + idx), Get(Key(idx)));\n }\n}\n\nTEST(CuckooTableDBTest, SameKeyInsertedInTwoDifferentFilesAndCompacted) {\n \/\/ Insert same key twice so that they go to different SST files. Then wait for\n \/\/ compaction and check if the latest value is stored and old value removed.\n Options options = CurrentOptions();\n options.write_buffer_size = 100 << 10; \/\/ 100KB\n options.level0_file_num_compaction_trigger = 2;\n Reopen(&options);\n\n \/\/ Write 11 values, each 10016 B\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a')));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n ASSERT_EQ(\"1\", FilesPerLevel());\n\n \/\/ Generate one more file in level-0, and should trigger level-0 compaction\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_OK(Put(Key(idx), std::string(10000, 'a' + idx)));\n }\n dbfull()->TEST_WaitForFlushMemTable();\n dbfull()->TEST_CompactRange(0, nullptr, nullptr);\n\n ASSERT_EQ(\"0,1\", FilesPerLevel());\n for (int idx = 0; idx < 11; ++idx) {\n ASSERT_EQ(std::string(10000, 'a' + idx), Get(Key(idx)));\n }\n}\n\nTEST(CuckooTableDBTest, AdaptiveTable) {\n Options options = CurrentOptions();\n\n \/\/ Write some keys using cuckoo table.\n options.table_factory.reset(NewCuckooTableFactory());\n Reopen(&options);\n\n ASSERT_OK(Put(\"key1\", \"v1\"));\n ASSERT_OK(Put(\"key2\", \"v2\"));\n ASSERT_OK(Put(\"key3\", \"v3\"));\n dbfull()->TEST_FlushMemTable();\n\n \/\/ Write some keys using plain table.\n options.create_if_missing = false;\n options.table_factory.reset(NewPlainTableFactory());\n Reopen(&options);\n ASSERT_OK(Put(\"key4\", \"v4\"));\n ASSERT_OK(Put(\"key1\", \"v5\"));\n dbfull()->TEST_FlushMemTable();\n\n \/\/ Write some keys using block based table.\n std::shared_ptr block_based_factory(\n NewBlockBasedTableFactory());\n options.table_factory.reset(NewAdaptiveTableFactory(block_based_factory));\n Reopen(&options);\n ASSERT_OK(Put(\"key5\", \"v6\"));\n ASSERT_OK(Put(\"key2\", \"v7\"));\n dbfull()->TEST_FlushMemTable();\n\n ASSERT_EQ(\"v5\", Get(\"key1\"));\n ASSERT_EQ(\"v7\", Get(\"key2\"));\n ASSERT_EQ(\"v3\", Get(\"key3\"));\n ASSERT_EQ(\"v4\", Get(\"key4\"));\n ASSERT_EQ(\"v6\", Get(\"key5\"));\n}\n} \/\/ namespace rocksdb\n\nint main(int argc, char** argv) { return rocksdb::test::RunAllTests(); }\n<|endoftext|>"} {"text":"#include \"robot_interface\/arm_ctrl.h\"\n#include \n\nusing namespace std;\nusing namespace geometry_msgs;\nusing namespace baxter_core_msgs;\n\nArmCtrl::ArmCtrl(string _name, string _limb, bool _no_robot) :\n RobotInterface(_name,_limb, _no_robot), Gripper(_limb, _no_robot),\n object(-1), action(\"\"), sub_state(\"\")\n{\n std::string topic = \"\/\"+getName()+\"\/state_\"+_limb;\n state_pub = _n.advertise(topic,1);\n ROS_INFO(\"[%s] Created state publisher with name : %s\", getLimb().c_str(), topic.c_str());\n\n std::string other_limb = getLimb() == \"right\" ? \"left\" : \"right\";\n\n topic = \"\/\"+getName()+\"\/service_\"+_limb;\n service = _n.advertiseService(topic, &ArmCtrl::serviceCb, this);\n ROS_INFO(\"[%s] Created service server with name : %s\", getLimb().c_str(), topic.c_str());\n\n topic = \"\/\"+getName()+\"\/service_\"+_limb+\"_to_\"+other_limb;\n service_other_limb = _n.advertiseService(topic, &ArmCtrl::serviceOtherLimbCb,this);\n ROS_INFO(\"[%s] Created service server with name : %s\", getLimb().c_str(), topic.c_str());\n\n insertAction(ACTION_HOME, &ArmCtrl::goHome);\n insertAction(ACTION_RELEASE, &ArmCtrl::releaseObject);\n\n insertAction(\"recover_\"+string(ACTION_HOME), &ArmCtrl::notImplemented);\n insertAction(\"recover_\"+string(ACTION_RELEASE), &ArmCtrl::notImplemented);\n\n _n.param(\"internal_recovery\", internal_recovery, true);\n ROS_INFO(\"[%s] Internal_recovery flag set to %s\", getLimb().c_str(),\n internal_recovery==true?\"true\":\"false\");\n}\n\nvoid ArmCtrl::InternalThreadEntry()\n{\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);\n _n.param(\"internal_recovery\", internal_recovery, true);\n\n std::string a = getAction();\n int s = int(getState());\n\n setState(WORKING);\n\n if (a == ACTION_HOME || a == ACTION_RELEASE)\n {\n if (callAction(a)) setState(DONE);\n }\n else if (s == START || s == ERROR ||\n s == DONE || s == KILLED )\n {\n if (doAction(s, a)) setState(DONE);\n else setState(ERROR);\n }\n else\n {\n ROS_ERROR(\"[%s] Invalid Action %s in state %i\", getLimb().c_str(), a.c_str(), s);\n }\n\n if (getState()==WORKING)\n {\n setState(ERROR);\n }\n\n if (getState()==ERROR)\n {\n ROS_ERROR(\"[%s] Action %s not successful! State %s %s\", getLimb().c_str(), a.c_str(),\n string(getState()).c_str(), getSubState().c_str());\n }\n\n closeInternalThread();\n return;\n}\n\nbool ArmCtrl::serviceOtherLimbCb(baxter_collaboration::AskFeedback::Request &req,\n baxter_collaboration::AskFeedback::Response &res)\n{\n res.success = false;\n res.reply = \"not implemented\";\n return true;\n}\n\nbool ArmCtrl::serviceCb(baxter_collaboration::DoAction::Request &req,\n baxter_collaboration::DoAction::Response &res)\n{\n string action = req.action;\n int obj = req.object;\n\n ROS_INFO(\"[%s] Service request received. Action: %s object: %i\", getLimb().c_str(),\n action.c_str(), obj);\n\n if (action == PROT_ACTION_LIST)\n {\n printDB();\n res.success = true;\n res.response = DBToString();\n return true;\n }\n\n if (is_no_robot())\n {\n ros::Duration(2.0).sleep();\n res.success = true;\n return true;\n }\n\n res.success = false;\n\n setAction(action);\n setObject(obj);\n\n startInternalThread();\n ros::Duration(0.5).sleep();\n\n ros::Rate r(100);\n while( ros::ok() && ( int(getState()) != START &&\n int(getState()) != ERROR &&\n int(getState()) != DONE &&\n int(getState()) != PICK_UP ))\n {\n if (ros::isShuttingDown())\n {\n setState(KILLED);\n return true;\n }\n\n if (getState()==KILLED)\n {\n recoverFromError();\n }\n\n r.sleep();\n }\n\n if ( int(getState()) == START ||\n int(getState()) == DONE ||\n int(getState()) == PICK_UP )\n {\n res.success = true;\n }\n\n ROS_INFO(\"[%s] Service reply with success: %s\\n\", getLimb().c_str(),\n res.success?\"true\":\"false\");\n return true;\n}\n\nbool ArmCtrl::notImplemented()\n{\n ROS_ERROR(\"[%s] Action not implemented!\", getLimb().c_str());\n return false;\n}\n\nbool ArmCtrl::insertAction(const std::string &a, ArmCtrl::f_action f)\n{\n if (a == PROT_ACTION_LIST)\n {\n ROS_ERROR(\"[%s][action_db] Attempted to insert protected action key: %s\",\n getLimb().c_str(), a.c_str());\n return false;\n }\n\n if (action_db.find(a) != action_db.end()) \/\/ The action is in the db\n {\n ROS_WARN(\"[%s][action_db] Overwriting existing action with key %s\",\n getLimb().c_str(), a.c_str());\n }\n\n action_db.insert( std::make_pair( a, f ));\n return true;\n}\n\nbool ArmCtrl::removeAction(const std::string &a)\n{\n if (action_db.find(a) != action_db.end()) \/\/ The action is in the db\n {\n action_db.erase(a);\n return true;\n }\n else\n {\n ROS_WARN(\"[%s][action_db] Action %s is not in the database.\",\n getLimb().c_str(), a.c_str());\n return false;\n }\n}\n\nbool ArmCtrl::callAction(const std::string &a)\n{\n if (action_db.find(a) != action_db.end()) \/\/ The action is in the db\n {\n f_action act = action_db[a];\n return (this->*act)();\n }\n else\n {\n ROS_ERROR(\"[%s][action_db] Action %s is not in the database!\",\n getLimb().c_str(), a.c_str());\n return false;\n }\n}\n\nvoid ArmCtrl::printDB()\n{\n ROS_INFO(\"[%s] Available actions in the database : %s\",\n getLimb().c_str(), DBToString().c_str());\n}\n\nstring ArmCtrl::DBToString()\n{\n string res = \"\";\n map::iterator it;\n\n for ( it = action_db.begin(); it != action_db.end(); it++ )\n {\n res = res + it->first + \", \";\n }\n res = res.substr(0, res.size()-2); \/\/ Remove the last \", \"\n return res;\n}\n\nbool ArmCtrl::moveArm(string dir, double dist, string mode, bool disable_coll_av)\n{\n Point start = getPos();\n Point final = getPos();\n\n Quaternion ori = getOri();\n\n if (dir == \"backward\") final.x -= dist;\n else if (dir == \"forward\") final.x += dist;\n else if (dir == \"right\") final.y -= dist;\n else if (dir == \"left\") final.y += dist;\n else if (dir == \"down\") final.z -= dist;\n else if (dir == \"up\") final.z += dist;\n else return false;\n\n ros::Time t_start = ros::Time::now();\n\n bool finish = false;\n\n ros::Rate r(100);\n while(RobotInterface::ok())\n {\n if (disable_coll_av) suppressCollisionAv();\n\n double t_elap = (ros::Time::now() - t_start).toSec();\n\n double px = start.x;\n double py = start.y;\n double pz = start.z;\n\n if (!finish)\n {\n if (dir == \"backward\" | dir == \"forward\")\n {\n int sgn = dir==\"backward\"?-1:+1;\n px = px + sgn * PICK_UP_SPEED * t_elap;\n\n if (dir == \"backward\")\n {\n if (px < final.x) finish = true;\n }\n else if (dir == \"forward\")\n {\n if (px > final.x) finish = true;\n }\n }\n if (dir == \"right\" | dir == \"left\")\n {\n int sgn = dir==\"right\"?-1:+1;\n py = py + sgn * PICK_UP_SPEED * t_elap;\n\n if (dir == \"right\")\n {\n if (py < final.y) finish = true;\n }\n else if (dir == \"left\")\n {\n if (py > final.y) finish = true;\n }\n }\n if (dir == \"down\" | dir == \"up\")\n {\n int sgn = dir==\"down\"?-1:+1;\n pz = pz + sgn * PICK_UP_SPEED * t_elap;\n\n if (dir == \"down\")\n {\n if (pz < final.z) finish = true;\n }\n else if (dir == \"up\")\n {\n if (pz > final.z) finish = true;\n }\n }\n }\n else\n {\n px = final.x;\n py = final.y;\n pz = final.z;\n }\n\n double ox = ori.x;\n double oy = ori.y;\n double oz = ori.z;\n double ow = ori.w;\n\n vector joint_angles;\n if (!computeIK(px, py, pz, ox, oy, oz, ow, joint_angles)) return false;\n\n if (!goToPoseNoCheck(joint_angles)) return false;\n\n if (isPositionReached(final.x, final.y, final.z, mode)) return true;\n\n r.sleep();\n }\n\n return false;\n}\n\nbool ArmCtrl::hoverAboveTable(double height, string mode, bool disable_coll_av)\n{\n if (getLimb() == \"right\")\n {\n return RobotInterface::goToPose(HOME_POS_R, height, VERTICAL_ORI_R,\n mode, disable_coll_av);\n }\n else if (getLimb() == \"left\")\n {\n return RobotInterface::goToPose(HOME_POS_L, height, VERTICAL_ORI_L,\n mode, disable_coll_av);\n }\n else return false;\n}\n\nbool ArmCtrl::homePoseStrict(bool disable_coll_av)\n{\n ROS_INFO(\"[%s] Going to home position strict..\", getLimb().c_str());\n\n ros::Rate r(100);\n while(ros::ok())\n {\n if (disable_coll_av) suppressCollisionAv();\n\n JointCommand joint_cmd;\n joint_cmd.mode = JointCommand::POSITION_MODE;\n setJointNames(joint_cmd);\n\n joint_cmd.command = home_conf.command;\n\n publish_joint_cmd(joint_cmd);\n\n r.sleep();\n\n if(isConfigurationReached(joint_cmd))\n {\n return true;\n }\n }\n ROS_INFO(\"[%s] Done\", getLimb().c_str());\n}\n\nvoid ArmCtrl::setHomeConf(double s0, double s1, double e0, double e1,\n double w0, double w1, double w2)\n{\n setJointCommands( s0, s1, e0, e1, w0, w1, w2, home_conf);\n}\n\nbool ArmCtrl::goHome()\n{\n bool res = homePoseStrict();\n releaseObject();\n return res;\n}\n\nvoid ArmCtrl::recoverFromError()\n{\n if (internal_recovery == true)\n {\n goHome();\n }\n}\n\nvoid ArmCtrl::setState(int _state)\n{\n if (_state == KILLED && getState() != WORKING)\n {\n ROS_WARN(\"[%s] Attempted to kill a non-working controller\", getLimb().c_str());\n return;\n }\n\n RobotInterface::setState(_state);\n\n \/\/ if (_state == DONE)\n \/\/ {\n \/\/ setAction(\"\");\n \/\/ setMarkerID(-1);\n \/\/ }\n if (_state == DONE)\n {\n setSubState(getAction());\n }\n publishState();\n}\n\nvoid ArmCtrl::setAction(string _action)\n{\n action = _action;\n publishState();\n}\n\nvoid ArmCtrl::publishState()\n{\n baxter_collaboration::ArmState msg;\n\n msg.state = string(getState());\n msg.action = getAction();\n msg.object = getObjName();\n\n state_pub.publish(msg);\n}\n\nstring ArmCtrl::getObjName()\n{\n if (object == 17) return \"left leg\";\n else if (object == 21) return \"top\";\n else if (object == 24) return \"central frame\";\n else if (object == 26) return \"right leg\";\n else return \"\";\n}\n\nArmCtrl::~ArmCtrl()\n{\n killInternalThread();\n}\n[armctrl] removed recoverhome and recover_release because they have little to no sense#include \"robot_interface\/arm_ctrl.h\"\n#include \n\nusing namespace std;\nusing namespace geometry_msgs;\nusing namespace baxter_core_msgs;\n\nArmCtrl::ArmCtrl(string _name, string _limb, bool _no_robot) :\n RobotInterface(_name,_limb, _no_robot), Gripper(_limb, _no_robot),\n object(-1), action(\"\"), sub_state(\"\")\n{\n std::string topic = \"\/\"+getName()+\"\/state_\"+_limb;\n state_pub = _n.advertise(topic,1);\n ROS_INFO(\"[%s] Created state publisher with name : %s\", getLimb().c_str(), topic.c_str());\n\n std::string other_limb = getLimb() == \"right\" ? \"left\" : \"right\";\n\n topic = \"\/\"+getName()+\"\/service_\"+_limb;\n service = _n.advertiseService(topic, &ArmCtrl::serviceCb, this);\n ROS_INFO(\"[%s] Created service server with name : %s\", getLimb().c_str(), topic.c_str());\n\n topic = \"\/\"+getName()+\"\/service_\"+_limb+\"_to_\"+other_limb;\n service_other_limb = _n.advertiseService(topic, &ArmCtrl::serviceOtherLimbCb,this);\n ROS_INFO(\"[%s] Created service server with name : %s\", getLimb().c_str(), topic.c_str());\n\n insertAction(ACTION_HOME, &ArmCtrl::goHome);\n insertAction(ACTION_RELEASE, &ArmCtrl::releaseObject);\n\n \/\/ insertAction(\"recover_\"+string(ACTION_HOME), &ArmCtrl::notImplemented);\n \/\/ insertAction(\"recover_\"+string(ACTION_RELEASE), &ArmCtrl::notImplemented);\n\n _n.param(\"internal_recovery\", internal_recovery, true);\n ROS_INFO(\"[%s] Internal_recovery flag set to %s\", getLimb().c_str(),\n internal_recovery==true?\"true\":\"false\");\n}\n\nvoid ArmCtrl::InternalThreadEntry()\n{\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);\n _n.param(\"internal_recovery\", internal_recovery, true);\n\n std::string a = getAction();\n int s = int(getState());\n\n setState(WORKING);\n\n if (a == ACTION_HOME || a == ACTION_RELEASE)\n {\n if (callAction(a)) setState(DONE);\n }\n else if (s == START || s == ERROR ||\n s == DONE || s == KILLED )\n {\n if (doAction(s, a)) setState(DONE);\n else setState(ERROR);\n }\n else\n {\n ROS_ERROR(\"[%s] Invalid Action %s in state %i\", getLimb().c_str(), a.c_str(), s);\n }\n\n if (getState()==WORKING)\n {\n setState(ERROR);\n }\n\n if (getState()==ERROR)\n {\n ROS_ERROR(\"[%s] Action %s not successful! State %s %s\", getLimb().c_str(), a.c_str(),\n string(getState()).c_str(), getSubState().c_str());\n }\n\n closeInternalThread();\n return;\n}\n\nbool ArmCtrl::serviceOtherLimbCb(baxter_collaboration::AskFeedback::Request &req,\n baxter_collaboration::AskFeedback::Response &res)\n{\n res.success = false;\n res.reply = \"not implemented\";\n return true;\n}\n\nbool ArmCtrl::serviceCb(baxter_collaboration::DoAction::Request &req,\n baxter_collaboration::DoAction::Response &res)\n{\n string action = req.action;\n int obj = req.object;\n\n ROS_INFO(\"[%s] Service request received. Action: %s object: %i\", getLimb().c_str(),\n action.c_str(), obj);\n\n if (action == PROT_ACTION_LIST)\n {\n printDB();\n res.success = true;\n res.response = DBToString();\n return true;\n }\n\n if (is_no_robot())\n {\n ros::Duration(2.0).sleep();\n res.success = true;\n return true;\n }\n\n res.success = false;\n\n setAction(action);\n setObject(obj);\n\n startInternalThread();\n ros::Duration(0.5).sleep();\n\n ros::Rate r(100);\n while( ros::ok() && ( int(getState()) != START &&\n int(getState()) != ERROR &&\n int(getState()) != DONE &&\n int(getState()) != PICK_UP ))\n {\n if (ros::isShuttingDown())\n {\n setState(KILLED);\n return true;\n }\n\n if (getState()==KILLED)\n {\n recoverFromError();\n }\n\n r.sleep();\n }\n\n if ( int(getState()) == START ||\n int(getState()) == DONE ||\n int(getState()) == PICK_UP )\n {\n res.success = true;\n }\n\n ROS_INFO(\"[%s] Service reply with success: %s\\n\", getLimb().c_str(),\n res.success?\"true\":\"false\");\n return true;\n}\n\nbool ArmCtrl::notImplemented()\n{\n ROS_ERROR(\"[%s] Action not implemented!\", getLimb().c_str());\n return false;\n}\n\nbool ArmCtrl::insertAction(const std::string &a, ArmCtrl::f_action f)\n{\n if (a == PROT_ACTION_LIST)\n {\n ROS_ERROR(\"[%s][action_db] Attempted to insert protected action key: %s\",\n getLimb().c_str(), a.c_str());\n return false;\n }\n\n if (action_db.find(a) != action_db.end()) \/\/ The action is in the db\n {\n ROS_WARN(\"[%s][action_db] Overwriting existing action with key %s\",\n getLimb().c_str(), a.c_str());\n }\n\n action_db.insert( std::make_pair( a, f ));\n return true;\n}\n\nbool ArmCtrl::removeAction(const std::string &a)\n{\n if (action_db.find(a) != action_db.end()) \/\/ The action is in the db\n {\n action_db.erase(a);\n return true;\n }\n else\n {\n ROS_WARN(\"[%s][action_db] Action %s is not in the database.\",\n getLimb().c_str(), a.c_str());\n return false;\n }\n}\n\nbool ArmCtrl::callAction(const std::string &a)\n{\n if (action_db.find(a) != action_db.end()) \/\/ The action is in the db\n {\n f_action act = action_db[a];\n return (this->*act)();\n }\n else\n {\n ROS_ERROR(\"[%s][action_db] Action %s is not in the database!\",\n getLimb().c_str(), a.c_str());\n return false;\n }\n}\n\nvoid ArmCtrl::printDB()\n{\n ROS_INFO(\"[%s] Available actions in the database : %s\",\n getLimb().c_str(), DBToString().c_str());\n}\n\nstring ArmCtrl::DBToString()\n{\n string res = \"\";\n map::iterator it;\n\n for ( it = action_db.begin(); it != action_db.end(); it++ )\n {\n res = res + it->first + \", \";\n }\n res = res.substr(0, res.size()-2); \/\/ Remove the last \", \"\n return res;\n}\n\nbool ArmCtrl::moveArm(string dir, double dist, string mode, bool disable_coll_av)\n{\n Point start = getPos();\n Point final = getPos();\n\n Quaternion ori = getOri();\n\n if (dir == \"backward\") final.x -= dist;\n else if (dir == \"forward\") final.x += dist;\n else if (dir == \"right\") final.y -= dist;\n else if (dir == \"left\") final.y += dist;\n else if (dir == \"down\") final.z -= dist;\n else if (dir == \"up\") final.z += dist;\n else return false;\n\n ros::Time t_start = ros::Time::now();\n\n bool finish = false;\n\n ros::Rate r(100);\n while(RobotInterface::ok())\n {\n if (disable_coll_av) suppressCollisionAv();\n\n double t_elap = (ros::Time::now() - t_start).toSec();\n\n double px = start.x;\n double py = start.y;\n double pz = start.z;\n\n if (!finish)\n {\n if (dir == \"backward\" | dir == \"forward\")\n {\n int sgn = dir==\"backward\"?-1:+1;\n px = px + sgn * PICK_UP_SPEED * t_elap;\n\n if (dir == \"backward\")\n {\n if (px < final.x) finish = true;\n }\n else if (dir == \"forward\")\n {\n if (px > final.x) finish = true;\n }\n }\n if (dir == \"right\" | dir == \"left\")\n {\n int sgn = dir==\"right\"?-1:+1;\n py = py + sgn * PICK_UP_SPEED * t_elap;\n\n if (dir == \"right\")\n {\n if (py < final.y) finish = true;\n }\n else if (dir == \"left\")\n {\n if (py > final.y) finish = true;\n }\n }\n if (dir == \"down\" | dir == \"up\")\n {\n int sgn = dir==\"down\"?-1:+1;\n pz = pz + sgn * PICK_UP_SPEED * t_elap;\n\n if (dir == \"down\")\n {\n if (pz < final.z) finish = true;\n }\n else if (dir == \"up\")\n {\n if (pz > final.z) finish = true;\n }\n }\n }\n else\n {\n px = final.x;\n py = final.y;\n pz = final.z;\n }\n\n double ox = ori.x;\n double oy = ori.y;\n double oz = ori.z;\n double ow = ori.w;\n\n vector joint_angles;\n if (!computeIK(px, py, pz, ox, oy, oz, ow, joint_angles)) return false;\n\n if (!goToPoseNoCheck(joint_angles)) return false;\n\n if (isPositionReached(final.x, final.y, final.z, mode)) return true;\n\n r.sleep();\n }\n\n return false;\n}\n\nbool ArmCtrl::hoverAboveTable(double height, string mode, bool disable_coll_av)\n{\n if (getLimb() == \"right\")\n {\n return RobotInterface::goToPose(HOME_POS_R, height, VERTICAL_ORI_R,\n mode, disable_coll_av);\n }\n else if (getLimb() == \"left\")\n {\n return RobotInterface::goToPose(HOME_POS_L, height, VERTICAL_ORI_L,\n mode, disable_coll_av);\n }\n else return false;\n}\n\nbool ArmCtrl::homePoseStrict(bool disable_coll_av)\n{\n ROS_INFO(\"[%s] Going to home position strict..\", getLimb().c_str());\n\n ros::Rate r(100);\n while(ros::ok())\n {\n if (disable_coll_av) suppressCollisionAv();\n\n JointCommand joint_cmd;\n joint_cmd.mode = JointCommand::POSITION_MODE;\n setJointNames(joint_cmd);\n\n joint_cmd.command = home_conf.command;\n\n publish_joint_cmd(joint_cmd);\n\n r.sleep();\n\n if(isConfigurationReached(joint_cmd))\n {\n return true;\n }\n }\n ROS_INFO(\"[%s] Done\", getLimb().c_str());\n}\n\nvoid ArmCtrl::setHomeConf(double s0, double s1, double e0, double e1,\n double w0, double w1, double w2)\n{\n setJointCommands( s0, s1, e0, e1, w0, w1, w2, home_conf);\n}\n\nbool ArmCtrl::goHome()\n{\n bool res = homePoseStrict();\n releaseObject();\n return res;\n}\n\nvoid ArmCtrl::recoverFromError()\n{\n if (internal_recovery == true)\n {\n goHome();\n }\n}\n\nvoid ArmCtrl::setState(int _state)\n{\n if (_state == KILLED && getState() != WORKING)\n {\n ROS_WARN(\"[%s] Attempted to kill a non-working controller\", getLimb().c_str());\n return;\n }\n\n RobotInterface::setState(_state);\n\n \/\/ if (_state == DONE)\n \/\/ {\n \/\/ setAction(\"\");\n \/\/ setMarkerID(-1);\n \/\/ }\n if (_state == DONE)\n {\n setSubState(getAction());\n }\n publishState();\n}\n\nvoid ArmCtrl::setAction(string _action)\n{\n action = _action;\n publishState();\n}\n\nvoid ArmCtrl::publishState()\n{\n baxter_collaboration::ArmState msg;\n\n msg.state = string(getState());\n msg.action = getAction();\n msg.object = getObjName();\n\n state_pub.publish(msg);\n}\n\nstring ArmCtrl::getObjName()\n{\n if (object == 17) return \"left leg\";\n else if (object == 21) return \"top\";\n else if (object == 24) return \"central frame\";\n else if (object == 26) return \"right leg\";\n else return \"\";\n}\n\nArmCtrl::~ArmCtrl()\n{\n killInternalThread();\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP\n#define STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/*\n * Reverse mode differentiation algorithm reference:\n *\n * The Differentiation of Pseudo-Inverses and Nonlinear Least Squares Problems\n * Whose Variables Separate. Author(s): G. H. Golub and V. Pereyra. Source: SIAM\n * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp. 413-432\n *\n * Equation 4.12 in the paper\n *\n * See also\n * http:\/\/mathoverflow.net\/questions\/25778\/analytical-formula-for-numerical-derivative-of-the-matrix-pseudo-inverse\n *\n * Implementation is based on\n * Title: Uncertainties Python Package\n * Author: Eric O. LEBIGOT\n * Date: 2020\n * Availability:\n * https:\/\/github.com\/lebigot\/uncertainties\/blob\/master\/uncertainties\/unumpy\/core.py\n *\/\ntemplate * = nullptr>\ninline auto generalized_inverse(const VarMat& G) {\n using value_t = value_type_t;\n using ret_type = promote_var_matrix_t;\n\n if (G.size() == 0)\n return ret_type(G);\n\n if (G.rows() == G.cols())\n return ret_type(inverse(G));\n\n if (G.rows() < G.cols()) {\n arena_t G_arena(G);\n auto A_spd = tcrossprod(G_arena.val_op());\n arena_t inv_G(\n transpose(mdivide_left_spd(A_spd.val_op(), G_arena.val_op())));\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n } else {\n arena_t G_arena(G);\n auto A_spd = crossprod(G_arena.val_op());\n arena_t inv_G(\n transpose(mdivide_right_spd(G_arena.val_op(), A_spd.val_op())));\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n }\n}\n\n\/*\n * Reverse mode differentiation algorithm reference:\n *\n * The Differentiation of Pseudo-Inverses and Nonlinear Least Squares Problems\n * Whose Variables Separate. Author(s): G. H. Golub and V. Pereyra. Source: SIAM\n * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp. 413-432\n *\n * Equation 4.12 in the paper\n * See also\n * http:\/\/mathoverflow.net\/questions\/25778\/analytical-formula-for-numerical-derivative-of-the-matrix-pseudo-inverse\n *\n * Implementation is based on\n * Title: Uncertainties Python Package\n * Author: Eric O. LEBIGOT\n * Date: 2020\n * Availability:\n * https:\/\/github.com\/lebigot\/uncertainties\/blob\/master\/uncertainties\/unumpy\/core.py\n *\/\ntemplate * = nullptr>\ninline auto generalized_inverse(const VarMat& G, const double a) {\n using value_t = value_type_t;\n using ret_type = promote_var_matrix_t;\n\n if (G.size() == 0)\n return ret_type(G);\n\n if (G.rows() == G.cols())\n return ret_type(inverse(G));\n\n if (G.rows() < G.cols()) {\n arena_t G_arena(G);\n auto A_spd = tcrossprod(G_arena.val_op());\n A_spd.diagonal().array() += a;\n arena_t inv_G(transpose(mdivide_left_spd(A_spd, G_arena.val_op())));\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n } else {\n arena_t G_arena(G);\n auto A_spd = crossprod(G_arena.val_op());\n A_spd.diagonal().array() += a;\n arena_t inv_G(\n transpose(mdivide_right_spd(G_arena.val_op(), A_spd)));\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\nmore fixes#ifndef STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP\n#define STAN_MATH_REV_FUN_GENERALIZED_INVERSE_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/*\n * Reverse mode differentiation algorithm reference:\n *\n * The Differentiation of Pseudo-Inverses and Nonlinear Least Squares Problems\n * Whose Variables Separate. Author(s): G. H. Golub and V. Pereyra. Source: SIAM\n * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp. 413-432\n *\n * Equation 4.12 in the paper\n *\n * See also\n * http:\/\/mathoverflow.net\/questions\/25778\/analytical-formula-for-numerical-derivative-of-the-matrix-pseudo-inverse\n *\n * Implementation is based on\n * Title: Uncertainties Python Package\n * Author: Eric O. LEBIGOT\n * Date: 2020\n * Availability:\n * https:\/\/github.com\/lebigot\/uncertainties\/blob\/master\/uncertainties\/unumpy\/core.py\n *\/\ntemplate * = nullptr>\ninline auto generalized_inverse(const VarMat& G) {\n using value_t = value_type_t;\n using ret_type = promote_var_matrix_t;\n\n if (G.size() == 0)\n return ret_type(G);\n\n if (G.rows() == G.cols())\n return ret_type(inverse(G));\n\n if (G.rows() < G.cols()) {\n arena_t G_arena(G);\n auto A_spd = tcrossprod(G_arena.val_op());\n arena_t inv_G(\n mdivide_left_spd(A_spd.val_op(), G_arena.val_op())).transpose();\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n } else {\n arena_t G_arena(G);\n auto A_spd = crossprod(G_arena.val_op());\n arena_t inv_G(\n mdivide_right_spd(G_arena.val_op(), A_spd.val_op())).transpose();\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n }\n}\n\n\/*\n * Reverse mode differentiation algorithm reference:\n *\n * The Differentiation of Pseudo-Inverses and Nonlinear Least Squares Problems\n * Whose Variables Separate. Author(s): G. H. Golub and V. Pereyra. Source: SIAM\n * Journal on Numerical Analysis, Vol. 10, No. 2 (Apr., 1973), pp. 413-432\n *\n * Equation 4.12 in the paper\n * See also\n * http:\/\/mathoverflow.net\/questions\/25778\/analytical-formula-for-numerical-derivative-of-the-matrix-pseudo-inverse\n *\n * Implementation is based on\n * Title: Uncertainties Python Package\n * Author: Eric O. LEBIGOT\n * Date: 2020\n * Availability:\n * https:\/\/github.com\/lebigot\/uncertainties\/blob\/master\/uncertainties\/unumpy\/core.py\n *\/\ntemplate * = nullptr>\ninline auto generalized_inverse(const VarMat& G, const double a) {\n using value_t = value_type_t;\n using ret_type = promote_var_matrix_t;\n\n if (G.size() == 0)\n return ret_type(G);\n\n if (G.rows() == G.cols())\n return ret_type(inverse(G));\n\n if (G.rows() < G.cols()) {\n arena_t G_arena(G);\n auto A_spd = tcrossprod(G_arena.val_op());\n A_spd.diagonal().array() += a;\n arena_t inv_G(mdivide_left_spd(A_spd, G_arena.val_op())).transpose();\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n } else {\n arena_t G_arena(G);\n auto A_spd = crossprod(G_arena.val_op());\n A_spd.diagonal().array() += a;\n arena_t inv_G(\n mdivide_right_spd(G_arena.val_op(), A_spd)).transpose();\n\n auto PG = to_arena(-G_arena.val_op() * inv_G.val_op());\n PG.diagonal().array() += 1.0;\n\n auto GP = to_arena(-inv_G.val_op() * G_arena.val_op());\n GP.diagonal().array() += 1.0;\n\n reverse_pass_callback([G_arena, inv_G, GP, PG]() mutable {\n G_arena.adj() += -inv_G.val_op() * G_arena.adj_op() * inv_G.val_op();\n G_arena.adj() += tcrossprod(inv_G.val_op()) * G_arena.adj_op().transpose()\n * PG.val_op();\n G_arena.adj() += GP.val_op() * G_arena.adj_op().transpose()\n * crossprod(inv_G.val_op());\n });\n return ret_type(inv_G);\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"mousecoordinatestracker.h\"\n\n\/\/ Qt headers.\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Standard headers.\n#include \n\nusing namespace foundation;\nusing namespace std;\n\nnamespace appleseed {\nnamespace studio {\n\nMouseCoordinatesTracker::MouseCoordinatesTracker(\n RenderWidget* widget,\n QLabel* label,\n QTextEdit* rgb_text) \n : m_widget(widget)\n , m_label(label)\n , m_rgb_text(rgb_text)\n , m_content_width(widget->width())\n , m_content_height(widget->height())\n{\n m_widget->installEventFilter(this);\n}\n\nMouseCoordinatesTracker::~MouseCoordinatesTracker()\n{\n m_widget->removeEventFilter(this);\n}\n\nVector2d MouseCoordinatesTracker::widget_to_ndc(const QPoint& point) const\n{\n return\n Vector2d(\n static_cast(point.x()) \/ m_widget->width(),\n static_cast(point.y()) \/ m_widget->height());\n}\n\nVector2i MouseCoordinatesTracker::widget_to_pixel(const QPoint& point) const\n{\n const Vector2d ndc = widget_to_ndc(point);\n\n return\n Vector2i(\n static_cast(ndc.x * m_content_width),\n static_cast(ndc.y * m_content_height));\n}\n\nbool MouseCoordinatesTracker::eventFilter(QObject* object, QEvent* event)\n{\n assert(object == m_widget);\n\n switch (event->type())\n {\n case QEvent::MouseMove:\n set_label_text(static_cast(event)->pos());\n set_rgb_text(static_cast(event)->pos());\n break;\n\n case QEvent::Leave:\n m_label->clear();\n m_rgb_text->clear();\n break;\n }\n\n return QObject::eventFilter(object, event);\n}\n\nvoid MouseCoordinatesTracker::set_label_text(const QPoint& point) const\n{\n const Vector2i pix = widget_to_pixel(point);\n const Vector2d ndc = widget_to_ndc(point);\n\n m_label->setText(\n QString(\"Pixel: %1, %2 - NDC: %3, %4 \")\n .arg(QString::number(pix.x), 4, '0')\n .arg(QString::number(pix.y), 4, '0')\n .arg(QString::number(ndc.x, 'f', 5))\n .arg(QString::number(ndc.y, 'f', 5)));\n\n}\n\nvoid MouseCoordinatesTracker::set_rgb_text(const QPoint& point) const \n{\n const Vector2i pix = widget_to_pixel(point);\n QRgb pixel_rgb = m_widget->get_image().pixel(pix.x, pix.y);\n\n m_rgb_text->clear();\n QTextCursor cursor(m_rgb_text->textCursor());\n\n \/\/ Set text color to red.\n QTextCharFormat format;\n format.setForeground(QColor(255, 0, 0));\n cursor.setCharFormat(format);\n \/\/ Insert the text at the position of the cursor.\n cursor.insertText(QString(\"%1\").arg(QString::number(qRed(pixel_rgb)), 3, '0'));\n\n \/\/ Move cursor to the end of the text. \n m_rgb_text->moveCursor(QTextCursor::End);\n format.setForeground(QColor(0, 255, 0)); \/\/green\n cursor.setCharFormat(format);\n cursor.insertText(QString(\" %1\").arg(QString::number(qGreen(pixel_rgb)), 3, '0'));\n\n m_rgb_text->moveCursor(QTextCursor::End);\n format.setForeground(QColor(0, 0, 255)); \/\/blue\n cursor.setCharFormat(format);\n cursor.insertText(QString(\" %1\").arg(QString::number(qBlue(pixel_rgb)), 3, '0'));\n\n m_rgb_text->moveCursor(QTextCursor::End);\n format.clearForeground();\n cursor.setCharFormat(format);\n cursor.insertText(QString(\" %1\").arg(QString::number(qAlpha(pixel_rgb)), 3, '0'));\n\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\nremoved redundant blank lines\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"mousecoordinatestracker.h\"\n\n\/\/ Qt headers.\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Standard headers.\n#include \n\nusing namespace foundation;\nusing namespace std;\n\nnamespace appleseed {\nnamespace studio {\n\nMouseCoordinatesTracker::MouseCoordinatesTracker(\n RenderWidget* widget,\n QLabel* label,\n QTextEdit* rgb_text) \n : m_widget(widget)\n , m_label(label)\n , m_rgb_text(rgb_text)\n , m_content_width(widget->width())\n , m_content_height(widget->height())\n{\n m_widget->installEventFilter(this);\n}\n\nMouseCoordinatesTracker::~MouseCoordinatesTracker()\n{\n m_widget->removeEventFilter(this);\n}\n\nVector2d MouseCoordinatesTracker::widget_to_ndc(const QPoint& point) const\n{\n return\n Vector2d(\n static_cast(point.x()) \/ m_widget->width(),\n static_cast(point.y()) \/ m_widget->height());\n}\n\nVector2i MouseCoordinatesTracker::widget_to_pixel(const QPoint& point) const\n{\n const Vector2d ndc = widget_to_ndc(point);\n\n return\n Vector2i(\n static_cast(ndc.x * m_content_width),\n static_cast(ndc.y * m_content_height));\n}\n\nbool MouseCoordinatesTracker::eventFilter(QObject* object, QEvent* event)\n{\n assert(object == m_widget);\n\n switch (event->type())\n {\n case QEvent::MouseMove:\n set_label_text(static_cast(event)->pos());\n set_rgb_text(static_cast(event)->pos());\n break;\n\n case QEvent::Leave:\n m_label->clear();\n m_rgb_text->clear();\n break;\n }\n\n return QObject::eventFilter(object, event);\n}\n\nvoid MouseCoordinatesTracker::set_label_text(const QPoint& point) const\n{\n const Vector2i pix = widget_to_pixel(point);\n const Vector2d ndc = widget_to_ndc(point);\n\n m_label->setText(\n QString(\"Pixel: %1, %2 - NDC: %3, %4 \")\n .arg(QString::number(pix.x), 4, '0')\n .arg(QString::number(pix.y), 4, '0')\n .arg(QString::number(ndc.x, 'f', 5))\n .arg(QString::number(ndc.y, 'f', 5)));\n}\n\nvoid MouseCoordinatesTracker::set_rgb_text(const QPoint& point) const \n{\n const Vector2i pix = widget_to_pixel(point);\n QRgb pixel_rgb = m_widget->get_image().pixel(pix.x, pix.y);\n\n m_rgb_text->clear();\n QTextCursor cursor(m_rgb_text->textCursor());\n\n \/\/ Set text color to red.\n QTextCharFormat format;\n format.setForeground(QColor(255, 0, 0));\n cursor.setCharFormat(format);\n \/\/ Insert the text at the position of the cursor.\n cursor.insertText(QString(\"%1\").arg(QString::number(qRed(pixel_rgb)), 3, '0'));\n\n \/\/ Move cursor to the end of the text. \n m_rgb_text->moveCursor(QTextCursor::End);\n format.setForeground(QColor(0, 255, 0)); \/\/green\n cursor.setCharFormat(format);\n cursor.insertText(QString(\" %1\").arg(QString::number(qGreen(pixel_rgb)), 3, '0'));\n\n m_rgb_text->moveCursor(QTextCursor::End);\n format.setForeground(QColor(0, 0, 255)); \/\/blue\n cursor.setCharFormat(format);\n cursor.insertText(QString(\" %1\").arg(QString::number(qBlue(pixel_rgb)), 3, '0'));\n\n m_rgb_text->moveCursor(QTextCursor::End);\n format.clearForeground();\n cursor.setCharFormat(format);\n cursor.insertText(QString(\" %1\").arg(QString::number(qAlpha(pixel_rgb)), 3, '0'));\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<|endoftext|>"} {"text":"#include \"eval.h\"\n#include \n#include \n#include \n\nnamespace Akumuli {\nnamespace QP {\n\n\nclass ParseError : public std::exception {\n const std::string message_;\n\npublic:\n ParseError(const char* msg)\n : message_(msg)\n {\n }\n\n ParseError(std::string msg)\n : message_(std::move(msg))\n {\n }\n\n const char* what() const noexcept override {\n return message_.c_str();\n }\n};\n\nclass ExpressionNode {\npublic:\n virtual ~ExpressionNode() = default;\n virtual double eval(MutableSample& mut) = 0;\n};\n\nclass ConstantNode : public ExpressionNode {\n const double cval_;\npublic:\n ConstantNode(double value)\n : cval_(value)\n {\n }\n\n double eval(MutableSample&) override {\n return cval_;\n }\n};\n\nclass ValueNode : public ExpressionNode {\n int ixval_;\npublic:\n ValueNode(int ixval)\n : ixval_(ixval)\n {\n }\n\n double eval(MutableSample& mut) override {\n return *mut[static_cast(ixval_)];\n }\n};\n\nstruct FunctionCallRegistry {\n typedef std::unique_ptr NodeT;\n typedef std::function&&)> CtorT;\n\nprivate:\n std::unordered_map registry_;\n FunctionCallRegistry() = default;\n\npublic:\n static FunctionCallRegistry& get() {\n static FunctionCallRegistry s_registry;\n return s_registry;\n }\n\n void add(std::string name, CtorT&& ctor) {\n registry_[std::move(name)] = ctor;\n }\n\n NodeT create(const std::string& fname, std::vector&& args) {\n NodeT res;\n auto it = registry_.find(fname);\n if (it == registry_.end()) {\n return res;\n }\n return it->second(std::move(args));\n }\n};\n\n\/**\n * Function call expression node.\n * Base interface:\n * - double apply(It begin, It end);\n * - bool check_arity(size_t n, string* errormsg);\n * - static const char* func_name\n *\/\ntemplate\nstruct FunctionCallNode : ExpressionNode, Base\n{\n typedef FunctionCallNode NodeT;\n\n std::vector> children_;\n std::vector args_;\n\n FunctionCallNode(FunctionCallNode const&) = delete;\n FunctionCallNode& operator = (FunctionCallNode const&) = delete;\n\n template\n FunctionCallNode(ArgT&& args)\n : children_(std::forward(args))\n , args_(children_.size())\n {\n std::string errormsg;\n if (!static_cast(this)->check_arity(children_.size(), &errormsg)) {\n ParseError err(std::string(\"function \") + Base::func_name + \" error: \" + errormsg);\n BOOST_THROW_EXCEPTION(err);\n }\n }\n\n double eval(MutableSample& mut) override {\n std::transform(children_.begin(), children_.end(), args_.begin(),\n [&mut](std::unique_ptr& node) {\n return node->eval(mut);\n });\n return static_cast(this)->apply(args_.begin(), args_.end());\n }\n\n static std::unique_ptr create_node(std::vector>&& args) {\n std::unique_ptr result;\n result.reset(new NodeT(std::move(args)));\n return result;\n }\n\nprivate:\n struct RegistryToken {\n RegistryToken() {\n FunctionCallRegistry::get().add(Base::func_name, &create_node);\n }\n };\n\n static RegistryToken regtoken_;\n};\n\ntemplate\ntypename FunctionCallNode::RegistryToken FunctionCallNode::regtoken_;\n\nstruct BuiltInFunctions {\n \/\/ Arithmetics\n struct Sum {\n template\n double apply(It begin, It end) {\n auto res = std::accumulate(begin, end, 0.0, [](double a, double b) {\n return a + b;\n });\n return res;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"+\";\n };\n\n struct Mul {\n template\n double apply(It begin, It end) {\n auto res = std::accumulate(begin, end, 1.0, [](double a, double b) {\n return a * b;\n });\n return res;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"*\";\n };\n\n \/\/ General\n struct Min {\n template\n double apply(It begin, It end) {\n auto it = std::min_element(begin, end);\n if (it != end) {\n return *it;\n }\n return NAN;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"min\";\n };\n\n struct Max {\n template\n double apply(It begin, It end) {\n auto it = std::max_element(begin, end);\n if (it != end) {\n return *it;\n }\n return NAN;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"max\";\n };\n\n struct Abs {\n template\n double apply(It begin, It end) {\n return std::abs(*begin);\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 1) {\n return true;\n }\n *error = \"single argument expected\";\n return false;\n }\n constexpr static const char* func_name = \"abs\";\n };\n};\n\n\/\/ Arithmetic\ntemplate struct FunctionCallNode;\ntemplate struct FunctionCallNode;\n\/\/ General\ntemplate struct FunctionCallNode;\ntemplate struct FunctionCallNode;\ntemplate struct FunctionCallNode;\n\ntypedef boost::property_tree::ptree PTree;\nstatic const int DEPTH_LIMIT = 10;\n\ntemplate\nstd::unique_ptr buildNode(int depth, const PTree& node, const LookupFn& lookup) {\n if (depth == DEPTH_LIMIT) {\n ParseError err(\"expression depth limit exceded\");\n BOOST_THROW_EXCEPTION(err);\n }\n \/\/ Expect array of: [op, arg1, arg2, ...,argN]\n \/\/ i-th arg can be a node in which case recursive call\n \/\/ have to be made.\n std::string op;\n std::vector> args;\n for (auto it = node.begin(); it != node.end(); it++) {\n if (it == node.begin()) {\n \/\/ Parse operator\n if (!it->first.empty()) {\n \/\/ Expect value here\n ParseError err(\"operator or function expected\");\n BOOST_THROW_EXCEPTION(err);\n }\n else {\n op = it->second.data();\n }\n }\n else {\n \/\/ Parse arguments\n auto value = it->second.data();\n if (value.empty()) {\n \/\/ Build sub-node\n auto arg = buildNode(depth + 1, it->second, lookup);\n args.push_back(std::move(arg));\n }\n else {\n std::unique_ptr node;\n std::stringstream str(value);\n double xs;\n str >> xs;\n if (!str.fail()) {\n node.reset(new ConstantNode(xs));\n }\n else {\n auto ix = lookup(value);\n if (ix < 0) {\n \/\/ Field can't be found\n ParseError err(\"unknown field '\" + value + \"'\");\n BOOST_THROW_EXCEPTION(err);\n }\n node.reset(new ValueNode(ix));\n }\n args.push_back(std::move(node));\n }\n }\n }\n std::unique_ptr res;\n res = FunctionCallRegistry::get().create(op, std::move(args));\n if (!res) {\n ParseError err(\"unknown operation '\" + op + \"'\");\n BOOST_THROW_EXCEPTION(err);\n }\n return res;\n}\n\n\n\/\/ ----\n\/\/ Eval\n\/\/ ----\n\n\nstatic std::unordered_map buildNameToIndexMapping(const QP::ReshapeRequest& req)\n{\n std::unordered_map result;\n const int ncol = static_cast(req.select.columns.size());\n for(int ix = 0; ix < ncol; ix++) {\n if (req.select.columns[ix].ids.empty()) {\n continue;\n }\n auto idcol = req.select.columns[ix].ids.front();\n auto rawstr = req.select.matcher->id2str(idcol);\n \/\/ copy metric name from the begining until the ' ' or ':'\n std::string sname(rawstr.first, rawstr.first + rawstr.second);\n auto it = std::find_if(sname.begin(), sname.end(), [](char c) {\n return std::isspace(c) || c == ':';\n });\n result[std::string(sname.begin(), it)] = ix;\n }\n return result;\n}\n\nEval::Eval(const boost::property_tree::ptree& ptree, const ReshapeRequest& req, std::shared_ptr next)\n : next_(next)\n{\n auto const& expr = ptree.get_child_optional(\"expr\");\n if (expr) {\n std::unordered_map lazyInitMap;\n bool initialized = false;\n auto lookupFn = [&](const std::string& fld) {\n if (!initialized) {\n initialized = true;\n lazyInitMap = buildNameToIndexMapping(req);\n }\n auto it = lazyInitMap.find(fld);\n if (it == lazyInitMap.end()) {\n return -1;\n }\n return it->second;\n };\n expr_ = buildNode(0, *expr, lookupFn);\n }\n}\n\nEval::Eval(const boost::property_tree::ptree& expr, const ReshapeRequest& req, std::shared_ptr next, bool)\n : next_(next)\n{\n std::unordered_map lazyInitMap;\n bool initialized = false;\n auto lookupFn = [&](const std::string& fld) {\n if (!initialized) {\n initialized = true;\n lazyInitMap = buildNameToIndexMapping(req);\n }\n auto it = lazyInitMap.find(fld);\n if (it == lazyInitMap.end()) {\n return -1;\n }\n return it->second;\n };\n expr_ = buildNode(0, expr, lookupFn);\n}\n\nvoid Eval::complete() {\n next_->complete();\n}\n\nbool Eval::put(MutableSample &mut) {\n double val = expr_->eval(mut);\n mut.collapse();\n if (std::isnormal(val)) {\n *mut[0] = val;\n return next_->put(mut);\n }\n return true;\n}\n\nvoid Eval::set_error(aku_Status status) {\n next_->set_error(status);\n}\n\nint Eval::get_requirements() const {\n return TERMINAL;\n}\n\nstatic QueryParserToken scale_token(\"eval\");\n\n}} \/\/ namespace\nAdd carrying mechanism#include \"eval.h\"\n#include \n#include \n#include \n\nnamespace Akumuli {\nnamespace QP {\n\n\nclass ParseError : public std::exception {\n const std::string message_;\n\npublic:\n ParseError(const char* msg)\n : message_(msg)\n {\n }\n\n ParseError(std::string msg)\n : message_(std::move(msg))\n {\n }\n\n const char* what() const noexcept override {\n return message_.c_str();\n }\n};\n\nclass ExpressionNode {\npublic:\n virtual ~ExpressionNode() = default;\n virtual double eval(MutableSample& mut) = 0;\n};\n\nclass ConstantNode : public ExpressionNode {\n const double cval_;\npublic:\n ConstantNode(double value)\n : cval_(value)\n {\n }\n\n double eval(MutableSample&) override {\n return cval_;\n }\n};\n\nclass ValueNode : public ExpressionNode {\n int ixval_;\npublic:\n ValueNode(int ixval)\n : ixval_(ixval)\n {\n }\n\n double eval(MutableSample& mut) override {\n return *mut[static_cast(ixval_)];\n }\n};\n\nstruct FunctionCallRegistry {\n typedef std::unique_ptr NodeT;\n typedef std::function&&)> CtorT;\n\nprivate:\n std::unordered_map registry_;\n FunctionCallRegistry() = default;\n\npublic:\n static FunctionCallRegistry& get() {\n static FunctionCallRegistry s_registry;\n return s_registry;\n }\n\n void add(std::string name, CtorT&& ctor) {\n registry_[std::move(name)] = ctor;\n }\n\n NodeT create(const std::string& fname, std::vector&& args) {\n NodeT res;\n auto it = registry_.find(fname);\n if (it == registry_.end()) {\n return res;\n }\n return it->second(std::move(args));\n }\n};\n\n\/**\n * Function call expression node.\n * Base interface:\n * - double apply(It begin, It end);\n * - bool check_arity(size_t n, string* errormsg);\n * - static const char* func_name\n *\/\ntemplate\nstruct FunctionCallNode : ExpressionNode, Base\n{\n typedef FunctionCallNode NodeT;\n\n std::vector> children_;\n std::vector args_;\n\n FunctionCallNode(FunctionCallNode const&) = delete;\n FunctionCallNode& operator = (FunctionCallNode const&) = delete;\n\n template\n FunctionCallNode(ArgT&& args)\n : children_(std::forward(args))\n , args_(children_.size())\n {\n std::string errormsg;\n if (!static_cast(this)->check_arity(children_.size(), &errormsg)) {\n ParseError err(std::string(\"function \") + Base::func_name + \" error: \" + errormsg);\n BOOST_THROW_EXCEPTION(err);\n }\n if (!static_cast(this)->carry(children_, &errormsg)) {\n ParseError err(std::string(\"function \") + Base::func_name + \" error: \" + errormsg);\n BOOST_THROW_EXCEPTION(err);\n }\n }\n\n double eval(MutableSample& mut) override {\n std::transform(children_.begin(), children_.end(), args_.begin(),\n [&mut](std::unique_ptr& node) {\n return node->eval(mut);\n });\n return static_cast(this)->apply(args_.begin(), args_.end());\n }\n\n static std::unique_ptr create_node(std::vector>&& args) {\n std::unique_ptr result;\n result.reset(new NodeT(std::move(args)));\n return result;\n }\n\nprivate:\n struct RegistryToken {\n RegistryToken() {\n FunctionCallRegistry::get().add(Base::func_name, &create_node);\n }\n };\n\n static RegistryToken regtoken_;\n};\n\ntemplate\ntypename FunctionCallNode::RegistryToken FunctionCallNode::regtoken_;\n\nstruct BuiltInFunctions {\n struct BuiltInFn {\n bool carry(std::vector>&, std::string*) {\n \/\/ Default implementation\n return true;\n }\n };\n\n \/\/ Arithmetics\n struct Sum : BuiltInFn {\n template\n double apply(It begin, It end) {\n auto res = std::accumulate(begin, end, 0.0, [](double a, double b) {\n return a + b;\n });\n return res;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"+\";\n };\n\n struct Mul : BuiltInFn {\n template\n double apply(It begin, It end) {\n auto res = std::accumulate(begin, end, 1.0, [](double a, double b) {\n return a * b;\n });\n return res;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"*\";\n };\n\n \/\/ General\n struct Min : BuiltInFn {\n template\n double apply(It begin, It end) {\n auto it = std::min_element(begin, end);\n if (it != end) {\n return *it;\n }\n return NAN;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"min\";\n };\n\n struct Max : BuiltInFn {\n template\n double apply(It begin, It end) {\n auto it = std::max_element(begin, end);\n if (it != end) {\n return *it;\n }\n return NAN;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 0) {\n *error = \"function require at least one parameter\";\n return false;\n }\n return true;\n }\n constexpr static const char* func_name = \"max\";\n };\n\n struct Abs : BuiltInFn {\n template\n double apply(It begin, It end) {\n return std::abs(*begin);\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 1) {\n return true;\n }\n *error = \"single argument expected\";\n return false;\n }\n constexpr static const char* func_name = \"abs\";\n };\n\n \/\/ Windowed functions\n struct SMA : BuiltInFn {\n int N;\n int pos;\n double sum;\n std::vector queue_;\n\n SMA() : N(0), pos(0), sum(0) {}\n\n bool carry(std::vector>& children, std::string* err) {\n static aku_Sample empty;\n static MutableSample mempty(&empty);\n \/\/ First parameter is supposed to be constant\n auto& c = children.front();\n auto cnode = dynamic_cast(c.get());\n if (cnode == nullptr) {\n *err = \"first 'sma' parameter should be constant\";\n return false;\n }\n double val = cnode->eval(mempty);\n N = static_cast(val);\n queue_.resize(N);\n return true;\n }\n\n template\n double apply(It begin, It end) {\n assert(begin != end);\n queue_.at(pos % N) = *begin;\n pos++;\n if (pos > N) {\n double prev = queue_.at(static_cast((pos - N) % N));\n sum -= prev;\n return sum \/ N;\n }\n return sum \/ pos;\n }\n bool check_arity(size_t n, std::string* error) const {\n if (n == 2) {\n return true;\n }\n *error = \"two arguments expected\";\n return false;\n }\n constexpr static const char* func_name = \"sma\";\n };\n};\n\n\/\/ Arithmetic\ntemplate struct FunctionCallNode;\ntemplate struct FunctionCallNode;\n\/\/ General\ntemplate struct FunctionCallNode;\ntemplate struct FunctionCallNode;\ntemplate struct FunctionCallNode;\n\/\/ Window methods\ntemplate struct FunctionCallNode;\n\ntypedef boost::property_tree::ptree PTree;\nstatic const int DEPTH_LIMIT = 10;\n\ntemplate\nstd::unique_ptr buildNode(int depth, const PTree& node, const LookupFn& lookup) {\n if (depth == DEPTH_LIMIT) {\n ParseError err(\"expression depth limit exceded\");\n BOOST_THROW_EXCEPTION(err);\n }\n \/\/ Expect array of: [op, arg1, arg2, ...,argN]\n \/\/ i-th arg can be a node in which case recursive call\n \/\/ have to be made.\n std::string op;\n std::vector> args;\n for (auto it = node.begin(); it != node.end(); it++) {\n if (it == node.begin()) {\n \/\/ Parse operator\n if (!it->first.empty()) {\n \/\/ Expect value here\n ParseError err(\"operator or function expected\");\n BOOST_THROW_EXCEPTION(err);\n }\n else {\n op = it->second.data();\n }\n }\n else {\n \/\/ Parse arguments\n auto value = it->second.data();\n if (value.empty()) {\n \/\/ Build sub-node\n auto arg = buildNode(depth + 1, it->second, lookup);\n args.push_back(std::move(arg));\n }\n else {\n std::unique_ptr node;\n std::stringstream str(value);\n double xs;\n str >> xs;\n if (!str.fail()) {\n node.reset(new ConstantNode(xs));\n }\n else {\n auto ix = lookup(value);\n if (ix < 0) {\n \/\/ Field can't be found\n ParseError err(\"unknown field '\" + value + \"'\");\n BOOST_THROW_EXCEPTION(err);\n }\n node.reset(new ValueNode(ix));\n }\n args.push_back(std::move(node));\n }\n }\n }\n std::unique_ptr res;\n res = FunctionCallRegistry::get().create(op, std::move(args));\n if (!res) {\n ParseError err(\"unknown operation '\" + op + \"'\");\n BOOST_THROW_EXCEPTION(err);\n }\n return res;\n}\n\n\n\/\/ ----\n\/\/ Eval\n\/\/ ----\n\n\nstatic std::unordered_map buildNameToIndexMapping(const QP::ReshapeRequest& req)\n{\n std::unordered_map result;\n const int ncol = static_cast(req.select.columns.size());\n for(int ix = 0; ix < ncol; ix++) {\n if (req.select.columns[ix].ids.empty()) {\n continue;\n }\n auto idcol = req.select.columns[ix].ids.front();\n auto rawstr = req.select.matcher->id2str(idcol);\n \/\/ copy metric name from the begining until the ' ' or ':'\n std::string sname(rawstr.first, rawstr.first + rawstr.second);\n auto it = std::find_if(sname.begin(), sname.end(), [](char c) {\n return std::isspace(c) || c == ':';\n });\n result[std::string(sname.begin(), it)] = ix;\n }\n return result;\n}\n\nEval::Eval(const boost::property_tree::ptree& ptree, const ReshapeRequest& req, std::shared_ptr next)\n : next_(next)\n{\n auto const& expr = ptree.get_child_optional(\"expr\");\n if (expr) {\n std::unordered_map lazyInitMap;\n bool initialized = false;\n auto lookupFn = [&](const std::string& fld) {\n if (!initialized) {\n initialized = true;\n lazyInitMap = buildNameToIndexMapping(req);\n }\n auto it = lazyInitMap.find(fld);\n if (it == lazyInitMap.end()) {\n return -1;\n }\n return it->second;\n };\n expr_ = buildNode(0, *expr, lookupFn);\n }\n}\n\nEval::Eval(const boost::property_tree::ptree& expr, const ReshapeRequest& req, std::shared_ptr next, bool)\n : next_(next)\n{\n std::unordered_map lazyInitMap;\n bool initialized = false;\n auto lookupFn = [&](const std::string& fld) {\n if (!initialized) {\n initialized = true;\n lazyInitMap = buildNameToIndexMapping(req);\n }\n auto it = lazyInitMap.find(fld);\n if (it == lazyInitMap.end()) {\n return -1;\n }\n return it->second;\n };\n expr_ = buildNode(0, expr, lookupFn);\n}\n\nvoid Eval::complete() {\n next_->complete();\n}\n\nbool Eval::put(MutableSample &mut) {\n double val = expr_->eval(mut);\n mut.collapse();\n if (std::isnormal(val)) {\n *mut[0] = val;\n return next_->put(mut);\n }\n return true;\n}\n\nvoid Eval::set_error(aku_Status status) {\n next_->set_error(status);\n}\n\nint Eval::get_requirements() const {\n return TERMINAL;\n}\n\nstatic QueryParserToken scale_token(\"eval\");\n\n}} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/ Copyright Joshua Boyce 2010-2012.\r\n\/\/ Distributed under the Boost Software License, Version 1.0.\r\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/ This file is part of HadesMem.\r\n\/\/ \r\n\r\n#include \"hadesmem\/module_list.hpp\"\r\n\r\n#include \"hadesmem\/detail\/warning_disable_prefix.hpp\"\r\n#include \r\n#include \"hadesmem\/detail\/warning_disable_suffix.hpp\"\r\n\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/module.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/detail\/module_iterator_impl.hpp\"\r\n#include \r\n#include \r\n\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/module.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/detail\/module_iterator_impl.hpp\"\r\n\r\nnamespace hadesmem\r\n{\r\n\r\nModuleIterator::ModuleIterator() BOOST_NOEXCEPT\r\n : impl_()\r\n{ }\r\n\r\nModuleIterator::ModuleIterator(Process const* process)\r\n : impl_(new detail::ModuleIteratorImpl)\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n BOOST_ASSERT(process != nullptr);\r\n \r\n impl_->process_ = process;\r\n \r\n impl_->snap_ = ::CreateToolhelp32Snapshot(\r\n TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, \r\n impl_->process_->GetId());\r\n if (impl_->snap_ == INVALID_HANDLE_VALUE)\r\n {\r\n if (GetLastError() == ERROR_BAD_LENGTH)\r\n {\r\n impl_->snap_ = ::CreateToolhelp32Snapshot(\r\n TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, \r\n impl_->process_->GetId());\r\n if (impl_->snap_ == INVALID_HANDLE_VALUE)\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"CreateToolhelp32Snapshot failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n }\r\n else\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"CreateToolhelp32Snapshot failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n }\r\n \r\n MODULEENTRY32 entry;\r\n ::ZeroMemory(&entry, sizeof(entry));\r\n entry.dwSize = sizeof(entry);\r\n if (!::Module32First(impl_->snap_, &entry))\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n if (last_error == ERROR_NO_MORE_FILES)\r\n {\r\n impl_.reset();\r\n return;\r\n }\r\n \r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"Module32First failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n \r\n impl_->module_ = Module(impl_->process_, entry);\r\n}\r\n\r\nModuleIterator::ModuleIterator(ModuleIterator const& other) BOOST_NOEXCEPT\r\n : impl_(other.impl_)\r\n{ }\r\n\r\nModuleIterator& ModuleIterator::operator=(ModuleIterator const& other) \r\n BOOST_NOEXCEPT\r\n{\r\n impl_ = other.impl_;\r\n \r\n return *this;\r\n}\r\n\r\nModuleIterator::ModuleIterator(ModuleIterator&& other) BOOST_NOEXCEPT\r\n : impl_(std::move(other.impl_))\r\n{ }\r\n\r\nModuleIterator& ModuleIterator::operator=(ModuleIterator&& other) \r\n BOOST_NOEXCEPT\r\n{\r\n impl_ = std::move(other.impl_);\r\n \r\n return *this;\r\n}\r\n\r\nModuleIterator::~ModuleIterator()\r\n{ }\r\n\r\nModuleIterator::reference ModuleIterator::operator*() const BOOST_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return *impl_->module_;\r\n}\r\n\r\nModuleIterator::pointer ModuleIterator::operator->() const BOOST_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return &*impl_->module_;\r\n}\r\n\r\nModuleIterator& ModuleIterator::operator++()\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n \r\n MODULEENTRY32 entry;\r\n ::ZeroMemory(&entry, sizeof(entry));\r\n entry.dwSize = sizeof(entry);\r\n if (!::Module32Next(impl_->snap_, &entry))\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n if (last_error == ERROR_NO_MORE_FILES)\r\n {\r\n impl_.reset();\r\n return *this;\r\n }\r\n \r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"Module32Next failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n \r\n impl_->module_ = Module(impl_->process_, entry);\r\n \r\n return *this;\r\n}\r\n\r\nModuleIterator ModuleIterator::operator++(int)\r\n{\r\n ModuleIterator iter(*this);\r\n ++*this;\r\n return iter;\r\n}\r\n\r\nbool ModuleIterator::operator==(ModuleIterator const& other) const \r\n BOOST_NOEXCEPT\r\n{\r\n return impl_ == other.impl_;\r\n}\r\n\r\nbool ModuleIterator::operator!=(ModuleIterator const& other) const \r\n BOOST_NOEXCEPT\r\n{\r\n return !(*this == other);\r\n}\r\n\r\nModuleList::ModuleList(Process const* process) BOOST_NOEXCEPT\r\n : process_(process)\r\n{\r\n BOOST_ASSERT(process != nullptr);\r\n}\r\n\r\nModuleList::ModuleList(ModuleList const& other) BOOST_NOEXCEPT\r\n : process_(other.process_)\r\n{ }\r\n\r\nModuleList& ModuleList::operator=(ModuleList const& other) BOOST_NOEXCEPT\r\n{\r\n process_ = other.process_;\r\n \r\n return *this;\r\n}\r\n\r\nModuleList::ModuleList(ModuleList&& other) BOOST_NOEXCEPT\r\n : process_(other.process_)\r\n{\r\n other.process_ = nullptr;\r\n}\r\n\r\nModuleList& ModuleList::operator=(ModuleList&& other) BOOST_NOEXCEPT\r\n{\r\n process_ = other.process_;\r\n \r\n other.process_ = nullptr;\r\n \r\n return *this;\r\n}\r\n\r\nModuleList::~ModuleList()\r\n{ }\r\n\r\nModuleList::iterator ModuleList::begin()\r\n{\r\n return ModuleList::iterator(process_);\r\n}\r\n\r\nModuleList::const_iterator ModuleList::begin() const\r\n{\r\n return ModuleList::iterator(process_);\r\n}\r\n\r\nModuleList::iterator ModuleList::end() BOOST_NOEXCEPT\r\n{\r\n return ModuleList::iterator();\r\n}\r\n\r\nModuleList::const_iterator ModuleList::end() const BOOST_NOEXCEPT\r\n{\r\n return ModuleList::iterator();\r\n}\r\n\r\n}\r\n* Remove accidental include.\/\/ Copyright Joshua Boyce 2010-2012.\r\n\/\/ Distributed under the Boost Software License, Version 1.0.\r\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/ This file is part of HadesMem.\r\n\/\/ \r\n\r\n#include \"hadesmem\/module_list.hpp\"\r\n\r\n#include \"hadesmem\/detail\/warning_disable_prefix.hpp\"\r\n#include \r\n#include \"hadesmem\/detail\/warning_disable_suffix.hpp\"\r\n\r\n#include \r\n#include \r\n\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/module.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/detail\/module_iterator_impl.hpp\"\r\n\r\nnamespace hadesmem\r\n{\r\n\r\nModuleIterator::ModuleIterator() BOOST_NOEXCEPT\r\n : impl_()\r\n{ }\r\n\r\nModuleIterator::ModuleIterator(Process const* process)\r\n : impl_(new detail::ModuleIteratorImpl)\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n BOOST_ASSERT(process != nullptr);\r\n \r\n impl_->process_ = process;\r\n \r\n impl_->snap_ = ::CreateToolhelp32Snapshot(\r\n TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, \r\n impl_->process_->GetId());\r\n if (impl_->snap_ == INVALID_HANDLE_VALUE)\r\n {\r\n if (GetLastError() == ERROR_BAD_LENGTH)\r\n {\r\n impl_->snap_ = ::CreateToolhelp32Snapshot(\r\n TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, \r\n impl_->process_->GetId());\r\n if (impl_->snap_ == INVALID_HANDLE_VALUE)\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"CreateToolhelp32Snapshot failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n }\r\n else\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"CreateToolhelp32Snapshot failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n }\r\n \r\n MODULEENTRY32 entry;\r\n ::ZeroMemory(&entry, sizeof(entry));\r\n entry.dwSize = sizeof(entry);\r\n if (!::Module32First(impl_->snap_, &entry))\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n if (last_error == ERROR_NO_MORE_FILES)\r\n {\r\n impl_.reset();\r\n return;\r\n }\r\n \r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"Module32First failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n \r\n impl_->module_ = Module(impl_->process_, entry);\r\n}\r\n\r\nModuleIterator::ModuleIterator(ModuleIterator const& other) BOOST_NOEXCEPT\r\n : impl_(other.impl_)\r\n{ }\r\n\r\nModuleIterator& ModuleIterator::operator=(ModuleIterator const& other) \r\n BOOST_NOEXCEPT\r\n{\r\n impl_ = other.impl_;\r\n \r\n return *this;\r\n}\r\n\r\nModuleIterator::ModuleIterator(ModuleIterator&& other) BOOST_NOEXCEPT\r\n : impl_(std::move(other.impl_))\r\n{ }\r\n\r\nModuleIterator& ModuleIterator::operator=(ModuleIterator&& other) \r\n BOOST_NOEXCEPT\r\n{\r\n impl_ = std::move(other.impl_);\r\n \r\n return *this;\r\n}\r\n\r\nModuleIterator::~ModuleIterator()\r\n{ }\r\n\r\nModuleIterator::reference ModuleIterator::operator*() const BOOST_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return *impl_->module_;\r\n}\r\n\r\nModuleIterator::pointer ModuleIterator::operator->() const BOOST_NOEXCEPT\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n return &*impl_->module_;\r\n}\r\n\r\nModuleIterator& ModuleIterator::operator++()\r\n{\r\n BOOST_ASSERT(impl_.get());\r\n \r\n MODULEENTRY32 entry;\r\n ::ZeroMemory(&entry, sizeof(entry));\r\n entry.dwSize = sizeof(entry);\r\n if (!::Module32Next(impl_->snap_, &entry))\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n if (last_error == ERROR_NO_MORE_FILES)\r\n {\r\n impl_.reset();\r\n return *this;\r\n }\r\n \r\n BOOST_THROW_EXCEPTION(HadesMemError() << \r\n ErrorString(\"Module32Next failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n \r\n impl_->module_ = Module(impl_->process_, entry);\r\n \r\n return *this;\r\n}\r\n\r\nModuleIterator ModuleIterator::operator++(int)\r\n{\r\n ModuleIterator iter(*this);\r\n ++*this;\r\n return iter;\r\n}\r\n\r\nbool ModuleIterator::operator==(ModuleIterator const& other) const \r\n BOOST_NOEXCEPT\r\n{\r\n return impl_ == other.impl_;\r\n}\r\n\r\nbool ModuleIterator::operator!=(ModuleIterator const& other) const \r\n BOOST_NOEXCEPT\r\n{\r\n return !(*this == other);\r\n}\r\n\r\nModuleList::ModuleList(Process const* process) BOOST_NOEXCEPT\r\n : process_(process)\r\n{\r\n BOOST_ASSERT(process != nullptr);\r\n}\r\n\r\nModuleList::ModuleList(ModuleList const& other) BOOST_NOEXCEPT\r\n : process_(other.process_)\r\n{ }\r\n\r\nModuleList& ModuleList::operator=(ModuleList const& other) BOOST_NOEXCEPT\r\n{\r\n process_ = other.process_;\r\n \r\n return *this;\r\n}\r\n\r\nModuleList::ModuleList(ModuleList&& other) BOOST_NOEXCEPT\r\n : process_(other.process_)\r\n{\r\n other.process_ = nullptr;\r\n}\r\n\r\nModuleList& ModuleList::operator=(ModuleList&& other) BOOST_NOEXCEPT\r\n{\r\n process_ = other.process_;\r\n \r\n other.process_ = nullptr;\r\n \r\n return *this;\r\n}\r\n\r\nModuleList::~ModuleList()\r\n{ }\r\n\r\nModuleList::iterator ModuleList::begin()\r\n{\r\n return ModuleList::iterator(process_);\r\n}\r\n\r\nModuleList::const_iterator ModuleList::begin() const\r\n{\r\n return ModuleList::iterator(process_);\r\n}\r\n\r\nModuleList::iterator ModuleList::end() BOOST_NOEXCEPT\r\n{\r\n return ModuleList::iterator();\r\n}\r\n\r\nModuleList::const_iterator ModuleList::end() const BOOST_NOEXCEPT\r\n{\r\n return ModuleList::iterator();\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/* Sirikata Network Utilities\n * TCPStream.cpp\n *\n * Copyright (c) 2009, Daniel Reiter Horn\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"util\/Platform.hpp\"\n#include \"util\/AtomicTypes.hpp\"\n\n#include \"network\/Asio.hpp\"\n#include \"TCPStream.hpp\"\n#include \"util\/ThreadSafeQueue.hpp\"\n#include \"ASIOSocketWrapper.hpp\"\n#include \"MultiplexedSocket.hpp\"\n#include \"TCPSetCallbacks.hpp\"\n#include \"network\/IOServiceFactory.hpp\"\n#include \"network\/IOService.hpp\"\n#include \"options\/Options.hpp\"\n#include \nnamespace Sirikata { namespace Network {\n\nusing namespace boost::asio::ip;\nTCPStream::TCPStream(const MultiplexedSocketPtr&shared_socket,const Stream::StreamID&sid):mSocket(shared_socket),mID(sid),mSendStatus(new AtomicValue(0)) {\n mNumSimultaneousSockets=shared_socket->numSockets();\n assert(mNumSimultaneousSockets);\n mSendBufferSize=shared_socket->getASIOSocketWrapper(0).getResourceMonitor().maxSize();\n}\n\nvoid TCPStream::readyRead() {\n MultiplexedSocketWPtr mpsocket(mSocket);\n mSocket->getASIOService().post(\n std::tr1::bind(&MultiplexedSocket::ioReactorThreadResumeRead,\n mpsocket,\n mID));\n}\n\nvoid TCPStream::pauseSend() {\n MultiplexedSocketWPtr mpsocket(mSocket);\n mSocket->getASIOService().post(\n std::tr1::bind(&MultiplexedSocket::ioReactorThreadPauseSend,\n mpsocket,\n mID));\n}\nbool TCPStream::canSend(const size_t dataSize)const {\n uint8 serializedStreamId[StreamID::MAX_SERIALIZED_LENGTH];\n unsigned int streamIdLength=StreamID::MAX_SERIALIZED_LENGTH;\n unsigned int successLengthNeeded=mID.serialize(serializedStreamId,streamIdLength);\n size_t totalSize=dataSize+successLengthNeeded;\n vuint32 packetLength=vuint32(totalSize);\n uint8 packetLengthSerialized[vuint32::MAX_SERIALIZED_LENGTH];\n unsigned int packetHeaderLength=packetLength.serialize(packetLengthSerialized,vuint32::MAX_SERIALIZED_LENGTH);\n totalSize+=packetHeaderLength;\n return mSocket->canSendBytes(mID,totalSize);\n}\nbool TCPStream::send(const Chunk&data, StreamReliability reliability) {\n return send(MemoryReference(data),reliability);\n}\nbool TCPStream::send(MemoryReference firstChunk, StreamReliability reliability) {\n return send(firstChunk,MemoryReference::null(),reliability);\n}\nbool TCPStream::send(MemoryReference firstChunk, MemoryReference secondChunk, StreamReliability reliability) {\n MultiplexedSocket::RawRequest toBeSent;\n \/\/ only allow 3 of the four possibilities because unreliable ordered is tricky and usually useless\n switch(reliability) {\n case Unreliable:\n toBeSent.unordered=true;\n toBeSent.unreliable=true;\n break;\n case ReliableOrdered:\n toBeSent.unordered=false;\n toBeSent.unreliable=false;\n break;\n case ReliableUnordered:\n toBeSent.unordered=true;\n toBeSent.unreliable=false;\n break;\n }\n toBeSent.originStream=getID();\n uint8 serializedStreamId[StreamID::MAX_SERIALIZED_LENGTH];\n unsigned int streamIdLength=StreamID::MAX_SERIALIZED_LENGTH;\n unsigned int successLengthNeeded=toBeSent.originStream.serialize(serializedStreamId,streamIdLength);\n \/\/\/this function should never return something larger than the MAX_SERIALIZED_LEGNTH\n assert(successLengthNeeded<=streamIdLength);\n streamIdLength=successLengthNeeded;\n size_t totalSize=firstChunk.size()+secondChunk.size();\n totalSize+=streamIdLength;\n vuint32 packetLength=vuint32(totalSize);\n uint8 packetLengthSerialized[vuint32::MAX_SERIALIZED_LENGTH];\n unsigned int packetHeaderLength=packetLength.serialize(packetLengthSerialized,vuint32::MAX_SERIALIZED_LENGTH);\n \/\/allocate a packet long enough to take both the length of the packet and the stream id as well as the packet data. totalSize = size of streamID + size of data and\n \/\/packetHeaderLength = the length of the length component of the packet\n toBeSent.data=new Chunk(totalSize+packetHeaderLength);\n\n uint8 *outputBuffer=&(*toBeSent.data)[0];\n std::memcpy(outputBuffer,packetLengthSerialized,packetHeaderLength);\n std::memcpy(outputBuffer+packetHeaderLength,serializedStreamId,streamIdLength);\n if (firstChunk.size()) {\n std::memcpy(&outputBuffer[packetHeaderLength+streamIdLength],\n firstChunk.data(),\n firstChunk.size());\n }\n if (secondChunk.size()) {\n std::memcpy(&outputBuffer[packetHeaderLength+streamIdLength+firstChunk.size()],\n secondChunk.data(),\n secondChunk.size());\n }\n bool didsend=false;\n \/\/indicate to other would-be TCPStream::close()ers that we are sending and they will have to wait until we give up control to actually ack the close and shut down the stream\n unsigned int sendStatus=++(*mSendStatus);\n if ((sendStatus&(3*SendStatusClosing))==0) {\/\/\/max of 3 entities can close the stream at once (FIXME: should implement |= on atomic ints), but as of now at most the recv thread the sender responsible and a user close() is all that is allowed at once...so 3 is fine)\n didsend=MultiplexedSocket::sendBytes(mSocket,toBeSent,mSendBufferSize);\n }\n \/\/relinquish control to a potential closer\n --(*mSendStatus);\n if (!didsend) {\n \/\/if the data was not sent, its our job to clean it up\n delete toBeSent.data;\n if ((mSendStatus->read()&(3*SendStatusClosing))!=0) {\/\/\/max of 3 entities can close the stream at once (FIXME: should implement |= on atomic ints), but as of now at most the recv thread the sender responsible and a user close() is all that is allowed at once...so 3 is fine)\n SILOG(tcpsst,debug,\"printing to closed stream id \"<&vSendStatus) {\n int sendStatus=vSendStatus.read();\n bool incd=false;\n if ((sendStatus&(SendStatusClosing*3))==0) {\n \/\/\/FIXME we want to |= here\n incd=((vSendStatus+=SendStatusClosing)==SendStatusClosing);\n }\n \/\/Wait until it's a pure sendStatus value without any 'remainders' caused by outstanding sends\n while ((sendStatus=vSendStatus.read())!=SendStatusClosing&&\n sendStatus!=2*SendStatusClosing&&\n sendStatus!=3*SendStatusClosing) {\n }\n return incd;\n}\nvoid TCPStream::close() {\n \/\/set the stream closed as soon as sends are done\n bool justClosed=closeSendStatus(*mSendStatus);\n if (justClosed) {\n \/\/obliterate all incoming callback to this stream\n mSocket->addCallbacks(getID(),NULL);\n \/\/send out that the stream is now closed on all sockets\n MultiplexedSocket::closeStream(mSocket,getID());\n }\n}\nTCPStream::~TCPStream() {\n close();\n}\nTCPStream::TCPStream(IOService&io,OptionSet*options):mSendStatus(new AtomicValue(0)) {\n mIO=&io;\n OptionValue *numSimultSockets=options->referenceOption(\"parallel-sockets\");\n OptionValue *sendBufferSize=options->referenceOption(\"send-buffer-size\");\n assert(numSimultSockets&&sendBufferSize);\n mNumSimultaneousSockets=(unsigned char)numSimultSockets->as();\n assert(mNumSimultaneousSockets);\n mSendBufferSize=sendBufferSize->as();\n}\n\nTCPStream::TCPStream(IOService&io,unsigned char numSimultSockets,unsigned int sendBufferSize):mSendStatus(new AtomicValue(0)) {\n mIO=&io;\n mNumSimultaneousSockets=(unsigned char)numSimultSockets;\n assert(mNumSimultaneousSockets);\n mSendBufferSize=sendBufferSize;\n}\n\nvoid TCPStream::connect(const Address&addy,\n const SubstreamCallback &substreamCallback,\n const ConnectionCallback &connectionCallback,\n const BytesReceivedCallback&bytesReceivedCallback,\n const ReadySendCallback&readySendCallback) {\n mSocket=MultiplexedSocket::construct(mIO,substreamCallback);\n *mSendStatus=0;\n mID=StreamID(1);\n mSocket->addCallbacks(getID(),new Callbacks(connectionCallback,\n bytesReceivedCallback,\n readySendCallback,\n mSendStatus));\n mSocket->connect(addy,mNumSimultaneousSockets,mSendBufferSize);\n}\n\nvoid TCPStream::prepareOutboundConnection(\n const SubstreamCallback &substreamCallback,\n const ConnectionCallback &connectionCallback,\n const BytesReceivedCallback&bytesReceivedCallback,\n const ReadySendCallback&readySendCallback) {\n mSocket=MultiplexedSocket::construct(mIO,substreamCallback);\n *mSendStatus=0;\n mID=StreamID(1);\n mSocket->addCallbacks(getID(),new Callbacks(connectionCallback,\n bytesReceivedCallback,\n readySendCallback,\n mSendStatus));\n mSocket->prepareConnect(mNumSimultaneousSockets,mSendBufferSize);\n}\nvoid TCPStream::connect(const Address&addy) {\n assert(mSocket);\n mSocket->connect(addy,0,mSendBufferSize);\n}\n\nStream*TCPStream::factory(){\n return new TCPStream(*mIO,mNumSimultaneousSockets,mSendBufferSize);\n}\nStream* TCPStream::clone(const SubstreamCallback &cloneCallback) {\n if (!mSocket) {\n return NULL;\n }\n TCPStream *retval=new TCPStream(*mIO,mNumSimultaneousSockets,mSendBufferSize);\n retval->mSocket=mSocket;\n\n StreamID newID=mSocket->getNewID();\n retval->mID=newID;\n TCPSetCallbacks setCallbackFunctor(&*mSocket,retval);\n cloneCallback(retval,setCallbackFunctor);\n return retval;\n}\n\nStream* TCPStream::clone(const ConnectionCallback &connectionCallback,\n const BytesReceivedCallback&chunkReceivedCallback,\n const ReadySendCallback&readySendCallback) {\n if (!mSocket) {\n return NULL;\n }\n TCPStream *retval=new TCPStream(*mIO,mNumSimultaneousSockets,mSendBufferSize);\n retval->mSocket=mSocket;\n\n StreamID newID=mSocket->getNewID();\n retval->mID=newID;\n TCPSetCallbacks setCallbackFunctor(&*mSocket,retval);\n setCallbackFunctor(connectionCallback,chunkReceivedCallback, readySendCallback);\n return retval;\n}\n\n\n\/\/\/Only returns a legitimate address if ConnectionStatus called back, otherwise return Address::null()\nAddress TCPStream::getRemoteEndpoint() const{\n return mSocket->getRemoteEndpoint(mID);\n}\n\/\/\/Only returns a legitimate address if ConnectionStatus called back, otherwise return Address::null()\nAddress TCPStream::getLocalEndpoint() const{\n return mSocket->getLocalEndpoint(mID);\n}\n\n} }\nFix thread safety of TCPStream by making a temporary copy of its MultiplexedSocketPtr and checking the copy before using it.\/* Sirikata Network Utilities\n * TCPStream.cpp\n *\n * Copyright (c) 2009, Daniel Reiter Horn\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"util\/Platform.hpp\"\n#include \"util\/AtomicTypes.hpp\"\n\n#include \"network\/Asio.hpp\"\n#include \"TCPStream.hpp\"\n#include \"util\/ThreadSafeQueue.hpp\"\n#include \"ASIOSocketWrapper.hpp\"\n#include \"MultiplexedSocket.hpp\"\n#include \"TCPSetCallbacks.hpp\"\n#include \"network\/IOServiceFactory.hpp\"\n#include \"network\/IOService.hpp\"\n#include \"options\/Options.hpp\"\n#include \nnamespace Sirikata { namespace Network {\n\nusing namespace boost::asio::ip;\nTCPStream::TCPStream(const MultiplexedSocketPtr&shared_socket,const Stream::StreamID&sid):mSocket(shared_socket),mID(sid),mSendStatus(new AtomicValue(0)) {\n mNumSimultaneousSockets=shared_socket->numSockets();\n assert(mNumSimultaneousSockets);\n mSendBufferSize=shared_socket->getASIOSocketWrapper(0).getResourceMonitor().maxSize();\n}\n\nvoid TCPStream::readyRead() {\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n SILOG(tcpsst,debug,\"Called TCPStream::readyRead() on closed stream.\" << getID().read());\n return;\n }\n\n MultiplexedSocketWPtr mpsocket(socket_copy);\n socket_copy->getASIOService().post(\n std::tr1::bind(&MultiplexedSocket::ioReactorThreadResumeRead,\n mpsocket,\n mID));\n}\n\nvoid TCPStream::pauseSend() {\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n SILOG(tcpsst,debug,\"Called TCPStream::pauseSend() on closed stream.\" << getID().read());\n return;\n }\n\n MultiplexedSocketWPtr mpsocket(socket_copy);\n socket_copy->getASIOService().post(\n std::tr1::bind(&MultiplexedSocket::ioReactorThreadPauseSend,\n mpsocket,\n mID));\n}\nbool TCPStream::canSend(const size_t dataSize)const {\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n SILOG(tcpsst,debug,\"Called TCPStream::canSend() on closed stream.\" << getID().read());\n return false;\n }\n\n uint8 serializedStreamId[StreamID::MAX_SERIALIZED_LENGTH];\n unsigned int streamIdLength=StreamID::MAX_SERIALIZED_LENGTH;\n unsigned int successLengthNeeded=mID.serialize(serializedStreamId,streamIdLength);\n size_t totalSize=dataSize+successLengthNeeded;\n vuint32 packetLength=vuint32(totalSize);\n uint8 packetLengthSerialized[vuint32::MAX_SERIALIZED_LENGTH];\n unsigned int packetHeaderLength=packetLength.serialize(packetLengthSerialized,vuint32::MAX_SERIALIZED_LENGTH);\n totalSize+=packetHeaderLength;\n return socket_copy->canSendBytes(mID,totalSize);\n}\nbool TCPStream::send(const Chunk&data, StreamReliability reliability) {\n return send(MemoryReference(data),reliability);\n}\nbool TCPStream::send(MemoryReference firstChunk, StreamReliability reliability) {\n return send(firstChunk,MemoryReference::null(),reliability);\n}\nbool TCPStream::send(MemoryReference firstChunk, MemoryReference secondChunk, StreamReliability reliability) {\n MultiplexedSocket::RawRequest toBeSent;\n \/\/ only allow 3 of the four possibilities because unreliable ordered is tricky and usually useless\n switch(reliability) {\n case Unreliable:\n toBeSent.unordered=true;\n toBeSent.unreliable=true;\n break;\n case ReliableOrdered:\n toBeSent.unordered=false;\n toBeSent.unreliable=false;\n break;\n case ReliableUnordered:\n toBeSent.unordered=true;\n toBeSent.unreliable=false;\n break;\n }\n toBeSent.originStream=getID();\n uint8 serializedStreamId[StreamID::MAX_SERIALIZED_LENGTH];\n unsigned int streamIdLength=StreamID::MAX_SERIALIZED_LENGTH;\n unsigned int successLengthNeeded=toBeSent.originStream.serialize(serializedStreamId,streamIdLength);\n \/\/\/this function should never return something larger than the MAX_SERIALIZED_LEGNTH\n assert(successLengthNeeded<=streamIdLength);\n streamIdLength=successLengthNeeded;\n size_t totalSize=firstChunk.size()+secondChunk.size();\n totalSize+=streamIdLength;\n vuint32 packetLength=vuint32(totalSize);\n uint8 packetLengthSerialized[vuint32::MAX_SERIALIZED_LENGTH];\n unsigned int packetHeaderLength=packetLength.serialize(packetLengthSerialized,vuint32::MAX_SERIALIZED_LENGTH);\n \/\/allocate a packet long enough to take both the length of the packet and the stream id as well as the packet data. totalSize = size of streamID + size of data and\n \/\/packetHeaderLength = the length of the length component of the packet\n toBeSent.data=new Chunk(totalSize+packetHeaderLength);\n\n uint8 *outputBuffer=&(*toBeSent.data)[0];\n std::memcpy(outputBuffer,packetLengthSerialized,packetHeaderLength);\n std::memcpy(outputBuffer+packetHeaderLength,serializedStreamId,streamIdLength);\n if (firstChunk.size()) {\n std::memcpy(&outputBuffer[packetHeaderLength+streamIdLength],\n firstChunk.data(),\n firstChunk.size());\n }\n if (secondChunk.size()) {\n std::memcpy(&outputBuffer[packetHeaderLength+streamIdLength+firstChunk.size()],\n secondChunk.data(),\n secondChunk.size());\n }\n bool didsend=false;\n \/\/indicate to other would-be TCPStream::close()ers that we are sending and they will have to wait until we give up control to actually ack the close and shut down the stream\n unsigned int sendStatus=++(*mSendStatus);\n if ((sendStatus&(3*SendStatusClosing))==0) {\/\/\/max of 3 entities can close the stream at once (FIXME: should implement |= on atomic ints), but as of now at most the recv thread the sender responsible and a user close() is all that is allowed at once...so 3 is fine)\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL)\n didsend = false;\n else\n didsend=MultiplexedSocket::sendBytes(socket_copy,toBeSent,mSendBufferSize);\n }\n \/\/relinquish control to a potential closer\n --(*mSendStatus);\n if (!didsend) {\n \/\/if the data was not sent, its our job to clean it up\n delete toBeSent.data;\n if ((mSendStatus->read()&(3*SendStatusClosing))!=0) {\/\/\/max of 3 entities can close the stream at once (FIXME: should implement |= on atomic ints), but as of now at most the recv thread the sender responsible and a user close() is all that is allowed at once...so 3 is fine)\n SILOG(tcpsst,debug,\"printing to closed stream id \"<&vSendStatus) {\n int sendStatus=vSendStatus.read();\n bool incd=false;\n if ((sendStatus&(SendStatusClosing*3))==0) {\n \/\/\/FIXME we want to |= here\n incd=((vSendStatus+=SendStatusClosing)==SendStatusClosing);\n }\n \/\/Wait until it's a pure sendStatus value without any 'remainders' caused by outstanding sends\n while ((sendStatus=vSendStatus.read())!=SendStatusClosing&&\n sendStatus!=2*SendStatusClosing&&\n sendStatus!=3*SendStatusClosing) {\n }\n return incd;\n}\nvoid TCPStream::close() {\n \/\/ For thread safety, make a copy so we are ensured it is valid throughout this method\n MultiplexedSocketPtr socket_copy(mSocket);\n\n \/\/ If its already been closed, there's nothing to do\n if (socket_copy.get() == NULL)\n return;\n\n \/\/Otherwise, set the stream closed as soon as sends are done\n bool justClosed=closeSendStatus(*mSendStatus);\n if (justClosed) {\n \/\/obliterate all incoming callback to this stream\n socket_copy->addCallbacks(getID(),NULL);\n \/\/send out that the stream is now closed on all sockets\n MultiplexedSocket::closeStream(socket_copy,getID());\n }\n\n \/\/ And get rid of the reference to the socket so it can (maybe) be cleaned up\n mSocket.reset();\n}\nTCPStream::~TCPStream() {\n close();\n}\nTCPStream::TCPStream(IOService&io,OptionSet*options):mSendStatus(new AtomicValue(0)) {\n mIO=&io;\n OptionValue *numSimultSockets=options->referenceOption(\"parallel-sockets\");\n OptionValue *sendBufferSize=options->referenceOption(\"send-buffer-size\");\n assert(numSimultSockets&&sendBufferSize);\n mNumSimultaneousSockets=(unsigned char)numSimultSockets->as();\n assert(mNumSimultaneousSockets);\n mSendBufferSize=sendBufferSize->as();\n}\n\nTCPStream::TCPStream(IOService&io,unsigned char numSimultSockets,unsigned int sendBufferSize):mSendStatus(new AtomicValue(0)) {\n mIO=&io;\n mNumSimultaneousSockets=(unsigned char)numSimultSockets;\n assert(mNumSimultaneousSockets);\n mSendBufferSize=sendBufferSize;\n}\n\nvoid TCPStream::connect(const Address&addy,\n const SubstreamCallback &substreamCallback,\n const ConnectionCallback &connectionCallback,\n const BytesReceivedCallback&bytesReceivedCallback,\n const ReadySendCallback&readySendCallback) {\n MultiplexedSocketPtr socket = MultiplexedSocket::construct(mIO,substreamCallback);\n mSocket = socket;\n *mSendStatus=0;\n mID=StreamID(1);\n socket->addCallbacks(getID(),new Callbacks(connectionCallback,\n bytesReceivedCallback,\n readySendCallback,\n mSendStatus));\n socket->connect(addy,mNumSimultaneousSockets,mSendBufferSize);\n}\n\nvoid TCPStream::prepareOutboundConnection(\n const SubstreamCallback &substreamCallback,\n const ConnectionCallback &connectionCallback,\n const BytesReceivedCallback&bytesReceivedCallback,\n const ReadySendCallback&readySendCallback) {\n MultiplexedSocketPtr socket = MultiplexedSocket::construct(mIO,substreamCallback);\n mSocket = socket;\n *mSendStatus=0;\n mID=StreamID(1);\n socket->addCallbacks(getID(),new Callbacks(connectionCallback,\n bytesReceivedCallback,\n readySendCallback,\n mSendStatus));\n socket->prepareConnect(mNumSimultaneousSockets,mSendBufferSize);\n}\nvoid TCPStream::connect(const Address&addy) {\n assert(mSocket);\n mSocket->connect(addy,0,mSendBufferSize);\n}\n\nStream*TCPStream::factory(){\n return new TCPStream(*mIO,mNumSimultaneousSockets,mSendBufferSize);\n}\nStream* TCPStream::clone(const SubstreamCallback &cloneCallback) {\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n return NULL;\n }\n\n TCPStream *retval=new TCPStream(*mIO,mNumSimultaneousSockets,mSendBufferSize);\n retval->mSocket = socket_copy;\n\n StreamID newID = socket_copy->getNewID();\n retval->mID=newID;\n TCPSetCallbacks setCallbackFunctor(socket_copy.get(), retval);\n cloneCallback(retval,setCallbackFunctor);\n return retval;\n}\n\nStream* TCPStream::clone(const ConnectionCallback &connectionCallback,\n const BytesReceivedCallback&chunkReceivedCallback,\n const ReadySendCallback&readySendCallback) {\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n return NULL;\n }\n\n TCPStream *retval=new TCPStream(*mIO,mNumSimultaneousSockets,mSendBufferSize);\n retval->mSocket = socket_copy;\n\n StreamID newID = socket_copy->getNewID();\n retval->mID=newID;\n TCPSetCallbacks setCallbackFunctor(socket_copy.get(), retval);\n setCallbackFunctor(connectionCallback,chunkReceivedCallback, readySendCallback);\n return retval;\n}\n\n\n\/\/\/Only returns a legitimate address if ConnectionStatus called back, otherwise return Address::null()\nAddress TCPStream::getRemoteEndpoint() const{\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n SILOG(tcpsst,debug,\"Called TCPStream::getRemoveEndpoint() on closed stream.\" << getID().read());\n return Address::null();\n }\n\n return socket_copy->getRemoteEndpoint(mID);\n}\n\/\/\/Only returns a legitimate address if ConnectionStatus called back, otherwise return Address::null()\nAddress TCPStream::getLocalEndpoint() const{\n MultiplexedSocketPtr socket_copy = mSocket;\n if (socket_copy.get() == NULL) {\n SILOG(tcpsst,debug,\"Called TCPStream::getLocalEndpoint() on closed stream.\" << getID().read());\n return Address::null();\n }\n\n return socket_copy->getLocalEndpoint(mID);\n}\n\n} }\n<|endoftext|>"} {"text":"\/**\n* Copyright (C) 2015 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see .\n*\/\n\n\/**\n* Allows geometry creation using ifcopenshell\n*\/\n\n#include \"repo_ifc_utils_geometry.h\"\n#include \"..\/..\/..\/core\/model\/bson\/repo_bson_factory.h\"\n#include \n\nusing namespace repo::manipulator::modelconvertor;\n\nIFCUtilsGeometry::IFCUtilsGeometry(const std::string &file) :\nfile(file)\n{\n}\n\nIFCUtilsGeometry::~IFCUtilsGeometry()\n{\n}\n\nrepo_material_t IFCUtilsGeometry::createMaterial(\n\tconst IfcGeom::Material &material)\n{\n\trepo_material_t matProp;\n\tif (material.hasDiffuse())\n\t{\n\t\tauto diffuse = material.diffuse();\n\t\tmatProp.diffuse = { (float)diffuse[0], (float)diffuse[1], (float)diffuse[2] };\n\t}\n\n\tif (material.hasSpecular())\n\t{\n\t\tauto specular = material.specular();\n\t\tmatProp.specular = { (float)specular[0], (float)specular[1], (float)specular[2] };\n\t}\n\n\tif (material.hasSpecularity())\n\t{\n\t\tmatProp.shininess = material.specularity();\n\t}\n\telse\n\t{\n\t\tmatProp.shininess = NAN;\n\t}\n\n\tmatProp.shininessStrength = NAN;\n\n\tif (material.hasTransparency())\n\t{\n\t\tmatProp.opacity = 1. - material.transparency();\n\t}\n\telse\n\t{\n\t\tmatProp.opacity = 1.;\n\t}\n\treturn matProp;\n}\n\nIfcGeom::IteratorSettings IFCUtilsGeometry::createSettings()\n{\n\tIfcGeom::IteratorSettings settings;\n\tsettings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, true);\n\tsettings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, false);\n\tsettings.set(IfcGeom::IteratorSettings::NO_NORMALS, false);\n\tsettings.set(IfcGeom::IteratorSettings::WELD_VERTICES, false);\n\tsettings.set(IfcGeom::IteratorSettings::GENERATE_UVS, true);\n\tsettings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, true);\n\n\treturn settings;\n}\n\nbool IFCUtilsGeometry::generateGeometry(std::string &errMsg)\n{\n\trepoInfo << \"Initialising Geometry.....\" << std::endl;\n\n\tauto settings = createSettings();\n\n\tIfcGeom::Iterator contextIterator(settings, file);\n\n\tstd::set exclude_entities;\n\t\/\/Do not generate geometry for openings and spaces\n\texclude_entities.insert(\"IfcOpeningElement\");\n\t\/\/exclude_entities.insert(\"IfcSpace\");\n\tcontextIterator.excludeEntities(exclude_entities);\n\n\trepoTrace << \"Initialising Geom iterator\";\n\tif (contextIterator.initialize())\n\t{\n\t\trepoTrace << \"Geom Iterator initialized\";\n\t}\n\telse\n\t{\n\t\terrMsg = \"Failed to initialised Geom Iterator\";\n\t\treturn false;\n\t}\n\n\tstd::vector> allFaces;\n\tstd::vector> allVertices;\n\tstd::vector> allNormals;\n\tstd::vector> allUVs;\n\tstd::vector allIds, allNames, allMaterials;\n\n\tretrieveGeometryFromIterator(contextIterator, settings.get(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES),\n\t\tallVertices, allFaces, allNormals, allUVs, allIds, allNames, allMaterials);\n\n\t\/\/now we have found all meshes, take the minimum bounding box of the scene as offset\n\t\/\/and create repo meshes\n\trepoTrace << \"Finished iterating. number of meshes found: \" << allVertices.size();\n\trepoTrace << \"Finished iterating. number of materials found: \" << materials.size();\n\n\tstd::map> materialParent;\n\tfor (int i = 0; i < allVertices.size(); ++i)\n\t{\n\t\tstd::vector vertices, normals;\n\t\tstd::vector uvs;\n\t\tstd::vector faces;\n\t\tstd::vector> boundingBox;\n\t\tfor (int j = 0; j < allVertices[i].size(); j += 3)\n\t\t{\n\t\t\tvertices.push_back({ allVertices[i][j] - offset[0], allVertices[i][j + 1] - offset[1], allVertices[i][j + 2] - offset[2] });\n\t\t\tif (allNormals[i].size())\n\t\t\t\tnormals.push_back({ allNormals[i][j], allNormals[i][j + 1], allNormals[i][j + 2] });\n\n\t\t\tauto vertex = vertices.back();\n\t\t\tif (j == 0)\n\t\t\t{\n\t\t\t\tboundingBox.push_back({ vertex.x, vertex.y, vertex.z });\n\t\t\t\tboundingBox.push_back({ vertex.x, vertex.y, vertex.z });\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tboundingBox[0][0] = boundingBox[0][0] > vertex.x ? vertex.x : boundingBox[0][0];\n\t\t\t\tboundingBox[0][1] = boundingBox[0][1] > vertex.y ? vertex.y : boundingBox[0][1];\n\t\t\t\tboundingBox[0][2] = boundingBox[0][2] > vertex.z ? vertex.z : boundingBox[0][2];\n\n\t\t\t\tboundingBox[1][0] = boundingBox[1][0] < vertex.x ? vertex.x : boundingBox[1][0];\n\t\t\t\tboundingBox[1][1] = boundingBox[1][1] < vertex.y ? vertex.y : boundingBox[1][1];\n\t\t\t\tboundingBox[1][2] = boundingBox[1][2] < vertex.z ? vertex.z : boundingBox[1][2];\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < allUVs[i].size(); j += 2)\n\t\t{\n\t\t\tuvs.push_back({ allUVs[i][j], allUVs[i][j + 1] });\n\t\t}\n\n\t\tstd::vector < std::vector> uvChannels;\n\t\tif (uvs.size())\n\t\t\tuvChannels.push_back(uvs);\n\n\t\tauto mesh = repo::core::model::RepoBSONFactory::makeMeshNode(vertices, allFaces[i], normals, boundingBox, uvChannels,\n\t\t\tstd::vector(), std::vector>());\n\n\t\tif (meshes.find(allIds[i]) == meshes.end())\n\t\t{\n\t\t\tmeshes[allIds[i]] = std::vector();\n\t\t}\n\t\tmeshes[allIds[i]].push_back(new repo::core::model::MeshNode(mesh));\n\n\t\tif (allMaterials[i] != \"\")\n\t\t{\n\t\t\tif (materialParent.find(allMaterials[i]) == materialParent.end())\n\t\t\t{\n\t\t\t\tmaterialParent[allMaterials[i]] = std::vector();\n\t\t\t}\n\n\t\t\tmaterialParent[allMaterials[i]].push_back(mesh.getSharedID());\n\t\t}\n\t}\n\n\trepoTrace << \"Meshes constructed. Wiring materials to parents...\";\n\n\tfor (const auto &pair : materialParent)\n\t{\n\t\tauto matIt = materials.find(pair.first);\n\t\tif (matIt != materials.end())\n\t\t{\n\t\t\t*(matIt->second) = matIt->second->cloneAndAddParent(pair.second);\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid IFCUtilsGeometry::retrieveGeometryFromIterator(\n\tIfcGeom::Iterator &contextIterator,\n\tconst bool useMaterialNames,\n\tstd::vector < std::vector> &allVertices,\n\tstd::vector> &allFaces,\n\tstd::vector < std::vector> &allNormals,\n\tstd::vector < std::vector> &allUVs,\n\tstd::vector &allIds,\n\tstd::vector &allNames,\n\tstd::vector &allMaterials)\n{\n\trepoTrace << \"Iterating through Geom Iterator.\";\n\tdo\n\t{\n\t\tIfcGeom::Element *ob = contextIterator.get();\n\t\tauto ob_geo = static_cast*>(ob);\n\t\tif (ob_geo)\n\t\t{\n\t\t\tauto faces = ob_geo->geometry().faces();\n\t\t\tauto vertices = ob_geo->geometry().verts();\n\t\t\tauto normals = ob_geo->geometry().normals();\n\t\t\tauto uvs = ob_geo->geometry().uvs();\n\t\t\tstd::unordered_map> indexMapping;\n\t\t\tstd::unordered_map vertexCount;\n\t\t\tstd::unordered_map> post_vertices, post_normals, post_uvs;\n\t\t\tstd::unordered_map> post_faces;\n\n\t\t\tauto matIndIt = ob_geo->geometry().material_ids().begin();\n\n\t\t\tfor (int i = 0; i < vertices.size(); i += 3)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t{\n\t\t\t\t\tint index = j + i;\n\t\t\t\t\tif (offset.size() < j + 1)\n\t\t\t\t\t{\n\t\t\t\t\t\toffset.push_back(vertices[index]);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\toffset[j] = offset[j] > vertices[index] ? vertices[index] : offset[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int iface = 0; iface < faces.size(); iface += 3)\n\t\t\t{\n\t\t\t\tauto matInd = *matIndIt;\n\t\t\t\tif (indexMapping.find(matInd) == indexMapping.end())\n\t\t\t\t{\n\t\t\t\t\t\/\/new material\n\t\t\t\t\tindexMapping[matInd] = std::unordered_map();\n\t\t\t\t\tvertexCount[matInd] = 0;\n\n\t\t\t\t\tstd::unordered_map> post_vertices, post_normals, post_uvs;\n\t\t\t\t\tstd::unordered_map> post_faces;\n\n\t\t\t\t\tpost_vertices[matInd] = std::vector();\n\t\t\t\t\tpost_normals[matInd] = std::vector();\n\t\t\t\t\tpost_uvs[matInd] = std::vector();\n\t\t\t\t\tpost_faces[matInd] = std::vector();\n\n\t\t\t\t\tauto material = ob_geo->geometry().materials()[matInd];\n\t\t\t\t\tstd::string matName = useMaterialNames ? material.original_name() : material.name();\n\t\t\t\t\tallMaterials.push_back(matName);\n\t\t\t\t\tif (materials.find(matName) == materials.end())\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/new material, add it to the vector\n\t\t\t\t\t\trepo_material_t matProp = createMaterial(material);\n\t\t\t\t\t\tmaterials[matName] = new repo::core::model::MaterialNode(repo::core::model::RepoBSONFactory::makeMaterialNode(matProp, matName));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trepo_face_t face;\n\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t{\n\t\t\t\t\tauto vIndex = faces[iface + j];\n\t\t\t\t\tif (indexMapping[matInd].find(vIndex) == indexMapping[matInd].end())\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/new index. create a mapping\n\t\t\t\t\t\tindexMapping[matInd][vIndex] = vertexCount[matInd]++;\n\t\t\t\t\t\tfor (int ivert = 0; ivert < 3; ++ivert)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto bufferInd = ivert + vIndex * 3;\n\t\t\t\t\t\t\tpost_vertices[matInd].push_back(vertices[bufferInd]);\n\n\t\t\t\t\t\t\tif (normals.size())\n\t\t\t\t\t\t\t\tpost_normals[matInd].push_back(normals[bufferInd]);\n\n\t\t\t\t\t\t\tif (uvs.size() && ivert < 2)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto uvbufferInd = ivert + vIndex * 2;\n\t\t\t\t\t\t\t\tpost_uvs[matInd].push_back(uvs[uvbufferInd]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tface.push_back(indexMapping[matInd][vIndex]);\n\t\t\t\t}\n\n\t\t\t\tpost_faces[matInd].push_back(face);\n\n\t\t\t\t++matIndIt;\n\t\t\t}\n\n\t\t\tauto guid = ob_geo->guid();\n\t\t\tauto name = ob_geo->name();\n\t\t\tfor (const auto& pair : post_faces)\n\t\t\t{\n\t\t\t\tauto index = pair.first;\n\t\t\t\tallVertices.push_back(post_vertices[index]);\n\t\t\t\tallNormals.push_back(post_normals[index]);\n\t\t\t\tallFaces.push_back(pair.second);\n\t\t\t\tallUVs.push_back(post_uvs[index]);\n\n\t\t\t\tallIds.push_back(guid);\n\t\t\t\tallNames.push_back(name);\n\t\t\t}\n\t\t}\n\t\tif (allIds.size() % 100 == 0)\n\t\t\trepoInfo << allIds.size() << \" meshes created\";\n\t} while (contextIterator.next());\n}#13 rid of narrowing conversion warning messages\/**\n* Copyright (C) 2015 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see .\n*\/\n\n\/**\n* Allows geometry creation using ifcopenshell\n*\/\n\n#include \"repo_ifc_utils_geometry.h\"\n#include \"..\/..\/..\/core\/model\/bson\/repo_bson_factory.h\"\n#include \n\nusing namespace repo::manipulator::modelconvertor;\n\nIFCUtilsGeometry::IFCUtilsGeometry(const std::string &file) :\nfile(file)\n{\n}\n\nIFCUtilsGeometry::~IFCUtilsGeometry()\n{\n}\n\nrepo_material_t IFCUtilsGeometry::createMaterial(\n\tconst IfcGeom::Material &material)\n{\n\trepo_material_t matProp;\n\tif (material.hasDiffuse())\n\t{\n\t\tauto diffuse = material.diffuse();\n\t\tmatProp.diffuse = { (float)diffuse[0], (float)diffuse[1], (float)diffuse[2] };\n\t}\n\n\tif (material.hasSpecular())\n\t{\n\t\tauto specular = material.specular();\n\t\tmatProp.specular = { (float)specular[0], (float)specular[1], (float)specular[2] };\n\t}\n\n\tif (material.hasSpecularity())\n\t{\n\t\tmatProp.shininess = material.specularity();\n\t}\n\telse\n\t{\n\t\tmatProp.shininess = NAN;\n\t}\n\n\tmatProp.shininessStrength = NAN;\n\n\tif (material.hasTransparency())\n\t{\n\t\tmatProp.opacity = 1. - material.transparency();\n\t}\n\telse\n\t{\n\t\tmatProp.opacity = 1.;\n\t}\n\treturn matProp;\n}\n\nIfcGeom::IteratorSettings IFCUtilsGeometry::createSettings()\n{\n\tIfcGeom::IteratorSettings settings;\n\tsettings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, true);\n\tsettings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, false);\n\tsettings.set(IfcGeom::IteratorSettings::NO_NORMALS, false);\n\tsettings.set(IfcGeom::IteratorSettings::WELD_VERTICES, false);\n\tsettings.set(IfcGeom::IteratorSettings::GENERATE_UVS, true);\n\tsettings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, true);\n\n\treturn settings;\n}\n\nbool IFCUtilsGeometry::generateGeometry(std::string &errMsg)\n{\n\trepoInfo << \"Initialising Geometry.....\" << std::endl;\n\n\tauto settings = createSettings();\n\n\tIfcGeom::Iterator contextIterator(settings, file);\n\n\tstd::set exclude_entities;\n\t\/\/Do not generate geometry for openings and spaces\n\texclude_entities.insert(\"IfcOpeningElement\");\n\t\/\/exclude_entities.insert(\"IfcSpace\");\n\tcontextIterator.excludeEntities(exclude_entities);\n\n\trepoTrace << \"Initialising Geom iterator\";\n\tif (contextIterator.initialize())\n\t{\n\t\trepoTrace << \"Geom Iterator initialized\";\n\t}\n\telse\n\t{\n\t\terrMsg = \"Failed to initialised Geom Iterator\";\n\t\treturn false;\n\t}\n\n\tstd::vector> allFaces;\n\tstd::vector> allVertices;\n\tstd::vector> allNormals;\n\tstd::vector> allUVs;\n\tstd::vector allIds, allNames, allMaterials;\n\n\tretrieveGeometryFromIterator(contextIterator, settings.get(IfcGeom::IteratorSettings::USE_MATERIAL_NAMES),\n\t\tallVertices, allFaces, allNormals, allUVs, allIds, allNames, allMaterials);\n\n\t\/\/now we have found all meshes, take the minimum bounding box of the scene as offset\n\t\/\/and create repo meshes\n\trepoTrace << \"Finished iterating. number of meshes found: \" << allVertices.size();\n\trepoTrace << \"Finished iterating. number of materials found: \" << materials.size();\n\n\tstd::map> materialParent;\n\tfor (int i = 0; i < allVertices.size(); ++i)\n\t{\n\t\tstd::vector vertices, normals;\n\t\tstd::vector uvs;\n\t\tstd::vector faces;\n\t\tstd::vector> boundingBox;\n\t\tfor (int j = 0; j < allVertices[i].size(); j += 3)\n\t\t{\n\t\t\tvertices.push_back({ (float)(allVertices[i][j] - offset[0]), (float)(allVertices[i][j + 1] - offset[1]), (float)(allVertices[i][j + 2] - offset[2]) });\n\t\t\tif (allNormals[i].size())\n\t\t\t\tnormals.push_back({ (float)allNormals[i][j], (float)allNormals[i][j + 1], (float)allNormals[i][j + 2] });\n\n\t\t\tauto vertex = vertices.back();\n\t\t\tif (j == 0)\n\t\t\t{\n\t\t\t\tboundingBox.push_back({ vertex.x, vertex.y, vertex.z });\n\t\t\t\tboundingBox.push_back({ vertex.x, vertex.y, vertex.z });\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tboundingBox[0][0] = boundingBox[0][0] > vertex.x ? vertex.x : boundingBox[0][0];\n\t\t\t\tboundingBox[0][1] = boundingBox[0][1] > vertex.y ? vertex.y : boundingBox[0][1];\n\t\t\t\tboundingBox[0][2] = boundingBox[0][2] > vertex.z ? vertex.z : boundingBox[0][2];\n\n\t\t\t\tboundingBox[1][0] = boundingBox[1][0] < vertex.x ? vertex.x : boundingBox[1][0];\n\t\t\t\tboundingBox[1][1] = boundingBox[1][1] < vertex.y ? vertex.y : boundingBox[1][1];\n\t\t\t\tboundingBox[1][2] = boundingBox[1][2] < vertex.z ? vertex.z : boundingBox[1][2];\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < allUVs[i].size(); j += 2)\n\t\t{\n\t\t\tuvs.push_back({ (float)allUVs[i][j], (float)allUVs[i][j + 1] });\n\t\t}\n\n\t\tstd::vector < std::vector> uvChannels;\n\t\tif (uvs.size())\n\t\t\tuvChannels.push_back(uvs);\n\n\t\tauto mesh = repo::core::model::RepoBSONFactory::makeMeshNode(vertices, allFaces[i], normals, boundingBox, uvChannels,\n\t\t\tstd::vector(), std::vector>());\n\n\t\tif (meshes.find(allIds[i]) == meshes.end())\n\t\t{\n\t\t\tmeshes[allIds[i]] = std::vector();\n\t\t}\n\t\tmeshes[allIds[i]].push_back(new repo::core::model::MeshNode(mesh));\n\n\t\tif (allMaterials[i] != \"\")\n\t\t{\n\t\t\tif (materialParent.find(allMaterials[i]) == materialParent.end())\n\t\t\t{\n\t\t\t\tmaterialParent[allMaterials[i]] = std::vector();\n\t\t\t}\n\n\t\t\tmaterialParent[allMaterials[i]].push_back(mesh.getSharedID());\n\t\t}\n\t}\n\n\trepoTrace << \"Meshes constructed. Wiring materials to parents...\";\n\n\tfor (const auto &pair : materialParent)\n\t{\n\t\tauto matIt = materials.find(pair.first);\n\t\tif (matIt != materials.end())\n\t\t{\n\t\t\t*(matIt->second) = matIt->second->cloneAndAddParent(pair.second);\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid IFCUtilsGeometry::retrieveGeometryFromIterator(\n\tIfcGeom::Iterator &contextIterator,\n\tconst bool useMaterialNames,\n\tstd::vector < std::vector> &allVertices,\n\tstd::vector> &allFaces,\n\tstd::vector < std::vector> &allNormals,\n\tstd::vector < std::vector> &allUVs,\n\tstd::vector &allIds,\n\tstd::vector &allNames,\n\tstd::vector &allMaterials)\n{\n\trepoTrace << \"Iterating through Geom Iterator.\";\n\tdo\n\t{\n\t\tIfcGeom::Element *ob = contextIterator.get();\n\t\tauto ob_geo = static_cast*>(ob);\n\t\tif (ob_geo)\n\t\t{\n\t\t\tauto faces = ob_geo->geometry().faces();\n\t\t\tauto vertices = ob_geo->geometry().verts();\n\t\t\tauto normals = ob_geo->geometry().normals();\n\t\t\tauto uvs = ob_geo->geometry().uvs();\n\t\t\tstd::unordered_map> indexMapping;\n\t\t\tstd::unordered_map vertexCount;\n\t\t\tstd::unordered_map> post_vertices, post_normals, post_uvs;\n\t\t\tstd::unordered_map> post_faces;\n\n\t\t\tauto matIndIt = ob_geo->geometry().material_ids().begin();\n\n\t\t\tfor (int i = 0; i < vertices.size(); i += 3)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t{\n\t\t\t\t\tint index = j + i;\n\t\t\t\t\tif (offset.size() < j + 1)\n\t\t\t\t\t{\n\t\t\t\t\t\toffset.push_back(vertices[index]);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\toffset[j] = offset[j] > vertices[index] ? vertices[index] : offset[j];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int iface = 0; iface < faces.size(); iface += 3)\n\t\t\t{\n\t\t\t\tauto matInd = *matIndIt;\n\t\t\t\tif (indexMapping.find(matInd) == indexMapping.end())\n\t\t\t\t{\n\t\t\t\t\t\/\/new material\n\t\t\t\t\tindexMapping[matInd] = std::unordered_map();\n\t\t\t\t\tvertexCount[matInd] = 0;\n\n\t\t\t\t\tstd::unordered_map> post_vertices, post_normals, post_uvs;\n\t\t\t\t\tstd::unordered_map> post_faces;\n\n\t\t\t\t\tpost_vertices[matInd] = std::vector();\n\t\t\t\t\tpost_normals[matInd] = std::vector();\n\t\t\t\t\tpost_uvs[matInd] = std::vector();\n\t\t\t\t\tpost_faces[matInd] = std::vector();\n\n\t\t\t\t\tauto material = ob_geo->geometry().materials()[matInd];\n\t\t\t\t\tstd::string matName = useMaterialNames ? material.original_name() : material.name();\n\t\t\t\t\tallMaterials.push_back(matName);\n\t\t\t\t\tif (materials.find(matName) == materials.end())\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/new material, add it to the vector\n\t\t\t\t\t\trepo_material_t matProp = createMaterial(material);\n\t\t\t\t\t\tmaterials[matName] = new repo::core::model::MaterialNode(repo::core::model::RepoBSONFactory::makeMaterialNode(matProp, matName));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trepo_face_t face;\n\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t{\n\t\t\t\t\tauto vIndex = faces[iface + j];\n\t\t\t\t\tif (indexMapping[matInd].find(vIndex) == indexMapping[matInd].end())\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/new index. create a mapping\n\t\t\t\t\t\tindexMapping[matInd][vIndex] = vertexCount[matInd]++;\n\t\t\t\t\t\tfor (int ivert = 0; ivert < 3; ++ivert)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto bufferInd = ivert + vIndex * 3;\n\t\t\t\t\t\t\tpost_vertices[matInd].push_back(vertices[bufferInd]);\n\n\t\t\t\t\t\t\tif (normals.size())\n\t\t\t\t\t\t\t\tpost_normals[matInd].push_back(normals[bufferInd]);\n\n\t\t\t\t\t\t\tif (uvs.size() && ivert < 2)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto uvbufferInd = ivert + vIndex * 2;\n\t\t\t\t\t\t\t\tpost_uvs[matInd].push_back(uvs[uvbufferInd]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tface.push_back(indexMapping[matInd][vIndex]);\n\t\t\t\t}\n\n\t\t\t\tpost_faces[matInd].push_back(face);\n\n\t\t\t\t++matIndIt;\n\t\t\t}\n\n\t\t\tauto guid = ob_geo->guid();\n\t\t\tauto name = ob_geo->name();\n\t\t\tfor (const auto& pair : post_faces)\n\t\t\t{\n\t\t\t\tauto index = pair.first;\n\t\t\t\tallVertices.push_back(post_vertices[index]);\n\t\t\t\tallNormals.push_back(post_normals[index]);\n\t\t\t\tallFaces.push_back(pair.second);\n\t\t\t\tallUVs.push_back(post_uvs[index]);\n\n\t\t\t\tallIds.push_back(guid);\n\t\t\t\tallNames.push_back(name);\n\t\t\t}\n\t\t}\n\t\tif (allIds.size() % 100 == 0)\n\t\t\trepoInfo << allIds.size() << \" meshes created\";\n\t} while (contextIterator.next());\n}<|endoftext|>"} {"text":"\/*******************************************************************************\n * libproxy - A library for proxy configuration\n * Copyright (C) 2006 Nathaniel McCallum \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n ******************************************************************************\/\n\n#include \/\/ ?\n#include \/\/ gethostname\n\n#include \"..\/extension_pacrunner.hpp\"\nusing namespace libproxy;\n\n\/\/ Work around a mozjs include bug\n#ifndef JS_HAS_FILE_OBJECT\n#define JS_HAS_FILE_OBJECT 0\n#endif\n#ifdef WIN32\n#ifndef XP_WIN\n#define XP_WIN\n#endif\n#endif\n#pragma GCC diagnostic ignored \"-Winvalid-offsetof\"\n#include \n#pragma GCC diagnostic error \"-Winvalid-offsetof\"\n#include \n#include \n\n#include \"pacutils.h\"\n\n#ifndef INET_ADDRSTRLEN\n#define INET_ADDRSTRLEN 16\n#endif\n\n#ifndef INET6_ADDRSTRLEN\n#define INET6_ADDRSTRLEN 46\n#endif\n\nstatic void dnsResolve_(JSContext *cx, JSString *hostname, JS::CallArgs *argv) {\n\t\/\/ Get hostname argument\n\tchar *tmp = JS_EncodeString(cx, hostname);\n\n\t\/\/ Set the default return value\n\targv->rval().setNull();\n\n\t\/\/ Look it up\n\tstruct addrinfo *info = nullptr;\n\tif (getaddrinfo(tmp, NULL, NULL, &info))\n\t\tgoto out;\n\n\t\/\/ Allocate the IP address\n\tJS_free(cx, tmp);\n\ttmp = (char *) JS_malloc(cx, INET6_ADDRSTRLEN+1);\n\tmemset(tmp, 0, INET6_ADDRSTRLEN+1);\n\n\t\/\/ Try for IPv4 and IPv6\n\tif (getnameinfo(info->ai_addr, info->ai_addrlen,\n\t\t\t\t\ttmp, INET6_ADDRSTRLEN+1,\n\t\t\t\t\tNULL, 0,\n\t\t\t\t\tNI_NUMERICHOST)) goto out;\n\n\t\/\/ We succeeded\n\targv->rval().setString(JS_NewStringCopyZ(cx, tmp));\n\ttmp = nullptr;\n\n\tout:\n\t\tif (info) freeaddrinfo(info);\n\t\tJS_free(cx, tmp);\n}\n\nstatic bool dnsResolve(JSContext *cx, unsigned argc, JS::Value *vp) {\n\tJS::CallArgs argv=JS::CallArgsFromVp(argc,vp);\n\tdnsResolve_(cx, argv[0].toString(), &argv);\n\treturn true;\n}\n\nstatic bool myIpAddress(JSContext *cx, unsigned argc, JS::Value *vp) {\n\tJS::CallArgs argv=JS::CallArgsFromVp(argc,vp);\n\tchar *hostname = (char *) JS_malloc(cx, 1024);\n\n\tif (!gethostname(hostname, 1023)) {\n\t\tJSString *myhost = JS_NewStringCopyN(cx, hostname, strlen(hostname));\n\t\tdnsResolve_(cx, myhost, &argv);\n\t} else {\n\t\targv.rval().setNull();\n\t}\n\n\tJS_free(cx, hostname);\n\treturn true;\n}\n\n\/\/ Setup Javascript global class\n\/\/ This MUST be a static global\nstatic JSClass cls = {\n\t\t\"global\", JSCLASS_GLOBAL_FLAGS,\n};\n\nclass mozjs_pacrunner : public pacrunner {\npublic:\n\tmozjs_pacrunner(string pac, const url& pacurl) throw (bad_alloc) : pacrunner(pac, pacurl) {\n\n\t\t\/\/ Set defaults\n\t\tthis->jsctx = nullptr;\n\t\tJS_Init();\n\n\t\t\/\/ Initialize Javascript context\n\t\tif (!(this->jsctx = JS_NewContext(1024 * 1024))) goto error;\n\t\t{\n\t\t\tJS::RootedValue rval(this->jsctx);\n\t\t\tJS::CompartmentOptions compart_opts;\n\n\t\t\tthis->jsglb = new JS::Heap(JS_NewGlobalObject(\n\t\t\t\t\t\t\t\t this->jsctx, &cls,\n\t\t\t\t\t\t\t\t nullptr, JS::DontFireOnNewGlobalHook,\n\t\t\t\t\t\t\t\t compart_opts));\n\n\t\t\tif (!(this->jsglb)) goto error;\n\t\t\tJS::RootedObject global(this->jsctx,this->jsglb->get());\n\t\t\tif (!(this->jsac = new JSAutoCompartment(this->jsctx, global))) goto error;\n\t\t\tif (!JS_InitStandardClasses(this->jsctx, global)) goto error;\n\n\t\t\t\/\/ Define Javascript functions\n\t\t\tJS_DefineFunction(this->jsctx, global, \"dnsResolve\", dnsResolve, 1, 0);\n\t\t\tJS_DefineFunction(this->jsctx, global, \"myIpAddress\", myIpAddress, 0, 0);\n\t\t\tJS::CompileOptions options(this->jsctx);\n\t\t\toptions.setUTF8(true);\n\n\t\t\tJS::Evaluate(this->jsctx, options, JAVASCRIPT_ROUTINES,\n\t\t\t\t strlen(JAVASCRIPT_ROUTINES), JS::MutableHandleValue(&rval));\n\n\t\t\t\/\/ Add PAC to the environment\n\t\t\tJS::Evaluate(this->jsctx, options, pac.c_str(), pac.length(), JS::MutableHandleValue(&rval));\n\t\t\treturn;\n\t\t}\n\t\terror:\n\t\t\tif (this->jsctx) JS_DestroyContext(this->jsctx);\n\t\t\tthrow bad_alloc();\n\t}\n\n\t~mozjs_pacrunner() {\n\t\tif (this->jsac) delete this->jsac;\n\t\tif (this->jsglb) delete this->jsglb;\n\t\tif (this->jsctx) JS_DestroyContext(this->jsctx);\n\t\tJS_ShutDown();\n\t}\n\n\tstring run(const url& url_) throw (bad_alloc) {\n\t\t\/\/ Build arguments to the FindProxyForURL() function\n\t\tchar *tmpurl = JS_strdup(this->jsctx, url_.to_string().c_str());\n\t\tchar *tmphost = JS_strdup(this->jsctx, url_.get_host().c_str());\n\t\tif (!tmpurl || !tmphost) {\n\t\t\tif (tmpurl) JS_free(this->jsctx, tmpurl);\n\t\t\tif (tmphost) JS_free(this->jsctx, tmphost);\n\t\t\tthrow bad_alloc();\n\t\t}\n\t\tJS::AutoValueArray<2> args(this->jsctx);\n\t\targs[0].setString(JS_NewStringCopyZ(this->jsctx, tmpurl));\n\t\targs[1].setString(JS_NewStringCopyZ(this->jsctx, tmphost));\n\n\t\t\/\/ Find the proxy (call FindProxyForURL())\n\t\tJS::RootedValue rval(this->jsctx);\n\t\tJS::RootedObject global(this->jsctx,this->jsglb->get());\n\t\tbool result = JS_CallFunctionName(this->jsctx, global, \"FindProxyForURL\", args, &rval);\n\t\tif (!result) return \"\";\n\n\t\tchar * tmpanswer = JS_EncodeString(this->jsctx, rval.toString());\n\t\tstring answer = string(tmpanswer);\n\t\tJS_free(this->jsctx, tmpanswer);\n\n\t\tif (answer == \"undefined\") return \"\";\n\t\treturn answer;\n\t}\n\nprivate:\n\tJSContext *jsctx;\n\tJS::Heap *jsglb;\n\tJSAutoCompartment *jsac;\n};\n\nPX_PACRUNNER_MODULE_EZ(mozjs, \"JS_DefineFunction\", \"mozjs\");\nAdd call to JS::InitSelfHostedCode()\/*******************************************************************************\n * libproxy - A library for proxy configuration\n * Copyright (C) 2006 Nathaniel McCallum \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n ******************************************************************************\/\n\n#include \/\/ ?\n#include \/\/ gethostname\n\n#include \"..\/extension_pacrunner.hpp\"\nusing namespace libproxy;\n\n\/\/ Work around a mozjs include bug\n#ifndef JS_HAS_FILE_OBJECT\n#define JS_HAS_FILE_OBJECT 0\n#endif\n#ifdef WIN32\n#ifndef XP_WIN\n#define XP_WIN\n#endif\n#endif\n#pragma GCC diagnostic ignored \"-Winvalid-offsetof\"\n#include \n#pragma GCC diagnostic error \"-Winvalid-offsetof\"\n#include \n#include \n\n#include \"pacutils.h\"\n\n#ifndef INET_ADDRSTRLEN\n#define INET_ADDRSTRLEN 16\n#endif\n\n#ifndef INET6_ADDRSTRLEN\n#define INET6_ADDRSTRLEN 46\n#endif\n\nstatic void dnsResolve_(JSContext *cx, JSString *hostname, JS::CallArgs *argv) {\n\t\/\/ Get hostname argument\n\tchar *tmp = JS_EncodeString(cx, hostname);\n\n\t\/\/ Set the default return value\n\targv->rval().setNull();\n\n\t\/\/ Look it up\n\tstruct addrinfo *info = nullptr;\n\tif (getaddrinfo(tmp, NULL, NULL, &info))\n\t\tgoto out;\n\n\t\/\/ Allocate the IP address\n\tJS_free(cx, tmp);\n\ttmp = (char *) JS_malloc(cx, INET6_ADDRSTRLEN+1);\n\tmemset(tmp, 0, INET6_ADDRSTRLEN+1);\n\n\t\/\/ Try for IPv4 and IPv6\n\tif (getnameinfo(info->ai_addr, info->ai_addrlen,\n\t\t\t\t\ttmp, INET6_ADDRSTRLEN+1,\n\t\t\t\t\tNULL, 0,\n\t\t\t\t\tNI_NUMERICHOST)) goto out;\n\n\t\/\/ We succeeded\n\targv->rval().setString(JS_NewStringCopyZ(cx, tmp));\n\ttmp = nullptr;\n\n\tout:\n\t\tif (info) freeaddrinfo(info);\n\t\tJS_free(cx, tmp);\n}\n\nstatic bool dnsResolve(JSContext *cx, unsigned argc, JS::Value *vp) {\n\tJS::CallArgs argv=JS::CallArgsFromVp(argc,vp);\n\tdnsResolve_(cx, argv[0].toString(), &argv);\n\treturn true;\n}\n\nstatic bool myIpAddress(JSContext *cx, unsigned argc, JS::Value *vp) {\n\tJS::CallArgs argv=JS::CallArgsFromVp(argc,vp);\n\tchar *hostname = (char *) JS_malloc(cx, 1024);\n\n\tif (!gethostname(hostname, 1023)) {\n\t\tJSString *myhost = JS_NewStringCopyN(cx, hostname, strlen(hostname));\n\t\tdnsResolve_(cx, myhost, &argv);\n\t} else {\n\t\targv.rval().setNull();\n\t}\n\n\tJS_free(cx, hostname);\n\treturn true;\n}\n\n\/\/ Setup Javascript global class\n\/\/ This MUST be a static global\nstatic JSClass cls = {\n\t\t\"global\", JSCLASS_GLOBAL_FLAGS,\n};\n\nclass mozjs_pacrunner : public pacrunner {\npublic:\n\tmozjs_pacrunner(string pac, const url& pacurl) throw (bad_alloc) : pacrunner(pac, pacurl) {\n\n\t\t\/\/ Set defaults\n\t\tthis->jsctx = nullptr;\n\t\tJS_Init();\n\n\t\t\/\/ Initialize Javascript context\n\t\tif (!(this->jsctx = JS_NewContext(1024 * 1024))) goto error;\n\t\t{\n\t\t\tif (!JS::InitSelfHostedCode(this->jsctx)) goto error;\n\n\t\t\tJS::RootedValue rval(this->jsctx);\n\t\t\tJS::CompartmentOptions compart_opts;\n\n\t\t\tthis->jsglb = new JS::Heap(JS_NewGlobalObject(\n\t\t\t\t\t\t\t\t this->jsctx, &cls,\n\t\t\t\t\t\t\t\t nullptr, JS::DontFireOnNewGlobalHook,\n\t\t\t\t\t\t\t\t compart_opts));\n\n\t\t\tif (!(this->jsglb)) goto error;\n\t\t\tJS::RootedObject global(this->jsctx,this->jsglb->get());\n\t\t\tif (!(this->jsac = new JSAutoCompartment(this->jsctx, global))) goto error;\n\t\t\tif (!JS_InitStandardClasses(this->jsctx, global)) goto error;\n\n\t\t\t\/\/ Define Javascript functions\n\t\t\tJS_DefineFunction(this->jsctx, global, \"dnsResolve\", dnsResolve, 1, 0);\n\t\t\tJS_DefineFunction(this->jsctx, global, \"myIpAddress\", myIpAddress, 0, 0);\n\t\t\tJS::CompileOptions options(this->jsctx);\n\t\t\toptions.setUTF8(true);\n\n\t\t\tJS::Evaluate(this->jsctx, options, JAVASCRIPT_ROUTINES,\n\t\t\t\t strlen(JAVASCRIPT_ROUTINES), JS::MutableHandleValue(&rval));\n\n\t\t\t\/\/ Add PAC to the environment\n\t\t\tJS::Evaluate(this->jsctx, options, pac.c_str(), pac.length(), JS::MutableHandleValue(&rval));\n\t\t\treturn;\n\t\t}\n\t\terror:\n\t\t\tif (this->jsctx) JS_DestroyContext(this->jsctx);\n\t\t\tthrow bad_alloc();\n\t}\n\n\t~mozjs_pacrunner() {\n\t\tif (this->jsac) delete this->jsac;\n\t\tif (this->jsglb) delete this->jsglb;\n\t\tif (this->jsctx) JS_DestroyContext(this->jsctx);\n\t\tJS_ShutDown();\n\t}\n\n\tstring run(const url& url_) throw (bad_alloc) {\n\t\t\/\/ Build arguments to the FindProxyForURL() function\n\t\tchar *tmpurl = JS_strdup(this->jsctx, url_.to_string().c_str());\n\t\tchar *tmphost = JS_strdup(this->jsctx, url_.get_host().c_str());\n\t\tif (!tmpurl || !tmphost) {\n\t\t\tif (tmpurl) JS_free(this->jsctx, tmpurl);\n\t\t\tif (tmphost) JS_free(this->jsctx, tmphost);\n\t\t\tthrow bad_alloc();\n\t\t}\n\t\tJS::AutoValueArray<2> args(this->jsctx);\n\t\targs[0].setString(JS_NewStringCopyZ(this->jsctx, tmpurl));\n\t\targs[1].setString(JS_NewStringCopyZ(this->jsctx, tmphost));\n\n\t\t\/\/ Find the proxy (call FindProxyForURL())\n\t\tJS::RootedValue rval(this->jsctx);\n\t\tJS::RootedObject global(this->jsctx,this->jsglb->get());\n\t\tbool result = JS_CallFunctionName(this->jsctx, global, \"FindProxyForURL\", args, &rval);\n\t\tif (!result) return \"\";\n\n\t\tchar * tmpanswer = JS_EncodeString(this->jsctx, rval.toString());\n\t\tstring answer = string(tmpanswer);\n\t\tJS_free(this->jsctx, tmpanswer);\n\n\t\tif (answer == \"undefined\") return \"\";\n\t\treturn answer;\n\t}\n\nprivate:\n\tJSContext *jsctx;\n\tJS::Heap *jsglb;\n\tJSAutoCompartment *jsac;\n};\n\nPX_PACRUNNER_MODULE_EZ(mozjs, \"JS_DefineFunction\", \"mozjs\");\n<|endoftext|>"} {"text":"\/*\n** Author(s):\n** - Cedric GESTES \n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include \n#include \n#include \n#include \"qimetatype_p.h\"\n#include \"qmetaobjectbuilder_p.h\"\n#include \n\nQString qi_MetatypeToNetworkType(const int metatype)\n{\n if (metatype == QMetaType::QString)\n return \"s\";\n return \"FAIL\";\n}\n\n\/\/QString qi_NetworkTypeToMetatype(const QString &metatype, const QMap &typemap)\nQString qi_NetworkTypeToMetatype(const QString &nettype)\n{\n if (nettype == \"s\")\n return \"QString\";\n return \"FAIL\";\n}\n\n\n\/\/ string\nqi::DataStream& operator>>(qi::DataStream &stream, QString &s)\n{\n int len;\n stream >> len;\n QByteArray qbb(len, '0');\n stream.read(qbb.data(), len);\n s.append(qbb);\n return stream;\n}\n\nqi::DataStream& operator<<(qi::DataStream &stream, const QString &s)\n{\n stream.writeString((const char *)s.toAscii().constData(), s.size());\n return stream;\n}\n\n\nbool qi_MetaTypeStore(qi::DataStream &stream, int metatype, void *data)\n{\n if (!data || !QMetaType::isRegistered(metatype))\n return false;\n\n switch(metatype) {\n case QMetaType::Void:\n case QMetaType::VoidStar:\n return false;\n\n case QMetaType::Char:\n \/\/ force a char to be signed\n stream << *static_cast(data);\n break;\n case QMetaType::UChar:\n stream << *static_cast(data);\n break;\n case QMetaType::Bool:\n stream << qint8(*static_cast(data));\n break;\n\n case QMetaType::Int:\n stream << *static_cast(data);\n break;\n\/\/ case QMetaType::UInt:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\n case QMetaType::Short:\n stream << *static_cast(data);\n break;\n\/\/ case QMetaType::UShort:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\n\/\/ case QMetaType::Long:\n\/\/ stream << qlonglong(*static_cast(data));\n\/\/ break;\n\/\/ case QMetaType::ULong:\n\/\/ stream << qulonglong(*static_cast(data));\n\/\/ break;\n\n\/\/ case QMetaType::LongLong:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::ULongLong:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\n case QMetaType::Float:\n stream << *static_cast(data);\n break;\n case QMetaType::Double:\n stream << *static_cast(data);\n break;\n\n\/\/ case QMetaType::QByteArray:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n case QMetaType::QString:\n stream << *static_cast(data);\n break;\n\/\/ case QMetaType::QStringList:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n default:\n return false;\n }\n return true;\n}\n\nbool qi_MetaTypeLoad(qi::DataStream &stream, int metatype, void *data)\n{\n if (!data || !QMetaType::isRegistered(metatype))\n return false;\n\n switch(metatype) {\n case QMetaType::Void:\n case QMetaType::VoidStar:\n return false;\n\n case QMetaType::Bool: {\n char b;\n stream >> b;\n *static_cast(data) = b;\n break;\n }\n\n\/\/ case QMetaType::Char:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::UChar:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n\/\/ case QMetaType::Short:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::UShort:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n case QMetaType::Int:\n stream >> *static_cast(data);\n break;\n\/\/ case QMetaType::UInt:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n\/\/ case QMetaType::Long: {\n\/\/ qlonglong l;\n\/\/ stream >> l;\n\/\/ *static_cast(data) = long(l);\n\/\/ break; }\n\/\/ case QMetaType::ULong: {\n\/\/ qulonglong ul;\n\/\/ stream >> ul;\n\/\/ *static_cast(data) = ulong(ul);\n\/\/ break; }\n\/\/ case QMetaType::LongLong:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::ULongLong:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n case QMetaType::Float:\n stream >> *static_cast(data);\n break;\n case QMetaType::Double:\n stream >> *static_cast(data);\n break;\n\n\/\/ case QMetaType::QByteArray:\n\/\/ stream >> *static_cast< NS(QByteArray)*>(data);\n\/\/ break;\n case QMetaType::QString:\n stream >> *static_cast< QString*>(data);\n break;\n default:\n return false;\n }\n return true;\n\n\n}\n\n\nvoid qi_SignatureToMetaMethod(const std::string &signature, QString *returnSig, QString *funcSig)\n{\n std::string retSig;\n std::string parSig;\n std::string funcName;\n\n int idx1 = signature.find(\"::\");\n if (idx1 != signature.npos)\n funcName = signature.substr(0, idx1);\n int idx2 = signature.find(\"(\", idx1);\n if (idx2 != signature.npos) {\n retSig = signature.substr(idx1 + 2, idx2 - idx1 - 2);\n parSig = signature.substr(idx2);\n }\n\n\n qi::Signature rets(retSig);\n qi::Signature funs(parSig);\n *returnSig = QString::fromStdString(rets.toQtSignature(false));\n *funcSig = QString::fromStdString(funcName) + QString::fromStdString(funs.toQtSignature(true));\n}\n\nFix type mismatch.\/*\n** Author(s):\n** - Cedric GESTES \n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include \n#include \n#include \n#include \"qimetatype_p.h\"\n#include \"qmetaobjectbuilder_p.h\"\n#include \n\nQString qi_MetatypeToNetworkType(const int metatype)\n{\n if (metatype == QMetaType::QString)\n return \"s\";\n return \"FAIL\";\n}\n\n\/\/QString qi_NetworkTypeToMetatype(const QString &metatype, const QMap &typemap)\nQString qi_NetworkTypeToMetatype(const QString &nettype)\n{\n if (nettype == \"s\")\n return \"QString\";\n return \"FAIL\";\n}\n\n\n\/\/ string\nqi::DataStream& operator>>(qi::DataStream &stream, QString &s)\n{\n int len;\n stream >> len;\n QByteArray qbb(len, '0');\n stream.read(qbb.data(), len);\n s.append(qbb);\n return stream;\n}\n\nqi::DataStream& operator<<(qi::DataStream &stream, const QString &s)\n{\n stream.writeString((const char *)s.toAscii().constData(), s.size());\n return stream;\n}\n\n\nbool qi_MetaTypeStore(qi::DataStream &stream, int metatype, void *data)\n{\n if (!data || !QMetaType::isRegistered(metatype))\n return false;\n\n switch(metatype) {\n case QMetaType::Void:\n case QMetaType::VoidStar:\n return false;\n\n case QMetaType::Char:\n \/\/ force a char to be signed\n stream << *static_cast(data);\n break;\n case QMetaType::UChar:\n stream << *static_cast(data);\n break;\n case QMetaType::Bool:\n stream << qint8(*static_cast(data));\n break;\n\n case QMetaType::Int:\n stream << *static_cast(data);\n break;\n\/\/ case QMetaType::UInt:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\n case QMetaType::Short:\n stream << *static_cast(data);\n break;\n\/\/ case QMetaType::UShort:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\n\/\/ case QMetaType::Long:\n\/\/ stream << qlonglong(*static_cast(data));\n\/\/ break;\n\/\/ case QMetaType::ULong:\n\/\/ stream << qulonglong(*static_cast(data));\n\/\/ break;\n\n\/\/ case QMetaType::LongLong:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::ULongLong:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n\n case QMetaType::Float:\n stream << *static_cast(data);\n break;\n case QMetaType::Double:\n stream << *static_cast(data);\n break;\n\n\/\/ case QMetaType::QByteArray:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n case QMetaType::QString:\n stream << *static_cast(data);\n break;\n\/\/ case QMetaType::QStringList:\n\/\/ stream << *static_cast(data);\n\/\/ break;\n default:\n return false;\n }\n return true;\n}\n\nbool qi_MetaTypeLoad(qi::DataStream &stream, int metatype, void *data)\n{\n if (!data || !QMetaType::isRegistered(metatype))\n return false;\n\n switch(metatype) {\n case QMetaType::Void:\n case QMetaType::VoidStar:\n return false;\n\n case QMetaType::Bool: {\n char b;\n stream >> b;\n *static_cast(data) = b;\n break;\n }\n\n\/\/ case QMetaType::Char:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::UChar:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n\/\/ case QMetaType::Short:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::UShort:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n case QMetaType::Int:\n stream >> *static_cast(data);\n break;\n\/\/ case QMetaType::UInt:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n\/\/ case QMetaType::Long: {\n\/\/ qlonglong l;\n\/\/ stream >> l;\n\/\/ *static_cast(data) = long(l);\n\/\/ break; }\n\/\/ case QMetaType::ULong: {\n\/\/ qulonglong ul;\n\/\/ stream >> ul;\n\/\/ *static_cast(data) = ulong(ul);\n\/\/ break; }\n\/\/ case QMetaType::LongLong:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\/\/ case QMetaType::ULongLong:\n\/\/ stream >> *static_cast(data);\n\/\/ break;\n\n case QMetaType::Float:\n stream >> *static_cast(data);\n break;\n case QMetaType::Double:\n stream >> *static_cast(data);\n break;\n\n\/\/ case QMetaType::QByteArray:\n\/\/ stream >> *static_cast< NS(QByteArray)*>(data);\n\/\/ break;\n case QMetaType::QString:\n stream >> *static_cast< QString*>(data);\n break;\n default:\n return false;\n }\n return true;\n\n\n}\n\n\nvoid qi_SignatureToMetaMethod(const std::string &signature, QString *returnSig, QString *funcSig)\n{\n std::string retSig;\n std::string parSig;\n std::string funcName;\n\n size_t idx1 = signature.find(\"::\");\n if (idx1 != signature.npos)\n funcName = signature.substr(0, idx1);\n size_t idx2 = signature.find(\"(\", idx1);\n if (idx2 != signature.npos) {\n retSig = signature.substr(idx1 + 2, idx2 - idx1 - 2);\n parSig = signature.substr(idx2);\n }\n\n\n qi::Signature rets(retSig);\n qi::Signature funs(parSig);\n *returnSig = QString::fromStdString(rets.toQtSignature(false));\n *funcSig = QString::fromStdString(funcName) + QString::fromStdString(funs.toQtSignature(true));\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_action_platform_delegate_views.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/api\/commands\/command_service.h\"\n#include \"chrome\/browser\/extensions\/api\/extension_action\/extension_action_api.h\"\n#include \"chrome\/browser\/extensions\/extension_action.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/session_tab_helper.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/extensions\/accelerator_priority.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/browser_actions_container.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/toolbar_action_view_delegate_views.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/toolbar_view.h\"\n#include \"chrome\/common\/extensions\/api\/extension_action\/action_info.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"extensions\/browser\/notification_types.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"ui\/gfx\/image\/image_skia_operations.h\"\n#include \"ui\/views\/controls\/menu\/menu_controller.h\"\n#include \"ui\/views\/controls\/menu\/menu_runner.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nusing extensions::ActionInfo;\nusing extensions::CommandService;\n\nnamespace {\n\n\/\/ The ExtensionActionPlatformDelegateViews which is currently showing its\n\/\/ context menu, if any.\n\/\/ Since only one context menu can be shown (even across browser windows), it's\n\/\/ safe to have this be a global singleton.\nExtensionActionPlatformDelegateViews* context_menu_owner = NULL;\n\n} \/\/ namespace\n\n\/\/ static\nscoped_ptr\nExtensionActionPlatformDelegate::Create(\n ExtensionActionViewController* controller) {\n return make_scoped_ptr(new ExtensionActionPlatformDelegateViews(controller));\n}\n\nExtensionActionPlatformDelegateViews::ExtensionActionPlatformDelegateViews(\n ExtensionActionViewController* controller)\n : controller_(controller),\n popup_(nullptr),\n weak_factory_(this) {\n content::NotificationSource notification_source = content::Source(\n controller_->browser()->profile()->GetOriginalProfile());\n registrar_.Add(this,\n extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED,\n notification_source);\n registrar_.Add(this,\n extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED,\n notification_source);\n}\n\nExtensionActionPlatformDelegateViews::~ExtensionActionPlatformDelegateViews() {\n DCHECK(!popup_); \/\/ We should never have a visible popup at shutdown.\n if (context_menu_owner == this)\n context_menu_owner = nullptr;\n UnregisterCommand(false);\n}\n\ngfx::NativeView ExtensionActionPlatformDelegateViews::GetPopupNativeView() {\n return popup_ ? popup_->GetWidget()->GetNativeView() : nullptr;\n}\n\nbool ExtensionActionPlatformDelegateViews::IsMenuRunning() const {\n return menu_runner_.get() != NULL;\n}\n\nvoid ExtensionActionPlatformDelegateViews::RegisterCommand() {\n \/\/ If we've already registered, do nothing.\n if (action_keybinding_.get())\n return;\n\n extensions::Command extension_command;\n views::FocusManager* focus_manager =\n GetDelegateViews()->GetFocusManagerForAccelerator();\n if (focus_manager && controller_->GetExtensionCommand(&extension_command)) {\n action_keybinding_.reset(\n new ui::Accelerator(extension_command.accelerator()));\n focus_manager->RegisterAccelerator(\n *action_keybinding_,\n GetAcceleratorPriority(extension_command.accelerator(),\n controller_->extension()),\n this);\n }\n}\n\nvoid ExtensionActionPlatformDelegateViews::OnDelegateSet() {\n GetDelegateViews()->GetAsView()->set_context_menu_controller(this);\n}\n\nvoid ExtensionActionPlatformDelegateViews::CloseActivePopup() {\n if (controller_->extension_action()->action_type() ==\n ActionInfo::TYPE_BROWSER) {\n BrowserView::GetBrowserViewForBrowser(controller_->browser())->toolbar()->\n browser_actions()->HideActivePopup();\n } else {\n DCHECK_EQ(ActionInfo::TYPE_PAGE,\n controller_->extension_action()->action_type());\n \/\/ Page actions only know how to close their own popups.\n controller_->HidePopup();\n }\n}\n\nvoid ExtensionActionPlatformDelegateViews::CloseOwnPopup() {\n \/\/ It's possible that the popup is already in the process of destroying.\n if (popup_)\n CleanupPopup(true);\n}\n\nextensions::ExtensionViewHost*\nExtensionActionPlatformDelegateViews::ShowPopupWithUrl(\n ExtensionActionViewController::PopupShowAction show_action,\n const GURL& popup_url,\n bool grant_tab_permissions) {\n \/\/ TOP_RIGHT is correct for both RTL and LTR, because the views platform\n \/\/ performs the flipping in RTL cases.\n views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;\n\n views::View* reference_view = GetDelegateViews()->GetReferenceViewForPopup();\n\n ExtensionPopup::ShowAction popup_show_action =\n show_action == ExtensionActionViewController::SHOW_POPUP ?\n ExtensionPopup::SHOW : ExtensionPopup::SHOW_AND_INSPECT;\n popup_ = ExtensionPopup::ShowPopup(popup_url,\n controller_->browser(),\n reference_view,\n arrow,\n popup_show_action);\n popup_->GetWidget()->AddObserver(this);\n\n return popup_->host();\n}\n\nvoid ExtensionActionPlatformDelegateViews::Observe(\n int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n DCHECK(type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED ||\n type == extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED);\n extensions::ExtensionCommandRemovedDetails* payload =\n content::Details(details)\n .ptr();\n if (controller_->extension()->id() == payload->extension_id &&\n (payload->command_name ==\n extensions::manifest_values::kBrowserActionCommandEvent ||\n payload->command_name ==\n extensions::manifest_values::kPageActionCommandEvent)) {\n if (type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED)\n RegisterCommand();\n else\n UnregisterCommand(true);\n }\n}\n\nbool ExtensionActionPlatformDelegateViews::AcceleratorPressed(\n const ui::Accelerator& accelerator) {\n \/\/ We shouldn't be handling any accelerators if the view is hidden, unless\n \/\/ this is a browser action.\n DCHECK(controller_->extension_action()->action_type() ==\n ActionInfo::TYPE_BROWSER ||\n GetDelegateViews()->GetAsView()->visible());\n\n \/\/ Normal priority shortcuts must be handled via standard browser commands to\n \/\/ be processed at the proper time.\n if (GetAcceleratorPriority(accelerator, controller_->extension()) ==\n ui::AcceleratorManager::kNormalPriority)\n return false;\n\n controller_->ExecuteAction(true);\n return true;\n}\n\nbool ExtensionActionPlatformDelegateViews::CanHandleAccelerators() const {\n \/\/ Page actions can only handle accelerators when they are visible.\n \/\/ Browser actions can handle accelerators even when not visible, since they\n \/\/ might be hidden in an overflow menu.\n return controller_->extension_action()->action_type() ==\n ActionInfo::TYPE_PAGE ? GetDelegateViews()->GetAsView()->visible() :\n true;\n}\n\nvoid ExtensionActionPlatformDelegateViews::OnWidgetDestroying(\n views::Widget* widget) {\n DCHECK(popup_);\n DCHECK_EQ(popup_->GetWidget(), widget);\n CleanupPopup(false);\n}\n\nvoid ExtensionActionPlatformDelegateViews::ShowContextMenuForView(\n views::View* source,\n const gfx::Point& point,\n ui::MenuSourceType source_type) {\n \/\/ If there's another active menu that won't be dismissed by opening this one,\n \/\/ then we can't show this one right away, since we can only show one nested\n \/\/ menu at a time.\n \/\/ If the other menu is an extension action's context menu, then we'll run\n \/\/ this one after that one closes. If it's a different type of menu, then we\n \/\/ close it and give up, for want of a better solution. (Luckily, this is\n \/\/ rare).\n \/\/ TODO(devlin): Update this when views code no longer runs menus in a nested\n \/\/ loop.\n if (context_menu_owner) {\n context_menu_owner->followup_context_menu_task_ =\n base::Bind(&ExtensionActionPlatformDelegateViews::DoShowContextMenu,\n weak_factory_.GetWeakPtr(),\n source_type);\n }\n if (CloseActiveMenuIfNeeded())\n return;\n\n \/\/ Otherwise, no other menu is showing, and we can proceed normally.\n DoShowContextMenu(source_type);\n}\n\nvoid ExtensionActionPlatformDelegateViews::DoShowContextMenu(\n ui::MenuSourceType source_type) {\n ui::MenuModel* context_menu_model = controller_->GetContextMenu();\n \/\/ It's possible the extension doesn't have a context menu.\n if (!context_menu_model)\n return;\n\n DCHECK(!context_menu_owner);\n context_menu_owner = this;\n\n \/\/ We shouldn't have both a popup and a context menu showing.\n CloseActivePopup();\n\n gfx::Point screen_loc;\n views::View::ConvertPointToScreen(GetDelegateViews()->GetAsView(),\n &screen_loc);\n\n int run_types =\n views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU;\n if (GetDelegateViews()->IsShownInMenu())\n run_types |= views::MenuRunner::IS_NESTED;\n\n views::Widget* parent = GetDelegateViews()->GetParentForContextMenu();\n\n menu_runner_.reset(new views::MenuRunner(context_menu_model, run_types));\n\n if (menu_runner_->RunMenuAt(\n parent,\n GetDelegateViews()->GetContextMenuButton(),\n gfx::Rect(screen_loc, GetDelegateViews()->GetAsView()->size()),\n views::MENU_ANCHOR_TOPLEFT,\n source_type) == views::MenuRunner::MENU_DELETED) {\n return;\n }\n\n context_menu_owner = NULL;\n menu_runner_.reset();\n\n \/\/ If another extension action wants to show its context menu, allow it to.\n if (!followup_context_menu_task_.is_null()) {\n base::Closure task = followup_context_menu_task_;\n followup_context_menu_task_ = base::Closure();\n task.Run();\n }\n}\n\nvoid ExtensionActionPlatformDelegateViews::UnregisterCommand(\n bool only_if_removed) {\n views::FocusManager* focus_manager =\n GetDelegateViews()->GetFocusManagerForAccelerator();\n if (!focus_manager || !action_keybinding_.get())\n return;\n\n \/\/ If |only_if_removed| is true, it means that we only need to unregister\n \/\/ ourselves as an accelerator if the command was removed. Otherwise, we need\n \/\/ to unregister ourselves no matter what (likely because we are shutting\n \/\/ down).\n extensions::Command extension_command;\n if (!only_if_removed ||\n !controller_->GetExtensionCommand(&extension_command)) {\n focus_manager->UnregisterAccelerator(*action_keybinding_, this);\n action_keybinding_.reset();\n }\n}\n\nbool ExtensionActionPlatformDelegateViews::CloseActiveMenuIfNeeded() {\n \/\/ If this view is shown inside another menu, there's a possibility that there\n \/\/ is another context menu showing that we have to close before we can\n \/\/ activate a different menu.\n if (GetDelegateViews()->IsShownInMenu()) {\n views::MenuController* menu_controller =\n views::MenuController::GetActiveInstance();\n \/\/ If this is shown inside a menu, then there should always be an active\n \/\/ menu controller.\n DCHECK(menu_controller);\n if (menu_controller->in_nested_run()) {\n \/\/ There is another menu showing. Close the outermost menu (since we are\n \/\/ shown in the same menu, we don't want to close the whole thing).\n menu_controller->Cancel(views::MenuController::EXIT_OUTERMOST);\n return true;\n }\n }\n\n return false;\n}\n\nvoid ExtensionActionPlatformDelegateViews::CleanupPopup(bool close_widget) {\n DCHECK(popup_);\n popup_->GetWidget()->RemoveObserver(this);\n if (close_widget)\n popup_->GetWidget()->Close();\n popup_ = nullptr;\n}\n\nToolbarActionViewDelegateViews*\nExtensionActionPlatformDelegateViews::GetDelegateViews() const {\n return static_cast(\n controller_->view_delegate());\n}\n[Extensions Toolbar] Ensure popup is closed at shutdown\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_action_platform_delegate_views.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/api\/commands\/command_service.h\"\n#include \"chrome\/browser\/extensions\/api\/extension_action\/extension_action_api.h\"\n#include \"chrome\/browser\/extensions\/extension_action.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/session_tab_helper.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/extensions\/accelerator_priority.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/browser_actions_container.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/toolbar_action_view_delegate_views.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/toolbar_view.h\"\n#include \"chrome\/common\/extensions\/api\/extension_action\/action_info.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"extensions\/browser\/notification_types.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"ui\/gfx\/image\/image_skia_operations.h\"\n#include \"ui\/views\/controls\/menu\/menu_controller.h\"\n#include \"ui\/views\/controls\/menu\/menu_runner.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nusing extensions::ActionInfo;\nusing extensions::CommandService;\n\nnamespace {\n\n\/\/ The ExtensionActionPlatformDelegateViews which is currently showing its\n\/\/ context menu, if any.\n\/\/ Since only one context menu can be shown (even across browser windows), it's\n\/\/ safe to have this be a global singleton.\nExtensionActionPlatformDelegateViews* context_menu_owner = NULL;\n\n} \/\/ namespace\n\n\/\/ static\nscoped_ptr\nExtensionActionPlatformDelegate::Create(\n ExtensionActionViewController* controller) {\n return make_scoped_ptr(new ExtensionActionPlatformDelegateViews(controller));\n}\n\nExtensionActionPlatformDelegateViews::ExtensionActionPlatformDelegateViews(\n ExtensionActionViewController* controller)\n : controller_(controller),\n popup_(nullptr),\n weak_factory_(this) {\n content::NotificationSource notification_source = content::Source(\n controller_->browser()->profile()->GetOriginalProfile());\n registrar_.Add(this,\n extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED,\n notification_source);\n registrar_.Add(this,\n extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED,\n notification_source);\n}\n\nExtensionActionPlatformDelegateViews::~ExtensionActionPlatformDelegateViews() {\n DCHECK(!popup_); \/\/ We should never have a visible popup at shutdown.\n if (context_menu_owner == this)\n context_menu_owner = nullptr;\n \/\/ Since the popup close process is asynchronous, it might not be fully closed\n \/\/ at shutdown. We still need to cleanup, though.\n if (popup_)\n CleanupPopup(true);\n UnregisterCommand(false);\n}\n\ngfx::NativeView ExtensionActionPlatformDelegateViews::GetPopupNativeView() {\n return popup_ ? popup_->GetWidget()->GetNativeView() : nullptr;\n}\n\nbool ExtensionActionPlatformDelegateViews::IsMenuRunning() const {\n return menu_runner_.get() != NULL;\n}\n\nvoid ExtensionActionPlatformDelegateViews::RegisterCommand() {\n \/\/ If we've already registered, do nothing.\n if (action_keybinding_.get())\n return;\n\n extensions::Command extension_command;\n views::FocusManager* focus_manager =\n GetDelegateViews()->GetFocusManagerForAccelerator();\n if (focus_manager && controller_->GetExtensionCommand(&extension_command)) {\n action_keybinding_.reset(\n new ui::Accelerator(extension_command.accelerator()));\n focus_manager->RegisterAccelerator(\n *action_keybinding_,\n GetAcceleratorPriority(extension_command.accelerator(),\n controller_->extension()),\n this);\n }\n}\n\nvoid ExtensionActionPlatformDelegateViews::OnDelegateSet() {\n GetDelegateViews()->GetAsView()->set_context_menu_controller(this);\n}\n\nvoid ExtensionActionPlatformDelegateViews::CloseActivePopup() {\n if (controller_->extension_action()->action_type() ==\n ActionInfo::TYPE_BROWSER) {\n BrowserView::GetBrowserViewForBrowser(controller_->browser())->toolbar()->\n browser_actions()->HideActivePopup();\n } else {\n DCHECK_EQ(ActionInfo::TYPE_PAGE,\n controller_->extension_action()->action_type());\n \/\/ Page actions only know how to close their own popups.\n controller_->HidePopup();\n }\n}\n\nvoid ExtensionActionPlatformDelegateViews::CloseOwnPopup() {\n \/\/ It's possible that the popup is already in the process of destroying.\n if (popup_)\n CleanupPopup(true);\n}\n\nextensions::ExtensionViewHost*\nExtensionActionPlatformDelegateViews::ShowPopupWithUrl(\n ExtensionActionViewController::PopupShowAction show_action,\n const GURL& popup_url,\n bool grant_tab_permissions) {\n \/\/ TOP_RIGHT is correct for both RTL and LTR, because the views platform\n \/\/ performs the flipping in RTL cases.\n views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;\n\n views::View* reference_view = GetDelegateViews()->GetReferenceViewForPopup();\n\n ExtensionPopup::ShowAction popup_show_action =\n show_action == ExtensionActionViewController::SHOW_POPUP ?\n ExtensionPopup::SHOW : ExtensionPopup::SHOW_AND_INSPECT;\n popup_ = ExtensionPopup::ShowPopup(popup_url,\n controller_->browser(),\n reference_view,\n arrow,\n popup_show_action);\n popup_->GetWidget()->AddObserver(this);\n\n return popup_->host();\n}\n\nvoid ExtensionActionPlatformDelegateViews::Observe(\n int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n DCHECK(type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED ||\n type == extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED);\n extensions::ExtensionCommandRemovedDetails* payload =\n content::Details(details)\n .ptr();\n if (controller_->extension()->id() == payload->extension_id &&\n (payload->command_name ==\n extensions::manifest_values::kBrowserActionCommandEvent ||\n payload->command_name ==\n extensions::manifest_values::kPageActionCommandEvent)) {\n if (type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED)\n RegisterCommand();\n else\n UnregisterCommand(true);\n }\n}\n\nbool ExtensionActionPlatformDelegateViews::AcceleratorPressed(\n const ui::Accelerator& accelerator) {\n \/\/ We shouldn't be handling any accelerators if the view is hidden, unless\n \/\/ this is a browser action.\n DCHECK(controller_->extension_action()->action_type() ==\n ActionInfo::TYPE_BROWSER ||\n GetDelegateViews()->GetAsView()->visible());\n\n \/\/ Normal priority shortcuts must be handled via standard browser commands to\n \/\/ be processed at the proper time.\n if (GetAcceleratorPriority(accelerator, controller_->extension()) ==\n ui::AcceleratorManager::kNormalPriority)\n return false;\n\n controller_->ExecuteAction(true);\n return true;\n}\n\nbool ExtensionActionPlatformDelegateViews::CanHandleAccelerators() const {\n \/\/ Page actions can only handle accelerators when they are visible.\n \/\/ Browser actions can handle accelerators even when not visible, since they\n \/\/ might be hidden in an overflow menu.\n return controller_->extension_action()->action_type() ==\n ActionInfo::TYPE_PAGE ? GetDelegateViews()->GetAsView()->visible() :\n true;\n}\n\nvoid ExtensionActionPlatformDelegateViews::OnWidgetDestroying(\n views::Widget* widget) {\n DCHECK(popup_);\n DCHECK_EQ(popup_->GetWidget(), widget);\n CleanupPopup(false);\n}\n\nvoid ExtensionActionPlatformDelegateViews::ShowContextMenuForView(\n views::View* source,\n const gfx::Point& point,\n ui::MenuSourceType source_type) {\n \/\/ If there's another active menu that won't be dismissed by opening this one,\n \/\/ then we can't show this one right away, since we can only show one nested\n \/\/ menu at a time.\n \/\/ If the other menu is an extension action's context menu, then we'll run\n \/\/ this one after that one closes. If it's a different type of menu, then we\n \/\/ close it and give up, for want of a better solution. (Luckily, this is\n \/\/ rare).\n \/\/ TODO(devlin): Update this when views code no longer runs menus in a nested\n \/\/ loop.\n if (context_menu_owner) {\n context_menu_owner->followup_context_menu_task_ =\n base::Bind(&ExtensionActionPlatformDelegateViews::DoShowContextMenu,\n weak_factory_.GetWeakPtr(),\n source_type);\n }\n if (CloseActiveMenuIfNeeded())\n return;\n\n \/\/ Otherwise, no other menu is showing, and we can proceed normally.\n DoShowContextMenu(source_type);\n}\n\nvoid ExtensionActionPlatformDelegateViews::DoShowContextMenu(\n ui::MenuSourceType source_type) {\n ui::MenuModel* context_menu_model = controller_->GetContextMenu();\n \/\/ It's possible the extension doesn't have a context menu.\n if (!context_menu_model)\n return;\n\n DCHECK(!context_menu_owner);\n context_menu_owner = this;\n\n \/\/ We shouldn't have both a popup and a context menu showing.\n CloseActivePopup();\n\n gfx::Point screen_loc;\n views::View::ConvertPointToScreen(GetDelegateViews()->GetAsView(),\n &screen_loc);\n\n int run_types =\n views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU;\n if (GetDelegateViews()->IsShownInMenu())\n run_types |= views::MenuRunner::IS_NESTED;\n\n views::Widget* parent = GetDelegateViews()->GetParentForContextMenu();\n\n menu_runner_.reset(new views::MenuRunner(context_menu_model, run_types));\n\n if (menu_runner_->RunMenuAt(\n parent,\n GetDelegateViews()->GetContextMenuButton(),\n gfx::Rect(screen_loc, GetDelegateViews()->GetAsView()->size()),\n views::MENU_ANCHOR_TOPLEFT,\n source_type) == views::MenuRunner::MENU_DELETED) {\n return;\n }\n\n context_menu_owner = NULL;\n menu_runner_.reset();\n\n \/\/ If another extension action wants to show its context menu, allow it to.\n if (!followup_context_menu_task_.is_null()) {\n base::Closure task = followup_context_menu_task_;\n followup_context_menu_task_ = base::Closure();\n task.Run();\n }\n}\n\nvoid ExtensionActionPlatformDelegateViews::UnregisterCommand(\n bool only_if_removed) {\n views::FocusManager* focus_manager =\n GetDelegateViews()->GetFocusManagerForAccelerator();\n if (!focus_manager || !action_keybinding_.get())\n return;\n\n \/\/ If |only_if_removed| is true, it means that we only need to unregister\n \/\/ ourselves as an accelerator if the command was removed. Otherwise, we need\n \/\/ to unregister ourselves no matter what (likely because we are shutting\n \/\/ down).\n extensions::Command extension_command;\n if (!only_if_removed ||\n !controller_->GetExtensionCommand(&extension_command)) {\n focus_manager->UnregisterAccelerator(*action_keybinding_, this);\n action_keybinding_.reset();\n }\n}\n\nbool ExtensionActionPlatformDelegateViews::CloseActiveMenuIfNeeded() {\n \/\/ If this view is shown inside another menu, there's a possibility that there\n \/\/ is another context menu showing that we have to close before we can\n \/\/ activate a different menu.\n if (GetDelegateViews()->IsShownInMenu()) {\n views::MenuController* menu_controller =\n views::MenuController::GetActiveInstance();\n \/\/ If this is shown inside a menu, then there should always be an active\n \/\/ menu controller.\n DCHECK(menu_controller);\n if (menu_controller->in_nested_run()) {\n \/\/ There is another menu showing. Close the outermost menu (since we are\n \/\/ shown in the same menu, we don't want to close the whole thing).\n menu_controller->Cancel(views::MenuController::EXIT_OUTERMOST);\n return true;\n }\n }\n\n return false;\n}\n\nvoid ExtensionActionPlatformDelegateViews::CleanupPopup(bool close_widget) {\n DCHECK(popup_);\n popup_->GetWidget()->RemoveObserver(this);\n if (close_widget)\n popup_->GetWidget()->Close();\n popup_ = nullptr;\n}\n\nToolbarActionViewDelegateViews*\nExtensionActionPlatformDelegateViews::GetDelegateViews() const {\n return static_cast(\n controller_->view_delegate());\n}\n<|endoftext|>"} {"text":"\/*\n* this file is part of the oxygen gtk engine\n* Copyright (c) 2010 Hugo Pereira Da Costa \n* Copyright (c) 2010 Ruslan Kabatsayev \n*\n* inspired notably from kdelibs\/kdeui\/color\/kcolorutils.h\n* Copyright (C) 2007 Matthew Woehlke \n* Copyright (C) 2007 Thomas Zander \n* Copyright (C) 2007 Zack Rusin \n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2 of the License, or( at your option ) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n* MA 02110-1301, USA.\n*\/\n\n#include \"oxygenshadowconfiguration.h\"\n#include \"config.h\"\n\n#include \n\nnamespace Oxygen\n{\n\n \/\/_________________________________________________________\n ShadowConfiguration::ShadowConfiguration( Palette::Group group ):\n _colorGroup(group),\n _enabled(true)\n {\n assert(group==Palette::Active||group==Palette::Inactive);\n\n if( _colorGroup == Palette::Active )\n {\n\n _shadowSize = 40;\n _horizontalOffset = 0;\n _verticalOffset = 0.1;\n\n _innerColor = ColorUtils::Rgba( 0.44, 0.94, 1.0 );\n _outerColor = ColorUtils::Rgba( 0.33, 0.64, 0.94 );\n _useOuterColor = true;\n\n } else {\n\n _shadowSize = 40;\n _horizontalOffset = 0;\n _verticalOffset = 0.2;\n\n _innerColor = ColorUtils::Rgba::black();\n _outerColor = _innerColor;\n _useOuterColor = false;\n\n }\n\n }\n\n\n \/\/_________________________________________________________\n void ShadowConfiguration::initialize( const OptionMap& options )\n {\n\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::ShadowConfiguration::initialize - \" << (_colorGroup == Palette::Active ? \"Active\": \"Inactive\" ) << std::endl;\n #endif\n\n if( _colorGroup == Palette::Active)\n {\n\n _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[ActiveShadow]\", \"InnerColor\", \"112,241,255\" ) );\n _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[ActiveShadow]\", \"OuterColor\", \"84,167,240\" ) );\n\n _shadowSize = options.getOption( \"[ActiveShadow]\",\"Size\" ).toVariant(40);\n _verticalOffset = options.getOption( \"[ActiveShadow]\",\"VerticalOffset\" ).toVariant(0.1);\n _useOuterColor = options.getOption( \"[ActiveShadow]\",\"UseOuterColor\" ).toVariant(\"true\") == \"true\";\n\n } else {\n\n _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[InactiveShadow]\", \"InnerColor\", \"0,0,0\" ) );\n _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[InactiveShadow]\", \"OuterColor\", \"0,0,0\" ) );\n\n _shadowSize = options.getOption( \"[InactiveShadow]\",\"Size\" ).toVariant(40);\n _verticalOffset = options.getOption( \"[InactiveShadow]\",\"VerticalOffset\" ).toVariant(0.2);\n _useOuterColor = options.getOption( \"[InactiveShadow]\", \"UseOuterColor\" ).toVariant(\"false\") == \"true\";\n\n }\n\n }\n\n \/\/_________________________________________________________\n std::ostream& operator << (std::ostream& out, const ShadowConfiguration& configuration )\n {\n out << \"Oxygen::ShadowConfiguration - (\" << (configuration._colorGroup == Palette::Active ? \"Active\": \"Inactive\" ) << \")\" << std::endl;\n out << \" enabled: \" << (configuration._enabled ? \"true\":\"false\" ) << std::endl;\n out << \" size: \" << configuration._shadowSize << std::endl;\n out << \" offset: \" << configuration._verticalOffset << std::endl;\n out << \" innerColor: \" << configuration._innerColor << std::endl;\n out << \" outerColor: \";\n if( configuration._useOuterColor ) out << \"unused\";\n else out << configuration._outerColor;\n out << std::endl;\n return out;\n }\n}\nMake use of \"UseOuterColor\" oxygenrc option\/*\n* this file is part of the oxygen gtk engine\n* Copyright (c) 2010 Hugo Pereira Da Costa \n* Copyright (c) 2010 Ruslan Kabatsayev \n*\n* inspired notably from kdelibs\/kdeui\/color\/kcolorutils.h\n* Copyright (C) 2007 Matthew Woehlke \n* Copyright (C) 2007 Thomas Zander \n* Copyright (C) 2007 Zack Rusin \n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2 of the License, or( at your option ) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n* MA 02110-1301, USA.\n*\/\n\n#include \"oxygenshadowconfiguration.h\"\n#include \"config.h\"\n\n#include \n\nnamespace Oxygen\n{\n\n \/\/_________________________________________________________\n ShadowConfiguration::ShadowConfiguration( Palette::Group group ):\n _colorGroup(group),\n _enabled(true)\n {\n assert(group==Palette::Active||group==Palette::Inactive);\n\n if( _colorGroup == Palette::Active )\n {\n\n _shadowSize = 40;\n _horizontalOffset = 0;\n _verticalOffset = 0.1;\n\n _innerColor = ColorUtils::Rgba( 0.44, 0.94, 1.0 );\n _outerColor = ColorUtils::Rgba( 0.33, 0.64, 0.94 );\n _useOuterColor = true;\n\n } else {\n\n _shadowSize = 40;\n _horizontalOffset = 0;\n _verticalOffset = 0.2;\n\n _innerColor = ColorUtils::Rgba::black();\n _outerColor = _innerColor;\n _useOuterColor = false;\n\n }\n\n }\n\n\n \/\/_________________________________________________________\n void ShadowConfiguration::initialize( const OptionMap& options )\n {\n\n #if OXYGEN_DEBUG\n std::cerr << \"Oxygen::ShadowConfiguration::initialize - \" << (_colorGroup == Palette::Active ? \"Active\": \"Inactive\" ) << std::endl;\n #endif\n\n if( _colorGroup == Palette::Active)\n {\n\n _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[ActiveShadow]\", \"InnerColor\", \"112,241,255\" ) );\n _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[ActiveShadow]\", \"OuterColor\", \"84,167,240\" ) );\n\n _shadowSize = options.getOption( \"[ActiveShadow]\",\"Size\" ).toVariant(40);\n _verticalOffset = options.getOption( \"[ActiveShadow]\",\"VerticalOffset\" ).toVariant(0.1);\n _useOuterColor = options.getOption( \"[ActiveShadow]\",\"UseOuterColor\" ).toVariant(\"true\") == \"true\";\n\n } else {\n\n _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[InactiveShadow]\", \"InnerColor\", \"0,0,0\" ) );\n _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( \"[InactiveShadow]\", \"OuterColor\", \"0,0,0\" ) );\n\n _shadowSize = options.getOption( \"[InactiveShadow]\",\"Size\" ).toVariant(40);\n _verticalOffset = options.getOption( \"[InactiveShadow]\",\"VerticalOffset\" ).toVariant(0.2);\n _useOuterColor = options.getOption( \"[InactiveShadow]\", \"UseOuterColor\" ).toVariant(\"false\") == \"true\";\n\n }\n\n \/\/ NOTE: doing just like in oxygen-qt.\n \/\/ Might need to implement calcOuterColor() if its logic becomes more complicated in oxygen-qt.\n if(!_useOuterColor)\n _outerColor=_innerColor;\n\n }\n\n \/\/_________________________________________________________\n std::ostream& operator << (std::ostream& out, const ShadowConfiguration& configuration )\n {\n out << \"Oxygen::ShadowConfiguration - (\" << (configuration._colorGroup == Palette::Active ? \"Active\": \"Inactive\" ) << \")\" << std::endl;\n out << \" enabled: \" << (configuration._enabled ? \"true\":\"false\" ) << std::endl;\n out << \" size: \" << configuration._shadowSize << std::endl;\n out << \" offset: \" << configuration._verticalOffset << std::endl;\n out << \" innerColor: \" << configuration._innerColor << std::endl;\n out << \" outerColor: \";\n if( configuration._useOuterColor ) out << \"unused\";\n else out << configuration._outerColor;\n out << std::endl;\n return out;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Time Complexity: O(logn)\n\/\/ Space Complexity: O(1)\n\nclass Solution {\n public:\n int divide(int dividend, int divisor) {\n long long a = dividend >= 0 ? dividend : -(long long)dividend;\n long long b = divisor >= 0 ? divisor : -(long long)divisor;\n\n long long result = 0;\n while(a >= b) {\n long long c = b;\n int i = 0;\n for(; a >= c; c <<= 1, ++i);\n if(i > 0) {\n a -= c >> 1;\n result += 1 << (i - 1);\n }\n }\n\n return ((dividend ^ divisor) >> 31)? -result : result;\n }\n};\nUpdate divide.cpp\/\/ Time: O(logn) = O(1)\n\/\/ Space: O(1)\n\n\/\/ Only using integer type.\nclass Solution {\npublic:\n int divide(int dividend, int divisor) {\n \/\/ Handle corner case.\n if (dividend == numeric_limits::min() && divisor == -1) {\n return numeric_limits::max();\n }\n\n int a = dividend > 0 ? -dividend : dividend;\n int b = divisor > 0 ? -divisor : divisor;\n\n int shift = 0;\n while (b << shift < 0 && shift < 32) {\n ++shift;\n }\n shift -= 1;\n\n int result = 0;\n while (shift >= 0) {\n if (a <= b << shift) {\n a -= b << shift;\n result += 1 << shift;\n }\n --shift;\n }\n\n result = (dividend ^ divisor) >> 31 ? -result : result;\n return result;\n }\n};\n\n\/\/ Time: O(logn) = O(1)\n\/\/ Space: O(1)\n\/\/ Using long long type.\nclass Solution2 {\npublic:\n int divide(int dividend, int divisor) {\n long long result = 0;\n long long a = llabs(dividend);\n long long b = llabs(divisor);\n\n int shift = 31;\n while (shift >= 0) {\n if (a >= b << shift) {\n a -= b << shift;\n result += 1LL << shift;\n }\n --shift;\n }\n\n result = ((dividend ^ divisor) >> 31) ? -result : result;\n return min(result, static_cast(numeric_limits::max()));\n }\n};\n\n\/\/ Time: O(logn) = O(1)\n\/\/ Space: O(1)\n\/\/ a \/ b = exp^(ln(a) - ln(b))\nclass Solution3 {\npublic:\n int divide(int dividend, int divisor) {\n if (dividend == 0) { \n return 0;\n }\n if (divisor == 0) {\n return numeric_limits::max();\n }\n\n long long result = exp(log(fabs(dividend)) - log(fabs(divisor)));\n\n result = ((dividend ^ divisor) >> 31) ? -result : result;\n return min(result, static_cast(numeric_limits::max()));\n }\n};\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/profiling\/memory\/unwinding.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"perfetto\/base\/file_utils.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/scoped_file.h\"\n#include \"perfetto\/base\/string_utils.h\"\n#include \"src\/profiling\/memory\/wire_protocol.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nsize_t kMaxFrames = 1000;\n\n#pragma GCC diagnostic push\n\/\/ We do not care about deterministic destructor order.\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\n#pragma GCC diagnostic ignored \"-Wexit-time-destructors\"\nstatic std::vector kSkipMaps{\"heapprofd_client.so\"};\n#pragma GCC diagnostic pop\n\nstd::unique_ptr CreateFromRawData(unwindstack::ArchEnum arch,\n void* raw_data) {\n std::unique_ptr ret;\n \/\/ unwindstack::RegsX::Read returns a raw ptr which we are expected to free.\n switch (arch) {\n case unwindstack::ARCH_X86:\n ret.reset(unwindstack::RegsX86::Read(raw_data));\n break;\n case unwindstack::ARCH_X86_64:\n ret.reset(unwindstack::RegsX86_64::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM:\n ret.reset(unwindstack::RegsArm::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM64:\n ret.reset(unwindstack::RegsArm64::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS:\n ret.reset(unwindstack::RegsMips::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS64:\n ret.reset(unwindstack::RegsMips64::Read(raw_data));\n break;\n case unwindstack::ARCH_UNKNOWN:\n ret.reset(nullptr);\n break;\n }\n return ret;\n}\n\n\/\/ Behaves as a pread64, emulating it if not already exposed by the standard\n\/\/ library. Safe to use on 32bit platforms for addresses with the top bit set.\n\/\/ Clobbers the |fd| seek position if emulating.\nssize_t ReadAtOffsetClobberSeekPos(int fd,\n void* buf,\n size_t count,\n uint64_t addr) {\n#ifdef __BIONIC__\n return pread64(fd, buf, count, static_cast(addr));\n#else\n if (lseek64(fd, static_cast(addr), SEEK_SET) == -1)\n return -1;\n return read(fd, buf, count);\n#endif\n}\n\n} \/\/ namespace\n\nStackOverlayMemory::StackOverlayMemory(std::shared_ptr mem,\n uint64_t sp,\n uint8_t* stack,\n size_t size)\n : mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}\n\nsize_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {\n if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {\n size_t offset = static_cast(addr - sp_);\n memcpy(dst, stack_ + offset, size);\n return size;\n }\n\n return mem_->Read(addr, dst, size);\n}\n\nFDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}\n\nsize_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {\n ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);\n if (rd == -1) {\n PERFETTO_DPLOG(\"read at offset\");\n return 0;\n }\n return static_cast(rd);\n}\n\nFileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)\n : fd_(std::move(fd)) {}\n\nbool FileDescriptorMaps::Parse() {\n \/\/ If the process has already exited, lseek or ReadFileDescriptor will\n \/\/ return false.\n if (lseek(*fd_, 0, SEEK_SET) == -1)\n return false;\n\n std::string content;\n if (!base::ReadFileDescriptor(*fd_, &content))\n return false;\n return android::procinfo::ReadMapFileContent(\n &content[0], [&](uint64_t start, uint64_t end, uint16_t flags,\n uint64_t pgoff, ino_t, const char* name) {\n \/\/ Mark a device map in \/dev\/ and not in \/dev\/ashmem\/ specially.\n if (strncmp(name, \"\/dev\/\", 5) == 0 &&\n strncmp(name + 5, \"ashmem\/\", 7) != 0) {\n flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;\n }\n maps_.push_back(\n new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));\n });\n}\n\nvoid FileDescriptorMaps::Reset() {\n for (unwindstack::MapInfo* info : maps_)\n delete info;\n maps_.clear();\n}\n\nbool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {\n AllocMetadata* alloc_metadata = msg->alloc_header;\n std::unique_ptr regs(\n CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));\n if (regs == nullptr) {\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR READING REGISTERS\";\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n PERFETTO_DLOG(\"regs\");\n return false;\n }\n uint8_t* stack = reinterpret_cast(msg->payload);\n std::shared_ptr mems =\n std::make_shared(metadata->fd_mem,\n alloc_metadata->stack_pointer, stack,\n msg->payload_size);\n\n unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n \/\/ Surpress incorrect \"variable may be uninitialized\" error for if condition\n \/\/ after this loop. error_code = LastErrorCode gets run at least once.\n uint8_t error_code = 0;\n for (int attempt = 0; attempt < 2; ++attempt) {\n if (attempt > 0) {\n metadata->ReparseMaps();\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n }\n unwinder.Unwind(&kSkipMaps, nullptr);\n error_code = unwinder.LastErrorCode();\n if (error_code != unwindstack::ERROR_INVALID_MAP)\n break;\n }\n std::vector frames = unwinder.ConsumeFrames();\n for (unwindstack::FrameData& fd : frames) {\n std::string build_id;\n if (fd.map_name != \"\") {\n unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);\n if (map_info)\n build_id = map_info->GetBuildID();\n }\n\n out->frames.emplace_back(std::move(fd), std::move(build_id));\n }\n\n if (error_code != 0) {\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR \" + std::to_string(error_code);\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n PERFETTO_DLOG(\"unwinding failed %\" PRIu8, error_code);\n }\n\n return true;\n}\n\nbool HandleUnwindingRecord(UnwindingRecord* rec, BookkeepingRecord* out) {\n WireMessage msg;\n if (!ReceiveWireMessage(reinterpret_cast(rec->data.get()), rec->size,\n &msg))\n return false;\n if (msg.record_type == RecordType::Malloc) {\n std::shared_ptr metadata = rec->metadata.lock();\n if (!metadata) {\n \/\/ Process has already gone away.\n return false;\n }\n\n out->alloc_record.alloc_metadata = *msg.alloc_header;\n out->pid = rec->pid;\n out->client_generation = msg.alloc_header->client_generation;\n out->record_type = BookkeepingRecord::Type::Malloc;\n DoUnwind(&msg, metadata.get(), &out->alloc_record);\n return true;\n } else if (msg.record_type == RecordType::Free) {\n out->record_type = BookkeepingRecord::Type::Free;\n out->pid = rec->pid;\n out->client_generation = msg.free_header->client_generation;\n \/\/ We need to keep this alive, because msg.free_header is a pointer into\n \/\/ this.\n out->free_record.free_data = std::move(rec->data);\n out->free_record.metadata = msg.free_header;\n return true;\n } else {\n PERFETTO_DFATAL(\"Invalid record type.\");\n return false;\n }\n}\n\nvoid UnwindingMainLoop(BoundedQueue* input_queue,\n BoundedQueue* output_queue) {\n for (;;) {\n UnwindingRecord rec;\n if (!input_queue->Get(&rec))\n return;\n BookkeepingRecord out;\n if (HandleUnwindingRecord(&rec, &out))\n output_queue->Add(std::move(out));\n }\n}\n\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\nUse emplace_back over push_back to support unique_ptr. am: 5abc126b07\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/profiling\/memory\/unwinding.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"perfetto\/base\/file_utils.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/scoped_file.h\"\n#include \"perfetto\/base\/string_utils.h\"\n#include \"src\/profiling\/memory\/wire_protocol.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nsize_t kMaxFrames = 1000;\n\n#pragma GCC diagnostic push\n\/\/ We do not care about deterministic destructor order.\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\n#pragma GCC diagnostic ignored \"-Wexit-time-destructors\"\nstatic std::vector kSkipMaps{\"heapprofd_client.so\"};\n#pragma GCC diagnostic pop\n\nstd::unique_ptr CreateFromRawData(unwindstack::ArchEnum arch,\n void* raw_data) {\n std::unique_ptr ret;\n \/\/ unwindstack::RegsX::Read returns a raw ptr which we are expected to free.\n switch (arch) {\n case unwindstack::ARCH_X86:\n ret.reset(unwindstack::RegsX86::Read(raw_data));\n break;\n case unwindstack::ARCH_X86_64:\n ret.reset(unwindstack::RegsX86_64::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM:\n ret.reset(unwindstack::RegsArm::Read(raw_data));\n break;\n case unwindstack::ARCH_ARM64:\n ret.reset(unwindstack::RegsArm64::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS:\n ret.reset(unwindstack::RegsMips::Read(raw_data));\n break;\n case unwindstack::ARCH_MIPS64:\n ret.reset(unwindstack::RegsMips64::Read(raw_data));\n break;\n case unwindstack::ARCH_UNKNOWN:\n ret.reset(nullptr);\n break;\n }\n return ret;\n}\n\n\/\/ Behaves as a pread64, emulating it if not already exposed by the standard\n\/\/ library. Safe to use on 32bit platforms for addresses with the top bit set.\n\/\/ Clobbers the |fd| seek position if emulating.\nssize_t ReadAtOffsetClobberSeekPos(int fd,\n void* buf,\n size_t count,\n uint64_t addr) {\n#ifdef __BIONIC__\n return pread64(fd, buf, count, static_cast(addr));\n#else\n if (lseek64(fd, static_cast(addr), SEEK_SET) == -1)\n return -1;\n return read(fd, buf, count);\n#endif\n}\n\n} \/\/ namespace\n\nStackOverlayMemory::StackOverlayMemory(std::shared_ptr mem,\n uint64_t sp,\n uint8_t* stack,\n size_t size)\n : mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}\n\nsize_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {\n if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {\n size_t offset = static_cast(addr - sp_);\n memcpy(dst, stack_ + offset, size);\n return size;\n }\n\n return mem_->Read(addr, dst, size);\n}\n\nFDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}\n\nsize_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {\n ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);\n if (rd == -1) {\n PERFETTO_DPLOG(\"read at offset\");\n return 0;\n }\n return static_cast(rd);\n}\n\nFileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)\n : fd_(std::move(fd)) {}\n\nbool FileDescriptorMaps::Parse() {\n \/\/ If the process has already exited, lseek or ReadFileDescriptor will\n \/\/ return false.\n if (lseek(*fd_, 0, SEEK_SET) == -1)\n return false;\n\n std::string content;\n if (!base::ReadFileDescriptor(*fd_, &content))\n return false;\n return android::procinfo::ReadMapFileContent(\n &content[0], [&](uint64_t start, uint64_t end, uint16_t flags,\n uint64_t pgoff, ino_t, const char* name) {\n \/\/ Mark a device map in \/dev\/ and not in \/dev\/ashmem\/ specially.\n if (strncmp(name, \"\/dev\/\", 5) == 0 &&\n strncmp(name + 5, \"ashmem\/\", 7) != 0) {\n flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;\n }\n maps_.emplace_back(\n new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));\n });\n}\n\nvoid FileDescriptorMaps::Reset() {\n maps_.clear();\n}\n\nbool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {\n AllocMetadata* alloc_metadata = msg->alloc_header;\n std::unique_ptr regs(\n CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));\n if (regs == nullptr) {\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR READING REGISTERS\";\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n PERFETTO_DLOG(\"regs\");\n return false;\n }\n uint8_t* stack = reinterpret_cast(msg->payload);\n std::shared_ptr mems =\n std::make_shared(metadata->fd_mem,\n alloc_metadata->stack_pointer, stack,\n msg->payload_size);\n\n unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n \/\/ Surpress incorrect \"variable may be uninitialized\" error for if condition\n \/\/ after this loop. error_code = LastErrorCode gets run at least once.\n uint8_t error_code = 0;\n for (int attempt = 0; attempt < 2; ++attempt) {\n if (attempt > 0) {\n metadata->ReparseMaps();\n#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)\n unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());\n unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());\n#endif\n }\n unwinder.Unwind(&kSkipMaps, nullptr);\n error_code = unwinder.LastErrorCode();\n if (error_code != unwindstack::ERROR_INVALID_MAP)\n break;\n }\n std::vector frames = unwinder.ConsumeFrames();\n for (unwindstack::FrameData& fd : frames) {\n std::string build_id;\n if (fd.map_name != \"\") {\n unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);\n if (map_info)\n build_id = map_info->GetBuildID();\n }\n\n out->frames.emplace_back(std::move(fd), std::move(build_id));\n }\n\n if (error_code != 0) {\n unwindstack::FrameData frame_data{};\n frame_data.function_name = \"ERROR \" + std::to_string(error_code);\n frame_data.map_name = \"ERROR\";\n\n out->frames.emplace_back(frame_data, \"\");\n PERFETTO_DLOG(\"unwinding failed %\" PRIu8, error_code);\n }\n\n return true;\n}\n\nbool HandleUnwindingRecord(UnwindingRecord* rec, BookkeepingRecord* out) {\n WireMessage msg;\n if (!ReceiveWireMessage(reinterpret_cast(rec->data.get()), rec->size,\n &msg))\n return false;\n if (msg.record_type == RecordType::Malloc) {\n std::shared_ptr metadata = rec->metadata.lock();\n if (!metadata) {\n \/\/ Process has already gone away.\n return false;\n }\n\n out->alloc_record.alloc_metadata = *msg.alloc_header;\n out->pid = rec->pid;\n out->client_generation = msg.alloc_header->client_generation;\n out->record_type = BookkeepingRecord::Type::Malloc;\n DoUnwind(&msg, metadata.get(), &out->alloc_record);\n return true;\n } else if (msg.record_type == RecordType::Free) {\n out->record_type = BookkeepingRecord::Type::Free;\n out->pid = rec->pid;\n out->client_generation = msg.free_header->client_generation;\n \/\/ We need to keep this alive, because msg.free_header is a pointer into\n \/\/ this.\n out->free_record.free_data = std::move(rec->data);\n out->free_record.metadata = msg.free_header;\n return true;\n } else {\n PERFETTO_DFATAL(\"Invalid record type.\");\n return false;\n }\n}\n\nvoid UnwindingMainLoop(BoundedQueue* input_queue,\n BoundedQueue* output_queue) {\n for (;;) {\n UnwindingRecord rec;\n if (!input_queue->Get(&rec))\n return;\n BookkeepingRecord out;\n if (HandleUnwindingRecord(&rec, &out))\n output_queue->Add(std::move(out));\n }\n}\n\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: app.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mba $ $Date: 2000-11-30 08:47:40 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"wrapper.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n\n#include \n#include \n#ifndef _UTL_CONFIGMGR_HXX_\n#include \n#endif\n\n#include \n#include \n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nDesktop aDesktop;\n\nDesktop::Desktop()\n{\n}\n\nvoid Desktop::Main()\n{\n SetAppName( DEFINE_CONST_UNICODE(\"soffice\") );\n\n Installer* pInstaller = new Installer;\n pInstaller->InitializeInstallation( Application::GetAppFileName() );\n delete pInstaller;\n\n SvtPathOptions* pPathOptions = new SvtPathOptions;\n RegisterServices();\n OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );\n\/\/ Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE(\"com.sun.star.office.OfficeWrapper\" ) ), UNO_QUERY );\n SfxApplicationClass::Main();\n\/\/ xWrapper->dispose();\n\n if( pWrapper!=NULL)\n {\n delete pWrapper;\n pWrapper=NULL;\n }\n\n delete pPathOptions;\n utl::ConfigManager::RemoveConfigManager();\n}\n\nvoid Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )\n{\n OFF_APP()->SystemSettingsChanging( rSettings, pFrame );\n}\n\n\n\n\n#79541#: ResourceHook for Strings\/*************************************************************************\n *\n * $RCSfile: app.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: mba $ $Date: 2000-12-08 08:45:22 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"wrapper.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n\n#include \n#include \n#ifndef _UTL_CONFIGMGR_HXX_\n#include \n#endif\n\n#include \n#include \n#include \n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\nvoid ReplaceStringHookProc( UniString& rStr )\n{\n static String aBrandName;\n if ( !aBrandName.Len() )\n {\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n rtl::OUString aTmp;\n aRet >>= aTmp;\n aBrandName = aTmp;\n }\n\n rStr.SearchAndReplaceAscii( \"%PRODUCTNAME\", aBrandName );\n}\n\nDesktop aDesktop;\n\nDesktop::Desktop()\n{\n}\n\nvoid Desktop::Main()\n{\n ResMgr::SetReadStringHook( ReplaceStringHookProc );\n SetAppName( DEFINE_CONST_UNICODE(\"soffice\") );\n\n Installer* pInstaller = new Installer;\n pInstaller->InitializeInstallation( Application::GetAppFileName() );\n delete pInstaller;\n\n SvtPathOptions* pPathOptions = new SvtPathOptions;\n RegisterServices();\n OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );\n\/\/ Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE(\"com.sun.star.office.OfficeWrapper\" ) ), UNO_QUERY );\n SfxApplicationClass::Main();\n\/\/ xWrapper->dispose();\n\n if( pWrapper!=NULL)\n {\n delete pWrapper;\n pWrapper=NULL;\n }\n\n delete pPathOptions;\n utl::ConfigManager::RemoveConfigManager();\n}\n\nvoid Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )\n{\n OFF_APP()->SystemSettingsChanging( rSettings, pFrame );\n}\n\n\n\n\n<|endoftext|>"} {"text":"#include\n#include\n#include\nusing namespace std;\nint main()\n{\n double x[] = {10.2,11.4,11.5,12.5,13.1,13.4,13.6,15,15.2,15.3,15.6,16.4,16.5,17,17.1};\n double y[] = {69.81,82.75,81.75,80.38,85.89,75.32,69.81,78.54,81.29,99.2,86.35,110.23,106.55,85.50,90.02};\n int i,j,k,n;\n cout<<\"\\n Cuantos partes de datos ingresaran?\\n\";\n cin>>n;\n double a0,a1,error,EE;\n \/\/cout<<\"\\n Pon los valores X\\n\";\n \/\/for (i=0;i>x[i];\n \/\/cout<<\"\\n Pon los valores Y\\n\";\n \/\/for (i=0;i>y[i];\n double xsum=0,x2sum=0,ysum=0,xysum=0,mediaX,mediaY;\n for (i=0;iUpdate linearRegresion.cpp#include\n#include\n#include\nusing namespace std;\nint main()\n{\n double x[] = {10.2,11.4,11.5,12.5,13.1,13.4,13.6,15,15.2,15.3,15.6,16.4,16.5,17,17.1};\n double y[] = {69.81,82.75,81.75,80.38,85.89,75.32,69.81,78.54,81.29,99.2,86.35,110.23,106.55,85.50,90.02};\n int i,j,k,n;\n cout<<\"\\n Cuantos pares de datos ingresaran?\\n\";\n cin>>n;\n double a0=0,a1=0,error=0,EE=0,xsum=0,x2sum=0,ysum=0,xysum=0,mediaX=0,mediaY=0;\n\n for (i=0;i"} {"text":"\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/kernels\/cwise_ops_common.h\"\n\nnamespace tensorflow {\n\nREGISTER5(BinaryOp, CPU, \"Mul\", functor::mul, float, Eigen::half, double,\n uint8, int32);\n\n#if TENSORFLOW_USE_SYCL\n#define REGISTER_SYCL_KERNEL(TYPE) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"Mul\") \\\n .Device(DEVICE_SYCL) \\\n .TypeConstraint(\"T\"), \\\n BinaryOp>);\nREGISTER_SYCL_KERNEL(float)\nREGISTER_SYCL_KERNEL(double)\n#undef REGISTER_SYCL_KERNEL\nREGISTER_KERNEL_BUILDER(Name(\"Mul\")\n .Device(DEVICE_SYCL)\n .HostMemory(\"x\")\n .HostMemory(\"y\")\n .HostMemory(\"z\")\n .TypeConstraint(\"T\"),\n BinaryOp>);\n#endif \/\/ TENSORFLOW_USE_SYCL\n#if GOOGLE_CUDA\nREGISTER4(BinaryOp, GPU, \"Mul\", functor::mul, float, Eigen::half, double,\n uint8);\n\/\/ A special GPU kernel for int32.\n\/\/ TODO(b\/25387198): Also enable int32 in device memory. This kernel\n\/\/ registration requires all int32 inputs and outputs to be in host memory.\nREGISTER_KERNEL_BUILDER(Name(\"Mul\")\n .Device(DEVICE_GPU)\n .HostMemory(\"x\")\n .HostMemory(\"y\")\n .HostMemory(\"z\")\n .TypeConstraint(\"T\"),\n BinaryOp>);\n#endif\n\n} \/\/ namespace tensorflow\nAdd int32 version of Mul kernel to the slim kernels. Change: 151267767\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/kernels\/cwise_ops_common.h\"\n\nnamespace tensorflow {\n\nREGISTER5(BinaryOp, CPU, \"Mul\", functor::mul, float, Eigen::half, double,\n uint8, int32);\n#if defined(__ANDROID_TYPES_SLIM__)\n\/\/ We only register the first type when we have multi-argument calls in the\n\/\/ case where we're trying to reduce executable size, but it turns out that the\n\/\/ int32 version of this op is needed, so explicitly include it.\nREGISTER(BinaryOp, CPU, \"Mul\", functor::mul, int32);\n#endif \/\/ __ANDROID_TYPES_SLIM__\n\n#if TENSORFLOW_USE_SYCL\n#define REGISTER_SYCL_KERNEL(TYPE) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"Mul\") \\\n .Device(DEVICE_SYCL) \\\n .TypeConstraint(\"T\"), \\\n BinaryOp>);\nREGISTER_SYCL_KERNEL(float)\nREGISTER_SYCL_KERNEL(double)\n#undef REGISTER_SYCL_KERNEL\nREGISTER_KERNEL_BUILDER(Name(\"Mul\")\n .Device(DEVICE_SYCL)\n .HostMemory(\"x\")\n .HostMemory(\"y\")\n .HostMemory(\"z\")\n .TypeConstraint(\"T\"),\n BinaryOp>);\n#endif \/\/ TENSORFLOW_USE_SYCL\n#if GOOGLE_CUDA\nREGISTER4(BinaryOp, GPU, \"Mul\", functor::mul, float, Eigen::half, double,\n uint8);\n\/\/ A special GPU kernel for int32.\n\/\/ TODO(b\/25387198): Also enable int32 in device memory. This kernel\n\/\/ registration requires all int32 inputs and outputs to be in host memory.\nREGISTER_KERNEL_BUILDER(Name(\"Mul\")\n .Device(DEVICE_GPU)\n .HostMemory(\"x\")\n .HostMemory(\"y\")\n .HostMemory(\"z\")\n .TypeConstraint(\"T\"),\n BinaryOp>);\n#endif\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ consists of redundancy, remove later\n\/\/ copied from rvizView to work with PointCloud2 object\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef pcl::PointCloud PointCloud;\n\n\n\/\/ represnts a point with x,y,z coordinates\nstruct Point {\n\n float x;\n float y;\n float z;\n};\n\n\nclass PMDCloudPublisher\n{\n \/\/ protected:\n \/\/ std::string tf_frame;\n \/\/ ros::NodeHandle nh;\n \/\/ ros::NodeHandle private_nh;\n\n \/\/ public:\n \/\/ pcl::PointCloud::Ptr cloud;\n \/\/ std::string file_name, cloud_topic;\n \/\/ pcl_ros::Publisher pub;\n\n \/\/ PMDCloudPublisher()\n \/\/ : tf_frame(\"\/map\"),\n \/\/ private_nh(\"~\")\n \/\/ {\n \/\/ cloud_topic = \"cloud\";\n \/\/ pub.advertise(nh, cloud_topic.c_str(), 1); \/\/ published here\n \/\/ private_nh.param(\"frame_id\", tf_frame, std::string(\"\/map\"));\n \/\/ ROS_INFO_STREAM(\"Publishing data on topic \\\"\" << nh.resolveName(cloud_topic) << \"\\\" with frame_id \\\"\" << tf_frame << \"\\\"\");\n \/\/ }\n\n \/\/ bool spin ()\n \/\/ {\n \/\/ int nr_points = cloud->width * cloud->height;\n \/\/ std::string fields_list = pcl::getFieldsList(cloud);\n \/\/ ros::Rate r(40);\n\n \/\/ while(nh.ok ())\n \/\/ {\n \/\/ ROS_DEBUG_STREAM_ONCE(\"Publishing data with \" << nr_points\n \/\/ << \" points \" << fields_list\n \/\/ << \" on topic \\\"\" << nh.resolveName(cloud_topic)\n \/\/ << \"\\\" in frame \\\"\" << cloud.header.frame_id << \"\\\"\");\n \/\/ \/\/ cloud.header.stamp = ros::Time::now();\n \/\/ pub.publish(cloud);\n\n \/\/ r.sleep();\n \/\/ }\n \/\/ return (true);\n \/\/ }\n};\n\n\nvoid publishData(pcl::PointCloud::Ptr filteredCloud, std::map viewablePoints){\n\n \/\/ \/\/ros::init (1, temp, \"cloud_publisher\");\n \/\/ ros::NodeHandle nh;\n\n \n \/\/ PMDCloudPublisher c;\n \/\/ c.file_name = \"spray_bottle.pcd\";\n \/\/ c.cloud = filteredCloud;\n \/\/ nh.getParam(filteredCloud, c.cloud);\n\n \/\/ if (c.start () == -1)\n \/\/ {\n \/\/ ROS_ERROR_STREAM(\"Could not load file \\\"\" << c.file_name <<\"\\\". Exiting...\");\n \/\/ }\n \/\/ ROS_INFO_STREAM(\"Loaded a point cloud with \" << c.cloud.width * c.cloud.height\n \/\/ << \" points (total size is \" << c.cloud.data.size() << \") and the following channels: \" << pcl::getFieldsList (c.cloud));\n \/\/ c.spin();\n}\n\n\n\/\/ calculating slope of line formed by two points in 3d space\nfloat calculate_slope(float pt_x, float pt_y, float pt_z, float pt2_x, float pt2_y, float pt2_z)\n{\n float rise = pt2_z - pt_z;\n\n float square = pow((pt2_x - pt_x), 2) + pow((pt2_y - pt_y), 2);\n float run = sqrt(square);\n return rise\/run;\n} \n\n\/\/ bool onLine(float view_x, float view_y, float view_z, float pt_x, float pt_y, float pt_z, float check_pt_x, float check_pt_y, float check_pt_z)\n\/\/ {\n\/\/ \/\/ Calculate the slope from the view to the check_pt\n\/\/ float slope_pt_to_view = calculate_slope(view_x, view_y, view_z, check_pt_x, check_pt_y, check_pt_z);\n\n\/\/ \/\/ printf(\"Slope from view to check_pt: %f\\n\", slope_pt_to_view);\n\n\/\/ \/\/ Calculate slope from the check_pt to the pt\n\/\/ float slope_check_pt_to_pt = calculate_slope(view_x, view_y, view_z, pt_x, pt_y, pt_z);\n\n\/\/ \/\/ printf(\"Slope from view to pt: %f\\n\", slope_check_pt_to_pt);\n\/\/ \/\/ printf(\"Are they equivalent?: %d\\n\", temp);\n\n\/\/ float delta = 0.0000000045f;\n\n\/\/ float diff = fabs(slope_pt_to_view - slope_check_pt_to_pt);\n\n\/\/ bool temp = (diff < delta);\n\/\/ \/\/ printf(\"Difference: %f\\n\", diff);\n\/\/ \/\/ printf(\"Boolean: %d\\n\", temp);\n\n\/\/ \/\/printf(\"Difference: %f\\n\", diff);\n\/\/ \/\/ If they are equal return true\n\/\/ return temp;\n\/\/ }\n\n\/\/ calculating distance between two points in 3d space\nfloat distance(float x1, float y1, float z1, float x2, float y2, float z2){\n\n return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2) + pow(z1 - z2, 2));\n}\n\n\n\/\/ method to find viewable points from a given view. \n\/\/ arg1: Passed in a pose that represents a point in space\n\/\/ arg2: the point cloud object of the pcd file\n\n\/\/ PENDING: consider orientation (various angles for a given point) when viewing the object\nfloat findPoints(const geometry_msgs::Pose createdPoint, const PointCloud::ConstPtr& msg)\n{\n\n\n \/\/ printing the current view point\n printf(\"Coordinates: %f, %f, %f\\n\", createdPoint.position.x, createdPoint.position.y, createdPoint.position.z);\n\n \/\/ x,y,z represents the cooridnates of the view \n float x = createdPoint.position.x;\n float y = createdPoint.position.y;\n float z = createdPoint.position.z;\n\n \/\/ total number of points in the point cloud\n int size = 0;\n\n \/\/ idea is that for a given line from the view point, slope is the same\n \/\/ we want to count for a single point and exclude all the other points on that line\n \/\/ by that way we count for a single point and not count points behind the counted \n \/\/ point\n \/\/ if slope is already contained, then check which point is closer\n \/\/ to the view point\n \/\/ map for: slope -> point\n std::map viewablePoints;\n std::map::iterator it;\n BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {\n float slope_pt_to_view = (int) floorf(calculate_slope(x, y, z, pt.x, pt.y, pt.z) * 100000000.0 + 0.5)\/100000000.0;\n it = viewablePoints.find(slope_pt_to_view);\n\n \/\/ if slope is already present\n if(it != viewablePoints.end()){\n \/\/ if the slop is already taken into account\n \/\/ then we must see the point it corresponds to is the closest to the view point\n \/\/ if this new point is closer then must updates the map accordingly\n geometry_msgs::Pose existingPoint = it->second; \/\/ get the point\n float oldDistance = distance(x, y, z, existingPoint.position.x, existingPoint.position.y, existingPoint.position.z);\n float newDistance = distance(x, y, z, pt.x, pt.y, pt.z);\n if(newDistance < oldDistance) {\n \tgeometry_msgs::Pose newPose;\n \t\t\tnewPose.position.x = pt.x;\n \t\t\tnewPose.position.y = pt.y;\n \t\t\tnewPose.position.z = pt.z;\n viewablePoints.insert(std::pair (slope_pt_to_view, newPose));\n \/\/printf(\"Old point: %f, %f, %f with distance of %f\\n\", existingPoint.x, existingPoint.y, existingPoint.z, oldDistance);\n \/\/printf(\"New point: %f, %f, %f with distance of %f\\n\", newPoint.x, newPoint.y, newPoint.z, newDistance);\n }\n\n } else {\n \/\/ first time looking at this point\n \/\/ just add it\n geometry_msgs::Pose newPose;\n newPose.position.x = pt.x;\n newPose.position.y = pt.y;\n newPose.position.z = pt.z;\n viewablePoints.insert(std::pair (slope_pt_to_view, newPose));\n }\n size++; \/\/ totalNum points\n\n }\n\n\n\n \/\/ displaying contents of the map\n \/\/ multipying by 10000 because %f truncates values, so it appears as if duplictes exist\n \/\/ for(it = viewablePoints.begin(); it != viewablePoints.end(); it++){\n \/\/ printf(\"key: %f, Value: %f, %f, %f\\n\", it->first * 10000, it->second.x, it->second.y, it->second.z);\n \/\/ }\n\n\n \/\/ at this point we have filtered points based on slope,distance and angle\n \/\/ these points need to be used to create a pointcloud2 object\n \/\/ once this is created, we will publish this to rviz and view it accoringly\n \/\/ references to publishing to rviz check rvizView and generateViews.cpp\n\n \/\/ in progress\n \/\/ refer: http:\/\/wiki.ros.org\/pcl_ros\n \/\/ refer: http:\/\/pointclouds.org\/documentation\/tutorials\/passthrough.php\n\n pcl::PointCloud::Ptr filteredCloud (new pcl::PointCloud);\n\n filteredCloud->width = viewablePoints.size(); \/\/ need to verify\n filteredCloud->height = 1;\n filteredCloud->points.resize(filteredCloud->width * filteredCloud->height);\n\n int filterIndex = 0;\n\n \/\/ loading a new pointcloud object from the points that we collected\n for(it = viewablePoints.begin(); it != viewablePoints.end(); it++, filterIndex++){\n\n \t\/\/ ideally no segfaults because filterdCloud size \n \t\/\/ is viewable points * 1 == viewablePoints.size();\n \tfilteredCloud->points[filterIndex].x = it->second.position.x;\n \tfilteredCloud->points[filterIndex].y = it->second.position.y;\n \tfilteredCloud->points[filterIndex].z = it->second.position.z;\n }\n\n publishData(filteredCloud, viewablePoints);\n\n float viewableAmount = 100 * viewablePoints.size() \/ (float) (size);\n return viewableAmount; \/\/ percentag of points viewed\n\n\n\n\n \/\/ old implementation!\n\n \/\/ traverse through points of the point cloud\n \/\/ for a given point we scan all the same points\n \/\/ for each pair of points, we check if they have the same slope or comparable slopes\n \/\/ if they are similar we discount this because we have seen this point before\n \/\/ by this way we count all the points, without duplicates\n \/\/ by doing numberInLine <=1 we make sure we count only unique points and not duplicates\n \/\/ BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {\n \/\/ int numberInLine = 0;\n \/\/ BOOST_FOREACH (const pcl::PointXYZ& pt2, msg->points) {\n \/\/ bool onTheLine = onLine(x, y, z, pt.x, pt.y, pt.z, pt2.x, pt2.y, pt2.z);\n \/\/ if (onTheLine) {\n \/\/ numberInLine++;\n \/\/ }\n \/\/ }\n \/\/ \/\/ printf(\"inView: %d\\n\", inView);\n \/\/ if (numberInLine <= 1) {\n \/\/ count++;\n \/\/ }\n \/\/ size++;\n \/\/ }\n\n \/\/ \/\/ printf(\"Count: %d\\n\", count);\n \/\/ \/\/ printf(\"Size: %d\\n\", size);\n\n \/\/ \/\/printf(\"Percent of points viewed from pose: %f\\n\", 100 * count\/(float)size);\n\n \/\/ \/\/ finally return a ratio of the points seen to the total number of points \n \/\/ \/\/ in the pcl \n \/\/ return (100 * count \/ (float) (size));\n}\n\n\/\/ void callback(const PointCloud::ConstPtr& msg)\n\/\/ {\n\/\/ \/\/ printf(\"Percent of points viewed: %f\\n\", findPoints(msg));\n\/\/ }\n\n\/\/ int main(int argc, char** argv)\n\/\/ {\n\/\/ ros::init(argc, argv, \"generate_views\");\n\/\/ ros::NodeHandle nh;\n\/\/ ros::Subscriber sub = nh.subscribe(\"cloud\", 1, callback);\n\/\/ ros::spin();\n\/\/ }findpoints: visualizing filtered cloud impl#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/ consists of redundancy, remove later\n\/\/ copied from rvizView to work with PointCloud2 object\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef pcl::PointCloud PointCloud;\n\n\n\/\/ represnts a point with x,y,z coordinates\nstruct Point {\n\n float x;\n float y;\n float z;\n};\n\n\nclass PMDCloudPublisher\n{\n \/\/ protected:\n \/\/ std::string tf_frame;\n \/\/ ros::NodeHandle nh;\n \/\/ ros::NodeHandle private_nh;\n\n \/\/ public:\n \/\/ pcl::PointCloud::Ptr cloud;\n \/\/ std::string file_name, cloud_topic;\n \/\/ pcl_ros::Publisher pub;\n\n \/\/ PMDCloudPublisher()\n \/\/ : tf_frame(\"\/map\"),\n \/\/ private_nh(\"~\")\n \/\/ {\n \/\/ cloud_topic = \"cloud\";\n \/\/ pub.advertise(nh, cloud_topic.c_str(), 1); \/\/ published here\n \/\/ private_nh.param(\"frame_id\", tf_frame, std::string(\"\/map\"));\n \/\/ ROS_INFO_STREAM(\"Publishing data on topic \\\"\" << nh.resolveName(cloud_topic) << \"\\\" with frame_id \\\"\" << tf_frame << \"\\\"\");\n \/\/ }\n\n \/\/ bool spin ()\n \/\/ {\n \/\/ int nr_points = cloud->width * cloud->height;\n \/\/ std::string fields_list = pcl::getFieldsList(cloud);\n \/\/ ros::Rate r(40);\n\n \/\/ while(nh.ok ())\n \/\/ {\n \/\/ ROS_DEBUG_STREAM_ONCE(\"Publishing data with \" << nr_points\n \/\/ << \" points \" << fields_list\n \/\/ << \" on topic \\\"\" << nh.resolveName(cloud_topic)\n \/\/ << \"\\\" in frame \\\"\" << cloud.header.frame_id << \"\\\"\");\n \/\/ \/\/ cloud.header.stamp = ros::Time::now();\n \/\/ pub.publish(cloud);\n\n \/\/ r.sleep();\n \/\/ }\n \/\/ return (true);\n \/\/ }\n};\n\n\nvoid publishData(pcl::PointCloud::Ptr filteredCloud, std::map viewablePoints){\n\n \/\/ \/\/ros::init (1, temp, \"cloud_publisher\");\n \/\/ ros::NodeHandle nh;\n\n \n \/\/ PMDCloudPublisher c;\n \/\/ c.file_name = \"spray_bottle.pcd\";\n \/\/ c.cloud = filteredCloud;\n \/\/ nh.getParam(filteredCloud, c.cloud);\n\n \/\/ if (c.start () == -1)\n \/\/ {\n \/\/ ROS_ERROR_STREAM(\"Could not load file \\\"\" << c.file_name <<\"\\\". Exiting...\");\n \/\/ }\n \/\/ ROS_INFO_STREAM(\"Loaded a point cloud with \" << c.cloud.width * c.cloud.height\n \/\/ << \" points (total size is \" << c.cloud.data.size() << \") and the following channels: \" << pcl::getFieldsList (c.cloud));\n \/\/ c.spin();\n}\n\n\n\/\/ calculating slope of line formed by two points in 3d space\nfloat calculate_slope(float pt_x, float pt_y, float pt_z, float pt2_x, float pt2_y, float pt2_z)\n{\n float rise = pt2_z - pt_z;\n\n float square = pow((pt2_x - pt_x), 2) + pow((pt2_y - pt_y), 2);\n float run = sqrt(square);\n return rise\/run;\n} \n\n\/\/ bool onLine(float view_x, float view_y, float view_z, float pt_x, float pt_y, float pt_z, float check_pt_x, float check_pt_y, float check_pt_z)\n\/\/ {\n\/\/ \/\/ Calculate the slope from the view to the check_pt\n\/\/ float slope_pt_to_view = calculate_slope(view_x, view_y, view_z, check_pt_x, check_pt_y, check_pt_z);\n\n\/\/ \/\/ printf(\"Slope from view to check_pt: %f\\n\", slope_pt_to_view);\n\n\/\/ \/\/ Calculate slope from the check_pt to the pt\n\/\/ float slope_check_pt_to_pt = calculate_slope(view_x, view_y, view_z, pt_x, pt_y, pt_z);\n\n\/\/ \/\/ printf(\"Slope from view to pt: %f\\n\", slope_check_pt_to_pt);\n\/\/ \/\/ printf(\"Are they equivalent?: %d\\n\", temp);\n\n\/\/ float delta = 0.0000000045f;\n\n\/\/ float diff = fabs(slope_pt_to_view - slope_check_pt_to_pt);\n\n\/\/ bool temp = (diff < delta);\n\/\/ \/\/ printf(\"Difference: %f\\n\", diff);\n\/\/ \/\/ printf(\"Boolean: %d\\n\", temp);\n\n\/\/ \/\/printf(\"Difference: %f\\n\", diff);\n\/\/ \/\/ If they are equal return true\n\/\/ return temp;\n\/\/ }\n\n\/\/ calculating distance between two points in 3d space\nfloat distance(float x1, float y1, float z1, float x2, float y2, float z2){\n\n return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2) + pow(z1 - z2, 2));\n}\n\n\n\/\/ method to find viewable points from a given view. \n\/\/ arg1: Passed in a pose that represents a point in space\n\/\/ arg2: the point cloud object of the pcd file\n\n\/\/ PENDING: consider orientation (various angles for a given point) when viewing the object\nvoid findPoints(const geometry_msgs::Pose createdPoint, const PointCloud::ConstPtr& msg)\n{\n\n\n \/\/ printing the current view point\n printf(\"Coordinates: %f, %f, %f\\n\", createdPoint.position.x, createdPoint.position.y, createdPoint.position.z);\n\n \/\/ x,y,z represents the cooridnates of the view \n float x = createdPoint.position.x;\n float y = createdPoint.position.y;\n float z = createdPoint.position.z;\n\n \/\/ total number of points in the point cloud\n int size = 0;\n\n \/\/ idea is that for a given line from the view point, slope is the same\n \/\/ we want to count for a single point and exclude all the other points on that line\n \/\/ by that way we count for a single point and not count points behind the counted \n \/\/ point\n \/\/ if slope is already contained, then check which point is closer\n \/\/ to the view point\n \/\/ map for: slope -> point\n std::map viewablePoints;\n std::map::iterator it;\n BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {\n\n float slope_pt_to_view = round(calculate_slope(x, y, z, pt.x, pt.y, pt.z) * 100000.0) \/ 100000.0 ;\n it = viewablePoints.find(slope_pt_to_view);\n\n \/\/ if slope is already present\n if(it != viewablePoints.end()){\n \/\/ if the slop is already taken into account\n \/\/ then we must see the point it corresponds to is the closest to the view point\n \/\/ if this new point is closer then must updates the map accordingly\n geometry_msgs::Pose existingPoint = it->second; \/\/ get the point\n float oldDistance = distance(x, y, z, existingPoint.position.x, existingPoint.position.y, existingPoint.position.z);\n float newDistance = distance(x, y, z, pt.x, pt.y, pt.z);\n if(newDistance < oldDistance) {\n \tgeometry_msgs::Pose newPose;\n \t\t\tnewPose.position.x = pt.x;\n \t\t\tnewPose.position.y = pt.y;\n \t\t\tnewPose.position.z = pt.z;\n viewablePoints.insert(std::pair (slope_pt_to_view, newPose));\n \/\/printf(\"Old point: %f, %f, %f with distance of %f\\n\", existingPoint.x, existingPoint.y, existingPoint.z, oldDistance);\n \/\/printf(\"New point: %f, %f, %f with distance of %f\\n\", newPoint.x, newPoint.y, newPoint.z, newDistance);\n }\n\n } else {\n \/\/ first time looking at this point\n \/\/ just add it\n geometry_msgs::Pose newPose;\n newPose.position.x = pt.x;\n newPose.position.y = pt.y;\n newPose.position.z = pt.z;\n viewablePoints.insert(std::pair (slope_pt_to_view, newPose));\n }\n size++; \/\/ totalNum points\n\n }\n\n\n\n \/\/ displaying contents of the map\n \/\/ multipying by 10000 because %f truncates values, so it appears as if duplictes exist\n \/\/ for(it = viewablePoints.begin(); it != viewablePoints.end(); it++){\n \/\/ printf(\"key: %f, Value: %f, %f, %f\\n\", it->first * 10000, it->second.x, it->second.y, it->second.z);\n \/\/ }\n\n\n \/\/ at this point we have filtered points based on slope,distance and angle\n \/\/ these points need to be used to create a pointcloud2 object\n \/\/ once this is created, we will publish this to rviz and view it accoringly\n \/\/ references to publishing to rviz check rvizView and generateViews.cpp\n\n \/\/ in progress\n \/\/ refer: http:\/\/wiki.ros.org\/pcl_ros\n \/\/ refer: http:\/\/pointclouds.org\/documentation\/tutorials\/passthrough.php\n\n \/\/ publishing data set\n ros::NodeHandle nh;\n ros::Publisher pub = nh.advertise (\"fileredCloud\", 1);\n\n pcl::PointCloud::Ptr filteredCloud (new pcl::PointCloud);\n\n filteredCloud->width = viewablePoints.size(); \/\/ need to verify\n filteredCloud->height = 1;\n filteredCloud->points.resize(filteredCloud->width * filteredCloud->height);\n filteredCloud->header.frame_id = \"\/map\";\n int filterIndex = 0;\n\n \/\/ loading a new pointcloud object from the points that we collected\n for(it = viewablePoints.begin(); it != viewablePoints.end(); it++, filterIndex++){\n\n \t\/\/ ideally no segfaults because filterdCloud size \n \t\/\/ is viewable points * 1 == viewablePoints.size();\n \tfilteredCloud->points[filterIndex].x = it->second.position.x;\n \tfilteredCloud->points[filterIndex].y = it->second.position.y;\n \tfilteredCloud->points[filterIndex].z = it->second.position.z;\n\n }\n\n \/\/ publishing to rviz topic\n \/\/ currently infinite\n ros::Rate loop_rate(4);\n while (nh.ok()) {\n filteredCloud->header.stamp = ros::Time::now().toNSec();\n pub.publish (filteredCloud);\n\n printf(\"view coordinates: %f, %f, %f - viewable: %f\\n\", x,y,z, 100 * viewablePoints.size() \/ (float) (size));\n ros::spinOnce ();\n loop_rate.sleep ();\n }\n\n \/\/ for modularity, break into separate methods\n \/\/ publishData(filteredCloud, viewablePoints);\n\n\n\n\n \/\/float viewableAmount = \n \/\/return viewableAmount; \/\/ percentag of points viewed\n\n\n\n\n \/\/ old implementation!\n\n \/\/ traverse through points of the point cloud\n \/\/ for a given point we scan all the same points\n \/\/ for each pair of points, we check if they have the same slope or comparable slopes\n \/\/ if they are similar we discount this because we have seen this point before\n \/\/ by this way we count all the points, without duplicates\n \/\/ by doing numberInLine <=1 we make sure we count only unique points and not duplicates\n \/\/ BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {\n \/\/ int numberInLine = 0;\n \/\/ BOOST_FOREACH (const pcl::PointXYZ& pt2, msg->points) {\n \/\/ bool onTheLine = onLine(x, y, z, pt.x, pt.y, pt.z, pt2.x, pt2.y, pt2.z);\n \/\/ if (onTheLine) {\n \/\/ numberInLine++;\n \/\/ }\n \/\/ }\n \/\/ \/\/ printf(\"inView: %d\\n\", inView);\n \/\/ if (numberInLine <= 1) {\n \/\/ count++;\n \/\/ }\n \/\/ size++;\n \/\/ }\n\n \/\/ \/\/ printf(\"Count: %d\\n\", count);\n \/\/ \/\/ printf(\"Size: %d\\n\", size);\n\n \/\/ \/\/printf(\"Percent of points viewed from pose: %f\\n\", 100 * count\/(float)size);\n\n \/\/ \/\/ finally return a ratio of the points seen to the total number of points \n \/\/ \/\/ in the pcl \n \/\/ return (100 * count \/ (float) (size));\n}\n\n\/\/ void callback(const PointCloud::ConstPtr& msg)\n\/\/ {\n\/\/ \/\/ printf(\"Percent of points viewed: %f\\n\", findPoints(msg));\n\/\/ }\n\n\/\/ int main(int argc, char** argv)\n\/\/ {\n\/\/ ros::init(argc, argv, \"generate_views\");\n\/\/ ros::NodeHandle nh;\n\/\/ ros::Subscriber sub = nh.subscribe(\"cloud\", 1, callback);\n\/\/ ros::spin();\n\/\/ }<|endoftext|>"} {"text":"#ifndef _DCM_DCM_SOCKET_SESSION_HPP_\n#define _DCM_DCM_SOCKET_SESSION_HPP_\n\n#include \n\nnamespace dcm {\n namespace streamsocket {\n template \n class receiver_session : public interproc::streamsocket::receiver_session {\n bool is_header_;\n bool is_size_;\n interproc::buffer message_;\n public:\n explicit receiver_session(asio::io_service &io_service):\n interproc::streamsocket::receiver_session(io_service){\n this->reader_->on_success = [this](interproc::buffer &&_buf){\n message_.append(_buf);\n if (is_size_) {\n interproc::block_size_t block_size;\n interproc::ibufstream bs(_buf);\n interproc::read_size(bs, block_size);\n is_size_ = !is_size_;\n this->reader_->read(block_size);\n } else {\n if (!is_header_) {\n if (this->on_message) {\n this->on_message(std::move(message_));\n message_.clear();\n }\n }\n is_header_ = !is_header_;\n is_size_ = !is_size_;\n this->reader_->read(interproc::BLOCK_SIZE_SIZE);\n }\n };\n this->reader_->on_fail = [this](const asio::error_code &_ec) {\n if (on_error) on_error(_ec);\n };\n }\n\n virtual void start() override {\n is_size_ = true;\n is_header_ = true;\n this->reader_->read(interproc::BLOCK_SIZE_SIZE);\n }\n\n std::function> _session)> on_connect;\n std::function> _session)> on_error;\n };\n }\n}\n#endif \/\/_DCM_DCM_SOCKET_SESSION_HPP_\n* comment on_error#ifndef _DCM_DCM_SOCKET_SESSION_HPP_\n#define _DCM_DCM_SOCKET_SESSION_HPP_\n\n#include \n\nnamespace dcm {\n namespace streamsocket {\n template \n class receiver_session : public interproc::streamsocket::receiver_session {\n bool is_header_;\n bool is_size_;\n interproc::buffer message_;\n public:\n explicit receiver_session(asio::io_service &io_service):\n interproc::streamsocket::receiver_session(io_service){\n this->reader_->on_success = [this](interproc::buffer &&_buf){\n message_.append(_buf);\n if (is_size_) {\n interproc::block_size_t block_size;\n interproc::ibufstream bs(_buf);\n interproc::read_size(bs, block_size);\n is_size_ = !is_size_;\n this->reader_->read(block_size);\n } else {\n if (!is_header_) {\n if (this->on_message) {\n this->on_message(std::move(message_));\n message_.clear();\n }\n }\n is_header_ = !is_header_;\n is_size_ = !is_size_;\n this->reader_->read(interproc::BLOCK_SIZE_SIZE);\n }\n };\n\/\/ this->reader_->on_fail = [this](const asio::error_code &_ec) {\n\/\/ if (on_error) on_error(_ec);\n\/\/ };\n }\n\n virtual void start() override {\n is_size_ = true;\n is_header_ = true;\n this->reader_->read(interproc::BLOCK_SIZE_SIZE);\n }\n\n std::function> _session)> on_connect;\n std::function> _session)> on_error;\n };\n }\n}\n#endif \/\/_DCM_DCM_SOCKET_SESSION_HPP_\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001 - 2006, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/etc.cmu.edu\/panda3d\/docs\/license\/ .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d-general@lists.sourceforge.net .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n\n#include \"config_osxdisplay.h\"\n#include \"osxGraphicsBuffer.h\"\n#include \"osxGraphicsPipe.h\"\n#include \"osxGraphicsStateGuardian.h\"\n#include \"osxGraphicsWindow.h\"\n\n#include \"graphicsPipeSelection.h\"\n#include \"dconfig.h\"\n#include \"pandaSystem.h\"\n\n\nConfigure(config_osxdisplay);\n\nNotifyCategoryDef( osxdisplay , \"display\");\n\nConfigureFn(config_osxdisplay) {\n init_libosxdisplay();\n}\n\nConfigVariableBool show_resize_box\n(\"show-resize-box\", true,\n PRC_DESC(\"When this variable is true, then resizable OSX Panda windows will \"\n \"be rendered with a resize control in the lower-right corner. \"\n \"This is specially handled by Panda, since otherwise the 3-d \"\n \"window would completely hide any resize control drawn by the \"\n \"OS. Set this variable false to allow this control to be hidden.\"));\n\nConfigVariableBool osx_disable_event_loop\n(\"osx-disable-event-loop\", false,\n PRC_DESC(\"Set this true to disable the window event loop for the Panda \"\n \"windows. This makes sense only in a publish environment where \"\n \"the window event loop is already handled by another part of the \"\n \"app.\"));\n\nConfigVariableInt osx_mouse_wheel_scale\n(\"osx-mouse-wheel-scale\", 5,\n PRC_DESC(\"Specify the number of units to spin the Mac mouse wheel to \"\n \"represent a single wheel_up or wheel_down message.\"));\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: init_libosxdisplay\n\/\/ Description: Initializes the library. This must be called at\n\/\/ least once before any of the functions or classes in\n\/\/ this library can be used. Normally it will be\n\/\/ called by the static initializers and need not be\n\/\/ called explicitly, but special cases exist.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\ninit_libosxdisplay() {\n static bool initialized = false;\n if (initialized) {\n return;\n }\n initialized = true;\n\n osxGraphicsStateGuardian::init_type();\n osxGraphicsPipe::init_type();\n osxGraphicsWindow::init_type();\n osxGraphicsStateGuardian::init_type();\n\n\n\n GraphicsPipeSelection *selection = GraphicsPipeSelection::get_global_ptr();\n selection->add_pipe_type(osxGraphicsPipe::get_class_type(), osxGraphicsPipe::pipe_constructor);\n\n PandaSystem *ps = PandaSystem::get_global_ptr();\n ps->set_system_tag(\"OpenGL\", \"window_system\", \"OSX\");\n}\nmake mouse scroll wheel instant\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001 - 2006, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/etc.cmu.edu\/panda3d\/docs\/license\/ .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d-general@lists.sourceforge.net .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n\n#include \"config_osxdisplay.h\"\n#include \"osxGraphicsBuffer.h\"\n#include \"osxGraphicsPipe.h\"\n#include \"osxGraphicsStateGuardian.h\"\n#include \"osxGraphicsWindow.h\"\n\n#include \"graphicsPipeSelection.h\"\n#include \"dconfig.h\"\n#include \"pandaSystem.h\"\n\n\nConfigure(config_osxdisplay);\n\nNotifyCategoryDef( osxdisplay , \"display\");\n\nConfigureFn(config_osxdisplay) {\n init_libosxdisplay();\n}\n\nConfigVariableBool show_resize_box\n(\"show-resize-box\", true,\n PRC_DESC(\"When this variable is true, then resizable OSX Panda windows will \"\n \"be rendered with a resize control in the lower-right corner. \"\n \"This is specially handled by Panda, since otherwise the 3-d \"\n \"window would completely hide any resize control drawn by the \"\n \"OS. Set this variable false to allow this control to be hidden.\"));\n\nConfigVariableBool osx_disable_event_loop\n(\"osx-disable-event-loop\", false,\n PRC_DESC(\"Set this true to disable the window event loop for the Panda \"\n \"windows. This makes sense only in a publish environment where \"\n \"the window event loop is already handled by another part of the \"\n \"app.\"));\n\nConfigVariableInt osx_mouse_wheel_scale\n(\"osx-mouse-wheel-scale\", 1,\n PRC_DESC(\"Specify the number of units to spin the Mac mouse wheel to \"\n \"represent a single wheel_up or wheel_down message.\"));\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: init_libosxdisplay\n\/\/ Description: Initializes the library. This must be called at\n\/\/ least once before any of the functions or classes in\n\/\/ this library can be used. Normally it will be\n\/\/ called by the static initializers and need not be\n\/\/ called explicitly, but special cases exist.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid\ninit_libosxdisplay() {\n static bool initialized = false;\n if (initialized) {\n return;\n }\n initialized = true;\n\n osxGraphicsStateGuardian::init_type();\n osxGraphicsPipe::init_type();\n osxGraphicsWindow::init_type();\n osxGraphicsStateGuardian::init_type();\n\n\n\n GraphicsPipeSelection *selection = GraphicsPipeSelection::get_global_ptr();\n selection->add_pipe_type(osxGraphicsPipe::get_class_type(), osxGraphicsPipe::pipe_constructor);\n\n PandaSystem *ps = PandaSystem::get_global_ptr();\n ps->set_system_tag(\"OpenGL\", \"window_system\", \"OSX\");\n}\n<|endoftext|>"} {"text":"#include \"retsetmidiportroute.h\"\n\nRetSetMidiPortRoute::RetSetMidiPortRoute(Device *device)\n\t\t: SysExMessage(SysExMessage::RET_SET_MIDI_PORT_INFO, SysExMessage::QUERY,\n\t\t\t\t\t\t\t\t\t device) {}\n\nvoid RetSetMidiPortRoute::parseAnswerData() {\n\tportId = MIDI::byteJoin(data, 1, 2);\n\tportRoutings = new BYTE_VECTOR(data->begin() + 2, data->end() - 2);\n}\nextract of routng data corrected#include \"retsetmidiportroute.h\"\n\nRetSetMidiPortRoute::RetSetMidiPortRoute(Device *device)\n\t\t: SysExMessage(SysExMessage::RET_SET_MIDI_PORT_INFO, SysExMessage::QUERY,\n\t\t\t\t\t\t\t\t\t device) {}\n\nvoid RetSetMidiPortRoute::parseAnswerData() {\n\tportId = MIDI::byteJoin(data, 1, 2);\n\tportRoutings = new BYTE_VECTOR(data->begin() + 3, data->end());\n}\n<|endoftext|>"} {"text":"added comment\/*\n\t\tCurrently, there is not any test code for parametrics.\n\t\tFeel free to create some.\n*\/<|endoftext|>"} {"text":"\/\/ Filename: rocketRenderInterface.cxx\n\/\/ Created by: rdb (04Nov11)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"rocketRenderInterface.h\"\n#include \"cullableObject.h\"\n#include \"cullHandler.h\"\n#include \"geomVertexData.h\"\n#include \"geomVertexArrayData.h\"\n#include \"internalName.h\"\n#include \"geomVertexWriter.h\"\n#include \"geomTriangles.h\"\n#include \"colorBlendAttrib.h\"\n#include \"cullBinAttrib.h\"\n#include \"depthTestAttrib.h\"\n#include \"depthWriteAttrib.h\"\n#include \"scissorAttrib.h\"\n#include \"texture.h\"\n#include \"textureAttrib.h\"\n#include \"texturePool.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::render\n\/\/ Access: Public\n\/\/ Description: Called by RocketNode in cull_callback. Invokes\n\/\/ context->Render() and culls the result.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nrender(Rocket::Core::Context* context, CullTraverser *trav) {\n nassertv(context != NULL);\n MutexHolder holder(_lock);\n\n _trav = trav;\n _net_transform = trav->get_world_transform();\n _net_state = RenderState::make(\n CullBinAttrib::make(\"unsorted\", 0),\n DepthTestAttrib::make(RenderAttrib::M_none),\n DepthWriteAttrib::make(DepthWriteAttrib::M_off),\n ColorBlendAttrib::make(ColorBlendAttrib::M_add,\n ColorBlendAttrib::O_incoming_alpha,\n ColorBlendAttrib::O_one_minus_incoming_alpha\n )\n );\n _dimensions = context->GetDimensions();\n\n context->Render();\n\n _trav = NULL;\n _net_transform = NULL;\n _net_state = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::make_geom\n\/\/ Access: Protected\n\/\/ Description: Called internally to make a Geom from Rocket data.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(Geom) RocketRenderInterface::\nmake_geom(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, GeomEnums::UsageHint uh) {\n PT(GeomVertexData) vdata = new GeomVertexData(\"\", GeomVertexFormat::get_v3c4t2(), uh);\n vdata->unclean_set_num_rows(num_vertices);\n {\n GeomVertexWriter vwriter(vdata, InternalName::get_vertex());\n GeomVertexWriter cwriter(vdata, InternalName::get_color());\n GeomVertexWriter twriter(vdata, InternalName::get_texcoord());\n\n \/\/ Write the vertex information.\n for (int i = 0; i < num_vertices; ++i) {\n const Rocket::Core::Vertex &vertex = vertices[i];\n\n vwriter.add_data3f(LVector3f::right() * vertex.position.x + LVector3f::up() * vertex.position.y);\n cwriter.add_data4i(vertex.colour.red, vertex.colour.green,\n vertex.colour.blue, vertex.colour.alpha);\n twriter.add_data2f(vertex.tex_coord.x, 1.0f - vertex.tex_coord.y);\n }\n }\n\n \/\/ Create a primitive and write the indices.\n PT(GeomTriangles) triangles = new GeomTriangles(uh);\n {\n PT(GeomVertexArrayData) idata = triangles->modify_vertices();\n idata->unclean_set_num_rows(num_indices);\n GeomVertexWriter iwriter(idata, 0);\n\n for (int i = 0; i < num_indices; ++i) {\n iwriter.add_data1i(indices[i]);\n }\n }\n\n PT(Geom) geom = new Geom(vdata);\n geom->add_primitive(triangles);\n return geom;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::render_geom\n\/\/ Access: Protected\n\/\/ Description: Only call this during render(). Culls a geom.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nrender_geom(const Geom* geom, const RenderState* state, const Rocket::Core::Vector2f& translation) {\n LVector3 offset = LVector3::right() * translation.x + LVector3::up() * translation.y;\n\n if (_enable_scissor) {\n state = state->add_attrib(ScissorAttrib::make(_scissor));\n rocket_cat.spam()\n << \"Rendering geom \" << geom << \" with state \"\n << *state << \", translation (\" << offset << \"), \"\n << \"scissor region (\" << _scissor << \")\\n\";\n } else {\n rocket_cat.spam()\n << \"Rendering geom \" << geom << \" with state \"\n << *state << \", translation (\" << offset << \")\\n\";\n }\n\n CPT(TransformState) net_transform, modelview_transform;\n net_transform = _net_transform->compose(TransformState::make_pos(offset));\n modelview_transform = _trav->get_world_transform()->compose(net_transform);\n\n CullableObject *object =\n new CullableObject(geom, _net_state->compose(state),\n net_transform, modelview_transform,\n _trav->get_gsg());\n _trav->get_cull_handler()->record_object(object, _trav);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::RenderGeometry\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to render geometry\n\/\/ that the application does not wish to optimize.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nRenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation) {\n PT(Geom) geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_stream);\n\n CPT(RenderState) state;\n if ((Texture*) texture != (Texture*) NULL) {\n state = RenderState::make(TextureAttrib::make((Texture*) texture));\n } else {\n state = RenderState::make_empty();\n }\n\n render_geom(geom, state, translation);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::CompileGeometry\n\/\/ Access: Protected \n\/\/ Description: Called by Rocket when it wants to compile geometry\n\/\/ it believes will be static for the forseeable future.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nRocket::Core::CompiledGeometryHandle RocketRenderInterface::\nCompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture) {\n\n CompiledGeometry *c = new CompiledGeometry;\n c->_geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_static);\n\n if ((Texture*) texture != (Texture*) NULL) {\n PT(TextureStage) stage = new TextureStage(\"\");\n stage->set_mode(TextureStage::M_replace);\n\n CPT(TextureAttrib) attr = DCAST(TextureAttrib, TextureAttrib::make());\n attr = DCAST(TextureAttrib, attr->add_on_stage(stage, (Texture*) texture));\n\n c->_state = RenderState::make(attr);\n\n rocket_cat.debug()\n << \"Compiled geom \" << c->_geom << \" with texture '\"\n << ((Texture*) texture)->get_name() << \"'\\n\";\n } else {\n c->_state = RenderState::make_empty();\n\n rocket_cat.debug()\n << \"Compiled geom \" << c->_geom << \" without texture\\n\";\n }\n\n return (Rocket::Core::CompiledGeometryHandle) c;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::RenderCompiledGeometry\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to render\n\/\/ application-compiled geometry.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nRenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation) {\n\n CompiledGeometry *c = (CompiledGeometry*) geometry;\n render_geom(c->_geom, c->_state, translation);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::ReleaseCompiledGeometry\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to release\n\/\/ application-compiled geometry.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry) {\n delete (CompiledGeometry*) geometry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::LoadTexture\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when a texture is required by the\n\/\/ library.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool RocketRenderInterface::\nLoadTexture(Rocket::Core::TextureHandle& texture_handle,\n Rocket::Core::Vector2i& texture_dimensions,\n const Rocket::Core::String& source) {\n\n PT(Texture) tex = TexturePool::load_texture(Filename::from_os_specific(source.CString()));\n if (tex == NULL) {\n texture_handle = 0;\n texture_dimensions.x = 0;\n texture_dimensions.y = 0;\n return false;\n }\n\n texture_dimensions.x = tex->get_x_size();\n texture_dimensions.y = tex->get_y_size();\n tex->ref();\n texture_handle = (Rocket::Core::TextureHandle) tex.p();\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::GenerateTexture\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when a texture is required to be\n\/\/ built from an internally-generated sequence of pixels.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool RocketRenderInterface::\nGenerateTexture(Rocket::Core::TextureHandle& texture_handle,\n const Rocket::Core::byte* source,\n const Rocket::Core::Vector2i& source_dimensions) {\n\n PT(Texture) tex = new Texture;\n tex->setup_2d_texture(source_dimensions.x, source_dimensions.y,\n Texture::T_unsigned_byte, Texture::F_rgba);\n PTA_uchar image = tex->modify_ram_image();\n\n \/\/ Convert RGBA to BGRA\n size_t row_size = source_dimensions.x * 4;\n size_t y2 = image.size();\n for (size_t y = 0; y < image.size(); y += row_size) {\n y2 -= row_size;\n for (size_t i = 0; i < row_size; i += 4) {\n image[y2 + i + 0] = source[y + i + 2];\n image[y2 + i + 1] = source[y + i + 1];\n image[y2 + i + 2] = source[y + i];\n image[y2 + i + 3] = source[y + i + 3];\n }\n }\n\n tex->set_wrap_u(Texture::WM_clamp);\n tex->set_wrap_v(Texture::WM_clamp);\n\n tex->ref();\n texture_handle = (Rocket::Core::TextureHandle) tex.p();\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::ReleaseTexture\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when a loaded texture is no longer\n\/\/ required.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nReleaseTexture(Rocket::Core::TextureHandle texture_handle) {\n Texture* tex = (Texture*) texture_handle;\n if (tex != (Texture*) NULL) {\n tex->unref();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::EnableScissorRegion\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to enable or disable\n\/\/ scissoring to clip content.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nEnableScissorRegion(bool enable) {\n _enable_scissor = enable;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::SetScissorRegion\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to change the\n\/\/ scissor region.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nSetScissorRegion(int x, int y, int width, int height) {\n _scissor[0] = x \/ (PN_stdfloat) _dimensions.x;\n _scissor[1] = (x + width) \/ (PN_stdfloat) _dimensions.x;\n _scissor[2] = 1.0f - ((y + height) \/ (PN_stdfloat) _dimensions.y);\n _scissor[3] = 1.0f - (y \/ (PN_stdfloat) _dimensions.y);\n}\nfix font colour issue (all text was showing up white regardless of font colour)\/\/ Filename: rocketRenderInterface.cxx\n\/\/ Created by: rdb (04Nov11)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"rocketRenderInterface.h\"\n#include \"cullableObject.h\"\n#include \"cullHandler.h\"\n#include \"geomVertexData.h\"\n#include \"geomVertexArrayData.h\"\n#include \"internalName.h\"\n#include \"geomVertexWriter.h\"\n#include \"geomTriangles.h\"\n#include \"colorBlendAttrib.h\"\n#include \"cullBinAttrib.h\"\n#include \"depthTestAttrib.h\"\n#include \"depthWriteAttrib.h\"\n#include \"scissorAttrib.h\"\n#include \"texture.h\"\n#include \"textureAttrib.h\"\n#include \"texturePool.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::render\n\/\/ Access: Public\n\/\/ Description: Called by RocketNode in cull_callback. Invokes\n\/\/ context->Render() and culls the result.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nrender(Rocket::Core::Context* context, CullTraverser *trav) {\n nassertv(context != NULL);\n MutexHolder holder(_lock);\n\n _trav = trav;\n _net_transform = trav->get_world_transform();\n _net_state = RenderState::make(\n CullBinAttrib::make(\"unsorted\", 0),\n DepthTestAttrib::make(RenderAttrib::M_none),\n DepthWriteAttrib::make(DepthWriteAttrib::M_off),\n ColorBlendAttrib::make(ColorBlendAttrib::M_add,\n ColorBlendAttrib::O_incoming_alpha,\n ColorBlendAttrib::O_one_minus_incoming_alpha\n )\n );\n _dimensions = context->GetDimensions();\n\n context->Render();\n\n _trav = NULL;\n _net_transform = NULL;\n _net_state = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::make_geom\n\/\/ Access: Protected\n\/\/ Description: Called internally to make a Geom from Rocket data.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPT(Geom) RocketRenderInterface::\nmake_geom(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, GeomEnums::UsageHint uh) {\n PT(GeomVertexData) vdata = new GeomVertexData(\"\", GeomVertexFormat::get_v3c4t2(), uh);\n vdata->unclean_set_num_rows(num_vertices);\n {\n GeomVertexWriter vwriter(vdata, InternalName::get_vertex());\n GeomVertexWriter cwriter(vdata, InternalName::get_color());\n GeomVertexWriter twriter(vdata, InternalName::get_texcoord());\n\n \/\/ Write the vertex information.\n for (int i = 0; i < num_vertices; ++i) {\n const Rocket::Core::Vertex &vertex = vertices[i];\n\n vwriter.add_data3f(LVector3f::right() * vertex.position.x + LVector3f::up() * vertex.position.y);\n cwriter.add_data4i(vertex.colour.red, vertex.colour.green,\n vertex.colour.blue, vertex.colour.alpha);\n twriter.add_data2f(vertex.tex_coord.x, 1.0f - vertex.tex_coord.y);\n }\n }\n\n \/\/ Create a primitive and write the indices.\n PT(GeomTriangles) triangles = new GeomTriangles(uh);\n {\n PT(GeomVertexArrayData) idata = triangles->modify_vertices();\n idata->unclean_set_num_rows(num_indices);\n GeomVertexWriter iwriter(idata, 0);\n\n for (int i = 0; i < num_indices; ++i) {\n iwriter.add_data1i(indices[i]);\n }\n }\n\n PT(Geom) geom = new Geom(vdata);\n geom->add_primitive(triangles);\n return geom;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::render_geom\n\/\/ Access: Protected\n\/\/ Description: Only call this during render(). Culls a geom.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nrender_geom(const Geom* geom, const RenderState* state, const Rocket::Core::Vector2f& translation) {\n LVector3 offset = LVector3::right() * translation.x + LVector3::up() * translation.y;\n\n if (_enable_scissor) {\n state = state->add_attrib(ScissorAttrib::make(_scissor));\n rocket_cat.spam()\n << \"Rendering geom \" << geom << \" with state \"\n << *state << \", translation (\" << offset << \"), \"\n << \"scissor region (\" << _scissor << \")\\n\";\n } else {\n rocket_cat.spam()\n << \"Rendering geom \" << geom << \" with state \"\n << *state << \", translation (\" << offset << \")\\n\";\n }\n\n CPT(TransformState) net_transform, modelview_transform;\n net_transform = _net_transform->compose(TransformState::make_pos(offset));\n modelview_transform = _trav->get_world_transform()->compose(net_transform);\n\n CullableObject *object =\n new CullableObject(geom, _net_state->compose(state),\n net_transform, modelview_transform,\n _trav->get_gsg());\n _trav->get_cull_handler()->record_object(object, _trav);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::RenderGeometry\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to render geometry\n\/\/ that the application does not wish to optimize.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nRenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation) {\n PT(Geom) geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_stream);\n\n CPT(RenderState) state;\n if ((Texture*) texture != (Texture*) NULL) {\n state = RenderState::make(TextureAttrib::make((Texture*) texture));\n } else {\n state = RenderState::make_empty();\n }\n\n render_geom(geom, state, translation);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::CompileGeometry\n\/\/ Access: Protected \n\/\/ Description: Called by Rocket when it wants to compile geometry\n\/\/ it believes will be static for the forseeable future.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nRocket::Core::CompiledGeometryHandle RocketRenderInterface::\nCompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture) {\n\n CompiledGeometry *c = new CompiledGeometry;\n c->_geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_static);\n\n if ((Texture*) texture != (Texture*) NULL) {\n PT(TextureStage) stage = new TextureStage(\"\");\n stage->set_mode(TextureStage::M_modulate);\n\n CPT(TextureAttrib) attr = DCAST(TextureAttrib, TextureAttrib::make());\n attr = DCAST(TextureAttrib, attr->add_on_stage(stage, (Texture*) texture));\n\n c->_state = RenderState::make(attr);\n\n rocket_cat.debug()\n << \"Compiled geom \" << c->_geom << \" with texture '\"\n << ((Texture*) texture)->get_name() << \"'\\n\";\n } else {\n c->_state = RenderState::make_empty();\n\n rocket_cat.debug()\n << \"Compiled geom \" << c->_geom << \" without texture\\n\";\n }\n\n return (Rocket::Core::CompiledGeometryHandle) c;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::RenderCompiledGeometry\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to render\n\/\/ application-compiled geometry.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nRenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation) {\n\n CompiledGeometry *c = (CompiledGeometry*) geometry;\n render_geom(c->_geom, c->_state, translation);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::ReleaseCompiledGeometry\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to release\n\/\/ application-compiled geometry.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry) {\n delete (CompiledGeometry*) geometry;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::LoadTexture\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when a texture is required by the\n\/\/ library.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool RocketRenderInterface::\nLoadTexture(Rocket::Core::TextureHandle& texture_handle,\n Rocket::Core::Vector2i& texture_dimensions,\n const Rocket::Core::String& source) {\n\n PT(Texture) tex = TexturePool::load_texture(Filename::from_os_specific(source.CString()));\n if (tex == NULL) {\n texture_handle = 0;\n texture_dimensions.x = 0;\n texture_dimensions.y = 0;\n return false;\n }\n\n texture_dimensions.x = tex->get_x_size();\n texture_dimensions.y = tex->get_y_size();\n tex->ref();\n texture_handle = (Rocket::Core::TextureHandle) tex.p();\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::GenerateTexture\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when a texture is required to be\n\/\/ built from an internally-generated sequence of pixels.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool RocketRenderInterface::\nGenerateTexture(Rocket::Core::TextureHandle& texture_handle,\n const Rocket::Core::byte* source,\n const Rocket::Core::Vector2i& source_dimensions) {\n\n PT(Texture) tex = new Texture;\n tex->setup_2d_texture(source_dimensions.x, source_dimensions.y,\n Texture::T_unsigned_byte, Texture::F_rgba);\n PTA_uchar image = tex->modify_ram_image();\n\n \/\/ Convert RGBA to BGRA\n size_t row_size = source_dimensions.x * 4;\n size_t y2 = image.size();\n for (size_t y = 0; y < image.size(); y += row_size) {\n y2 -= row_size;\n for (size_t i = 0; i < row_size; i += 4) {\n image[y2 + i + 0] = source[y + i + 2];\n image[y2 + i + 1] = source[y + i + 1];\n image[y2 + i + 2] = source[y + i];\n image[y2 + i + 3] = source[y + i + 3];\n }\n }\n\n tex->set_wrap_u(Texture::WM_clamp);\n tex->set_wrap_v(Texture::WM_clamp);\n\n tex->ref();\n texture_handle = (Rocket::Core::TextureHandle) tex.p();\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::ReleaseTexture\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when a loaded texture is no longer\n\/\/ required.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nReleaseTexture(Rocket::Core::TextureHandle texture_handle) {\n Texture* tex = (Texture*) texture_handle;\n if (tex != (Texture*) NULL) {\n tex->unref();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::EnableScissorRegion\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to enable or disable\n\/\/ scissoring to clip content.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nEnableScissorRegion(bool enable) {\n _enable_scissor = enable;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: RocketRenderInterface::SetScissorRegion\n\/\/ Access: Protected\n\/\/ Description: Called by Rocket when it wants to change the\n\/\/ scissor region.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid RocketRenderInterface::\nSetScissorRegion(int x, int y, int width, int height) {\n _scissor[0] = x \/ (PN_stdfloat) _dimensions.x;\n _scissor[1] = (x + width) \/ (PN_stdfloat) _dimensions.x;\n _scissor[2] = 1.0f - ((y + height) \/ (PN_stdfloat) _dimensions.y);\n _scissor[3] = 1.0f - (y \/ (PN_stdfloat) _dimensions.y);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/runtime\/browser\/runtime_url_request_context_getter.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/cookie_store_factory.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"net\/cert\/cert_verifier.h\"\n#include \"net\/cookies\/cookie_monster.h\"\n#include \"net\/dns\/host_resolver.h\"\n#include \"net\/dns\/mapped_host_resolver.h\"\n#include \"net\/http\/http_auth_handler_factory.h\"\n#include \"net\/http\/http_cache.h\"\n#include \"net\/http\/http_network_session.h\"\n#include \"net\/http\/http_server_properties_impl.h\"\n#include \"net\/proxy\/proxy_service.h\"\n#include \"net\/ssl\/channel_id_service.h\"\n#include \"net\/ssl\/default_channel_id_store.h\"\n#include \"net\/ssl\/ssl_config_service_defaults.h\"\n#include \"net\/url_request\/data_protocol_handler.h\"\n#include \"net\/url_request\/file_protocol_handler.h\"\n#include \"net\/url_request\/static_http_user_agent_settings.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_context_storage.h\"\n#include \"net\/url_request\/url_request_intercepting_job_factory.h\"\n#include \"net\/url_request\/url_request_interceptor.h\"\n#include \"net\/url_request\/url_request_job_factory_impl.h\"\n#include \"xwalk\/application\/common\/constants.h\"\n#include \"xwalk\/runtime\/browser\/runtime_network_delegate.h\"\n#include \"xwalk\/runtime\/common\/xwalk_content_client.h\"\n#include \"xwalk\/runtime\/common\/xwalk_switches.h\"\n\n#if defined(OS_ANDROID)\n#include \"net\/proxy\/proxy_config_service_android.h\"\n#include \"xwalk\/runtime\/browser\/android\/cookie_manager.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/android_protocol_handler.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/url_constants.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/xwalk_cookie_store_wrapper.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/xwalk_url_request_job_factory.h\"\n#include \"xwalk\/runtime\/browser\/android\/xwalk_request_interceptor.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace xwalk {\n\nint GetDiskCacheSize() {\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n\n if (!command_line->HasSwitch(switches::kDiskCacheSize))\n return 0;\n\n std::string str_value = command_line->GetSwitchValueASCII(\n switches::kDiskCacheSize);\n\n int size = 0;\n if (!base::StringToInt(str_value, &size)) {\n LOG(ERROR) << \"The value \" << str_value\n << \" can not be converted to integer, ignoring!\";\n }\n\n return size;\n}\n\nRuntimeURLRequestContextGetter::RuntimeURLRequestContextGetter(\n bool ignore_certificate_errors,\n const base::FilePath& base_path,\n base::MessageLoop* io_loop,\n base::MessageLoop* file_loop,\n content::ProtocolHandlerMap* protocol_handlers,\n content::URLRequestInterceptorScopedVector request_interceptors)\n : ignore_certificate_errors_(ignore_certificate_errors),\n base_path_(base_path),\n io_loop_(io_loop),\n file_loop_(file_loop),\n request_interceptors_(std::move(request_interceptors)) {\n \/\/ Must first be created on the UI thread.\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n std::swap(protocol_handlers_, *protocol_handlers);\n\n \/\/ We must create the proxy config service on the UI loop on Linux because it\n \/\/ must synchronously run on the glib message loop. This will be passed to\n \/\/ the URLRequestContextStorage on the IO thread in GetURLRequestContext().\n#if defined(OS_ANDROID)\n proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(\n io_loop_->task_runner(), file_loop_->task_runner());\n net::ProxyConfigServiceAndroid* android_config_service =\n static_cast(proxy_config_service_.get());\n android_config_service->set_exclude_pac_url(true);\n#else\n proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(\n io_loop_->task_runner(), file_loop_->task_runner());\n#endif\n}\n\nRuntimeURLRequestContextGetter::~RuntimeURLRequestContextGetter() {\n}\n\nnet::URLRequestContext* RuntimeURLRequestContextGetter::GetURLRequestContext() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n if (!url_request_context_) {\n url_request_context_.reset(new net::URLRequestContext());\n network_delegate_.reset(new RuntimeNetworkDelegate);\n url_request_context_->set_network_delegate(network_delegate_.get());\n storage_.reset(\n new net::URLRequestContextStorage(url_request_context_.get()));\n#if defined(OS_ANDROID)\n storage_->set_cookie_store(new XWalkCookieStoreWrapper());\n#else\n content::CookieStoreConfig cookie_config(base_path_.Append(\n application::kCookieDatabaseFilename),\n content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES,\n NULL, NULL);\n\n cookie_config.cookieable_schemes.push_back(application::kApplicationScheme);\n cookie_config.cookieable_schemes.push_back(content::kChromeDevToolsScheme);\n\n net::CookieStore* cookie_store = content::CreateCookieStore(cookie_config);\n storage_->set_cookie_store(cookie_store);\n#endif\n storage_->set_channel_id_service(make_scoped_ptr(new net::ChannelIDService(\n new net::DefaultChannelIDStore(NULL),\n base::WorkerPool::GetTaskRunner(true))));\n storage_->set_http_user_agent_settings(make_scoped_ptr(\n new net::StaticHttpUserAgentSettings(\"en-us,en\",\n xwalk::GetUserAgent())));\n\n scoped_ptr host_resolver(\n net::HostResolver::CreateDefaultResolver(NULL));\n\n storage_->set_cert_verifier(net::CertVerifier::CreateDefault());\n storage_->set_transport_security_state(\n make_scoped_ptr(new net::TransportSecurityState));\n#if defined(OS_ANDROID)\n \/\/ Android provides a local HTTP proxy that handles all the proxying.\n \/\/ Create the proxy without a resolver since we rely\n \/\/ on this local HTTP proxy.\n storage_->set_proxy_service(\n net::ProxyService::CreateWithoutProxyResolver(\n std::move(proxy_config_service_),\n NULL));\n#else\n storage_->set_proxy_service(\n net::ProxyService::CreateUsingSystemProxyResolver(\n std::move(proxy_config_service_),\n 0,\n NULL));\n#endif\n storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);\n storage_->set_http_auth_handler_factory(\n net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));\n storage_->set_http_server_properties(scoped_ptr(\n new net::HttpServerPropertiesImpl));\n\n base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL(\"Cache\"));\n scoped_ptr main_backend(\n new net::HttpCache::DefaultBackend(\n net::DISK_CACHE,\n net::CACHE_BACKEND_DEFAULT,\n cache_path,\n GetDiskCacheSize(),\n BrowserThread::GetMessageLoopProxyForThread(\n BrowserThread::CACHE)));\n\n net::HttpNetworkSession::Params network_session_params;\n network_session_params.cert_verifier =\n url_request_context_->cert_verifier();\n network_session_params.transport_security_state =\n url_request_context_->transport_security_state();\n network_session_params.channel_id_service =\n url_request_context_->channel_id_service();\n network_session_params.proxy_service =\n url_request_context_->proxy_service();\n network_session_params.ssl_config_service =\n url_request_context_->ssl_config_service();\n network_session_params.http_auth_handler_factory =\n url_request_context_->http_auth_handler_factory();\n network_session_params.network_delegate =\n network_delegate_.get();\n network_session_params.http_server_properties =\n url_request_context_->http_server_properties();\n network_session_params.ignore_certificate_errors =\n ignore_certificate_errors_;\n\n \/\/ Give |storage_| ownership at the end in case it's |mapped_host_resolver|.\n storage_->set_host_resolver(std::move(host_resolver));\n network_session_params.host_resolver =\n url_request_context_->host_resolver();\n\n storage_->set_http_network_session(\n make_scoped_ptr(new net::HttpNetworkSession(network_session_params)));\n storage_->set_http_transaction_factory(\n make_scoped_ptr(new net::HttpCache(storage_->http_network_session(),\n std::move(main_backend),\n false \/* set_up_quic_server_info *\/)));\n#if defined(OS_ANDROID)\n scoped_ptr job_factory_impl(\n new XWalkURLRequestJobFactory);\n#else\n scoped_ptr job_factory_impl(\n new net::URLRequestJobFactoryImpl);\n#endif\n\n bool set_protocol;\n\n \/\/ Step 1:\n \/\/ Install all the default schemes for crosswalk.\n for (content::ProtocolHandlerMap::iterator it =\n protocol_handlers_.begin();\n it != protocol_handlers_.end();\n ++it) {\n set_protocol = job_factory_impl->SetProtocolHandler(\n it->first, make_scoped_ptr(it->second.release()));\n DCHECK(set_protocol);\n }\n protocol_handlers_.clear();\n\n \/\/ Step 2:\n \/\/ Add new basic schemes.\n set_protocol = job_factory_impl->SetProtocolHandler(\n url::kDataScheme,\n make_scoped_ptr(new net::DataProtocolHandler));\n DCHECK(set_protocol);\n set_protocol = job_factory_impl->SetProtocolHandler(\n url::kFileScheme,\n make_scoped_ptr(new net::FileProtocolHandler(\n content::BrowserThread::GetBlockingPool()->\n GetTaskRunnerWithShutdownBehavior(\n base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));\n DCHECK(set_protocol);\n\n \/\/ Step 3:\n \/\/ Add the scheme interceptors.\n \/\/ in the order in which they appear in the |request_interceptors| vector.\n typedef std::vector\n URLRequestInterceptorVector;\n URLRequestInterceptorVector request_interceptors;\n\n#if defined(OS_ANDROID)\n request_interceptors.push_back(\n CreateContentSchemeRequestInterceptor().release());\n request_interceptors.push_back(\n CreateAssetFileRequestInterceptor().release());\n request_interceptors.push_back(\n CreateAppSchemeRequestInterceptor().release());\n \/\/ The XWalkRequestInterceptor must come after the content and asset\n \/\/ file job factories. This for WebViewClassic compatibility where it\n \/\/ was not possible to intercept resource loads to resolvable content:\/\/\n \/\/ and file:\/\/ URIs.\n \/\/ This logical dependency is also the reason why the Content\n \/\/ ProtocolHandler has to be added as a ProtocolInterceptJobFactory rather\n \/\/ than via SetProtocolHandler.\n request_interceptors.push_back(new XWalkRequestInterceptor());\n#endif\n\n \/\/ The chain of responsibility will execute the handlers in reverse to the\n \/\/ order in which the elements of the chain are created.\n scoped_ptr job_factory(\n std::move(job_factory_impl));\n for (URLRequestInterceptorVector::reverse_iterator\n i = request_interceptors.rbegin();\n i != request_interceptors.rend();\n ++i) {\n job_factory.reset(new net::URLRequestInterceptingJobFactory(\n std::move(job_factory), make_scoped_ptr(*i)));\n }\n\n \/\/ Set up interceptors in the reverse order.\n scoped_ptr top_job_factory =\n std::move(job_factory);\n for (content::URLRequestInterceptorScopedVector::reverse_iterator i =\n request_interceptors_.rbegin();\n i != request_interceptors_.rend();\n ++i) {\n top_job_factory.reset(new net::URLRequestInterceptingJobFactory(\n std::move(top_job_factory), make_scoped_ptr(*i)));\n }\n request_interceptors_.weak_clear();\n\n storage_->set_job_factory(std::move(top_job_factory));\n }\n\n return url_request_context_.get();\n}\n\nscoped_refptr\n RuntimeURLRequestContextGetter::GetNetworkTaskRunner() const {\n return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);\n}\n\nnet::HostResolver* RuntimeURLRequestContextGetter::host_resolver() {\n return url_request_context_->host_resolver();\n}\n\nvoid RuntimeURLRequestContextGetter::UpdateAcceptLanguages(\n const std::string& accept_languages) {\n if (!storage_)\n return;\n storage_->set_http_user_agent_settings(make_scoped_ptr(\n new net::StaticHttpUserAgentSettings(accept_languages,\n xwalk::GetUserAgent())));\n}\n\n} \/\/ namespace xwalk\nMake sure default schemes (https, http...) are allowed to store cookies.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/runtime\/browser\/runtime_url_request_context_getter.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/cookie_store_factory.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"net\/cert\/cert_verifier.h\"\n#include \"net\/cookies\/cookie_monster.h\"\n#include \"net\/dns\/host_resolver.h\"\n#include \"net\/dns\/mapped_host_resolver.h\"\n#include \"net\/http\/http_auth_handler_factory.h\"\n#include \"net\/http\/http_cache.h\"\n#include \"net\/http\/http_network_session.h\"\n#include \"net\/http\/http_server_properties_impl.h\"\n#include \"net\/proxy\/proxy_service.h\"\n#include \"net\/ssl\/channel_id_service.h\"\n#include \"net\/ssl\/default_channel_id_store.h\"\n#include \"net\/ssl\/ssl_config_service_defaults.h\"\n#include \"net\/url_request\/data_protocol_handler.h\"\n#include \"net\/url_request\/file_protocol_handler.h\"\n#include \"net\/url_request\/static_http_user_agent_settings.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_context_storage.h\"\n#include \"net\/url_request\/url_request_intercepting_job_factory.h\"\n#include \"net\/url_request\/url_request_interceptor.h\"\n#include \"net\/url_request\/url_request_job_factory_impl.h\"\n#include \"xwalk\/application\/common\/constants.h\"\n#include \"xwalk\/runtime\/browser\/runtime_network_delegate.h\"\n#include \"xwalk\/runtime\/common\/xwalk_content_client.h\"\n#include \"xwalk\/runtime\/common\/xwalk_switches.h\"\n\n#if defined(OS_ANDROID)\n#include \"net\/proxy\/proxy_config_service_android.h\"\n#include \"xwalk\/runtime\/browser\/android\/cookie_manager.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/android_protocol_handler.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/url_constants.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/xwalk_cookie_store_wrapper.h\"\n#include \"xwalk\/runtime\/browser\/android\/net\/xwalk_url_request_job_factory.h\"\n#include \"xwalk\/runtime\/browser\/android\/xwalk_request_interceptor.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace xwalk {\n\nint GetDiskCacheSize() {\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n\n if (!command_line->HasSwitch(switches::kDiskCacheSize))\n return 0;\n\n std::string str_value = command_line->GetSwitchValueASCII(\n switches::kDiskCacheSize);\n\n int size = 0;\n if (!base::StringToInt(str_value, &size)) {\n LOG(ERROR) << \"The value \" << str_value\n << \" can not be converted to integer, ignoring!\";\n }\n\n return size;\n}\n\nRuntimeURLRequestContextGetter::RuntimeURLRequestContextGetter(\n bool ignore_certificate_errors,\n const base::FilePath& base_path,\n base::MessageLoop* io_loop,\n base::MessageLoop* file_loop,\n content::ProtocolHandlerMap* protocol_handlers,\n content::URLRequestInterceptorScopedVector request_interceptors)\n : ignore_certificate_errors_(ignore_certificate_errors),\n base_path_(base_path),\n io_loop_(io_loop),\n file_loop_(file_loop),\n request_interceptors_(std::move(request_interceptors)) {\n \/\/ Must first be created on the UI thread.\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n std::swap(protocol_handlers_, *protocol_handlers);\n\n \/\/ We must create the proxy config service on the UI loop on Linux because it\n \/\/ must synchronously run on the glib message loop. This will be passed to\n \/\/ the URLRequestContextStorage on the IO thread in GetURLRequestContext().\n#if defined(OS_ANDROID)\n proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(\n io_loop_->task_runner(), file_loop_->task_runner());\n net::ProxyConfigServiceAndroid* android_config_service =\n static_cast(proxy_config_service_.get());\n android_config_service->set_exclude_pac_url(true);\n#else\n proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(\n io_loop_->task_runner(), file_loop_->task_runner());\n#endif\n}\n\nRuntimeURLRequestContextGetter::~RuntimeURLRequestContextGetter() {\n}\n\nnet::URLRequestContext* RuntimeURLRequestContextGetter::GetURLRequestContext() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n if (!url_request_context_) {\n url_request_context_.reset(new net::URLRequestContext());\n network_delegate_.reset(new RuntimeNetworkDelegate);\n url_request_context_->set_network_delegate(network_delegate_.get());\n storage_.reset(\n new net::URLRequestContextStorage(url_request_context_.get()));\n#if defined(OS_ANDROID)\n storage_->set_cookie_store(new XWalkCookieStoreWrapper());\n#else\n content::CookieStoreConfig cookie_config(base_path_.Append(\n application::kCookieDatabaseFilename),\n content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES,\n NULL, NULL);\n\n cookie_config.cookieable_schemes.insert(\n cookie_config.cookieable_schemes.begin(),\n net::CookieMonster::kDefaultCookieableSchemes,\n net::CookieMonster::kDefaultCookieableSchemes +\n net::CookieMonster::kDefaultCookieableSchemesCount);\n cookie_config.cookieable_schemes.push_back(application::kApplicationScheme);\n cookie_config.cookieable_schemes.push_back(content::kChromeDevToolsScheme);\n\n net::CookieStore* cookie_store = content::CreateCookieStore(cookie_config);\n storage_->set_cookie_store(cookie_store);\n#endif\n storage_->set_channel_id_service(make_scoped_ptr(new net::ChannelIDService(\n new net::DefaultChannelIDStore(NULL),\n base::WorkerPool::GetTaskRunner(true))));\n storage_->set_http_user_agent_settings(make_scoped_ptr(\n new net::StaticHttpUserAgentSettings(\"en-us,en\",\n xwalk::GetUserAgent())));\n\n scoped_ptr host_resolver(\n net::HostResolver::CreateDefaultResolver(NULL));\n\n storage_->set_cert_verifier(net::CertVerifier::CreateDefault());\n storage_->set_transport_security_state(\n make_scoped_ptr(new net::TransportSecurityState));\n#if defined(OS_ANDROID)\n \/\/ Android provides a local HTTP proxy that handles all the proxying.\n \/\/ Create the proxy without a resolver since we rely\n \/\/ on this local HTTP proxy.\n storage_->set_proxy_service(\n net::ProxyService::CreateWithoutProxyResolver(\n std::move(proxy_config_service_),\n NULL));\n#else\n storage_->set_proxy_service(\n net::ProxyService::CreateUsingSystemProxyResolver(\n std::move(proxy_config_service_),\n 0,\n NULL));\n#endif\n storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);\n storage_->set_http_auth_handler_factory(\n net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));\n storage_->set_http_server_properties(scoped_ptr(\n new net::HttpServerPropertiesImpl));\n\n base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL(\"Cache\"));\n scoped_ptr main_backend(\n new net::HttpCache::DefaultBackend(\n net::DISK_CACHE,\n net::CACHE_BACKEND_DEFAULT,\n cache_path,\n GetDiskCacheSize(),\n BrowserThread::GetMessageLoopProxyForThread(\n BrowserThread::CACHE)));\n\n net::HttpNetworkSession::Params network_session_params;\n network_session_params.cert_verifier =\n url_request_context_->cert_verifier();\n network_session_params.transport_security_state =\n url_request_context_->transport_security_state();\n network_session_params.channel_id_service =\n url_request_context_->channel_id_service();\n network_session_params.proxy_service =\n url_request_context_->proxy_service();\n network_session_params.ssl_config_service =\n url_request_context_->ssl_config_service();\n network_session_params.http_auth_handler_factory =\n url_request_context_->http_auth_handler_factory();\n network_session_params.network_delegate =\n network_delegate_.get();\n network_session_params.http_server_properties =\n url_request_context_->http_server_properties();\n network_session_params.ignore_certificate_errors =\n ignore_certificate_errors_;\n\n \/\/ Give |storage_| ownership at the end in case it's |mapped_host_resolver|.\n storage_->set_host_resolver(std::move(host_resolver));\n network_session_params.host_resolver =\n url_request_context_->host_resolver();\n\n storage_->set_http_network_session(\n make_scoped_ptr(new net::HttpNetworkSession(network_session_params)));\n storage_->set_http_transaction_factory(\n make_scoped_ptr(new net::HttpCache(storage_->http_network_session(),\n std::move(main_backend),\n false \/* set_up_quic_server_info *\/)));\n#if defined(OS_ANDROID)\n scoped_ptr job_factory_impl(\n new XWalkURLRequestJobFactory);\n#else\n scoped_ptr job_factory_impl(\n new net::URLRequestJobFactoryImpl);\n#endif\n\n bool set_protocol;\n\n \/\/ Step 1:\n \/\/ Install all the default schemes for crosswalk.\n for (content::ProtocolHandlerMap::iterator it =\n protocol_handlers_.begin();\n it != protocol_handlers_.end();\n ++it) {\n set_protocol = job_factory_impl->SetProtocolHandler(\n it->first, make_scoped_ptr(it->second.release()));\n DCHECK(set_protocol);\n }\n protocol_handlers_.clear();\n\n \/\/ Step 2:\n \/\/ Add new basic schemes.\n set_protocol = job_factory_impl->SetProtocolHandler(\n url::kDataScheme,\n make_scoped_ptr(new net::DataProtocolHandler));\n DCHECK(set_protocol);\n set_protocol = job_factory_impl->SetProtocolHandler(\n url::kFileScheme,\n make_scoped_ptr(new net::FileProtocolHandler(\n content::BrowserThread::GetBlockingPool()->\n GetTaskRunnerWithShutdownBehavior(\n base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));\n DCHECK(set_protocol);\n\n \/\/ Step 3:\n \/\/ Add the scheme interceptors.\n \/\/ in the order in which they appear in the |request_interceptors| vector.\n typedef std::vector\n URLRequestInterceptorVector;\n URLRequestInterceptorVector request_interceptors;\n\n#if defined(OS_ANDROID)\n request_interceptors.push_back(\n CreateContentSchemeRequestInterceptor().release());\n request_interceptors.push_back(\n CreateAssetFileRequestInterceptor().release());\n request_interceptors.push_back(\n CreateAppSchemeRequestInterceptor().release());\n \/\/ The XWalkRequestInterceptor must come after the content and asset\n \/\/ file job factories. This for WebViewClassic compatibility where it\n \/\/ was not possible to intercept resource loads to resolvable content:\/\/\n \/\/ and file:\/\/ URIs.\n \/\/ This logical dependency is also the reason why the Content\n \/\/ ProtocolHandler has to be added as a ProtocolInterceptJobFactory rather\n \/\/ than via SetProtocolHandler.\n request_interceptors.push_back(new XWalkRequestInterceptor());\n#endif\n\n \/\/ The chain of responsibility will execute the handlers in reverse to the\n \/\/ order in which the elements of the chain are created.\n scoped_ptr job_factory(\n std::move(job_factory_impl));\n for (URLRequestInterceptorVector::reverse_iterator\n i = request_interceptors.rbegin();\n i != request_interceptors.rend();\n ++i) {\n job_factory.reset(new net::URLRequestInterceptingJobFactory(\n std::move(job_factory), make_scoped_ptr(*i)));\n }\n\n \/\/ Set up interceptors in the reverse order.\n scoped_ptr top_job_factory =\n std::move(job_factory);\n for (content::URLRequestInterceptorScopedVector::reverse_iterator i =\n request_interceptors_.rbegin();\n i != request_interceptors_.rend();\n ++i) {\n top_job_factory.reset(new net::URLRequestInterceptingJobFactory(\n std::move(top_job_factory), make_scoped_ptr(*i)));\n }\n request_interceptors_.weak_clear();\n\n storage_->set_job_factory(std::move(top_job_factory));\n }\n\n return url_request_context_.get();\n}\n\nscoped_refptr\n RuntimeURLRequestContextGetter::GetNetworkTaskRunner() const {\n return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);\n}\n\nnet::HostResolver* RuntimeURLRequestContextGetter::host_resolver() {\n return url_request_context_->host_resolver();\n}\n\nvoid RuntimeURLRequestContextGetter::UpdateAcceptLanguages(\n const std::string& accept_languages) {\n if (!storage_)\n return;\n storage_->set_http_user_agent_settings(make_scoped_ptr(\n new net::StaticHttpUserAgentSettings(accept_languages,\n xwalk::GetUserAgent())));\n}\n\n} \/\/ namespace xwalk\n<|endoftext|>"} {"text":"INTEGRATION: CWS os8 (1.41.2.1.58); FILE MERGED 2003\/04\/03 07:10:58 os 1.41.2.1.58.1: #108583# precompiled headers removed<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/end2end\/end2end_tests.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \"src\/core\/lib\/debug\/stats.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"test\/core\/end2end\/cq_verifier.h\"\n\nstatic void* tag(intptr_t t) { return (void*)t; }\n\nstatic grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,\n const char* test_name,\n grpc_channel_args* client_args,\n grpc_channel_args* server_args) {\n grpc_end2end_test_fixture f;\n gpr_log(GPR_INFO, \"Running test: %s\/%s\", test_name, config.name);\n f = config.create_fixture(client_args, server_args);\n config.init_server(&f, server_args);\n config.init_client(&f, client_args);\n return f;\n}\n\nstatic gpr_timespec n_seconds_from_now(int n) {\n return grpc_timeout_seconds_to_deadline(n);\n}\n\nstatic gpr_timespec five_seconds_from_now(void) {\n return n_seconds_from_now(5);\n}\n\nstatic void drain_cq(grpc_completion_queue* cq) {\n grpc_event ev;\n do {\n ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);\n } while (ev.type != GRPC_QUEUE_SHUTDOWN);\n}\n\nstatic void shutdown_server(grpc_end2end_test_fixture* f) {\n if (!f->server) return;\n grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000));\n GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000),\n grpc_timeout_seconds_to_deadline(5),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_server_destroy(f->server);\n f->server = nullptr;\n}\n\nstatic void shutdown_client(grpc_end2end_test_fixture* f) {\n if (!f->client) return;\n grpc_channel_destroy(f->client);\n f->client = nullptr;\n}\n\nstatic void end_test(grpc_end2end_test_fixture* f) {\n shutdown_server(f);\n shutdown_client(f);\n\n grpc_completion_queue_shutdown(f->cq);\n drain_cq(f->cq);\n grpc_completion_queue_destroy(f->cq);\n grpc_completion_queue_destroy(f->shutdown_cq);\n}\n\nstatic void simple_request_body(grpc_end2end_test_config config,\n grpc_end2end_test_fixture f) {\n grpc_call* c;\n grpc_call* s;\n cq_verifier* cqv = cq_verifier_create(f.cq);\n grpc_op ops[6];\n grpc_op* op;\n grpc_metadata_array initial_metadata_recv;\n grpc_metadata_array trailing_metadata_recv;\n grpc_metadata_array request_metadata_recv;\n grpc_call_details call_details;\n grpc_status_code status;\n const char* error_string;\n grpc_call_error error;\n grpc_slice details;\n int was_cancelled = 2;\n char* peer;\n grpc_stats_data* before =\n static_cast(gpr_malloc(sizeof(grpc_stats_data)));\n grpc_stats_data* after =\n static_cast(gpr_malloc(sizeof(grpc_stats_data)));\n\n grpc_stats_collect(before);\n\n gpr_timespec deadline = five_seconds_from_now();\n c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,\n grpc_slice_from_static_string(\"\/foo\"), nullptr,\n deadline, nullptr);\n GPR_ASSERT(c);\n\n peer = grpc_call_get_peer(c);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"client_peer_before_call=%s\", peer);\n gpr_free(peer);\n\n grpc_metadata_array_init(&initial_metadata_recv);\n grpc_metadata_array_init(&trailing_metadata_recv);\n grpc_metadata_array_init(&request_metadata_recv);\n grpc_call_details_init(&call_details);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_INITIAL_METADATA;\n op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;\n op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;\n op->data.recv_status_on_client.status = &status;\n op->data.recv_status_on_client.status_details = &details;\n op->data.recv_status_on_client.error_string = &error_string;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(c, ops, static_cast(op - ops), tag(1),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n error =\n grpc_server_request_call(f.server, &s, &call_details,\n &request_metadata_recv, f.cq, f.cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), 1);\n cq_verify(cqv);\n\n peer = grpc_call_get_peer(s);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"server_peer=%s\", peer);\n gpr_free(peer);\n peer = grpc_call_get_peer(c);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"client_peer=%s\", peer);\n gpr_free(peer);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;\n op->data.send_status_from_server.trailing_metadata_count = 0;\n op->data.send_status_from_server.status = GRPC_STATUS_UNIMPLEMENTED;\n grpc_slice status_details = grpc_slice_from_static_string(\"xyz\");\n op->data.send_status_from_server.status_details = &status_details;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;\n op->data.recv_close_on_server.cancelled = &was_cancelled;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(s, ops, static_cast(op - ops), tag(102),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n CQ_EXPECT_COMPLETION(cqv, tag(102), 1);\n CQ_EXPECT_COMPLETION(cqv, tag(1), 1);\n cq_verify(cqv);\n\n GPR_ASSERT(status == GRPC_STATUS_UNIMPLEMENTED);\n GPR_ASSERT(0 == grpc_slice_str_cmp(details, \"xyz\"));\n \/\/ the following sanity check makes sure that the requested error string is\n \/\/ correctly populated by the core. It looks for certain substrings that are\n \/\/ not likely to change much. Some parts of the error, like time created,\n \/\/ obviously are not checked.\n GPR_ASSERT(nullptr != strstr(error_string, \"xyz\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"description\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"Error received from peer\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"grpc_message\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"grpc_status\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/foo\"));\n GPR_ASSERT(0 == call_details.flags);\n GPR_ASSERT(was_cancelled == 1);\n\n grpc_slice_unref(details);\n gpr_free((void*)error_string);\n grpc_metadata_array_destroy(&initial_metadata_recv);\n grpc_metadata_array_destroy(&trailing_metadata_recv);\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n\n grpc_call_unref(c);\n grpc_call_unref(s);\n\n cq_verifier_destroy(cqv);\n\n grpc_stats_collect(after);\n\n char* stats = grpc_stats_data_as_json(after);\n gpr_log(GPR_DEBUG, \"%s\", stats);\n gpr_free(stats);\n\n int expected_calls = 1;\n if (config.feature_mask & FEATURE_MASK_SUPPORTS_REQUEST_PROXYING) {\n expected_calls *= 2;\n }\n#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)\n GPR_ASSERT(after->counters[GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED] -\n before->counters[GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED] ==\n expected_calls);\n GPR_ASSERT(after->counters[GRPC_STATS_COUNTER_SERVER_CALLS_CREATED] -\n before->counters[GRPC_STATS_COUNTER_SERVER_CALLS_CREATED] ==\n expected_calls);\n#endif \/* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) *\/\n gpr_free(before);\n gpr_free(after);\n}\n\nstatic void test_invoke_simple_request(grpc_end2end_test_config config) {\n grpc_end2end_test_fixture f;\n\n f = begin_test(config, \"test_invoke_simple_request\", nullptr, nullptr);\n simple_request_body(config, f);\n end_test(&f);\n config.tear_down_data(&f);\n}\n\n\/\/ static void test_invoke_10_simple_requests(grpc_end2end_test_config config) {\n\/\/ int i;\n\/\/ grpc_end2end_test_fixture f =\n\/\/ begin_test(config, \"test_invoke_10_simple_requests\", nullptr, nullptr);\n\/\/ for (i = 0; i < 10; i++) {\n\/\/ simple_request_body(config, f);\n\/\/ gpr_log(GPR_INFO, \"Running test: Passed simple request %d\", i);\n\/\/ }\n\/\/ end_test(&f);\n\/\/ config.tear_down_data(&f);\n\/\/ }\n\nvoid simple_request(grpc_end2end_test_config config) {\n \/\/ int i;\n \/\/ for (i = 0; i < 10; i++) {\n test_invoke_simple_request(config);\n \/\/ }\n \/\/ test_invoke_10_simple_requests(config);\n}\n\nvoid simple_request_pre_init(void) {}\nUn-pare simple_request\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"test\/core\/end2end\/end2end_tests.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \"src\/core\/lib\/debug\/stats.h\"\n#include \"src\/core\/lib\/gpr\/string.h\"\n#include \"test\/core\/end2end\/cq_verifier.h\"\n\nstatic void* tag(intptr_t t) { return (void*)t; }\n\nstatic grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config,\n const char* test_name,\n grpc_channel_args* client_args,\n grpc_channel_args* server_args) {\n grpc_end2end_test_fixture f;\n gpr_log(GPR_INFO, \"Running test: %s\/%s\", test_name, config.name);\n f = config.create_fixture(client_args, server_args);\n config.init_server(&f, server_args);\n config.init_client(&f, client_args);\n return f;\n}\n\nstatic gpr_timespec n_seconds_from_now(int n) {\n return grpc_timeout_seconds_to_deadline(n);\n}\n\nstatic gpr_timespec five_seconds_from_now(void) {\n return n_seconds_from_now(5);\n}\n\nstatic void drain_cq(grpc_completion_queue* cq) {\n grpc_event ev;\n do {\n ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr);\n } while (ev.type != GRPC_QUEUE_SHUTDOWN);\n}\n\nstatic void shutdown_server(grpc_end2end_test_fixture* f) {\n if (!f->server) return;\n grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000));\n GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000),\n grpc_timeout_seconds_to_deadline(5),\n nullptr)\n .type == GRPC_OP_COMPLETE);\n grpc_server_destroy(f->server);\n f->server = nullptr;\n}\n\nstatic void shutdown_client(grpc_end2end_test_fixture* f) {\n if (!f->client) return;\n grpc_channel_destroy(f->client);\n f->client = nullptr;\n}\n\nstatic void end_test(grpc_end2end_test_fixture* f) {\n shutdown_server(f);\n shutdown_client(f);\n\n grpc_completion_queue_shutdown(f->cq);\n drain_cq(f->cq);\n grpc_completion_queue_destroy(f->cq);\n grpc_completion_queue_destroy(f->shutdown_cq);\n}\n\nstatic void simple_request_body(grpc_end2end_test_config config,\n grpc_end2end_test_fixture f) {\n grpc_call* c;\n grpc_call* s;\n cq_verifier* cqv = cq_verifier_create(f.cq);\n grpc_op ops[6];\n grpc_op* op;\n grpc_metadata_array initial_metadata_recv;\n grpc_metadata_array trailing_metadata_recv;\n grpc_metadata_array request_metadata_recv;\n grpc_call_details call_details;\n grpc_status_code status;\n const char* error_string;\n grpc_call_error error;\n grpc_slice details;\n int was_cancelled = 2;\n char* peer;\n grpc_stats_data* before =\n static_cast(gpr_malloc(sizeof(grpc_stats_data)));\n grpc_stats_data* after =\n static_cast(gpr_malloc(sizeof(grpc_stats_data)));\n\n grpc_stats_collect(before);\n\n gpr_timespec deadline = five_seconds_from_now();\n c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq,\n grpc_slice_from_static_string(\"\/foo\"), nullptr,\n deadline, nullptr);\n GPR_ASSERT(c);\n\n peer = grpc_call_get_peer(c);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"client_peer_before_call=%s\", peer);\n gpr_free(peer);\n\n grpc_metadata_array_init(&initial_metadata_recv);\n grpc_metadata_array_init(&trailing_metadata_recv);\n grpc_metadata_array_init(&request_metadata_recv);\n grpc_call_details_init(&call_details);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_INITIAL_METADATA;\n op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;\n op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;\n op->data.recv_status_on_client.status = &status;\n op->data.recv_status_on_client.status_details = &details;\n op->data.recv_status_on_client.error_string = &error_string;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(c, ops, static_cast(op - ops), tag(1),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n error =\n grpc_server_request_call(f.server, &s, &call_details,\n &request_metadata_recv, f.cq, f.cq, tag(101));\n GPR_ASSERT(GRPC_CALL_OK == error);\n CQ_EXPECT_COMPLETION(cqv, tag(101), 1);\n cq_verify(cqv);\n\n peer = grpc_call_get_peer(s);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"server_peer=%s\", peer);\n gpr_free(peer);\n peer = grpc_call_get_peer(c);\n GPR_ASSERT(peer != nullptr);\n gpr_log(GPR_DEBUG, \"client_peer=%s\", peer);\n gpr_free(peer);\n\n memset(ops, 0, sizeof(ops));\n op = ops;\n op->op = GRPC_OP_SEND_INITIAL_METADATA;\n op->data.send_initial_metadata.count = 0;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;\n op->data.send_status_from_server.trailing_metadata_count = 0;\n op->data.send_status_from_server.status = GRPC_STATUS_UNIMPLEMENTED;\n grpc_slice status_details = grpc_slice_from_static_string(\"xyz\");\n op->data.send_status_from_server.status_details = &status_details;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;\n op->data.recv_close_on_server.cancelled = &was_cancelled;\n op->flags = 0;\n op->reserved = nullptr;\n op++;\n error = grpc_call_start_batch(s, ops, static_cast(op - ops), tag(102),\n nullptr);\n GPR_ASSERT(GRPC_CALL_OK == error);\n\n CQ_EXPECT_COMPLETION(cqv, tag(102), 1);\n CQ_EXPECT_COMPLETION(cqv, tag(1), 1);\n cq_verify(cqv);\n\n GPR_ASSERT(status == GRPC_STATUS_UNIMPLEMENTED);\n GPR_ASSERT(0 == grpc_slice_str_cmp(details, \"xyz\"));\n \/\/ the following sanity check makes sure that the requested error string is\n \/\/ correctly populated by the core. It looks for certain substrings that are\n \/\/ not likely to change much. Some parts of the error, like time created,\n \/\/ obviously are not checked.\n GPR_ASSERT(nullptr != strstr(error_string, \"xyz\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"description\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"Error received from peer\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"grpc_message\"));\n GPR_ASSERT(nullptr != strstr(error_string, \"grpc_status\"));\n GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, \"\/foo\"));\n GPR_ASSERT(0 == call_details.flags);\n GPR_ASSERT(was_cancelled == 1);\n\n grpc_slice_unref(details);\n gpr_free((void*)error_string);\n grpc_metadata_array_destroy(&initial_metadata_recv);\n grpc_metadata_array_destroy(&trailing_metadata_recv);\n grpc_metadata_array_destroy(&request_metadata_recv);\n grpc_call_details_destroy(&call_details);\n\n grpc_call_unref(c);\n grpc_call_unref(s);\n\n cq_verifier_destroy(cqv);\n\n grpc_stats_collect(after);\n\n char* stats = grpc_stats_data_as_json(after);\n gpr_log(GPR_DEBUG, \"%s\", stats);\n gpr_free(stats);\n\n int expected_calls = 1;\n if (config.feature_mask & FEATURE_MASK_SUPPORTS_REQUEST_PROXYING) {\n expected_calls *= 2;\n }\n#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)\n GPR_ASSERT(after->counters[GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED] -\n before->counters[GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED] ==\n expected_calls);\n GPR_ASSERT(after->counters[GRPC_STATS_COUNTER_SERVER_CALLS_CREATED] -\n before->counters[GRPC_STATS_COUNTER_SERVER_CALLS_CREATED] ==\n expected_calls);\n#endif \/* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) *\/\n gpr_free(before);\n gpr_free(after);\n}\n\nstatic void test_invoke_simple_request(grpc_end2end_test_config config) {\n grpc_end2end_test_fixture f;\n\n f = begin_test(config, \"test_invoke_simple_request\", nullptr, nullptr);\n simple_request_body(config, f);\n end_test(&f);\n config.tear_down_data(&f);\n}\n\nstatic void test_invoke_10_simple_requests(grpc_end2end_test_config config) {\n int i;\n grpc_end2end_test_fixture f =\n begin_test(config, \"test_invoke_10_simple_requests\", nullptr, nullptr);\n for (i = 0; i < 10; i++) {\n simple_request_body(config, f);\n gpr_log(GPR_INFO, \"Running test: Passed simple request %d\", i);\n }\n end_test(&f);\n config.tear_down_data(&f);\n}\n\nvoid simple_request(grpc_end2end_test_config config) {\n int i;\n for (i = 0; i < 10; i++) {\n test_invoke_simple_request(config);\n }\n test_invoke_10_simple_requests(config);\n}\n\nvoid simple_request_pre_init(void) {}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: advisesink.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: mav $ $Date: 2003-12-09 12:52:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n\nOleWrapperAdviseSink::OleWrapperAdviseSink( OleComponent* pOleComp )\n: m_nRefCount( 0 )\n, m_pOleComp( pOleComp )\n{\n OSL_ENSURE( m_pOleComp, \"No ole component is provided!\\n\" );\n}\n\nOleWrapperAdviseSink::~OleWrapperAdviseSink()\n{\n}\n\nSTDMETHODIMP OleWrapperAdviseSink::QueryInterface( REFIID riid , void** ppv )\n{\n *ppv=NULL;\n\n if ( riid == IID_IUnknown )\n *ppv = (IUnknown*)this;\n\n if ( riid == IID_IAdviseSink )\n *ppv = (IAdviseSink*)this;\n\n if ( *ppv != NULL )\n {\n ((IUnknown*)*ppv)->AddRef();\n return S_OK;\n }\n\n return E_NOINTERFACE;\n}\n\nSTDMETHODIMP_(ULONG) OleWrapperAdviseSink::AddRef()\n{\n return osl_incrementInterlockedCount( &m_nRefCount);\n}\n\nSTDMETHODIMP_(ULONG) OleWrapperAdviseSink::Release()\n{\n ULONG nReturn = --m_nRefCount;\n if ( m_nRefCount == 0 )\n delete this;\n\n return nReturn;\n}\n\nvoid OleWrapperAdviseSink::disconnectOleComponent()\n{\n \/\/ must not be called from the descructor of OleComponent!!!\n osl::MutexGuard aGuard( m_aMutex );\n m_pOleComp = NULL;\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnDataChange(LPFORMATETC pFEIn, LPSTGMEDIUM pSTM)\n{\n \/\/ Unused for now ( no registration for IDataObject events )\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnViewChange(DWORD dwAspect, LONG lindex)\n{\n OleComponent* pLockComponent = NULL;\n\n {\n osl::MutexGuard aGuard( m_aMutex );\n if ( m_pOleComp )\n {\n pLockComponent = m_pOleComp;\n pLockComponent->acquire();\n }\n }\n\n if ( pLockComponent )\n {\n pLockComponent->OnViewChange_Impl( dwAspect );\n pLockComponent->release();\n }\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnRename(LPMONIKER pmk)\n{\n \/\/ handled by default inprocess handler\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnSave(void)\n{\n \/\/ TODO: ???\n \/\/ The object knows about document saving already since it contolls it as ClienSite\n \/\/ other interested listeners must be registered for the object\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnClose(void)\n{\n \/\/ mainly handled by inprocess handler\n\n \/\/ TODO: sometimes it can be necessary to simulate OnShowWindow( False ) here\n}\n\nINTEGRATION: CWS ooo19126 (1.2.114); FILE MERGED 2005\/09\/05 17:18:10 rt 1.2.114.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: advisesink.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:40:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n\nOleWrapperAdviseSink::OleWrapperAdviseSink( OleComponent* pOleComp )\n: m_nRefCount( 0 )\n, m_pOleComp( pOleComp )\n{\n OSL_ENSURE( m_pOleComp, \"No ole component is provided!\\n\" );\n}\n\nOleWrapperAdviseSink::~OleWrapperAdviseSink()\n{\n}\n\nSTDMETHODIMP OleWrapperAdviseSink::QueryInterface( REFIID riid , void** ppv )\n{\n *ppv=NULL;\n\n if ( riid == IID_IUnknown )\n *ppv = (IUnknown*)this;\n\n if ( riid == IID_IAdviseSink )\n *ppv = (IAdviseSink*)this;\n\n if ( *ppv != NULL )\n {\n ((IUnknown*)*ppv)->AddRef();\n return S_OK;\n }\n\n return E_NOINTERFACE;\n}\n\nSTDMETHODIMP_(ULONG) OleWrapperAdviseSink::AddRef()\n{\n return osl_incrementInterlockedCount( &m_nRefCount);\n}\n\nSTDMETHODIMP_(ULONG) OleWrapperAdviseSink::Release()\n{\n ULONG nReturn = --m_nRefCount;\n if ( m_nRefCount == 0 )\n delete this;\n\n return nReturn;\n}\n\nvoid OleWrapperAdviseSink::disconnectOleComponent()\n{\n \/\/ must not be called from the descructor of OleComponent!!!\n osl::MutexGuard aGuard( m_aMutex );\n m_pOleComp = NULL;\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnDataChange(LPFORMATETC pFEIn, LPSTGMEDIUM pSTM)\n{\n \/\/ Unused for now ( no registration for IDataObject events )\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnViewChange(DWORD dwAspect, LONG lindex)\n{\n OleComponent* pLockComponent = NULL;\n\n {\n osl::MutexGuard aGuard( m_aMutex );\n if ( m_pOleComp )\n {\n pLockComponent = m_pOleComp;\n pLockComponent->acquire();\n }\n }\n\n if ( pLockComponent )\n {\n pLockComponent->OnViewChange_Impl( dwAspect );\n pLockComponent->release();\n }\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnRename(LPMONIKER pmk)\n{\n \/\/ handled by default inprocess handler\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnSave(void)\n{\n \/\/ TODO: ???\n \/\/ The object knows about document saving already since it contolls it as ClienSite\n \/\/ other interested listeners must be registered for the object\n}\n\nSTDMETHODIMP_(void) OleWrapperAdviseSink::OnClose(void)\n{\n \/\/ mainly handled by inprocess handler\n\n \/\/ TODO: sometimes it can be necessary to simulate OnShowWindow( False ) here\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsFontProvider.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 06:21:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_VIEW_FONT_PROVIDER_HXX\n#define SD_SLIDESORTER_VIEW_FONT_PROVIDER_HXX\n\n#include \"tools\/SdGlobalResourceContainer.hxx\"\n\n#include \n#include \n\nclass Font;\nclass OutputDevice;\nclass VclWindowEvent;\n\nnamespace sd { namespace slidesorter { namespace view {\n\n\/** This simple singleton class provides fonts that are scaled so that they\n have a fixed height on the given device regardless of its map mode.\n*\/\nclass FontProvider\n : public SdGlobalResource\n{\npublic:\n typedef ::boost::shared_ptr SharedFontPointer;\n\n \/** Return the single instance of this class. Throws a RuntimeException\n when no instance can be created.\n *\/\n static FontProvider& Instance (void);\n\n \/** Return a font that is scaled according to the current map mode of\n the given device. Repeated calls with a device, not necessarily the\n same device, with the same map mode will return the same font. The\n first call with a different map mode will release the old font and\n create a new one that is correctly scaled.\n *\/\n SharedFontPointer GetFont (const OutputDevice& rDevice);\n\n \/** Call this method to tell an object to release its currently used\n font. The next call to GetFont() will then create a new one.\n Typically called after a DataChange event when for instance a system\n font has been modified.\n *\/\n void Invalidate (void);\n\nprivate:\n static FontProvider* mpInstance;\n\n \/** The font that was created by a previous call to GetFont(). It is\n replaced by another one only when GetFont() is called with a device\n with a different map mode or by a call to Invalidate().\n *\/\n SharedFontPointer maFont;\n \/** The mape mode for which maFont was created.\n *\/\n MapMode maMapMode;\n\n FontProvider (void);\n virtual ~FontProvider (void);\n\n \/\/ Copy constructor is not implemented.\n FontProvider (const FontProvider&);\n \/\/ Assignment operator is not implemented.\n FontProvider& operator= (const FontProvider&);\n};\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n#endif\nINTEGRATION: CWS changefileheader (1.3.624); FILE MERGED 2008\/03\/31 13:58:52 rt 1.3.624.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsFontProvider.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_VIEW_FONT_PROVIDER_HXX\n#define SD_SLIDESORTER_VIEW_FONT_PROVIDER_HXX\n\n#include \"tools\/SdGlobalResourceContainer.hxx\"\n\n#include \n#include \n\nclass Font;\nclass OutputDevice;\nclass VclWindowEvent;\n\nnamespace sd { namespace slidesorter { namespace view {\n\n\/** This simple singleton class provides fonts that are scaled so that they\n have a fixed height on the given device regardless of its map mode.\n*\/\nclass FontProvider\n : public SdGlobalResource\n{\npublic:\n typedef ::boost::shared_ptr SharedFontPointer;\n\n \/** Return the single instance of this class. Throws a RuntimeException\n when no instance can be created.\n *\/\n static FontProvider& Instance (void);\n\n \/** Return a font that is scaled according to the current map mode of\n the given device. Repeated calls with a device, not necessarily the\n same device, with the same map mode will return the same font. The\n first call with a different map mode will release the old font and\n create a new one that is correctly scaled.\n *\/\n SharedFontPointer GetFont (const OutputDevice& rDevice);\n\n \/** Call this method to tell an object to release its currently used\n font. The next call to GetFont() will then create a new one.\n Typically called after a DataChange event when for instance a system\n font has been modified.\n *\/\n void Invalidate (void);\n\nprivate:\n static FontProvider* mpInstance;\n\n \/** The font that was created by a previous call to GetFont(). It is\n replaced by another one only when GetFont() is called with a device\n with a different map mode or by a call to Invalidate().\n *\/\n SharedFontPointer maFont;\n \/** The mape mode for which maFont was created.\n *\/\n MapMode maMapMode;\n\n FontProvider (void);\n virtual ~FontProvider (void);\n\n \/\/ Copy constructor is not implemented.\n FontProvider (const FontProvider&);\n \/\/ Assignment operator is not implemented.\n FontProvider& operator= (const FontProvider&);\n};\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n#endif\n<|endoftext|>"} {"text":"#include \"TestApplication.h\"\n\nTestApplication::TestApplication(void)\n{\n}\n\nTestApplication::~TestApplication(void)\n{\n}\n\nvoid TestApplication::createCamera()\n{\n\tmCamera = mSceneMgr->createCamera(\"PlayerCam\");\n\n\tmCamera->setPosition(Ogre::Vector3(0, 300, 500));\n\tmCamera->lookAt(Ogre::Vector3(0, 0, 0));\n\tmCamera->setNearClipDistance(5);\n\n\tmCameraMan = new OgreBites::SdkCameraMan(mCamera);\n}\n\nvoid TestApplication::createViewports()\n{\n\tOgre::Viewport* vp = mWindow->addViewport(mCamera);\n\n\tvp->setBackgroundColour(Ogre::ColourValue(0, 0, 0));\n\n\tmCamera->setAspectRatio(\n\t\tOgre::Real(vp->getActualWidth()) \/\n\t\tOgre::Real(vp->getActualHeight()));\n\n}\n\nvoid TestApplication::createScene()\n{\n\tcreateLight();\n\tcreatePlane();\n\tcreateSphere();\n}\n\nvoid TestApplication::createPlane()\n{\n\t\/\/ Create ground\n\tOgre::Plane plane(Ogre::Vector3::UNIT_Y, 0);\n\n\tOgre::MeshManager::getSingleton().createPlane(\n\t\t\"ground\",\n\t\tOgre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n\t\tplane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);\n\n\tOgre::Entity* groundEntity = mSceneMgr->createEntity(\"ground\");\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);\n\n\tgroundEntity->setMaterialName(\"Examples\/Rockwall\");\n\tgroundEntity->setCastShadows(false);\n}\n\n\nvoid TestApplication::createLight()\n{\n\tmSceneMgr->setAmbientLight(Ogre::ColourValue::White);\n\tmSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);\n\n\t\/\/ Directional light\n\tOgre::Light* directionalLight = mSceneMgr->createLight(\"DirectionalLight\");\n\tdirectionalLight->setType(Ogre::Light::LT_DIRECTIONAL);\n\n\tdirectionalLight->setDiffuseColour(Ogre::ColourValue(.3, .3, .3));\n\tdirectionalLight->setSpecularColour(Ogre::ColourValue(.3, .3, .3));\n\n\tdirectionalLight->setDirection(Ogre::Vector3(0, -1, 1));\n}\n\nvoid TestApplication::createSphere()\n{\n\tOgre::Entity *sphereEntity = mSceneMgr->createEntity(\"Sphere\", \"sphere.mesh\");\n\tballNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(0, 100, 0));\n\tballNode->attachObject(sphereEntity);\n}\n\nbool iDown = false;\nbool jDown = false;\nbool kDown = false;\nbool lDown = false;\n\nbool TestApplication::keyPressed(const OIS::KeyEvent& ke)\n{\n\tswitch (ke.key)\n\t{\n\t\tcase OIS::KC_I:\n\t\t\tiDown = true;\n\t\t\tbreak;\n\t\tcase OIS::KC_J:\n\t\t\tjDown = true;\n\t\t\tbreak;\n\t\tcase OIS::KC_K:\n\t\t\tkDown = true;\n\t\t\tbreak;\n\t\tcase OIS::KC_L:\n\t\t\tlDown = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn BaseApplication::keyPressed(ke);\n}\n\nbool TestApplication::keyReleased(const OIS::KeyEvent& ke)\n{\n\tswitch (ke.key)\n\t{\n\tcase OIS::KC_I:\n\t\tiDown = false;\n\t\tbreak;\n\tcase OIS::KC_J:\n\t\tjDown = false;\n\t\tbreak;\n\tcase OIS::KC_K:\n\t\tkDown = false;\n\t\tbreak;\n\tcase OIS::KC_L:\n\t\tlDown = false;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn BaseApplication::keyReleased(ke);\n}\n\n\nbool TestApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)\n{\n\tOgre::Vector3 movePos = Ogre::Vector3(0, 0, 0);\n\tif (iDown)\n\t{\n\t\tmovePos.z = -0.1f;\n\t}\n\tif (jDown)\n\t{\n\t\tmovePos.x = -0.1f;\n\t}\n\tif (kDown)\n\t{\n\t\tmovePos.z = 0.1f;\n\t}\n\tif (lDown)\n\t{\n\t\tmovePos.x = 0.1f;\n\t}\n\n\tOgre::Vector3 currPos = ballNode->getPosition();\n\n\tOgre::Vector3 newPos = currPos + movePos;\n\tballNode->setPosition(newPos);\n\n\treturn BaseApplication::frameRenderingQueued(evt);\n}\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n#define WIN32_LEAN_AND_MEAN\n#include \"windows.h\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\tINT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)\n#else\n\tint main(int argc, char *argv[])\n#endif\n\t{\n\t\t\/\/ Create application object\n\t\tTestApplication app;\n\n\t\ttry {\n\t\t\tapp.go();\n\t\t}\n\t\tcatch (Ogre::Exception& e) {\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\t\t\tMessageBox(NULL, e.getFullDescription().c_str(), \"An exception has occured!\", MB_OK | MB_ICONERROR | MB_TASKMODAL);\n#else\n\t\t\tstd::cerr << \"An exception has occured: \" <<\n\t\t\t\te.getFullDescription().c_str() << std::endl;\n#endif\n\t\t}\n\n\t\treturn 0;\n\t}\n\n#ifdef __cplusplus\n}\n#endifMake movement speed constant, not fps dependant#include \"TestApplication.h\"\nconst float moveSpeed = 100;\n\nTestApplication::TestApplication(void)\n{\n}\n\nTestApplication::~TestApplication(void)\n{\n}\n\nvoid TestApplication::createCamera()\n{\n\tmCamera = mSceneMgr->createCamera(\"PlayerCam\");\n\n\tmCamera->setPosition(Ogre::Vector3(0, 300, 500));\n\tmCamera->lookAt(Ogre::Vector3(0, 0, 0));\n\tmCamera->setNearClipDistance(5);\n\n\tmCameraMan = new OgreBites::SdkCameraMan(mCamera);\n}\n\nvoid TestApplication::createViewports()\n{\n\tOgre::Viewport* vp = mWindow->addViewport(mCamera);\n\n\tvp->setBackgroundColour(Ogre::ColourValue(0, 0, 0));\n\n\tmCamera->setAspectRatio(\n\t\tOgre::Real(vp->getActualWidth()) \/\n\t\tOgre::Real(vp->getActualHeight()));\n\n}\n\nvoid TestApplication::createScene()\n{\n\tcreateLight();\n\tcreatePlane();\n\tcreateSphere();\n}\n\nvoid TestApplication::createPlane()\n{\n\t\/\/ Create ground\n\tOgre::Plane plane(Ogre::Vector3::UNIT_Y, 0);\n\n\tOgre::MeshManager::getSingleton().createPlane(\n\t\t\"ground\",\n\t\tOgre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n\t\tplane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);\n\n\tOgre::Entity* groundEntity = mSceneMgr->createEntity(\"ground\");\n\tmSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity);\n\n\tgroundEntity->setMaterialName(\"Examples\/Rockwall\");\n\tgroundEntity->setCastShadows(false);\n}\n\n\nvoid TestApplication::createLight()\n{\n\tmSceneMgr->setAmbientLight(Ogre::ColourValue::White);\n\tmSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);\n\n\t\/\/ Directional light\n\tOgre::Light* directionalLight = mSceneMgr->createLight(\"DirectionalLight\");\n\tdirectionalLight->setType(Ogre::Light::LT_DIRECTIONAL);\n\n\tdirectionalLight->setDiffuseColour(Ogre::ColourValue(.3, .3, .3));\n\tdirectionalLight->setSpecularColour(Ogre::ColourValue(.3, .3, .3));\n\n\tdirectionalLight->setDirection(Ogre::Vector3(0, -1, 1));\n}\n\nvoid TestApplication::createSphere()\n{\n\tOgre::Entity *sphereEntity = mSceneMgr->createEntity(\"Sphere\", \"sphere.mesh\");\n\tballNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(0, 100, 0));\n\tballNode->attachObject(sphereEntity);\n}\n\nbool iDown = false;\nbool jDown = false;\nbool kDown = false;\nbool lDown = false;\n\nbool TestApplication::keyPressed(const OIS::KeyEvent& ke)\n{\n\tswitch (ke.key)\n\t{\n\t\tcase OIS::KC_I:\n\t\t\tiDown = true;\n\t\t\tbreak;\n\t\tcase OIS::KC_J:\n\t\t\tjDown = true;\n\t\t\tbreak;\n\t\tcase OIS::KC_K:\n\t\t\tkDown = true;\n\t\t\tbreak;\n\t\tcase OIS::KC_L:\n\t\t\tlDown = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\treturn BaseApplication::keyPressed(ke);\n}\n\nbool TestApplication::keyReleased(const OIS::KeyEvent& ke)\n{\n\tswitch (ke.key)\n\t{\n\tcase OIS::KC_I:\n\t\tiDown = false;\n\t\tbreak;\n\tcase OIS::KC_J:\n\t\tjDown = false;\n\t\tbreak;\n\tcase OIS::KC_K:\n\t\tkDown = false;\n\t\tbreak;\n\tcase OIS::KC_L:\n\t\tlDown = false;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn BaseApplication::keyReleased(ke);\n}\n\n\nbool TestApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)\n{\n\tOgre::Vector3 movePos = Ogre::Vector3(0, 0, 0);\n\tif (iDown)\n\t{\n\t\tmovePos.z = -moveSpeed;\n\t}\n\tif (jDown)\n\t{\n\t\tmovePos.x = -moveSpeed;\n\t}\n\tif (kDown)\n\t{\n\t\tmovePos.z = moveSpeed;\n\t}\n\tif (lDown)\n\t{\n\t\tmovePos.x = moveSpeed;\n\t}\n\n\tballNode->translate(movePos * evt.timeSinceLastFrame, Ogre::Node::TS_LOCAL);\n\t\/\/ Ogre::Vector3 currPos = ballNode->getPosition();\n\n\t\/\/ Ogre::Vector3 newPos = currPos + movePos;\n\t\/\/ ballNode->setPosition(newPos);\n\n\treturn BaseApplication::frameRenderingQueued(evt);\n}\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n#define WIN32_LEAN_AND_MEAN\n#include \"windows.h\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\tINT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT)\n#else\n\tint main(int argc, char *argv[])\n#endif\n\t{\n\t\t\/\/ Create application object\n\t\tTestApplication app;\n\n\t\ttry {\n\t\t\tapp.go();\n\t\t}\n\t\tcatch (Ogre::Exception& e) {\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\t\t\tMessageBox(NULL, e.getFullDescription().c_str(), \"An exception has occured!\", MB_OK | MB_ICONERROR | MB_TASKMODAL);\n#else\n\t\t\tstd::cerr << \"An exception has occured: \" <<\n\t\t\t\te.getFullDescription().c_str() << std::endl;\n#endif\n\t\t}\n\n\t\treturn 0;\n\t}\n\n#ifdef __cplusplus\n}\n#endif<|endoftext|>"} {"text":"\/\/ Copyright the project authors as listed in the AUTHORS file.\n\/\/ All rights reserved. Use of this source code is governed by the\n\/\/ license that can be found in the LICENSE file.\n#include \n#include \n#include \n#include \n\/\/#include \n#include \n\n\/\/ device specifics\n#include \"WirelessConfig.h\"\n#include \"MqttScale.h\"\n\n#define TRANSMIT_INTERVAL_SECONDS 5\n#define MILLIS_IN_SECOND 1000\n#define LOOP_DELAY 100\n\n#define MAX_MESSAGE_SIZE 100\n\nHX711 scale;\n\nvoid callback(char* topic, uint8_t* message, unsigned int length) {\n if (strcmp(topic, SCALE_TARE_TOPIC) == 0) {\n scale.tare();\n }\n}\n\nESP8266WiFiGenericClass wifi;\n\n#ifdef USE_CERTS\n\/\/ if certs are used the following must be defined in WirelessConfig.h\n\/\/ unsigned char client_cert[] PROGMEM = {bytes in DER format};\n\/\/ unsigned int client_cert_len = 918;\n\/\/ unsigned char client_key[] PROGMEM = {bytes in DER format};\n\/\/ unsigned int client_key_len = 1193;\n\/\/\n\/\/ conversion can be done using\n\/\/ openssl x509 -in cert -out client.cert -outform DER\n\/\/ openssl rsa -in key -out client.key -outform DER\n\/\/ and then using xxd to generate the required array and lengths\n\/\/ see https:\/\/nofurtherquestions.wordpress.com\/2016\/03\/14\/making-an-esp8266-web-accessible\/\n\/\/ for more detailed info\nWiFiClientSecure wclient;\n#else\nWiFiClient wclient;\n#endif\n\nPubSubClient client(mqttServerString, mqttServerPort, callback, wclient);\n\nint counter = 0;\nchar macAddress[] = \"00:00:00:00:00:00\";\n\n\/\/ scale parameters \nint SCALE_DOUT = D2;\nint SCALE_SCK = D3;\nint SCALE_READINGS = 20;\nint BUTTON_PIN = D5;\nunsigned int MIN_BUTTON_TIME_MICROS = 250000;\n\nICACHE_RAM_ATTR void handleButton() {\n static unsigned long lastInterruptTime = 0;\n\n long timeMicros = micros();\n if (digitalRead(BUTTON_PIN) == LOW) {\n \/\/ get the duration of the button press and only accept as button\n \/\/ press if it is long enough that we know it is not noise.\n unsigned long duration = timeMicros - lastInterruptTime;\n if (duration > MIN_BUTTON_TIME_MICROS) {\n scale.tare();\n }\n }\n\n lastInterruptTime = timeMicros;\n}\n\nvoid setup() {\n delay(1000);\n\n \/\/ Setup console\n Serial.begin(115200);\n delay(10);\n Serial.println();\n Serial.println(\"Started\");\n\n \/\/ setup the scale\n scale.begin(SCALE_DOUT, SCALE_SCK);\n scale.set_scale(SCALE_MULTIPLIER);\n scale.set_offset(0);\n\n pinMode(BUTTON_PIN, INPUT_PULLUP);\n attachInterrupt(digitalPinToInterrupt(BUTTON_PIN),&handleButton,CHANGE);\n\n#ifdef USE_CERTS\n wclient.setCertificate_P(client_cert, client_cert_len);\n wclient.setPrivateKey_P(client_key, client_key_len);\n#endif\n\n \/\/ turn of the Access Point as we are not using it\n wifi.mode(WIFI_STA);\n WiFi.begin(ssid, pass);\n\n \/\/ get the mac address to be used as a unique id for connecting to the mqtt server\n byte macRaw[6];\n WiFi.macAddress(macRaw);\n sprintf(macAddress,\n \"%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X\",\n macRaw[0],\n macRaw[1],\n macRaw[2],\n macRaw[3],\n macRaw[4],\n macRaw[5]);\n}\n\nvoid loop() {\n client.loop();\n delay(LOOP_DELAY);\n\n \/\/ make sure we are good for wifi\n if (WiFi.status() != WL_CONNECTED) {\n Serial.print(\"Connecting to \");\n Serial.println(ssid);\n WiFi.reconnect();\n\n if (WiFi.waitForConnectResult() != WL_CONNECTED) {\n Serial.println(\"Failed to reconnect WIFI\");\n Serial.println(WiFi.waitForConnectResult());\n delay(1000);\n return;\n }\n }\n\n \n if (!client.connected()) {\n if (client.connect(macAddress)) {\n Serial.println(\"mqtt connected:\");\n Serial.println(macAddress);\n Serial.println(\"\\n\");\n client.subscribe(SCALE_TARE_TOPIC);\n }\n scale.tare();\n }\n\n counter++;\n if (counter == (TRANSMIT_INTERVAL_SECONDS * (MILLIS_IN_SECOND\/LOOP_DELAY))) {\n Serial.println(\"Sending\");\n\n char tempMessage[MAX_MESSAGE_SIZE];\n char floatBuffer[10];\n Serial.println(scale.get_units(SCALE_READINGS), 2);\n float currentWeight = scale.get_units(SCALE_READINGS);\n snprintf(tempMessage, MAX_MESSAGE_SIZE, \"%s\",\n dtostrf(currentWeight, 4, 2, floatBuffer));\n client.publish(SCALE_TOPIC, tempMessage);\n\n counter = 0;\n }\n}src: round to nearest g\/\/ Copyright the project authors as listed in the AUTHORS file.\n\/\/ All rights reserved. Use of this source code is governed by the\n\/\/ license that can be found in the LICENSE file.\n#include \n#include \n#include \n#include \n\/\/#include \n#include \n\n\/\/ device specifics\n#include \"WirelessConfig.h\"\n#include \"MqttScale.h\"\n\n#define TRANSMIT_INTERVAL_SECONDS 5\n#define MILLIS_IN_SECOND 1000\n#define LOOP_DELAY 100\n\n#define MAX_MESSAGE_SIZE 100\n\nHX711 scale;\n\nvoid callback(char* topic, uint8_t* message, unsigned int length) {\n if (strcmp(topic, SCALE_TARE_TOPIC) == 0) {\n scale.tare();\n }\n}\n\nESP8266WiFiGenericClass wifi;\n\n#ifdef USE_CERTS\n\/\/ if certs are used the following must be defined in WirelessConfig.h\n\/\/ unsigned char client_cert[] PROGMEM = {bytes in DER format};\n\/\/ unsigned int client_cert_len = 918;\n\/\/ unsigned char client_key[] PROGMEM = {bytes in DER format};\n\/\/ unsigned int client_key_len = 1193;\n\/\/\n\/\/ conversion can be done using\n\/\/ openssl x509 -in cert -out client.cert -outform DER\n\/\/ openssl rsa -in key -out client.key -outform DER\n\/\/ and then using xxd to generate the required array and lengths\n\/\/ see https:\/\/nofurtherquestions.wordpress.com\/2016\/03\/14\/making-an-esp8266-web-accessible\/\n\/\/ for more detailed info\nWiFiClientSecure wclient;\n#else\nWiFiClient wclient;\n#endif\n\nPubSubClient client(mqttServerString, mqttServerPort, callback, wclient);\n\nint counter = 0;\nchar macAddress[] = \"00:00:00:00:00:00\";\n\n\/\/ scale parameters \nint SCALE_DOUT = D2;\nint SCALE_SCK = D3;\nint SCALE_READINGS = 20;\nint BUTTON_PIN = D5;\nunsigned int MIN_BUTTON_TIME_MICROS = 250000;\n\nICACHE_RAM_ATTR void handleButton() {\n static unsigned long lastInterruptTime = 0;\n\n long timeMicros = micros();\n if (digitalRead(BUTTON_PIN) == LOW) {\n \/\/ get the duration of the button press and only accept as button\n \/\/ press if it is long enough that we know it is not noise.\n unsigned long duration = timeMicros - lastInterruptTime;\n if (duration > MIN_BUTTON_TIME_MICROS) {\n scale.tare();\n }\n }\n\n lastInterruptTime = timeMicros;\n}\n\nvoid setup() {\n delay(1000);\n\n \/\/ Setup console\n Serial.begin(115200);\n delay(10);\n Serial.println();\n Serial.println(\"Started\");\n\n \/\/ setup the scale\n scale.begin(SCALE_DOUT, SCALE_SCK);\n scale.set_scale(SCALE_MULTIPLIER);\n scale.set_offset(0);\n\n pinMode(BUTTON_PIN, INPUT_PULLUP);\n attachInterrupt(digitalPinToInterrupt(BUTTON_PIN),&handleButton,CHANGE);\n\n#ifdef USE_CERTS\n wclient.setCertificate_P(client_cert, client_cert_len);\n wclient.setPrivateKey_P(client_key, client_key_len);\n#endif\n\n \/\/ turn of the Access Point as we are not using it\n wifi.mode(WIFI_STA);\n WiFi.begin(ssid, pass);\n\n \/\/ get the mac address to be used as a unique id for connecting to the mqtt server\n byte macRaw[6];\n WiFi.macAddress(macRaw);\n sprintf(macAddress,\n \"%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X\",\n macRaw[0],\n macRaw[1],\n macRaw[2],\n macRaw[3],\n macRaw[4],\n macRaw[5]);\n}\n\nvoid loop() {\n client.loop();\n delay(LOOP_DELAY);\n\n \/\/ make sure we are good for wifi\n if (WiFi.status() != WL_CONNECTED) {\n Serial.print(\"Connecting to \");\n Serial.println(ssid);\n WiFi.reconnect();\n\n if (WiFi.waitForConnectResult() != WL_CONNECTED) {\n Serial.println(\"Failed to reconnect WIFI\");\n Serial.println(WiFi.waitForConnectResult());\n delay(1000);\n return;\n }\n }\n\n \n if (!client.connected()) {\n if (client.connect(macAddress)) {\n Serial.println(\"mqtt connected:\");\n Serial.println(macAddress);\n Serial.println(\"\\n\");\n client.subscribe(SCALE_TARE_TOPIC);\n }\n scale.tare();\n }\n\n counter++;\n if (counter == (TRANSMIT_INTERVAL_SECONDS * (MILLIS_IN_SECOND\/LOOP_DELAY))) {\n Serial.println(\"Sending\");\n\n char tempMessage[MAX_MESSAGE_SIZE];\n char floatBuffer[10];\n Serial.println(scale.get_units(SCALE_READINGS), 2);\n float currentWeight = round(scale.get_units(SCALE_READINGS));\n snprintf(tempMessage, MAX_MESSAGE_SIZE, \"%s\",\n dtostrf(currentWeight, 4, 0, floatBuffer));\n client.publish(SCALE_TOPIC, tempMessage);\n\n counter = 0;\n }\n}<|endoftext|>"} {"text":"#ifndef PILA_MAX\n#define PILA_MAX\n\n#include \"vector_dinamico.hpp\"\n\ntemplate \nclass PilaMax{\n private:\n struct Elemento{\n T elem;\n T max;\n\n Elemento(){}\n Elemento(T e, T m): elem(e), max(m){}\n };\n\n VectorDinamico datos;\n\n public:\n \/*\n Constructores, destructores y op asignacion\n *\/\n PilaMax(){}\n PilaMax(const PilaMax& p):datos(p.datos){}\n \/\/~PilaMax();\n PilaMax& operator=(const PilaMax& p){datos = p.datos;}\n\n \/*\n Metodos propios de una pila\n *\/\n\n bool vacia() const{return datos.vacia();}\n void poner(const T& t_elem);\n void quitar(){datos.popback();}\n T tope() const{return datos.getLast().elem;}\n T max() const{return datos.getLast().max;}\n};\n\n#include \"..\/src\/Pila_max_VD.cpp\"\n\n\n#endif\nUpdate Pila_max_VD.hpp\/**\n * @file Pila_max_VD.h\n * @brief Fichero cabecera del TDA Pila_max_VD\n *\n *\/#ifndef PILA_MAX\n#define PILA_MAX\n\n#include \"vector_dinamico.hpp\"\n\/**\n * @brief T.D.A. Pila_mx_VD\n *\n * Una instancia @e c del tipo de datos abstracto @c Pila_max_VD es un objeto\n * para agrupar datos de tipo Elemento en una Pila, compuesto Elemento por dos \n * objetos: elem y max,ambos de tipo T. La clase está compuesta por uN vector dinamico\n * de Elementos.\n *\n * @author J. Capote, G. Galindo y C. de la Torre\n * @date Noviembre 2016\n *\/\ntemplate \nclass PilaMax{\n private:\n \/**\n * @page repConjunto Rep del TDA Pila_max_VD\n *\n * @section faConjunto Funci�n de abstracci�n\n *\n * Un objeto v�lido @e rep del TDA Pila_max_VD representa\n *\n * A un conjunto de Elementos agrupados en una vector dinamico\n *\n *\/\n struct Elemento{\n T elem;\n T max;\n \/**\n * @brief Constructor por defecto de Elemento. Crea el elemento\n * con elem=0 y max=0.\n *\/\n Elemento(){}\n \/**\n * @brief Constructor de Elemento. Crea el elemento con elem=e y\n * max=m.\n * @param e dato de tipo T que da el valor de elem\n * @param m dato de tipo T que da el valor de max\n *\/\n Elemento(T e, T m): elem(e), max(m){}\n };\/**< Elemento *\/\n\n VectorDinamico datos;\/** vectos dinamico de Elementos *\/\n\n public:\n \/**\n * @brief Constructor por defecto de la clase. Crea el vectordinamico vacío.\n *\/\n PilaMax(){}\n \/**\n * @brief Constructor copia de la clase. \n * @param p objeto a copiar\n *\/\n PilaMax(const PilaMax& p):datos(p.datos){}\n \/**\n * @brief Operador de asignacion.\n * @param p objeto a asignar.\n *\/\n PilaMax& operator=(const PilaMax& p){datos = p.datos;}\n \/**\n * @brief Comprueba si la pila está vacía\n * @return bool verdadero si está vacía y falso si no lo está.\n *\/\n bool vacia() const{return datos.vacia();}\n \/**\n * @brief Añade un nuevo elemento al vector dinamico de la pila\n * @param t_elem valor del nuevo elemento a añadir\n *\/\n void poner(const T& t_elem);\n \/**\n * @brief Elimina el útimo elemento de la pila\n *\/\n void quitar(){datos.popback();}\n \/**\n * @brief Devolver el tope de la pila\n * @return devuelve el valor del último elemento introducido en la pila\n *\/\n T tope() const{return datos.getLast().elem;}\n \/**\n * @brief Devolver el valor maximo de los elementos de la pila\n * @return devuelve el valor del maximo elemento de toda la pila\n *\/\n T max() const{return datos.getLast().max;}\n};\n\n#include \"..\/src\/Pila_max_VD.cpp\"\n\n\n#endif\n<|endoftext|>"} {"text":"File should not have been committed<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Native Client Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"native_client\/src\/include\/nacl_macros.h\"\n#include \"native_client\/src\/shared\/ppapi_proxy\/browser_callback.h\"\n#include \"native_client\/src\/shared\/ppapi_proxy\/browser_globals.h\"\n#include \"native_client\/src\/shared\/ppapi_proxy\/utility.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/pp_file_info.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/pp_completion_callback.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/pp_errors.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/ppb_file_io.h\"\n#include \"srpcgen\/ppb_rpc.h\"\n\nusing ppapi_proxy::DebugPrintf;\nusing ppapi_proxy::DeleteRemoteCallbackInfo;\nusing ppapi_proxy::MakeRemoteCompletionCallback;\nusing ppapi_proxy::PPBFileIOInterface;\n\nvoid PpbFileIORpcServer::PPB_FileIO_Create(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ input\n PP_Instance instance,\n \/\/ output\n PP_Resource* resource) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_OK;\n\n *resource = PPBFileIOInterface()->Create(instance);\n DebugPrintf(\"PPB_FileIO::Create: resource=%\"NACL_PRIu32\"\\n\", *resource);\n}\n\n\/\/ TODO(sanga): Use a caching resource tracker instead of going over the proxy\n\/\/ to determine if the given resource is a file io.\nvoid PpbFileIORpcServer::PPB_FileIO_IsFileIO(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ inputs\n PP_Resource resource,\n \/\/ output\n int32_t* success) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_OK;\n\n PP_Bool pp_success = PPBFileIOInterface()->IsFileIO(resource);\n DebugPrintf(\"PPB_FileIO::IsFileIO: pp_success=%d\\n\", pp_success);\n\n *success = (pp_success == PP_TRUE);\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Open(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ inputs\n PP_Resource file_io,\n PP_Resource file_ref,\n int32_t open_flags,\n int32_t callback_id,\n \/\/ output\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback =\n MakeRemoteCompletionCallback(rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->Open(\n file_io,\n file_ref,\n open_flags,\n remote_callback);\n DebugPrintf(\"PPB_FileIO::Open: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n\n if (*pp_error != PP_OK_COMPLETIONPENDING) \/\/ Async error.\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nnamespace {\n\nbool IsResultPP_OK(int32_t result) {\n return (result == PP_OK);\n}\n\nnacl_abi_size_t SizeOfPP_FileInfo(int32_t \/*query_callback_result*\/) {\n return sizeof(PP_FileInfo);\n}\n\n} \/\/ namespace\n\nvoid PpbFileIORpcServer::PPB_FileIO_Query(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int32_t bytes_to_read,\n int32_t callback_id,\n nacl_abi_size_t* info_bytes, char* info,\n int32_t* pp_error) {\n \/\/ Since PPB_FileIO::Query does not complete synchronously, and we use remote\n \/\/ completion callback with completion callback table on the untrusted side\n \/\/ (see browser_callback.h and plugin_callback.h), so the actual file info\n \/\/ parameter is not used.\n UNREFERENCED_PARAMETER(info);\n\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n \/\/ TODO(sanga): Drop bytes_to_read for parameters since it is not part of the\n \/\/ interface, and just use the buffer size itself.\n CHECK(bytes_to_read == sizeof(PP_FileInfo));\n char* callback_buffer = NULL;\n PP_CompletionCallback remote_callback =\n MakeRemoteCompletionCallback(rpc->channel, callback_id, bytes_to_read,\n &callback_buffer, IsResultPP_OK,\n SizeOfPP_FileInfo);\n if (NULL == remote_callback.func)\n return;\n\n \/\/ callback_buffer has been assigned to a buffer on the heap, the size\n \/\/ of PP_FileInfo.\n PP_FileInfo* file_info = reinterpret_cast(callback_buffer);\n *pp_error = PPBFileIOInterface()->Query(file_io, file_info, remote_callback);\n DebugPrintf(\"PPB_FileIO::Query: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ Query should not complete synchronously\n\n *info_bytes = 0;\n if (*pp_error != PP_OK_COMPLETIONPENDING) {\n DeleteRemoteCallbackInfo(remote_callback);\n }\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Touch(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n double last_access_time,\n double last_modified_time,\n int32_t callback_id,\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel,\n callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->Touch(file_io, last_access_time,\n last_modified_time, remote_callback);\n DebugPrintf(\"PPB_FileIO::Touch: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ Touch should not complete synchronously\n\n if (*pp_error != PP_OK_COMPLETIONPENDING)\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Read(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ inputs\n PP_Resource file_io,\n int64_t offset,\n int32_t bytes_to_read,\n int32_t callback_id,\n \/\/ outputs\n nacl_abi_size_t* buffer_size,\n char* buffer,\n int32_t* pp_error_or_bytes) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n CHECK(*buffer_size == static_cast(bytes_to_read));\n\n char* callback_buffer = NULL;\n PP_CompletionCallback remote_callback =\n MakeRemoteCompletionCallback(rpc->channel, callback_id, bytes_to_read,\n &callback_buffer);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error_or_bytes = PPBFileIOInterface()->Read(\n file_io,\n offset,\n callback_buffer,\n bytes_to_read,\n remote_callback);\n DebugPrintf(\"PPB_FileIO::Read: pp_error_or_bytes=%\"NACL_PRId32\"\\n\",\n *pp_error_or_bytes);\n CHECK(*pp_error_or_bytes <= bytes_to_read);\n\n if (*pp_error_or_bytes > 0) { \/\/ Bytes read into |callback_buffer|.\n \/\/ No callback scheduled.\n *buffer_size = static_cast(*pp_error_or_bytes);\n memcpy(buffer, callback_buffer, *buffer_size);\n DeleteRemoteCallbackInfo(remote_callback);\n } else if (*pp_error_or_bytes != PP_OK_COMPLETIONPENDING) { \/\/ Async error.\n \/\/ No callback scheduled.\n *buffer_size = 0;\n DeleteRemoteCallbackInfo(remote_callback);\n } else {\n \/\/ Callback scheduled.\n *buffer_size = 0;\n }\n\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Write(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int64_t offset,\n nacl_abi_size_t buffer_bytes, char* buffer,\n int32_t bytes_to_write,\n int32_t callback_id,\n int32_t* pp_error_or_bytes) {\n \/\/ TODO(sanga): Add comments for the parameters.\n UNREFERENCED_PARAMETER(buffer_bytes);\n\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error_or_bytes = PPBFileIOInterface()->Write(file_io, offset, buffer,\n bytes_to_write,\n remote_callback);\n DebugPrintf(\"PPB_FileIO::Write: pp_error_or_bytes=%\"NACL_PRId32\"\\n\",\n *pp_error_or_bytes);\n\n \/\/ Bytes must be written asynchronously.\n if (*pp_error_or_bytes != PP_OK_COMPLETIONPENDING) {\n DeleteRemoteCallbackInfo(remote_callback);\n }\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_SetLength(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int64_t length,\n int32_t callback_id,\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->SetLength(file_io, length, remote_callback);\n DebugPrintf(\"PPB_FileIO::SetLength: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ SetLength should not complete synchronously\n\n if (*pp_error != PP_OK_COMPLETIONPENDING)\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Flush(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int32_t callback_id,\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->Flush(file_io, remote_callback);\n DebugPrintf(\"PPB_FileIO::Flush: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ Flush should not complete synchronously\n\n if (*pp_error != PP_OK_COMPLETIONPENDING)\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Close(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_OK;\n DebugPrintf(\"PPB_FileIO::Close: file_io=%\"NACL_PRIu32\"\\n\", file_io);\n PPBFileIOInterface()->Close(file_io);\n}\nAdding a check for the number of bytes to write against the buffer size for PPB_FileIO_Write.\/\/ Copyright (c) 2011 The Native Client Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \"native_client\/src\/include\/nacl_macros.h\"\n#include \"native_client\/src\/shared\/ppapi_proxy\/browser_callback.h\"\n#include \"native_client\/src\/shared\/ppapi_proxy\/browser_globals.h\"\n#include \"native_client\/src\/shared\/ppapi_proxy\/utility.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/pp_file_info.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/pp_completion_callback.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/pp_errors.h\"\n#include \"native_client\/src\/third_party\/ppapi\/c\/ppb_file_io.h\"\n#include \"srpcgen\/ppb_rpc.h\"\n\nusing ppapi_proxy::DebugPrintf;\nusing ppapi_proxy::DeleteRemoteCallbackInfo;\nusing ppapi_proxy::MakeRemoteCompletionCallback;\nusing ppapi_proxy::PPBFileIOInterface;\n\nvoid PpbFileIORpcServer::PPB_FileIO_Create(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ input\n PP_Instance instance,\n \/\/ output\n PP_Resource* resource) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_OK;\n\n *resource = PPBFileIOInterface()->Create(instance);\n DebugPrintf(\"PPB_FileIO::Create: resource=%\"NACL_PRIu32\"\\n\", *resource);\n}\n\n\/\/ TODO(sanga): Use a caching resource tracker instead of going over the proxy\n\/\/ to determine if the given resource is a file io.\nvoid PpbFileIORpcServer::PPB_FileIO_IsFileIO(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ inputs\n PP_Resource resource,\n \/\/ output\n int32_t* success) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_OK;\n\n PP_Bool pp_success = PPBFileIOInterface()->IsFileIO(resource);\n DebugPrintf(\"PPB_FileIO::IsFileIO: pp_success=%d\\n\", pp_success);\n\n *success = (pp_success == PP_TRUE);\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Open(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ inputs\n PP_Resource file_io,\n PP_Resource file_ref,\n int32_t open_flags,\n int32_t callback_id,\n \/\/ output\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback =\n MakeRemoteCompletionCallback(rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->Open(\n file_io,\n file_ref,\n open_flags,\n remote_callback);\n DebugPrintf(\"PPB_FileIO::Open: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n\n if (*pp_error != PP_OK_COMPLETIONPENDING) \/\/ Async error.\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nnamespace {\n\nbool IsResultPP_OK(int32_t result) {\n return (result == PP_OK);\n}\n\nnacl_abi_size_t SizeOfPP_FileInfo(int32_t \/*query_callback_result*\/) {\n return sizeof(PP_FileInfo);\n}\n\n} \/\/ namespace\n\nvoid PpbFileIORpcServer::PPB_FileIO_Query(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int32_t bytes_to_read,\n int32_t callback_id,\n nacl_abi_size_t* info_bytes, char* info,\n int32_t* pp_error) {\n \/\/ Since PPB_FileIO::Query does not complete synchronously, and we use remote\n \/\/ completion callback with completion callback table on the untrusted side\n \/\/ (see browser_callback.h and plugin_callback.h), so the actual file info\n \/\/ parameter is not used.\n UNREFERENCED_PARAMETER(info);\n\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n \/\/ TODO(sanga): Drop bytes_to_read for parameters since it is not part of the\n \/\/ interface, and just use the buffer size itself.\n CHECK(bytes_to_read == sizeof(PP_FileInfo));\n char* callback_buffer = NULL;\n PP_CompletionCallback remote_callback =\n MakeRemoteCompletionCallback(rpc->channel, callback_id, bytes_to_read,\n &callback_buffer, IsResultPP_OK,\n SizeOfPP_FileInfo);\n if (NULL == remote_callback.func)\n return;\n\n \/\/ callback_buffer has been assigned to a buffer on the heap, the size\n \/\/ of PP_FileInfo.\n PP_FileInfo* file_info = reinterpret_cast(callback_buffer);\n *pp_error = PPBFileIOInterface()->Query(file_io, file_info, remote_callback);\n DebugPrintf(\"PPB_FileIO::Query: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ Query should not complete synchronously\n\n *info_bytes = 0;\n if (*pp_error != PP_OK_COMPLETIONPENDING) {\n DeleteRemoteCallbackInfo(remote_callback);\n }\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Touch(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n double last_access_time,\n double last_modified_time,\n int32_t callback_id,\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel,\n callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->Touch(file_io, last_access_time,\n last_modified_time, remote_callback);\n DebugPrintf(\"PPB_FileIO::Touch: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ Touch should not complete synchronously\n\n if (*pp_error != PP_OK_COMPLETIONPENDING)\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Read(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n \/\/ inputs\n PP_Resource file_io,\n int64_t offset,\n int32_t bytes_to_read,\n int32_t callback_id,\n \/\/ outputs\n nacl_abi_size_t* buffer_size,\n char* buffer,\n int32_t* pp_error_or_bytes) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n CHECK(*buffer_size == static_cast(bytes_to_read));\n\n char* callback_buffer = NULL;\n PP_CompletionCallback remote_callback =\n MakeRemoteCompletionCallback(rpc->channel, callback_id, bytes_to_read,\n &callback_buffer);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error_or_bytes = PPBFileIOInterface()->Read(\n file_io,\n offset,\n callback_buffer,\n bytes_to_read,\n remote_callback);\n DebugPrintf(\"PPB_FileIO::Read: pp_error_or_bytes=%\"NACL_PRId32\"\\n\",\n *pp_error_or_bytes);\n CHECK(*pp_error_or_bytes <= bytes_to_read);\n\n if (*pp_error_or_bytes > 0) { \/\/ Bytes read into |callback_buffer|.\n \/\/ No callback scheduled.\n *buffer_size = static_cast(*pp_error_or_bytes);\n memcpy(buffer, callback_buffer, *buffer_size);\n DeleteRemoteCallbackInfo(remote_callback);\n } else if (*pp_error_or_bytes != PP_OK_COMPLETIONPENDING) { \/\/ Async error.\n \/\/ No callback scheduled.\n *buffer_size = 0;\n DeleteRemoteCallbackInfo(remote_callback);\n } else {\n \/\/ Callback scheduled.\n *buffer_size = 0;\n }\n\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Write(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int64_t offset,\n nacl_abi_size_t buffer_bytes, char* buffer,\n int32_t bytes_to_write,\n int32_t callback_id,\n int32_t* pp_error_or_bytes) {\n \/\/ TODO(sanga): Add comments for the parameters.\n\n CHECK(buffer_bytes <=\n static_cast(std::numeric_limits::max()));\n CHECK(static_cast(bytes_to_write) <= buffer_bytes);\n\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error_or_bytes = PPBFileIOInterface()->Write(file_io, offset, buffer,\n bytes_to_write,\n remote_callback);\n DebugPrintf(\"PPB_FileIO::Write: pp_error_or_bytes=%\"NACL_PRId32\"\\n\",\n *pp_error_or_bytes);\n\n \/\/ Bytes must be written asynchronously.\n if (*pp_error_or_bytes != PP_OK_COMPLETIONPENDING) {\n DeleteRemoteCallbackInfo(remote_callback);\n }\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_SetLength(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int64_t length,\n int32_t callback_id,\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->SetLength(file_io, length, remote_callback);\n DebugPrintf(\"PPB_FileIO::SetLength: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ SetLength should not complete synchronously\n\n if (*pp_error != PP_OK_COMPLETIONPENDING)\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Flush(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io,\n int32_t callback_id,\n int32_t* pp_error) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_APP_ERROR;\n\n PP_CompletionCallback remote_callback = MakeRemoteCompletionCallback(\n rpc->channel, callback_id);\n if (NULL == remote_callback.func)\n return;\n\n *pp_error = PPBFileIOInterface()->Flush(file_io, remote_callback);\n DebugPrintf(\"PPB_FileIO::Flush: pp_error=%\"NACL_PRId32\"\\n\", *pp_error);\n CHECK(*pp_error != PP_OK); \/\/ Flush should not complete synchronously\n\n if (*pp_error != PP_OK_COMPLETIONPENDING)\n DeleteRemoteCallbackInfo(remote_callback);\n rpc->result = NACL_SRPC_RESULT_OK;\n}\n\nvoid PpbFileIORpcServer::PPB_FileIO_Close(\n NaClSrpcRpc* rpc,\n NaClSrpcClosure* done,\n PP_Resource file_io) {\n NaClSrpcClosureRunner runner(done);\n rpc->result = NACL_SRPC_RESULT_OK;\n DebugPrintf(\"PPB_FileIO::Close: file_io=%\"NACL_PRIu32\"\\n\", file_io);\n PPBFileIOInterface()->Close(file_io);\n}\n<|endoftext|>"} {"text":"\/*\n * GLGraphicsPSO.cpp\n *\n * This file is part of the \"LLGL\" project (Copyright (c) 2015-2019 by Lukas Hermanns)\n * See \"LICENSE.txt\" for license information.\n *\/\n\n#include \"GLGraphicsPSO.h\"\n#include \"GLRenderPass.h\"\n#include \"GLStatePool.h\"\n#include \"..\/Ext\/GLExtensions.h\"\n#include \"..\/Shader\/GLShaderProgram.h\"\n#include \"..\/GLTypes.h\"\n#include \"..\/GLCore.h\"\n#include \"..\/..\/CheckedCast.h\"\n#include \"..\/..\/..\/Core\/Helper.h\"\n#include \"..\/..\/..\/Core\/ByteBufferIterator.h\"\n#include \n#include \n\n\nnamespace LLGL\n{\n\n\nGLGraphicsPSO::GLGraphicsPSO(const GraphicsPipelineDescriptor& desc, const RenderingLimits& limits) :\n GLPipelineState { true, desc.pipelineLayout, desc.shaderProgram }\n{\n \/* Convert input-assembler state *\/\n drawMode_ = GLTypes::ToDrawMode(desc.primitiveTopology);\n primitiveMode_ = GLTypes::ToPrimitiveMode(desc.primitiveTopology);\n\n if (IsPrimitiveTopologyPatches(desc.primitiveTopology))\n {\n \/* Store patch vertices and check limit *\/\n const auto patchSize = GetPrimitiveTopologyPatchSize(desc.primitiveTopology);\n if (patchSize > limits.maxPatchVertices)\n {\n throw std::runtime_error(\n \"renderer does not support \" + std::to_string(patchVertices_) +\n \" control points for patches (limit is \" + std::to_string(limits.maxPatchVertices) + \")\"\n );\n }\n else\n patchVertices_ = static_cast(patchSize);\n }\n else\n patchVertices_ = 0;\n\n \/* Create depth-stencil state *\/\n depthStencilState_ = GLStatePool::Get().CreateDepthStencilState(desc.depth, desc.stencil);\n\n \/* Create rasterizer state *\/\n rasterizerState_ = GLStatePool::Get().CreateRasterizerState(desc.rasterizer);\n\n \/* Create blend state *\/\n if (auto renderPass = desc.renderPass)\n {\n auto renderPassGL = LLGL_CAST(const GLRenderPass*, renderPass);\n blendState_ = GLStatePool::Get().CreateBlendState(desc.blend, renderPassGL->GetNumColorAttachments());\n }\n else\n blendState_ = GLStatePool::Get().CreateBlendState(desc.blend, 1);\n\n \/* Build static state buffer for viewports and scissors *\/\n if (!desc.viewports.empty() || !desc.scissors.empty())\n BuildStaticStateBuffer(desc);\n}\n\nGLGraphicsPSO::~GLGraphicsPSO()\n{\n GLStatePool::Get().ReleaseDepthStencilState(std::move(depthStencilState_));\n GLStatePool::Get().ReleaseRasterizerState(std::move(rasterizerState_));\n GLStatePool::Get().ReleaseBlendState(std::move(blendState_));\n}\n\nvoid GLGraphicsPSO::Bind(GLStateManager& stateMngr)\n{\n \/* Bind shader program and binding layout from base class *\/\n GLPipelineState::Bind(stateMngr);\n\n \/* Set input-assembler state *\/\n if (patchVertices_ > 0)\n stateMngr.SetPatchVertices(patchVertices_);\n\n \/* Bind depth-stencil, rasterizer, and blend states *\/\n stateMngr.BindDepthStencilState(depthStencilState_.get());\n stateMngr.BindRasterizerState(rasterizerState_.get());\n stateMngr.BindBlendState(blendState_.get());\n\n \/* Set static viewports and scissors *\/\n if (staticStateBuffer_)\n {\n ByteBufferIterator byteBufferIter { staticStateBuffer_.get() };\n if (numStaticViewports_ > 0)\n SetStaticViewports(stateMngr, byteBufferIter);\n if (numStaticScissors_ > 0)\n SetStaticScissors(stateMngr, byteBufferIter);\n }\n}\n\n\n\/*\n * ======= Private: =======\n *\/\n\nvoid GLGraphicsPSO::BuildStaticStateBuffer(const GraphicsPipelineDescriptor& desc)\n{\n \/* Allocate packed raw buffer *\/\n const std::size_t bufferSize =\n (\n desc.viewports.size() * (sizeof(GLViewport) + sizeof(GLDepthRange)) +\n desc.scissors.size() * (sizeof(GLScissor))\n );\n staticStateBuffer_ = MakeUniqueArray(bufferSize);\n\n ByteBufferIterator byteBufferIter { staticStateBuffer_.get() };\n\n \/* Build static viewports in raw buffer *\/\n if (!desc.viewports.empty())\n BuildStaticViewports(desc.viewports.size(), desc.viewports.data(), byteBufferIter);\n\n \/* Build static scissors in raw buffer *\/\n if (!desc.scissors.empty())\n BuildStaticScissors(desc.scissors.size(), desc.scissors.data(), byteBufferIter);\n}\n\nvoid GLGraphicsPSO::BuildStaticViewports(std::size_t numViewports, const Viewport* viewports, ByteBufferIterator& byteBufferIter)\n{\n \/* Store number of viewports and validate limit *\/\n numStaticViewports_ = static_cast(numViewports);\n\n if (numStaticViewports_ > LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS)\n {\n throw std::invalid_argument(\n \"too many viewports in graphics pipeline state (\" + std::to_string(numStaticViewports_) +\n \" specified, but limit is \" + std::to_string(LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS) + \")\"\n );\n }\n\n \/* Build entries *\/\n for (std::size_t i = 0; i < numViewports; ++i)\n {\n auto dst = byteBufferIter.Next();\n {\n dst->x = static_cast(viewports[i].x);\n dst->y = static_cast(viewports[i].y);\n dst->width = static_cast(viewports[i].width);\n dst->height = static_cast(viewports[i].height);\n }\n }\n\n \/* Build entries *\/\n for (std::size_t i = 0; i < numViewports; ++i)\n {\n auto dst = byteBufferIter.Next();\n {\n dst->minDepth = static_cast(viewports[i].minDepth);\n dst->maxDepth = static_cast(viewports[i].maxDepth);\n }\n }\n}\n\nvoid GLGraphicsPSO::BuildStaticScissors(std::size_t numScissors, const Scissor* scissors, ByteBufferIterator& byteBufferIter)\n{\n \/* Store number of scissors and validate limit *\/\n numStaticScissors_ = static_cast(numScissors);\n\n if (numStaticScissors_ > LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS)\n {\n throw std::invalid_argument(\n \"too many scissors in graphics pipeline state (\" + std::to_string(numStaticScissors_) +\n \" specified, but limit is \" + std::to_string(LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS) + \")\"\n );\n }\n\n \/* Build entries *\/\n for (std::size_t i = 0; i < numScissors; ++i)\n {\n auto dst = byteBufferIter.Next();\n {\n dst->x = static_cast(scissors[i].x);\n dst->y = static_cast(scissors[i].y);\n dst->width = static_cast(scissors[i].width);\n dst->height = static_cast(scissors[i].height);\n }\n }\n}\n\nvoid GLGraphicsPSO::SetStaticViewports(GLStateManager& stateMngr, ByteBufferIterator& byteBufferIter)\n{\n \/* Copy viewports to intermediate array (must be adjusted when framebuffer is bound) *\/\n GLViewport intermediateViewports[LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS];\n ::memcpy(\n intermediateViewports,\n byteBufferIter.Next(numStaticViewports_),\n numStaticViewports_ * sizeof(GLViewport)\n );\n stateMngr.SetViewportArray(0, numStaticViewports_, intermediateViewports);\n\n \/* Set depth ranges *\/\n stateMngr.SetDepthRangeArray(0, numStaticViewports_, byteBufferIter.Next(numStaticViewports_));\n}\n\nvoid GLGraphicsPSO::SetStaticScissors(GLStateManager& stateMngr, ByteBufferIterator& byteBufferIter)\n{\n \/* Copy scissors to intermediate array (must be adjusted when framebuffer is bound) *\/\n GLScissor intermediateScissors[LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS];\n ::memcpy(\n intermediateScissors,\n byteBufferIter.Next(numStaticScissors_),\n numStaticScissors_ * sizeof(GLScissor)\n );\n stateMngr.SetScissorArray(0, numStaticScissors_, intermediateScissors);\n}\n\n\n} \/\/ \/namespace LLGL\n\n\n\n\/\/ ================================================================================\nRemove unnecessary copy of viewport and depth-range arrays in GL graphics PSO after viewport interface change.\/*\n * GLGraphicsPSO.cpp\n *\n * This file is part of the \"LLGL\" project (Copyright (c) 2015-2019 by Lukas Hermanns)\n * See \"LICENSE.txt\" for license information.\n *\/\n\n#include \"GLGraphicsPSO.h\"\n#include \"GLRenderPass.h\"\n#include \"GLStatePool.h\"\n#include \"..\/Ext\/GLExtensions.h\"\n#include \"..\/Shader\/GLShaderProgram.h\"\n#include \"..\/GLTypes.h\"\n#include \"..\/GLCore.h\"\n#include \"..\/..\/CheckedCast.h\"\n#include \"..\/..\/..\/Core\/Helper.h\"\n#include \"..\/..\/..\/Core\/ByteBufferIterator.h\"\n#include \n#include \n\n\nnamespace LLGL\n{\n\n\nGLGraphicsPSO::GLGraphicsPSO(const GraphicsPipelineDescriptor& desc, const RenderingLimits& limits) :\n GLPipelineState { true, desc.pipelineLayout, desc.shaderProgram }\n{\n \/* Convert input-assembler state *\/\n drawMode_ = GLTypes::ToDrawMode(desc.primitiveTopology);\n primitiveMode_ = GLTypes::ToPrimitiveMode(desc.primitiveTopology);\n\n if (IsPrimitiveTopologyPatches(desc.primitiveTopology))\n {\n \/* Store patch vertices and check limit *\/\n const auto patchSize = GetPrimitiveTopologyPatchSize(desc.primitiveTopology);\n if (patchSize > limits.maxPatchVertices)\n {\n throw std::runtime_error(\n \"renderer does not support \" + std::to_string(patchVertices_) +\n \" control points for patches (limit is \" + std::to_string(limits.maxPatchVertices) + \")\"\n );\n }\n else\n patchVertices_ = static_cast(patchSize);\n }\n else\n patchVertices_ = 0;\n\n \/* Create depth-stencil state *\/\n depthStencilState_ = GLStatePool::Get().CreateDepthStencilState(desc.depth, desc.stencil);\n\n \/* Create rasterizer state *\/\n rasterizerState_ = GLStatePool::Get().CreateRasterizerState(desc.rasterizer);\n\n \/* Create blend state *\/\n if (auto renderPass = desc.renderPass)\n {\n auto renderPassGL = LLGL_CAST(const GLRenderPass*, renderPass);\n blendState_ = GLStatePool::Get().CreateBlendState(desc.blend, renderPassGL->GetNumColorAttachments());\n }\n else\n blendState_ = GLStatePool::Get().CreateBlendState(desc.blend, 1);\n\n \/* Build static state buffer for viewports and scissors *\/\n if (!desc.viewports.empty() || !desc.scissors.empty())\n BuildStaticStateBuffer(desc);\n}\n\nGLGraphicsPSO::~GLGraphicsPSO()\n{\n GLStatePool::Get().ReleaseDepthStencilState(std::move(depthStencilState_));\n GLStatePool::Get().ReleaseRasterizerState(std::move(rasterizerState_));\n GLStatePool::Get().ReleaseBlendState(std::move(blendState_));\n}\n\nvoid GLGraphicsPSO::Bind(GLStateManager& stateMngr)\n{\n \/* Bind shader program and binding layout from base class *\/\n GLPipelineState::Bind(stateMngr);\n\n \/* Set input-assembler state *\/\n if (patchVertices_ > 0)\n stateMngr.SetPatchVertices(patchVertices_);\n\n \/* Bind depth-stencil, rasterizer, and blend states *\/\n stateMngr.BindDepthStencilState(depthStencilState_.get());\n stateMngr.BindRasterizerState(rasterizerState_.get());\n stateMngr.BindBlendState(blendState_.get());\n\n \/* Set static viewports and scissors *\/\n if (staticStateBuffer_)\n {\n ByteBufferIterator byteBufferIter { staticStateBuffer_.get() };\n if (numStaticViewports_ > 0)\n SetStaticViewports(stateMngr, byteBufferIter);\n if (numStaticScissors_ > 0)\n SetStaticScissors(stateMngr, byteBufferIter);\n }\n}\n\n\n\/*\n * ======= Private: =======\n *\/\n\nvoid GLGraphicsPSO::BuildStaticStateBuffer(const GraphicsPipelineDescriptor& desc)\n{\n \/* Allocate packed raw buffer *\/\n const std::size_t bufferSize =\n (\n desc.viewports.size() * (sizeof(GLViewport) + sizeof(GLDepthRange)) +\n desc.scissors.size() * (sizeof(GLScissor))\n );\n staticStateBuffer_ = MakeUniqueArray(bufferSize);\n\n ByteBufferIterator byteBufferIter { staticStateBuffer_.get() };\n\n \/* Build static viewports in raw buffer *\/\n if (!desc.viewports.empty())\n BuildStaticViewports(desc.viewports.size(), desc.viewports.data(), byteBufferIter);\n\n \/* Build static scissors in raw buffer *\/\n if (!desc.scissors.empty())\n BuildStaticScissors(desc.scissors.size(), desc.scissors.data(), byteBufferIter);\n}\n\nvoid GLGraphicsPSO::BuildStaticViewports(std::size_t numViewports, const Viewport* viewports, ByteBufferIterator& byteBufferIter)\n{\n \/* Store number of viewports and validate limit *\/\n numStaticViewports_ = static_cast(numViewports);\n\n if (numStaticViewports_ > LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS)\n {\n throw std::invalid_argument(\n \"too many viewports in graphics pipeline state (\" + std::to_string(numStaticViewports_) +\n \" specified, but limit is \" + std::to_string(LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS) + \")\"\n );\n }\n\n \/* Build entries *\/\n for (std::size_t i = 0; i < numViewports; ++i)\n {\n auto dst = byteBufferIter.Next();\n {\n dst->x = static_cast(viewports[i].x);\n dst->y = static_cast(viewports[i].y);\n dst->width = static_cast(viewports[i].width);\n dst->height = static_cast(viewports[i].height);\n }\n }\n\n \/* Build entries *\/\n for (std::size_t i = 0; i < numViewports; ++i)\n {\n auto dst = byteBufferIter.Next();\n {\n dst->minDepth = static_cast(viewports[i].minDepth);\n dst->maxDepth = static_cast(viewports[i].maxDepth);\n }\n }\n}\n\nvoid GLGraphicsPSO::BuildStaticScissors(std::size_t numScissors, const Scissor* scissors, ByteBufferIterator& byteBufferIter)\n{\n \/* Store number of scissors and validate limit *\/\n numStaticScissors_ = static_cast(numScissors);\n\n if (numStaticScissors_ > LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS)\n {\n throw std::invalid_argument(\n \"too many scissors in graphics pipeline state (\" + std::to_string(numStaticScissors_) +\n \" specified, but limit is \" + std::to_string(LLGL_MAX_NUM_VIEWPORTS_AND_SCISSORS) + \")\"\n );\n }\n\n \/* Build entries *\/\n for (std::size_t i = 0; i < numScissors; ++i)\n {\n auto dst = byteBufferIter.Next();\n {\n dst->x = static_cast(scissors[i].x);\n dst->y = static_cast(scissors[i].y);\n dst->width = static_cast(scissors[i].width);\n dst->height = static_cast(scissors[i].height);\n }\n }\n}\n\nvoid GLGraphicsPSO::SetStaticViewports(GLStateManager& stateMngr, ByteBufferIterator& byteBufferIter)\n{\n stateMngr.SetViewportArray(0, numStaticViewports_, byteBufferIter.Next(numStaticViewports_));\n stateMngr.SetDepthRangeArray(0, numStaticViewports_, byteBufferIter.Next(numStaticViewports_));\n}\n\nvoid GLGraphicsPSO::SetStaticScissors(GLStateManager& stateMngr, ByteBufferIterator& byteBufferIter)\n{\n stateMngr.SetScissorArray(0, numStaticScissors_, byteBufferIter.Next(numStaticScissors_));\n}\n\n\n} \/\/ \/namespace LLGL\n\n\n\n\/\/ ================================================================================\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \"DecimalConverter.h\"\nusing namespace std;\n\nnamespace NumberBaseConverter\n{\n string DecimalConverter::convertToBinary(int number)\n {\n string binRep(\"\");\n if(number \/ 2 != 0)\n {\n binRep.append(convertToBinary(number \/ 2));\n } \/\/ end if\n \n char temp[1];\n sprintf(temp, \"%d\", number % 2);\n binRep.append(temp);\n \n return binRep;\n }\n \n string DecimalConverter::ConvertToBinary(string decStr)\n {\n int number;\n stringstream ss;\n ss << std::dec << decStr;\n ss >> number;\n \n return convertToBinary(number);\n } \/\/ end method\n \n string DecimalConverter::convertToHexadecimal(int number)\n {\n string hexRep(\"\");\n if(number \/ 16 != 0)\n {\n hexRep.append(convertToHexadecimal(number \/ 16));\n } \/\/ end if\n \n char temp[1];\n sprintf(temp, \"%x\", number % 16);\n hexRep.append(temp);\n \n return hexRep;\n } \/\/ end method\n \n string DecimalConverter::ConvertToHexadecimal(string decStr)\n {\n int number;\n stringstream ss;\n ss << std::dec << decStr;\n ss >> number;\n \n return convertToHexadecimal(number);\n } \/\/ end method \n} \/\/ end namespace rearranging the private\/public methods\n#include \n#include \n#include \"DecimalConverter.h\"\nusing namespace std;\n\nnamespace NumberBaseConverter\n{\n string DecimalConverter::ConvertToBinary(string decStr)\n {\n int number;\n stringstream ss;\n ss << std::dec << decStr;\n ss >> number;\n \n return convertToBinary(number);\n } \/\/ end method\n \n string DecimalConverter::ConvertToHexadecimal(string decStr)\n {\n int number;\n stringstream ss;\n ss << std::dec << decStr;\n ss >> number;\n \n return convertToHexadecimal(number);\n } \/\/ end method \n \n string DecimalConverter::convertToBinary(int number)\n {\n string binRep(\"\");\n if(number \/ 2 != 0)\n {\n binRep.append(convertToBinary(number \/ 2));\n } \/\/ end if\n \n char temp[1];\n sprintf(temp, \"%d\", number % 2);\n binRep.append(temp);\n \n return binRep;\n } \/\/ end method\n \n string DecimalConverter::convertToHexadecimal(int number)\n {\n string hexRep(\"\");\n if(number \/ 16 != 0)\n {\n hexRep.append(convertToHexadecimal(number \/ 16));\n } \/\/ end if\n \n char temp[1];\n sprintf(temp, \"%x\", number % 16);\n hexRep.append(temp);\n \n return hexRep;\n } \/\/ end method\n} \/\/ end namespace<|endoftext|>"} {"text":"#include \"StorageArchiveLogSegmentJob.h\"\n#include \"System\/FileSystem.h\"\n#include \"System\/Config.h\"\n#include \"System\/Stopwatch.h\"\n#include \"StorageEnvironment.h\"\n\nStorageArchiveLogSegmentJob::StorageArchiveLogSegmentJob(StorageEnvironment* env_, \n StorageLogSegment* logSegment_, const char* script_)\n{\n env = env_;\n logSegment = logSegment_;\n script = script_;\n}\n\nvoid StorageArchiveLogSegmentJob::Execute()\n{\n Buffer dest;\n Buffer cmdline;\n \n if (ReadBuffer::Cmp(script, \"$archive\") == 0)\n {\n Log_Debug(\"Archiving log segment %U...\", logSegment->GetLogSegmentID());\n\n dest.Write(env->archivePath);\n dest.Appendf(\"log.%020U\", logSegment->GetLogSegmentID());\n dest.NullTerminate();\n\n FS_Rename(logSegment->filename.GetBuffer(), dest.GetBuffer());\n }\n else if (ReadBuffer::Cmp(script, \"$delete\") == 0)\n {\n Log_Debug(\"Deleting archive log segment %U...\", logSegment->GetLogSegmentID());\n FS_Delete(logSegment->filename.GetBuffer());\n }\n else\n {\n Log_Debug(\"Executing script on archive log segment %U (%s)...\", \n logSegment->GetLogSegmentID(), script);\n \n EvalScriptVariables();\n ShellExec(command.GetBuffer());\n }\n}\n\nvoid StorageArchiveLogSegmentJob::EvalScriptVariables()\n{\n Buffer var;\n const char* p;\n bool inVar;\n \n p = script;\n inVar = false;\n while (*p)\n {\n \/\/ Replace $(variableName) in the script to the value of a config variable\n if (p[0] == '$' && p[1] == '(')\n {\n inVar = true;\n p += 2; \/\/ skip \"$(\"\n }\n \n if (inVar && p[0] == ')')\n {\n var.NullTerminate();\n command.Append(GetVarValue(var.GetBuffer()));\n var.Reset();\n inVar = false;\n p += 1; \/\/ skip \")\"\n }\n\n if (*p == 0)\n break;\n \n if (inVar)\n var.Append(*p);\n else\n command.Append(*p);\n \n p++;\n }\n \n command.NullTerminate();\n}\n\nconst char* StorageArchiveLogSegmentJob::GetVarValue(const char* var)\n{\n if (strcmp(var, \"archiveFile\") == 0)\n return logSegment->filename.GetBuffer();\n else\n return configFile.GetValue(var, \"\");\n}\n\nvoid StorageArchiveLogSegmentJob::OnComplete()\n{\n env->OnLogArchive(this); \/\/ deletes this\n}\nImproved Log_Debug message.#include \"StorageArchiveLogSegmentJob.h\"\n#include \"System\/FileSystem.h\"\n#include \"System\/Config.h\"\n#include \"System\/Stopwatch.h\"\n#include \"StorageEnvironment.h\"\n\nStorageArchiveLogSegmentJob::StorageArchiveLogSegmentJob(StorageEnvironment* env_, \n StorageLogSegment* logSegment_, const char* script_)\n{\n env = env_;\n logSegment = logSegment_;\n script = script_;\n}\n\nvoid StorageArchiveLogSegmentJob::Execute()\n{\n Buffer dest;\n Buffer cmdline;\n \n if (ReadBuffer::Cmp(script, \"$archive\") == 0)\n {\n Log_Debug(\"Archiving log segment %U...\", logSegment->GetLogSegmentID());\n\n dest.Write(env->archivePath);\n dest.Appendf(\"log.%020U\", logSegment->GetLogSegmentID());\n dest.NullTerminate();\n\n FS_Rename(logSegment->filename.GetBuffer(), dest.GetBuffer());\n }\n else if (ReadBuffer::Cmp(script, \"$delete\") == 0)\n {\n Log_Debug(\"Deleting archive log segment %U\/%U...\",\n logSegment->GetTrackID(), logSegment->GetLogSegmentID());\n FS_Delete(logSegment->filename.GetBuffer());\n }\n else\n {\n Log_Debug(\"Executing script on archive log segment %U (%s)...\", \n logSegment->GetLogSegmentID(), script);\n \n EvalScriptVariables();\n ShellExec(command.GetBuffer());\n }\n}\n\nvoid StorageArchiveLogSegmentJob::EvalScriptVariables()\n{\n Buffer var;\n const char* p;\n bool inVar;\n \n p = script;\n inVar = false;\n while (*p)\n {\n \/\/ Replace $(variableName) in the script to the value of a config variable\n if (p[0] == '$' && p[1] == '(')\n {\n inVar = true;\n p += 2; \/\/ skip \"$(\"\n }\n \n if (inVar && p[0] == ')')\n {\n var.NullTerminate();\n command.Append(GetVarValue(var.GetBuffer()));\n var.Reset();\n inVar = false;\n p += 1; \/\/ skip \")\"\n }\n\n if (*p == 0)\n break;\n \n if (inVar)\n var.Append(*p);\n else\n command.Append(*p);\n \n p++;\n }\n \n command.NullTerminate();\n}\n\nconst char* StorageArchiveLogSegmentJob::GetVarValue(const char* var)\n{\n if (strcmp(var, \"archiveFile\") == 0)\n return logSegment->filename.GetBuffer();\n else\n return configFile.GetValue(var, \"\");\n}\n\nvoid StorageArchiveLogSegmentJob::OnComplete()\n{\n env->OnLogArchive(this); \/\/ deletes this\n}\n<|endoftext|>"} {"text":"#include \"antsUtilities.h\"\n#include \n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkDeformationFieldGradientTensorImageFilter.h\"\n#include \"itkDeterminantTensorImageFilter.h\"\n#include \"itkGeometricJacobianDeterminantImageFilter.h\"\n#include \"itkLogImageFilter.h\"\n#include \"itkMaximumImageFilter.h\"\n\nnamespace ants\n{\ntemplate \nint CreateJacobianDeterminantImage( int argc, char *argv[] )\n{\n typedef double RealType;\n typedef itk::Image ImageType;\n typedef itk::Vector VectorType;\n typedef itk::Image VectorImageType;\n\n \/**\n * Read in vector field\n *\/\n typedef itk::ImageFileReader ReaderType;\n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[2] );\n reader->Update();\n\n typename ImageType::Pointer jacobian = ITK_NULLPTR;\n\n typename ImageType::Pointer minimumConstantImage = ImageType::New();\n minimumConstantImage->CopyInformation( reader->GetOutput() );\n minimumConstantImage->SetRegions( reader->GetOutput()->GetRequestedRegion() );\n minimumConstantImage->Allocate();\n minimumConstantImage->FillBuffer( 0.001 );\n\n bool calculateLogJacobian = false;\n if ( argc > 4 )\n {\n calculateLogJacobian = static_cast( atoi( argv[4] ) );\n }\n\n bool calculateGeometricJacobian = false;\n if ( argc > 5 )\n {\n calculateGeometricJacobian = static_cast( atoi( argv[5] ) );\n }\n\n if( calculateGeometricJacobian )\n {\n typedef itk::GeometricJacobianDeterminantImageFilter\n JacobianFilterType;\n typename JacobianFilterType::Pointer jacobianFilter = JacobianFilterType::New();\n jacobianFilter->SetInput( reader->GetOutput() );\n\n jacobian = jacobianFilter->GetOutput();\n jacobian->Update();\n jacobian->DisconnectPipeline();\n }\n else\n {\n typedef itk::DeformationFieldGradientTensorImageFilter JacobianFilterType;\n typename JacobianFilterType::Pointer jacobianFilter = JacobianFilterType::New();\n jacobianFilter->SetInput( reader->GetOutput() );\n jacobianFilter->SetCalculateJacobian( true );\n jacobianFilter->SetUseImageSpacing( true );\n jacobianFilter->SetOrder( 2 );\n jacobianFilter->SetUseCenteredDifference( true );\n\n typedef itk::DeterminantTensorImageFilter\n DeterminantFilterType;\n typename DeterminantFilterType::Pointer determinantFilter = DeterminantFilterType::New();\n determinantFilter->SetInput( jacobianFilter->GetOutput() );\n determinantFilter->Update();\n\n minimumConstantImage->FillBuffer( 0.0 );\n\n typedef itk::MaximumImageFilter MaxFilterType;\n typename MaxFilterType::Pointer maxFilter = MaxFilterType::New();\n maxFilter->SetInput1( determinantFilter->GetOutput() );\n maxFilter->SetInput2( minimumConstantImage );\n\n jacobian = maxFilter->GetOutput();\n jacobian->Update();\n jacobian->DisconnectPipeline();\n }\n\n if( calculateLogJacobian )\n {\n minimumConstantImage->FillBuffer( 0.001 );\n\n typedef itk::MaximumImageFilter MaxFilterType;\n typename MaxFilterType::Pointer maxFilter = MaxFilterType::New();\n maxFilter->SetInput1( jacobian );\n maxFilter->SetInput2( minimumConstantImage );\n\n typedef itk::LogImageFilter LogFilterType;\n typename LogFilterType::Pointer logFilter = LogFilterType::New();\n logFilter->SetInput( maxFilter->GetOutput() );\n logFilter->Update();\n\n typedef itk::ImageFileWriter ImageWriterType;\n typename ImageWriterType::Pointer writer = ImageWriterType::New();\n writer->SetFileName( argv[3] );\n writer->SetInput( logFilter->GetOutput() );\n writer->Update();\n }\n else\n {\n typedef itk::ImageFileWriter ImageWriterType;\n typename ImageWriterType::Pointer writer = ImageWriterType::New();\n writer->SetFileName( argv[3] );\n writer->SetInput( jacobian );\n writer->Update();\n }\n\n return EXIT_SUCCESS;\n}\n\n\n\n\n\n\/\/ entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to\n\/\/ 'main()'\nint CreateJacobianDeterminantImage( std::vector args, std::ostream* itkNotUsed( out_stream ) )\n{\n \/\/ put the arguments coming in as 'args' into standard (argc,argv) format;\n \/\/ 'args' doesn't have the command name as first, argument, so add it manually;\n \/\/ 'args' may have adjacent arguments concatenated into one argument,\n \/\/ which the parser should handle\n args.insert( args.begin(), \"CreateJacobianDeterminantImage\" );\n\n int argc = args.size();\n char* * argv = new char *[args.size() + 1];\n for( unsigned int i = 0; i < args.size(); ++i )\n {\n \/\/ allocate space for the string plus a null character\n argv[i] = new char[args[i].length() + 1];\n std::strncpy( argv[i], args[i].c_str(), args[i].length() );\n \/\/ place the null character in the end\n argv[i][args[i].length()] = '\\0';\n }\n argv[argc] = ITK_NULLPTR;\n \/\/ class to automatically cleanup argv upon destruction\n class Cleanup_argv\n {\npublic:\n Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )\n {\n }\n\n ~Cleanup_argv()\n {\n for( unsigned int i = 0; i < argc_plus_one; ++i )\n {\n delete[] argv[i];\n }\n delete[] argv;\n }\n\nprivate:\n char* * argv;\n unsigned int argc_plus_one;\n };\n Cleanup_argv cleanup_argv( argv, argc + 1 );\n\n \/\/ antscout->set_stream( out_stream );\n\n if( argc < 3 )\n {\n std::cout << \"Usage: \" << argv[0] << \" imageDimension deformationField outputImage [doLogJacobian=0] [useGeometric=0]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n CreateJacobianDeterminantImage<2>( argc, argv );\n }\n break;\n case 3:\n {\n CreateJacobianDeterminantImage<3>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n} \/\/ namespace ants\nBUG: (antsr-specific) need ReadWriteData#include \"antsUtilities.h\"\n#include \n#include \"ReadWriteData.h\"\n#include \"itkDeformationFieldGradientTensorImageFilter.h\"\n#include \"itkDeterminantTensorImageFilter.h\"\n#include \"itkGeometricJacobianDeterminantImageFilter.h\"\n#include \"itkLogImageFilter.h\"\n#include \"itkMaximumImageFilter.h\"\n\nnamespace ants\n{\ntemplate \nint CreateJacobianDeterminantImage( int argc, char *argv[] )\n{\n typedef double RealType;\n typedef itk::Image ImageType;\n typedef itk::Vector VectorType;\n typedef itk::Image VectorImageType;\n\n \/**\n * Read in vector field\n *\/\n typedef itk::ImageFileReader ReaderType;\n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[2] );\n reader->Update();\n\n typename ImageType::Pointer jacobian = ITK_NULLPTR;\n\n typename ImageType::Pointer minimumConstantImage = ImageType::New();\n minimumConstantImage->CopyInformation( reader->GetOutput() );\n minimumConstantImage->SetRegions( reader->GetOutput()->GetRequestedRegion() );\n minimumConstantImage->Allocate();\n minimumConstantImage->FillBuffer( 0.001 );\n\n bool calculateLogJacobian = false;\n if ( argc > 4 )\n {\n calculateLogJacobian = static_cast( atoi( argv[4] ) );\n }\n\n bool calculateGeometricJacobian = false;\n if ( argc > 5 )\n {\n calculateGeometricJacobian = static_cast( atoi( argv[5] ) );\n }\n\n if( calculateGeometricJacobian )\n {\n typedef itk::GeometricJacobianDeterminantImageFilter\n JacobianFilterType;\n typename JacobianFilterType::Pointer jacobianFilter = JacobianFilterType::New();\n jacobianFilter->SetInput( reader->GetOutput() );\n\n jacobian = jacobianFilter->GetOutput();\n jacobian->Update();\n jacobian->DisconnectPipeline();\n }\n else\n {\n typedef itk::DeformationFieldGradientTensorImageFilter JacobianFilterType;\n typename JacobianFilterType::Pointer jacobianFilter = JacobianFilterType::New();\n jacobianFilter->SetInput( reader->GetOutput() );\n jacobianFilter->SetCalculateJacobian( true );\n jacobianFilter->SetUseImageSpacing( true );\n jacobianFilter->SetOrder( 2 );\n jacobianFilter->SetUseCenteredDifference( true );\n\n typedef itk::DeterminantTensorImageFilter\n DeterminantFilterType;\n typename DeterminantFilterType::Pointer determinantFilter = DeterminantFilterType::New();\n determinantFilter->SetInput( jacobianFilter->GetOutput() );\n determinantFilter->Update();\n\n minimumConstantImage->FillBuffer( 0.0 );\n\n typedef itk::MaximumImageFilter MaxFilterType;\n typename MaxFilterType::Pointer maxFilter = MaxFilterType::New();\n maxFilter->SetInput1( determinantFilter->GetOutput() );\n maxFilter->SetInput2( minimumConstantImage );\n\n jacobian = maxFilter->GetOutput();\n jacobian->Update();\n jacobian->DisconnectPipeline();\n }\n\n if( calculateLogJacobian )\n {\n minimumConstantImage->FillBuffer( 0.001 );\n\n typedef itk::MaximumImageFilter MaxFilterType;\n typename MaxFilterType::Pointer maxFilter = MaxFilterType::New();\n maxFilter->SetInput1( jacobian );\n maxFilter->SetInput2( minimumConstantImage );\n\n typedef itk::LogImageFilter LogFilterType;\n typename LogFilterType::Pointer logFilter = LogFilterType::New();\n logFilter->SetInput( maxFilter->GetOutput() );\n logFilter->Update();\n WriteImage(logFilter->GetOutput(), argv[3] );\n }\n else\n {\n WriteImage(jacobian, argv[3] );\n }\n return EXIT_SUCCESS;\n}\n\n\n\n\n\n\/\/ entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to\n\/\/ 'main()'\nint CreateJacobianDeterminantImage( std::vector args, std::ostream* itkNotUsed( out_stream ) )\n{\n \/\/ put the arguments coming in as 'args' into standard (argc,argv) format;\n \/\/ 'args' doesn't have the command name as first, argument, so add it manually;\n \/\/ 'args' may have adjacent arguments concatenated into one argument,\n \/\/ which the parser should handle\n args.insert( args.begin(), \"CreateJacobianDeterminantImage\" );\n\n int argc = args.size();\n char* * argv = new char *[args.size() + 1];\n for( unsigned int i = 0; i < args.size(); ++i )\n {\n \/\/ allocate space for the string plus a null character\n argv[i] = new char[args[i].length() + 1];\n std::strncpy( argv[i], args[i].c_str(), args[i].length() );\n \/\/ place the null character in the end\n argv[i][args[i].length()] = '\\0';\n }\n argv[argc] = ITK_NULLPTR;\n \/\/ class to automatically cleanup argv upon destruction\n class Cleanup_argv\n {\npublic:\n Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )\n {\n }\n\n ~Cleanup_argv()\n {\n for( unsigned int i = 0; i < argc_plus_one; ++i )\n {\n delete[] argv[i];\n }\n delete[] argv;\n }\n\nprivate:\n char* * argv;\n unsigned int argc_plus_one;\n };\n Cleanup_argv cleanup_argv( argv, argc + 1 );\n\n \/\/ antscout->set_stream( out_stream );\n\n if( argc < 3 )\n {\n std::cout << \"Usage: \" << argv[0] << \" imageDimension deformationField outputImage [doLogJacobian=0] [useGeometric=0]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n switch( atoi( argv[1] ) )\n {\n case 2:\n {\n CreateJacobianDeterminantImage<2>( argc, argv );\n }\n break;\n case 3:\n {\n CreateJacobianDeterminantImage<3>( argc, argv );\n }\n break;\n default:\n std::cout << \"Unsupported dimension\" << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n} \/\/ namespace ants\n<|endoftext|>"} {"text":"#include \n#include \n\nnamespace\n{\n\n\/\/holds a sequence of integers.\ntemplate\nstruct sequence { };\n\n\/\/generate a sequence of incrementing values starting at zero\ntemplate\nstruct generate_sequence\n{\n typedef typename generate_sequence::type type;\n};\n\n\/\/generate a sequence of incrementing values starting at zero\ntemplate\nstruct generate_sequence<0, S...>\n{\n typedef sequence type;\n};\n\n\n\/\/apply a functor to each element in a parameter pack\ntemplate\nstruct forEach\n{\n template\n void operator()(Functor f, First first, T... t) const\n {\n forEach()(f,t...);\n }\n};\n\n\/\/apply a functor to each element in a parameter pack\ntemplate\nstruct forEach\n{\n template\n void operator()(Functor f, First first) const\n {\n }\n};\n\n\/\/applies the functor to each element in a parameter pack\ntemplate\nvoid for_each(Functor f, T... items)\n{\n ::forEach()(f,items...);\n}\n\n\/\/special version of for_each that is a helper to get the length of indicies\n\/\/as a parameter type. I can't figure out how to do this step inside for_each specialized\n\/\/on tuple\ntemplate\nvoid for_each(Functor f, std::tuple tuple, ::sequence)\n{\n ::for_each(f,std::get(tuple)...);\n}\n\n\/\/function overload that detects tuples being sent to for each\n\/\/and expands the tuple elements\ntemplate\nvoid for_each(Functor f, std::tuple& tuple)\n{\n \/\/to iterate each item in the tuple we have to convert back from\n \/\/a tuple to a parameter pack\n enum { len = std::tuple_size< std::tuple >::value};\n typedef typename ::generate_sequence::type SequenceType;\n ::for_each(f,tuple,SequenceType());\n}\n\n\ntemplate\nvoid InvokeTuple(Values... v)\n{\n std::tuple tuple(v...);\n ::for_each(tuple);\n}\n\n}\n\nint main(int argc, char** argv)\n{\n InvokeTuple(\"0\",'1',2.0f,3);\n return 0;\n}\nUpdate the C11 try compile code to actually compile.#include \n#include \n\nnamespace\n{\n\nstruct test_functor {\n template\n void operator()(T& t) const { t = T(); }\n};\n\n\/\/holds a sequence of integers.\ntemplate\nstruct sequence { };\n\n\/\/generate a sequence of incrementing values starting at zero\ntemplate\nstruct generate_sequence\n{\n typedef typename generate_sequence::type type;\n};\n\n\/\/generate a sequence of incrementing values starting at zero\ntemplate\nstruct generate_sequence<0, S...>\n{\n typedef sequence type;\n};\n\n\n\/\/apply a functor to each element in a parameter pack\ntemplate\nstruct forEach\n{\n template\n void operator()(Functor f, First first, T... t) const\n {\n forEach()(f,t...);\n }\n};\n\n\/\/apply a functor to each element in a parameter pack\ntemplate\nstruct forEach\n{\n template\n void operator()(Functor f, First first) const\n {\n }\n};\n\n\/\/applies the functor to each element in a parameter pack\ntemplate\nvoid for_each(Functor f, T... items)\n{\n ::forEach()(f,items...);\n}\n\n\/\/special version of for_each that is a helper to get the length of indicies\n\/\/as a parameter type. I can't figure out how to do this step inside for_each specialized\n\/\/on tuple\ntemplate\nvoid for_each(Functor f, std::tuple tuple, ::sequence)\n{\n ::for_each(f,std::get(tuple)...);\n}\n\n\/\/function overload that detects tuples being sent to for each\n\/\/and expands the tuple elements\ntemplate\nvoid for_each(Functor f, std::tuple& tuple)\n{\n \/\/to iterate each item in the tuple we have to convert back from\n \/\/a tuple to a parameter pack\n enum { len = std::tuple_size< std::tuple >::value};\n typedef typename ::generate_sequence::type SequenceType;\n ::for_each(f,tuple,SequenceType());\n}\n\n\ntemplate\nvoid InvokeTuple(Values... v)\n{\n std::tuple tuple(v...);\n ::for_each(::test_functor(),tuple);\n}\n\n}\n\nint main(int argc, char** argv)\n{\n InvokeTuple(\"0\",'1',2.0f,3);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Library: CTK\n \n Copyright (c) 2010 Kitware Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.commontk.org\/LICENSE\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n =========================================================================*\/\n\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ CTK includes\n#include \"ctkWorkflowButtonBoxWidget.h\"\n#include \"ctkWorkflowStep.h\"\n#include \"ctkWorkflowWidgetStep.h\"\n#include \"ctkWorkflow.h\"\n\n\/\/ STD includes\n#include \n\n\/\/-----------------------------------------------------------------------------\nclass ctkWorkflowButtonBoxWidgetPrivate : public ctkPrivate\n{\npublic:\n CTK_DECLARE_PUBLIC(ctkWorkflowButtonBoxWidget);\n ctkWorkflowButtonBoxWidgetPrivate();\n ~ctkWorkflowButtonBoxWidgetPrivate(){}\n\n void setupUi(QWidget * newParent);\n\n QPointer Workflow;\n\n \/\/ Convenient typedefs\n typedef QMap ButtonToStepMapType;\n\n \/\/ The buttons on the widget (maintain maps associating each forward\/goTo button with its step)\n QPushButton* BackButton;\n QString BackButtonDefaultText;\n QPushButton* NextButton;\n QString NextButtonDefaultText;\n ButtonToStepMapType GoToButtonToStepMap;\n\n \/\/ Direction for layout (for use with QBoxLayout only)\n QBoxLayout::Direction Direction;\n\n bool HideInvalidButtons;\n\n \/\/ Functions to add\/remove buttons\n void updateBackButton(ctkWorkflowStep* currentStep);\n void updateNextButton(ctkWorkflowStep* currentStep);\n void updateGoToButtons(ctkWorkflowStep* currentStep);\n\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ctkWorkflowButtonBoxWidgetPrivate methods\n\n\/\/-----------------------------------------------------------------------------\nctkWorkflowButtonBoxWidgetPrivate::ctkWorkflowButtonBoxWidgetPrivate()\n{\n this->BackButton = 0;\n this->BackButtonDefaultText = \"Back\";\n this->NextButton = 0;\n this->NextButtonDefaultText = \"Next\";\n this->Direction = QBoxLayout::LeftToRight;\n this->HideInvalidButtons = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidgetPrivate::setupUi(QWidget * newParent)\n{\n QBoxLayout * boxLayout = new QBoxLayout(this->Direction, newParent);\n boxLayout->setSpacing(0);\n boxLayout->setContentsMargins(0, 0, 0, 0);\n newParent->setLayout(boxLayout);\n\n \/\/ Retrieve standard icons\n QIcon backIcon = newParent->style()->standardIcon(QStyle::SP_ArrowLeft);\n QIcon nextIcon = newParent->style()->standardIcon(QStyle::SP_ArrowRight);\n\n \/\/ Setup the buttons\n this->BackButton = new QPushButton(backIcon, this->BackButtonDefaultText, newParent);\n newParent->layout()->addWidget(this->BackButton);\n\n this->NextButton = new QPushButton(nextIcon, this->NextButtonDefaultText, newParent);\n this->NextButton->setLayoutDirection(Qt::RightToLeft);\n newParent->layout()->addWidget(this->NextButton);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidgetPrivate::updateBackButton(ctkWorkflowStep* currentStep)\n{\n CTK_P(ctkWorkflowButtonBoxWidget);\n\n Q_ASSERT(this->Workflow);\n Q_ASSERT(currentStep);\n Q_ASSERT(p->layout());\n\n ctkWorkflowWidgetStep* step = qobject_cast(currentStep);\n\n \/\/ Set the back button text\n QString backButtonText = this->BackButtonDefaultText;\n if (step && !step->backButtonText().isEmpty())\n {\n backButtonText = step->backButtonText();\n }\n this->BackButton->setText(backButtonText);\n\n \/\/ Enable and show the back button if we can go backward\n if (this->Workflow->canGoBackward(currentStep))\n {\n this->BackButton->setEnabled(true);\n this->BackButton->show();\n\n \/\/ Apply the buttonBox hints if possible\n if (step)\n {\n this->BackButton->setDisabled(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::BackButtonDisabled);\n this->BackButton->setHidden(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::BackButtonHidden);\n }\n }\n \/\/ Disable the back button if we can't go backward, and optionally hide it\n else\n {\n this->BackButton->setEnabled(false);\n this->HideInvalidButtons ? this->BackButton->hide() : this->BackButton->show();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ This will change for branching workflows, to look more like updateGoToButtons()\nvoid ctkWorkflowButtonBoxWidgetPrivate::updateNextButton(ctkWorkflowStep* currentStep)\n{\n CTK_P(ctkWorkflowButtonBoxWidget);\n\n Q_ASSERT(this->Workflow);\n Q_ASSERT(currentStep);\n Q_ASSERT(p->layout());\n\n ctkWorkflowWidgetStep* step = qobject_cast(currentStep);\n\n \/\/ Set the next button text\n QString nextButtonText = this->NextButtonDefaultText;\n if (step && !step->nextButtonText().isEmpty())\n {\n nextButtonText = step->nextButtonText();\n }\n this->NextButton->setText(nextButtonText);\n\n \/\/ Enable and show the next button if we can go forward\n if (this->Workflow->canGoForward(currentStep))\n {\n this->NextButton->setEnabled(true);\n this->NextButton->show();\n\n \/\/ Apply the buttonBox hints if possible\n if (step)\n {\n this->NextButton->setDisabled(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::NextButtonDisabled);\n this->NextButton->setHidden(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::NextButtonHidden);\n }\n }\n \/\/ Disable the next button if we can't go forward, and optionally hide it\n else\n {\n this->NextButton->setEnabled(false);\n this->HideInvalidButtons ? this->NextButton->hide() : this->NextButton->show();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidgetPrivate::updateGoToButtons(ctkWorkflowStep* currentStep)\n{\n CTK_P(ctkWorkflowButtonBoxWidget);\n\n Q_ASSERT(this->Workflow);\n Q_ASSERT(currentStep);\n Q_ASSERT(p->layout());\n\n \/\/ Change the buttons only if the set of steps to have goTo buttons is either empty or has changed\n QSet goToStepsToHaveButtons = QSet::fromList(this->Workflow->finishSteps());\n QSet goToStepsThatHaveButtons = QSet::fromList(this->GoToButtonToStepMap.values());\n\n \/\/ Remove the buttons if the set of steps to have goTo buttons has changed\n if (!this->GoToButtonToStepMap.isEmpty() && goToStepsThatHaveButtons != goToStepsToHaveButtons)\n {\n foreach (QPushButton* goToButton, this->GoToButtonToStepMap.keys())\n {\n p->layout()->removeWidget(goToButton);\n delete goToButton;\n }\n this->GoToButtonToStepMap.clear();\n }\n\n \/\/ Create the buttons, either for the first time or after removing them above\n if (this->GoToButtonToStepMap.isEmpty())\n {\n \/\/ Create a button for each of the goToSteps\n foreach (ctkWorkflowStep* step, goToStepsToHaveButtons)\n {\n \/\/ TODO shouldn't have id here\n QPushButton* goToButton = new QPushButton(step->id());\n p->layout()->addWidget(goToButton);\n QObject::connect(goToButton, SIGNAL(clicked()), p, SLOT(prepareGoToStep()));\n this->GoToButtonToStepMap[goToButton] = step;\n }\n \n }\n\n \/\/ Show\/hide the goTo buttons depending on whether they are accessible from the current step\n foreach (QPushButton* goToButton, this->GoToButtonToStepMap.keys())\n {\n \/\/ TODO enable and show the goTo button if we can go to it\n \/\/ ctkWorkflowStep* goToStep = this->GoToButtonToStepMap[goToButton];\n \/\/ if (this->Workflow->canGoToStep(currentStep, goToStep))\n \/\/ for now we'll assume we can go to the step\n if (true)\n {\n goToButton->setEnabled(true);\n goToButton->show();\n }\n \/\/ disable the goTo button if we can't go to it, and optionally hide it\n else\n {\n goToButton->setEnabled(false);\n this->HideInvalidButtons ? goToButton->hide() : goToButton->show();\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ctkWorkflowButtonBoxWidget methods\n\n\/\/-----------------------------------------------------------------------------\nctkWorkflowButtonBoxWidget::ctkWorkflowButtonBoxWidget(ctkWorkflow* newWorkflow, QWidget* newParent) :\n Superclass(newParent)\n{\n CTK_INIT_PRIVATE(ctkWorkflowButtonBoxWidget);\n CTK_D(ctkWorkflowButtonBoxWidget);\n\n d->setupUi(this);\n\n this->setWorkflow(newWorkflow);\n}\n\n\/\/-----------------------------------------------------------------------------\nctkWorkflowButtonBoxWidget::ctkWorkflowButtonBoxWidget(QWidget* newParent) :\n Superclass(newParent)\n{\n CTK_INIT_PRIVATE(ctkWorkflowButtonBoxWidget);\n CTK_D(ctkWorkflowButtonBoxWidget);\n\n d->setupUi(this);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setWorkflow(ctkWorkflow * newWorkflow)\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n\n if (d->Workflow == newWorkflow)\n {\n return;\n }\n\n \/\/ Disconnect\n if (!d->Workflow.isNull())\n {\n QObject::disconnect(d->BackButton, SIGNAL(clicked()), d->Workflow, SLOT(goBackward()));\n QObject::disconnect(d->NextButton, SIGNAL(clicked()), d->Workflow, SLOT(goForward()));\n }\n\n \/\/ Connect\n if (newWorkflow)\n {\n QObject::connect(d->BackButton, SIGNAL(clicked()), newWorkflow, SLOT(goBackward()));\n QObject::connect(d->NextButton, SIGNAL(clicked()), newWorkflow, SLOT(goForward()));\n }\n\n d->Workflow = newWorkflow;\n}\n\n\/\/-----------------------------------------------------------------------------\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QString, backButtonDefaultText,\n BackButtonDefaultText);\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setBackButtonDefaultText(const QString& defaultText)\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n d->BackButtonDefaultText = defaultText;\n if (d->Workflow)\n {\n this->updateButtons();\n }\n else\n {\n d->BackButton->setText(d->BackButtonDefaultText);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QString, nextButtonDefaultText,\n NextButtonDefaultText);\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setNextButtonDefaultText(const QString& defaultText)\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n d->NextButtonDefaultText = defaultText;\n this->updateButtons();\n if (d->Workflow)\n {\n this->updateButtons();\n }\n else\n {\n d->NextButton->setText(d->NextButtonDefaultText);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, ctkWorkflow*, workflow, Workflow);\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QPushButton*, backButton, BackButton);\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QBoxLayout::Direction, direction, Direction);\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, bool, hideInvalidButtons, HideInvalidButtons);\nCTK_SET_CXX(ctkWorkflowButtonBoxWidget, bool, setHideInvalidButtons, HideInvalidButtons);\n\n\/\/-----------------------------------------------------------------------------\n\/\/ TODO will be list of next buttons for branching workflow\nQPushButton* ctkWorkflowButtonBoxWidget::nextButton()const\n{\n CTK_D(const ctkWorkflowButtonBoxWidget);\n return d->NextButton;\n}\n\n\/\/-----------------------------------------------------------------------------\nQList ctkWorkflowButtonBoxWidget::goToButtons()const\n{\n CTK_D(const ctkWorkflowButtonBoxWidget);\n return d->GoToButtonToStepMap.keys();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setDirection(const QBoxLayout::Direction& newDirection)\n{\n if (QBoxLayout* layout = qobject_cast(this->layout()))\n {\n layout->setDirection(newDirection);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::updateButtons()\n{\n\n CTK_D(ctkWorkflowButtonBoxWidget);\n if (d->Workflow.isNull())\n {\n return;\n }\n\n ctkWorkflowStep* currentStep = d->Workflow->currentStep();\n if (!currentStep)\n {\n return;\n }\n\n d->updateBackButton(currentStep);\n d->updateNextButton(currentStep);\n d->updateGoToButtons(currentStep);\n}\n\n\/\/--------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::prepareGoToStep()\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n if (QPushButton* button = qobject_cast(QObject::sender()))\n {\n if (ctkWorkflowStep* step = d->GoToButtonToStepMap.value(button))\n {\n d->Workflow->goToStep(step->id());\n }\n }\n}\nSTYLE: WorkflowWidget - Remove extra call to updateButtons in ctkWorkflowButtonBoxWidget\/*=========================================================================\n\n Library: CTK\n \n Copyright (c) 2010 Kitware Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.commontk.org\/LICENSE\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n =========================================================================*\/\n\n\/\/ Qt includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ CTK includes\n#include \"ctkWorkflowButtonBoxWidget.h\"\n#include \"ctkWorkflowStep.h\"\n#include \"ctkWorkflowWidgetStep.h\"\n#include \"ctkWorkflow.h\"\n\n\/\/ STD includes\n#include \n\n\/\/-----------------------------------------------------------------------------\nclass ctkWorkflowButtonBoxWidgetPrivate : public ctkPrivate\n{\npublic:\n CTK_DECLARE_PUBLIC(ctkWorkflowButtonBoxWidget);\n ctkWorkflowButtonBoxWidgetPrivate();\n ~ctkWorkflowButtonBoxWidgetPrivate(){}\n\n void setupUi(QWidget * newParent);\n\n QPointer Workflow;\n\n \/\/ Convenient typedefs\n typedef QMap ButtonToStepMapType;\n\n \/\/ The buttons on the widget (maintain maps associating each forward\/goTo button with its step)\n QPushButton* BackButton;\n QString BackButtonDefaultText;\n QPushButton* NextButton;\n QString NextButtonDefaultText;\n ButtonToStepMapType GoToButtonToStepMap;\n\n \/\/ Direction for layout (for use with QBoxLayout only)\n QBoxLayout::Direction Direction;\n\n bool HideInvalidButtons;\n\n \/\/ Functions to add\/remove buttons\n void updateBackButton(ctkWorkflowStep* currentStep);\n void updateNextButton(ctkWorkflowStep* currentStep);\n void updateGoToButtons(ctkWorkflowStep* currentStep);\n\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ctkWorkflowButtonBoxWidgetPrivate methods\n\n\/\/-----------------------------------------------------------------------------\nctkWorkflowButtonBoxWidgetPrivate::ctkWorkflowButtonBoxWidgetPrivate()\n{\n this->BackButton = 0;\n this->BackButtonDefaultText = \"Back\";\n this->NextButton = 0;\n this->NextButtonDefaultText = \"Next\";\n this->Direction = QBoxLayout::LeftToRight;\n this->HideInvalidButtons = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidgetPrivate::setupUi(QWidget * newParent)\n{\n QBoxLayout * boxLayout = new QBoxLayout(this->Direction, newParent);\n boxLayout->setSpacing(0);\n boxLayout->setContentsMargins(0, 0, 0, 0);\n newParent->setLayout(boxLayout);\n\n \/\/ Retrieve standard icons\n QIcon backIcon = newParent->style()->standardIcon(QStyle::SP_ArrowLeft);\n QIcon nextIcon = newParent->style()->standardIcon(QStyle::SP_ArrowRight);\n\n \/\/ Setup the buttons\n this->BackButton = new QPushButton(backIcon, this->BackButtonDefaultText, newParent);\n newParent->layout()->addWidget(this->BackButton);\n\n this->NextButton = new QPushButton(nextIcon, this->NextButtonDefaultText, newParent);\n this->NextButton->setLayoutDirection(Qt::RightToLeft);\n newParent->layout()->addWidget(this->NextButton);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidgetPrivate::updateBackButton(ctkWorkflowStep* currentStep)\n{\n CTK_P(ctkWorkflowButtonBoxWidget);\n\n Q_ASSERT(this->Workflow);\n Q_ASSERT(currentStep);\n Q_ASSERT(p->layout());\n\n ctkWorkflowWidgetStep* step = qobject_cast(currentStep);\n\n \/\/ Set the back button text\n QString backButtonText = this->BackButtonDefaultText;\n if (step && !step->backButtonText().isEmpty())\n {\n backButtonText = step->backButtonText();\n }\n this->BackButton->setText(backButtonText);\n\n \/\/ Enable and show the back button if we can go backward\n if (this->Workflow->canGoBackward(currentStep))\n {\n this->BackButton->setEnabled(true);\n this->BackButton->show();\n\n \/\/ Apply the buttonBox hints if possible\n if (step)\n {\n this->BackButton->setDisabled(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::BackButtonDisabled);\n this->BackButton->setHidden(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::BackButtonHidden);\n }\n }\n \/\/ Disable the back button if we can't go backward, and optionally hide it\n else\n {\n this->BackButton->setEnabled(false);\n this->HideInvalidButtons ? this->BackButton->hide() : this->BackButton->show();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ This will change for branching workflows, to look more like updateGoToButtons()\nvoid ctkWorkflowButtonBoxWidgetPrivate::updateNextButton(ctkWorkflowStep* currentStep)\n{\n CTK_P(ctkWorkflowButtonBoxWidget);\n\n Q_ASSERT(this->Workflow);\n Q_ASSERT(currentStep);\n Q_ASSERT(p->layout());\n\n ctkWorkflowWidgetStep* step = qobject_cast(currentStep);\n\n \/\/ Set the next button text\n QString nextButtonText = this->NextButtonDefaultText;\n if (step && !step->nextButtonText().isEmpty())\n {\n nextButtonText = step->nextButtonText();\n }\n this->NextButton->setText(nextButtonText);\n\n \/\/ Enable and show the next button if we can go forward\n if (this->Workflow->canGoForward(currentStep))\n {\n this->NextButton->setEnabled(true);\n this->NextButton->show();\n\n \/\/ Apply the buttonBox hints if possible\n if (step)\n {\n this->NextButton->setDisabled(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::NextButtonDisabled);\n this->NextButton->setHidden(\n step->buttonBoxHints() & ctkWorkflowWidgetStep::NextButtonHidden);\n }\n }\n \/\/ Disable the next button if we can't go forward, and optionally hide it\n else\n {\n this->NextButton->setEnabled(false);\n this->HideInvalidButtons ? this->NextButton->hide() : this->NextButton->show();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidgetPrivate::updateGoToButtons(ctkWorkflowStep* currentStep)\n{\n CTK_P(ctkWorkflowButtonBoxWidget);\n\n Q_ASSERT(this->Workflow);\n Q_ASSERT(currentStep);\n Q_ASSERT(p->layout());\n\n \/\/ Change the buttons only if the set of steps to have goTo buttons is either empty or has changed\n QSet goToStepsToHaveButtons = QSet::fromList(this->Workflow->finishSteps());\n QSet goToStepsThatHaveButtons = QSet::fromList(this->GoToButtonToStepMap.values());\n\n \/\/ Remove the buttons if the set of steps to have goTo buttons has changed\n if (!this->GoToButtonToStepMap.isEmpty() && goToStepsThatHaveButtons != goToStepsToHaveButtons)\n {\n foreach (QPushButton* goToButton, this->GoToButtonToStepMap.keys())\n {\n p->layout()->removeWidget(goToButton);\n delete goToButton;\n }\n this->GoToButtonToStepMap.clear();\n }\n\n \/\/ Create the buttons, either for the first time or after removing them above\n if (this->GoToButtonToStepMap.isEmpty())\n {\n \/\/ Create a button for each of the goToSteps\n foreach (ctkWorkflowStep* step, goToStepsToHaveButtons)\n {\n \/\/ TODO shouldn't have id here\n QPushButton* goToButton = new QPushButton(step->id());\n p->layout()->addWidget(goToButton);\n QObject::connect(goToButton, SIGNAL(clicked()), p, SLOT(prepareGoToStep()));\n this->GoToButtonToStepMap[goToButton] = step;\n }\n \n }\n\n \/\/ Show\/hide the goTo buttons depending on whether they are accessible from the current step\n foreach (QPushButton* goToButton, this->GoToButtonToStepMap.keys())\n {\n \/\/ TODO enable and show the goTo button if we can go to it\n \/\/ ctkWorkflowStep* goToStep = this->GoToButtonToStepMap[goToButton];\n \/\/ if (this->Workflow->canGoToStep(currentStep, goToStep))\n \/\/ for now we'll assume we can go to the step\n if (true)\n {\n goToButton->setEnabled(true);\n goToButton->show();\n }\n \/\/ disable the goTo button if we can't go to it, and optionally hide it\n else\n {\n goToButton->setEnabled(false);\n this->HideInvalidButtons ? goToButton->hide() : goToButton->show();\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ ctkWorkflowButtonBoxWidget methods\n\n\/\/-----------------------------------------------------------------------------\nctkWorkflowButtonBoxWidget::ctkWorkflowButtonBoxWidget(ctkWorkflow* newWorkflow, QWidget* newParent) :\n Superclass(newParent)\n{\n CTK_INIT_PRIVATE(ctkWorkflowButtonBoxWidget);\n CTK_D(ctkWorkflowButtonBoxWidget);\n\n d->setupUi(this);\n\n this->setWorkflow(newWorkflow);\n}\n\n\/\/-----------------------------------------------------------------------------\nctkWorkflowButtonBoxWidget::ctkWorkflowButtonBoxWidget(QWidget* newParent) :\n Superclass(newParent)\n{\n CTK_INIT_PRIVATE(ctkWorkflowButtonBoxWidget);\n CTK_D(ctkWorkflowButtonBoxWidget);\n\n d->setupUi(this);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setWorkflow(ctkWorkflow * newWorkflow)\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n\n if (d->Workflow == newWorkflow)\n {\n return;\n }\n\n \/\/ Disconnect\n if (!d->Workflow.isNull())\n {\n QObject::disconnect(d->BackButton, SIGNAL(clicked()), d->Workflow, SLOT(goBackward()));\n QObject::disconnect(d->NextButton, SIGNAL(clicked()), d->Workflow, SLOT(goForward()));\n }\n\n \/\/ Connect\n if (newWorkflow)\n {\n QObject::connect(d->BackButton, SIGNAL(clicked()), newWorkflow, SLOT(goBackward()));\n QObject::connect(d->NextButton, SIGNAL(clicked()), newWorkflow, SLOT(goForward()));\n }\n\n d->Workflow = newWorkflow;\n}\n\n\/\/-----------------------------------------------------------------------------\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QString, backButtonDefaultText,\n BackButtonDefaultText);\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setBackButtonDefaultText(const QString& defaultText)\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n d->BackButtonDefaultText = defaultText;\n if (d->Workflow)\n {\n this->updateButtons();\n }\n else\n {\n d->BackButton->setText(d->BackButtonDefaultText);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QString, nextButtonDefaultText,\n NextButtonDefaultText);\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setNextButtonDefaultText(const QString& defaultText)\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n d->NextButtonDefaultText = defaultText;\n if (d->Workflow)\n {\n this->updateButtons();\n }\n else\n {\n d->NextButton->setText(d->NextButtonDefaultText);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, ctkWorkflow*, workflow, Workflow);\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QPushButton*, backButton, BackButton);\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, QBoxLayout::Direction, direction, Direction);\nCTK_GET_CXX(ctkWorkflowButtonBoxWidget, bool, hideInvalidButtons, HideInvalidButtons);\nCTK_SET_CXX(ctkWorkflowButtonBoxWidget, bool, setHideInvalidButtons, HideInvalidButtons);\n\n\/\/-----------------------------------------------------------------------------\n\/\/ TODO will be list of next buttons for branching workflow\nQPushButton* ctkWorkflowButtonBoxWidget::nextButton()const\n{\n CTK_D(const ctkWorkflowButtonBoxWidget);\n return d->NextButton;\n}\n\n\/\/-----------------------------------------------------------------------------\nQList ctkWorkflowButtonBoxWidget::goToButtons()const\n{\n CTK_D(const ctkWorkflowButtonBoxWidget);\n return d->GoToButtonToStepMap.keys();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::setDirection(const QBoxLayout::Direction& newDirection)\n{\n if (QBoxLayout* layout = qobject_cast(this->layout()))\n {\n layout->setDirection(newDirection);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::updateButtons()\n{\n\n CTK_D(ctkWorkflowButtonBoxWidget);\n if (d->Workflow.isNull())\n {\n return;\n }\n\n ctkWorkflowStep* currentStep = d->Workflow->currentStep();\n if (!currentStep)\n {\n return;\n }\n\n d->updateBackButton(currentStep);\n d->updateNextButton(currentStep);\n d->updateGoToButtons(currentStep);\n}\n\n\/\/--------------------------------------------------------------------------\nvoid ctkWorkflowButtonBoxWidget::prepareGoToStep()\n{\n CTK_D(ctkWorkflowButtonBoxWidget);\n if (QPushButton* button = qobject_cast(QObject::sender()))\n {\n if (ctkWorkflowStep* step = d->GoToButtonToStepMap.value(button))\n {\n d->Workflow->goToStep(step->id());\n }\n }\n}\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"colorentity.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/color\/wavelengths.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/containers\/specializedarrays.h\"\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ ColorEntity class implementation.\n\/\/\n\nstruct ColorEntity::Impl\n{\n ColorValueArray m_values;\n ColorValueArray m_alpha;\n ColorSpace m_color_space;\n Vector2f m_wavelength_range;\n float m_multiplier;\n};\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n\n const char* color_space_name(const ColorSpace color_space)\n {\n switch (color_space)\n {\n case ColorSpaceLinearRGB: return \"linear_rgb\";\n case ColorSpaceSRGB: return \"srgb\";\n case ColorSpaceCIEXYZ: return \"ciexyz\";\n case ColorSpaceSpectral: return \"spectral\";\n default: return \"\";\n }\n }\n}\n\nColorEntity::ColorEntity(\n const char* name,\n const ParamArray& params)\n : Entity(g_class_uid, params)\n , impl(new Impl())\n{\n set_name(name);\n\n extract_parameters();\n extract_values();\n\n check_validity();\n}\n\nColorEntity::ColorEntity(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values)\n : Entity(g_class_uid, params)\n , impl(new Impl())\n{\n set_name(name);\n\n extract_parameters();\n\n impl->m_values = values;\n impl->m_alpha.push_back(1.0f);\n\n check_validity();\n}\n\nColorEntity::ColorEntity(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values,\n const ColorValueArray& alpha)\n : Entity(g_class_uid, params)\n , impl(new Impl())\n{\n set_name(name);\n\n extract_parameters();\n\n impl->m_values = values;\n impl->m_alpha = alpha;\n\n check_validity();\n}\n\nColorEntity::~ColorEntity()\n{\n delete impl;\n}\n\nvoid ColorEntity::extract_parameters()\n{\n \/\/ Retrieve the color space.\n const string color_space = m_params.get_required(\"color_space\", \"linear_rgb\");\n if (color_space == \"linear_rgb\")\n impl->m_color_space = ColorSpaceLinearRGB;\n else if (color_space == \"srgb\")\n impl->m_color_space = ColorSpaceSRGB;\n else if (color_space == \"ciexyz\")\n impl->m_color_space = ColorSpaceCIEXYZ;\n else if (color_space == \"spectral\")\n impl->m_color_space = ColorSpaceSpectral;\n else\n {\n RENDERER_LOG_ERROR(\n \"invalid value \\\"%s\\\" for parameter \\\"color_space\\\", \"\n \"using default value \\\"linear_rgb\\\"\",\n color_space.c_str());\n impl->m_color_space = ColorSpaceLinearRGB;\n }\n\n \/\/ For the spectral color space, retrieve the wavelength range.\n if (impl->m_color_space == ColorSpaceSpectral)\n {\n const Vector2f DefaultWavelengthRange(LowWavelength, HighWavelength);\n impl->m_wavelength_range =\n m_params.get_required(\n \"wavelength_range\",\n DefaultWavelengthRange);\n\n if (impl->m_wavelength_range[0] < 0.0 ||\n impl->m_wavelength_range[1] < 0.0 ||\n impl->m_wavelength_range[0] > impl->m_wavelength_range[1])\n {\n RENDERER_LOG_ERROR(\n \"invalid value \\\"%f %f\\\" for parameter \\\"%s\\\", \"\n \"using default value \\\"%f %f\\\"\",\n impl->m_wavelength_range[0],\n impl->m_wavelength_range[1],\n \"wavelength_range\",\n DefaultWavelengthRange[0],\n DefaultWavelengthRange[1]);\n\n impl->m_wavelength_range = DefaultWavelengthRange;\n }\n }\n else\n {\n impl->m_wavelength_range[0] =\n impl->m_wavelength_range[1] = 0.0f;\n }\n\n \/\/ Retrieve multiplier.\n impl->m_multiplier = m_params.get_optional(\"multiplier\", 1.0f);\n}\n\nvoid ColorEntity::extract_values()\n{\n ColorValueArray black;\n black.push_back(0.0f);\n\n impl->m_values = m_params.get_required(\"color\", black);\n\n ColorValueArray opaque;\n opaque.push_back(1.0f);\n\n impl->m_alpha = m_params.get_optional(\"alpha\", opaque);\n}\n\nvoid ColorEntity::check_validity()\n{\n \/\/ Check the number of color values.\n if (impl->m_color_space == ColorSpaceSpectral)\n {\n if (impl->m_values.empty())\n {\n RENDERER_LOG_ERROR(\"1 or more values required for \\\"spectral\\\" color space, got 0\");\n }\n }\n else\n {\n if (impl->m_values.size() != 1 && impl->m_values.size() != 3)\n {\n RENDERER_LOG_ERROR(\n \"1 or 3 values required for \\\"%s\\\" color space, got \" FMT_SIZE_T,\n color_space_name(impl->m_color_space),\n impl->m_values.size());\n }\n }\n}\n\nvoid ColorEntity::release()\n{\n delete this;\n}\n\nconst ColorValueArray& ColorEntity::get_values() const\n{\n return impl->m_values;\n}\n\nconst ColorValueArray& ColorEntity::get_alpha() const\n{\n return impl->m_alpha;\n}\n\nColorSpace ColorEntity::get_color_space() const\n{\n return impl->m_color_space;\n}\n\nconst Vector2f& ColorEntity::get_wavelength_range() const\n{\n assert(impl->m_color_space == ColorSpaceSpectral);\n return impl->m_wavelength_range;\n}\n\nfloat ColorEntity::get_multiplier() const\n{\n return impl->m_multiplier;\n}\n\n\n\/\/\n\/\/ ColorEntityFactory class implementation.\n\/\/\n\nDictionaryArray ColorEntityFactory::get_widget_definitions()\n{\n DictionaryArray definitions;\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"color_space\")\n .insert(\"label\", \"Color Space\")\n .insert(\"widget\", \"dropdown_list\")\n .insert(\"dropdown_items\",\n Dictionary()\n .insert(\"Linear RGB\", \"linear_rgb\")\n .insert(\"sRGB\", \"srgb\")\n .insert(\"CIE XYZ\", \"ciexyz\")\n .insert(\"Spectral\", \"spectral\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"linear_rgb\")\n\/* .insert(\"on_change\", \"rebuild_form\")*\/);\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"wavelength_range\")\n .insert(\"label\", \"Wavelength Range\")\n .insert(\"widget\", \"text_box\")\n .insert(\"default\", \"400.0 700.0\")\n .insert(\"use\", \"optional\"));\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"color\")\n .insert(\"label\", \"Color\")\n .insert(\"widget\", \"color_picker\")\n .insert(\"default\", \"0.0 0.0 0.0\")\n .insert(\"use\", \"required\"));\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"alpha\")\n .insert(\"label\", \"Alpha\")\n .insert(\"widget\", \"text_box\")\n .insert(\"default\", \"1.0\")\n .insert(\"use\", \"optional\"));\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"multiplier\")\n .insert(\"label\", \"Multiplier\")\n .insert(\"widget\", \"text_box\")\n .insert(\"default\", \"1.0\")\n .insert(\"use\", \"optional\"));\n\n return definitions;\n}\n\nauto_release_ptr ColorEntityFactory::create(\n const char* name,\n const ParamArray& params)\n{\n return\n auto_release_ptr(\n new ColorEntity(name, params));\n}\n\nauto_release_ptr ColorEntityFactory::create(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values)\n{\n return\n auto_release_ptr(\n new ColorEntity(name, params, values));\n}\n\nauto_release_ptr ColorEntityFactory::create(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values,\n const ColorValueArray& alpha)\n{\n return\n auto_release_ptr(\n new ColorEntity(name, params, values, alpha));\n}\n\n} \/\/ namespace renderer\nswitched the default color space for color entities from linear RGB to sRGB.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"colorentity.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/color\/wavelengths.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/containers\/specializedarrays.h\"\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ ColorEntity class implementation.\n\/\/\n\nstruct ColorEntity::Impl\n{\n ColorValueArray m_values;\n ColorValueArray m_alpha;\n ColorSpace m_color_space;\n Vector2f m_wavelength_range;\n float m_multiplier;\n};\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n\n const char* color_space_name(const ColorSpace color_space)\n {\n switch (color_space)\n {\n case ColorSpaceLinearRGB: return \"linear_rgb\";\n case ColorSpaceSRGB: return \"srgb\";\n case ColorSpaceCIEXYZ: return \"ciexyz\";\n case ColorSpaceSpectral: return \"spectral\";\n default: return \"\";\n }\n }\n}\n\nColorEntity::ColorEntity(\n const char* name,\n const ParamArray& params)\n : Entity(g_class_uid, params)\n , impl(new Impl())\n{\n set_name(name);\n\n extract_parameters();\n extract_values();\n\n check_validity();\n}\n\nColorEntity::ColorEntity(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values)\n : Entity(g_class_uid, params)\n , impl(new Impl())\n{\n set_name(name);\n\n extract_parameters();\n\n impl->m_values = values;\n impl->m_alpha.push_back(1.0f);\n\n check_validity();\n}\n\nColorEntity::ColorEntity(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values,\n const ColorValueArray& alpha)\n : Entity(g_class_uid, params)\n , impl(new Impl())\n{\n set_name(name);\n\n extract_parameters();\n\n impl->m_values = values;\n impl->m_alpha = alpha;\n\n check_validity();\n}\n\nColorEntity::~ColorEntity()\n{\n delete impl;\n}\n\nvoid ColorEntity::extract_parameters()\n{\n \/\/ Retrieve the color space.\n const ColorSpace DefaultColorSpace = ColorSpaceSRGB;\n const char* DefaultColorSpaceName = color_space_name(DefaultColorSpace);\n const string color_space = m_params.get_required(\"color_space\", DefaultColorSpaceName);\n if (color_space == \"linear_rgb\")\n impl->m_color_space = ColorSpaceLinearRGB;\n else if (color_space == \"srgb\")\n impl->m_color_space = ColorSpaceSRGB;\n else if (color_space == \"ciexyz\")\n impl->m_color_space = ColorSpaceCIEXYZ;\n else if (color_space == \"spectral\")\n impl->m_color_space = ColorSpaceSpectral;\n else\n {\n RENDERER_LOG_ERROR(\n \"invalid value \\\"%s\\\" for parameter \\\"color_space\\\", \"\n \"using default value \\\"%s\\\"\",\n color_space.c_str(),\n DefaultColorSpaceName);\n impl->m_color_space = DefaultColorSpace;\n }\n\n \/\/ For the spectral color space, retrieve the wavelength range.\n if (impl->m_color_space == ColorSpaceSpectral)\n {\n const Vector2f DefaultWavelengthRange(LowWavelength, HighWavelength);\n impl->m_wavelength_range =\n m_params.get_required(\n \"wavelength_range\",\n DefaultWavelengthRange);\n\n if (impl->m_wavelength_range[0] < 0.0 ||\n impl->m_wavelength_range[1] < 0.0 ||\n impl->m_wavelength_range[0] > impl->m_wavelength_range[1])\n {\n RENDERER_LOG_ERROR(\n \"invalid value \\\"%f %f\\\" for parameter \\\"%s\\\", \"\n \"using default value \\\"%f %f\\\"\",\n impl->m_wavelength_range[0],\n impl->m_wavelength_range[1],\n \"wavelength_range\",\n DefaultWavelengthRange[0],\n DefaultWavelengthRange[1]);\n\n impl->m_wavelength_range = DefaultWavelengthRange;\n }\n }\n else\n {\n impl->m_wavelength_range[0] =\n impl->m_wavelength_range[1] = 0.0f;\n }\n\n \/\/ Retrieve multiplier.\n impl->m_multiplier = m_params.get_optional(\"multiplier\", 1.0f);\n}\n\nvoid ColorEntity::extract_values()\n{\n ColorValueArray black;\n black.push_back(0.0f);\n\n impl->m_values = m_params.get_required(\"color\", black);\n\n ColorValueArray opaque;\n opaque.push_back(1.0f);\n\n impl->m_alpha = m_params.get_optional(\"alpha\", opaque);\n}\n\nvoid ColorEntity::check_validity()\n{\n \/\/ Check the number of color values.\n if (impl->m_color_space == ColorSpaceSpectral)\n {\n if (impl->m_values.empty())\n {\n RENDERER_LOG_ERROR(\"1 or more values required for \\\"spectral\\\" color space, got 0\");\n }\n }\n else\n {\n if (impl->m_values.size() != 1 && impl->m_values.size() != 3)\n {\n RENDERER_LOG_ERROR(\n \"1 or 3 values required for \\\"%s\\\" color space, got \" FMT_SIZE_T,\n color_space_name(impl->m_color_space),\n impl->m_values.size());\n }\n }\n}\n\nvoid ColorEntity::release()\n{\n delete this;\n}\n\nconst ColorValueArray& ColorEntity::get_values() const\n{\n return impl->m_values;\n}\n\nconst ColorValueArray& ColorEntity::get_alpha() const\n{\n return impl->m_alpha;\n}\n\nColorSpace ColorEntity::get_color_space() const\n{\n return impl->m_color_space;\n}\n\nconst Vector2f& ColorEntity::get_wavelength_range() const\n{\n assert(impl->m_color_space == ColorSpaceSpectral);\n return impl->m_wavelength_range;\n}\n\nfloat ColorEntity::get_multiplier() const\n{\n return impl->m_multiplier;\n}\n\n\n\/\/\n\/\/ ColorEntityFactory class implementation.\n\/\/\n\nDictionaryArray ColorEntityFactory::get_widget_definitions()\n{\n DictionaryArray definitions;\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"color_space\")\n .insert(\"label\", \"Color Space\")\n .insert(\"widget\", \"dropdown_list\")\n .insert(\"dropdown_items\",\n Dictionary()\n .insert(\"Linear RGB\", \"linear_rgb\")\n .insert(\"sRGB\", \"srgb\")\n .insert(\"CIE XYZ\", \"ciexyz\")\n .insert(\"Spectral\", \"spectral\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"srgb\")\n\/* .insert(\"on_change\", \"rebuild_form\")*\/);\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"wavelength_range\")\n .insert(\"label\", \"Wavelength Range\")\n .insert(\"widget\", \"text_box\")\n .insert(\"default\", \"400.0 700.0\")\n .insert(\"use\", \"optional\"));\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"color\")\n .insert(\"label\", \"Color\")\n .insert(\"widget\", \"color_picker\")\n .insert(\"default\", \"0.0 0.0 0.0\")\n .insert(\"use\", \"required\"));\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"alpha\")\n .insert(\"label\", \"Alpha\")\n .insert(\"widget\", \"text_box\")\n .insert(\"default\", \"1.0\")\n .insert(\"use\", \"optional\"));\n\n definitions.push_back(\n Dictionary()\n .insert(\"name\", \"multiplier\")\n .insert(\"label\", \"Multiplier\")\n .insert(\"widget\", \"text_box\")\n .insert(\"default\", \"1.0\")\n .insert(\"use\", \"optional\"));\n\n return definitions;\n}\n\nauto_release_ptr ColorEntityFactory::create(\n const char* name,\n const ParamArray& params)\n{\n return\n auto_release_ptr(\n new ColorEntity(name, params));\n}\n\nauto_release_ptr ColorEntityFactory::create(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values)\n{\n return\n auto_release_ptr(\n new ColorEntity(name, params, values));\n}\n\nauto_release_ptr ColorEntityFactory::create(\n const char* name,\n const ParamArray& params,\n const ColorValueArray& values,\n const ColorValueArray& alpha)\n{\n return\n auto_release_ptr(\n new ColorEntity(name, params, values, alpha));\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ logger_configuration.cpp\n\/\/\n\/\/ Identification: src\/backend\/benchmark\/logger\/logger_configuration.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \n#include \n#include \n\n#include \"backend\/common\/exception.h\"\n#include \"backend\/common\/logger.h\"\n#include \"backend\/benchmark\/logger\/logger_configuration.h\"\n#include \"backend\/benchmark\/ycsb\/ycsb_configuration.h\"\n#include \"backend\/benchmark\/tpcc\/tpcc_configuration.h\"\n\nnamespace peloton {\nnamespace benchmark {\nnamespace logger {\n\nvoid Usage(FILE* out) {\n fprintf(out,\n \"Command line options : logger \\n\"\n \" -h --help : Print help message \\n\"\n \" -a --asynchronous-mode : Asynchronous mode \\n\"\n \" -e --experiment-type : Experiment Type \\n\"\n \" -f --data-file-size : Data file size (MB) \\n\"\n \" -l --logging-type : Logging type \\n\"\n \" -n --nvm-latency : NVM latency \\n\"\n \" -p --pcommit-latency : pcommit latency \\n\"\n \" -v --flush-mode : Flush mode \\n\"\n \" -w --commit-interval : Group commit interval \\n\"\n \" -y --benchmark-type : Benchmark type \\n\"\n );\n}\n\nstatic struct option opts[] = {\n {\"asynchronous_mode\", optional_argument, NULL, 'a'},\n {\"experiment-type\", optional_argument, NULL, 'e'},\n {\"data-file-size\", optional_argument, NULL, 'f'},\n {\"logging-type\", optional_argument, NULL, 'l'},\n {\"nvm-latency\", optional_argument, NULL, 'n'},\n {\"pcommit-latency\", optional_argument, NULL, 'p'},\n {\"skew\", optional_argument, NULL, 's'},\n {\"flush-mode\", optional_argument, NULL, 'v'},\n {\"commit-interval\", optional_argument, NULL, 'w'},\n {\"benchmark-type\", optional_argument, NULL, 'y'},\n {NULL, 0, NULL, 0}};\n\nstatic void ValidateLoggingType(const configuration& state) {\n if (state.logging_type <= LOGGING_TYPE_INVALID) {\n LOG_ERROR(\"Invalid logging_type :: %d\", state.logging_type);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"Logging_type :: %s\", LoggingTypeToString(state.logging_type).c_str());\n}\n\nstd::string BenchmarkTypeToString(BenchmarkType type) {\n switch (type) {\n case BENCHMARK_TYPE_INVALID:\n return \"INVALID\";\n\n case BENCHMARK_TYPE_YCSB:\n return \"YCSB\";\n case BENCHMARK_TYPE_TPCC:\n return \"TPCC\";\n\n default:\n LOG_ERROR(\"Invalid benchmark_type :: %d\", type);\n exit(EXIT_FAILURE);\n }\n return \"INVALID\";\n}\n\nstd::string ExperimentTypeToString(ExperimentType type) {\n switch (type) {\n case EXPERIMENT_TYPE_INVALID:\n return \"INVALID\";\n\n case EXPERIMENT_TYPE_THROUGHPUT:\n return \"THROUGHPUT\";\n case EXPERIMENT_TYPE_RECOVERY:\n return \"RECOVERY\";\n case EXPERIMENT_TYPE_STORAGE:\n return \"STORAGE\";\n case EXPERIMENT_TYPE_LATENCY:\n return \"LATENCY\";\n\n default:\n LOG_ERROR(\"Invalid experiment_type :: %d\", type);\n exit(EXIT_FAILURE);\n }\n\n return \"INVALID\";\n}\n\nstd::string AsynchronousTypeToString(AsynchronousType type) {\n switch (type) {\n case ASYNCHRONOUS_TYPE_INVALID:\n return \"INVALID\";\n\n case ASYNCHRONOUS_TYPE_SYNC:\n return \"SYNC\";\n case ASYNCHRONOUS_TYPE_ASYNC:\n return \"ASYNC\";\n case ASYNCHRONOUS_TYPE_DISABLED:\n return \"DISABLED\";\n\n default:\n LOG_ERROR(\"Invalid asynchronous_mode :: %d\", type);\n exit(EXIT_FAILURE);\n }\n\n return \"INVALID\";\n}\n\n\nstatic void ValidateBenchmarkType(\n const configuration& state) {\n if (state.benchmark_type <= 0 || state.benchmark_type > 3) {\n LOG_ERROR(\"Invalid benchmark_type :: %d\", state.benchmark_type);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"%s : %s\", \"benchmark_type\", BenchmarkTypeToString(state.benchmark_type).c_str());\n}\n\nstatic void ValidateDataFileSize(\n const configuration& state) {\n if (state.data_file_size <= 0) {\n LOG_ERROR(\"Invalid data_file_size :: %lu\", state.data_file_size);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"data_file_size :: %lu\", state.data_file_size);\n}\n\nstatic void ValidateExperimentType(\n const configuration& state) {\n if (state.experiment_type < 0 || state.experiment_type > 4) {\n LOG_ERROR(\"Invalid experiment_type :: %d\", state.experiment_type);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"%s : %s\", \"experiment_type\", ExperimentTypeToString(state.experiment_type).c_str());\n}\n\nstatic void ValidateWaitTimeout(const configuration& state) {\n if (state.wait_timeout < 0) {\n LOG_ERROR(\"Invalid wait_timeout :: %d\", state.wait_timeout);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"wait_timeout :: %d\", state.wait_timeout);\n}\n\nstatic void ValidateFlushMode(\n const configuration& state) {\n if (state.flush_mode <= 0 || state.flush_mode >= 3) {\n LOG_ERROR(\"Invalid flush_mode :: %d\", state.flush_mode);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"flush_mode :: %d\", state.flush_mode);\n}\n\nstatic void ValidateAsynchronousMode(\n const configuration& state) {\n if (state.asynchronous_mode <= ASYNCHRONOUS_TYPE_INVALID ||\n state.asynchronous_mode > ASYNCHRONOUS_TYPE_DISABLED) {\n LOG_ERROR(\"Invalid asynchronous_mode :: %d\", state.asynchronous_mode);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"%s : %s\", \"asynchronous_mode\", AsynchronousTypeToString(state.asynchronous_mode).c_str());\n}\n\nstatic void ValidateNVMLatency(\n const configuration& state) {\n if (state.nvm_latency < 0) {\n LOG_ERROR(\"Invalid nvm_latency :: %d\", state.nvm_latency);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"nvm_latency :: %d\", state.nvm_latency);\n}\n\nstatic void ValidatePCOMMITLatency(\n const configuration& state) {\n if (state.pcommit_latency < 0) {\n LOG_ERROR(\"Invalid pcommit_latency :: %d\", state.pcommit_latency);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"pcommit_latency :: %d\", state.pcommit_latency);\n}\n\nstatic void ValidateLogFileDir(\n configuration& state) {\n struct stat data_stat;\n\n \/\/ Assign log file dir based on logging type\n switch (state.logging_type) {\n \/\/ Log file on NVM\n case LOGGING_TYPE_NVM_WAL:\n case LOGGING_TYPE_NVM_WBL: {\n int status = stat(NVM_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = NVM_DIR;\n }\n } break;\n\n \/\/ Log file on SSD\n case LOGGING_TYPE_SSD_WAL:\n case LOGGING_TYPE_SSD_WBL: {\n int status = stat(SSD_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = SSD_DIR;\n }\n } break;\n\n \/\/ Log file on HDD\n case LOGGING_TYPE_HDD_WAL:\n case LOGGING_TYPE_HDD_WBL: {\n int status = stat(HDD_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = HDD_DIR;\n }\n } break;\n\n case LOGGING_TYPE_INVALID:\n default: {\n int status = stat(TMP_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = TMP_DIR;\n } else {\n throw Exception(\"Could not find temp directory : \" +\n std::string(TMP_DIR));\n }\n } break;\n }\n\n LOG_INFO(\"log_file_dir :: %s\", state.log_file_dir.c_str());\n}\n\nvoid ParseArguments(int argc, char* argv[], configuration& state) {\n\n \/\/ Default Logger Values\n state.logging_type = LOGGING_TYPE_NVM_WAL;\n state.log_file_dir = TMP_DIR;\n state.data_file_size = 512;\n\n state.experiment_type = EXPERIMENT_TYPE_THROUGHPUT;\n state.wait_timeout = 200;\n state.benchmark_type = BENCHMARK_TYPE_YCSB;\n state.flush_mode = 2;\n state.nvm_latency = 0;\n state.pcommit_latency = 0;\n state.asynchronous_mode = ASYNCHRONOUS_TYPE_SYNC;\n\n \/\/ Default YCSB Values\n ycsb::state.scale_factor = 1;\n ycsb::state.duration = 1000;\n ycsb::state.column_count = 10;\n ycsb::state.update_ratio = 0.5;\n ycsb::state.backend_count = 2;\n\n \/\/ Default Values\n tpcc::state.warehouse_count = 2; \/\/ 10\n tpcc::state.duration = 1000;\n tpcc::state.backend_count = 2;\n\n \/\/ Parse args\n while (1) {\n int idx = 0;\n \/\/ logger - a:e:f:hl:n:p:v:w:y:\n \/\/ ycsb - b:c:d:k:u:\n \/\/ tpcc - b:d:k:\n int c = getopt_long(argc, argv, \"a:e:f:hl:n:p:v:w:y:b:c:d:k:u:\", opts, &idx);\n\n if (c == -1) break;\n\n switch (c) {\n case 'a':\n state.asynchronous_mode = (AsynchronousType) atoi(optarg);\n break;\n case 'e':\n state.experiment_type = (ExperimentType)atoi(optarg);\n break;\n case 'f':\n state.data_file_size = atoi(optarg);\n break;\n case 'l':\n state.logging_type = (LoggingType)atoi(optarg);\n break;\n case 'n':\n state.nvm_latency = atoi(optarg);\n break;\n case 'p':\n state.pcommit_latency = atoi(optarg);\n break;\n case 'v':\n state.flush_mode = atoi(optarg);\n break;\n case 'w':\n state.wait_timeout = atoi(optarg);\n break;\n case 'y':\n state.benchmark_type = (BenchmarkType)atoi(optarg);\n break;\n\n \/\/ YCSB\n case 'b':\n ycsb::state.backend_count = atoi(optarg);\n tpcc::state.backend_count = atoi(optarg);\n break;\n case 'c':\n ycsb::state.column_count = atoi(optarg);\n break;\n case 'd':\n ycsb::state.duration = atoi(optarg);\n tpcc::state.duration = atoi(optarg);\n break;\n case 'k':\n ycsb::state.scale_factor = atoi(optarg);\n tpcc::state.warehouse_count = atoi(optarg);\n break;\n case 'u':\n ycsb::state.update_ratio = atof(optarg);\n break;\n\n case 'h':\n Usage(stderr);\n ycsb::Usage(stderr);\n exit(EXIT_FAILURE);\n break;\n\n default:\n fprintf(stderr, \"\\nUnknown option: -%c-\\n\", c);\n Usage(stderr);\n exit(EXIT_FAILURE);\n break;\n }\n }\n\n \/\/ Print Logger configuration\n ValidateLoggingType(state);\n ValidateExperimentType(state);\n ValidateAsynchronousMode(state);\n ValidateBenchmarkType(state);\n ValidateDataFileSize(state);\n ValidateLogFileDir(state);\n ValidateWaitTimeout(state);\n ValidateFlushMode(state);\n ValidateNVMLatency(state);\n ValidatePCOMMITLatency(state);\n\n \/\/ Print YCSB configuration\n if(state.benchmark_type == BENCHMARK_TYPE_YCSB) {\n ycsb::ValidateScaleFactor(ycsb::state);\n ycsb::ValidateColumnCount(ycsb::state);\n ycsb::ValidateUpdateRatio(ycsb::state);\n ycsb::ValidateBackendCount(ycsb::state);\n ycsb::ValidateDuration(ycsb::state);\n }\n \/\/ Print TPCC configuration\n else if(state.benchmark_type == BENCHMARK_TYPE_TPCC){\n tpcc::ValidateBackendCount(tpcc::state);\n tpcc::ValidateDuration(tpcc::state);\n tpcc::ValidateWarehouseCount(tpcc::state);\n\n \/\/ Static TPCC parameters\n tpcc::state.item_count = 10000; \/\/ 100000\n tpcc::state.districts_per_warehouse = 2; \/\/ 10\n tpcc::state.customers_per_district = 300; \/\/ 3000\n tpcc::state.new_orders_per_district = 90; \/\/ 900\n\n }\n\n}\n\n} \/\/ namespace logger\n} \/\/ namespace benchmark\n} \/\/ namespace peloton\nUpdated conf\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ logger_configuration.cpp\n\/\/\n\/\/ Identification: src\/backend\/benchmark\/logger\/logger_configuration.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \n#include \n#include \n\n#include \"backend\/common\/exception.h\"\n#include \"backend\/common\/logger.h\"\n#include \"backend\/benchmark\/logger\/logger_configuration.h\"\n#include \"backend\/benchmark\/ycsb\/ycsb_configuration.h\"\n#include \"backend\/benchmark\/tpcc\/tpcc_configuration.h\"\n\nnamespace peloton {\nnamespace benchmark {\nnamespace logger {\n\nvoid Usage(FILE* out) {\n fprintf(out,\n \"Command line options : logger \\n\"\n \" -h --help : Print help message \\n\"\n \" -a --asynchronous-mode : Asynchronous mode \\n\"\n \" -e --experiment-type : Experiment Type \\n\"\n \" -f --data-file-size : Data file size (MB) \\n\"\n \" -l --logging-type : Logging type \\n\"\n \" -n --nvm-latency : NVM latency \\n\"\n \" -p --pcommit-latency : pcommit latency \\n\"\n \" -v --flush-mode : Flush mode \\n\"\n \" -w --commit-interval : Group commit interval \\n\"\n \" -y --benchmark-type : Benchmark type \\n\"\n );\n}\n\nstatic struct option opts[] = {\n {\"asynchronous_mode\", optional_argument, NULL, 'a'},\n {\"experiment-type\", optional_argument, NULL, 'e'},\n {\"data-file-size\", optional_argument, NULL, 'f'},\n {\"logging-type\", optional_argument, NULL, 'l'},\n {\"nvm-latency\", optional_argument, NULL, 'n'},\n {\"pcommit-latency\", optional_argument, NULL, 'p'},\n {\"skew\", optional_argument, NULL, 's'},\n {\"flush-mode\", optional_argument, NULL, 'v'},\n {\"commit-interval\", optional_argument, NULL, 'w'},\n {\"benchmark-type\", optional_argument, NULL, 'y'},\n {NULL, 0, NULL, 0}};\n\nstatic void ValidateLoggingType(const configuration& state) {\n if (state.logging_type <= LOGGING_TYPE_INVALID) {\n LOG_ERROR(\"Invalid logging_type :: %d\", state.logging_type);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"Logging_type :: %s\", LoggingTypeToString(state.logging_type).c_str());\n}\n\nstd::string BenchmarkTypeToString(BenchmarkType type) {\n switch (type) {\n case BENCHMARK_TYPE_INVALID:\n return \"INVALID\";\n\n case BENCHMARK_TYPE_YCSB:\n return \"YCSB\";\n case BENCHMARK_TYPE_TPCC:\n return \"TPCC\";\n\n default:\n LOG_ERROR(\"Invalid benchmark_type :: %d\", type);\n exit(EXIT_FAILURE);\n }\n return \"INVALID\";\n}\n\nstd::string ExperimentTypeToString(ExperimentType type) {\n switch (type) {\n case EXPERIMENT_TYPE_INVALID:\n return \"INVALID\";\n\n case EXPERIMENT_TYPE_THROUGHPUT:\n return \"THROUGHPUT\";\n case EXPERIMENT_TYPE_RECOVERY:\n return \"RECOVERY\";\n case EXPERIMENT_TYPE_STORAGE:\n return \"STORAGE\";\n case EXPERIMENT_TYPE_LATENCY:\n return \"LATENCY\";\n\n default:\n LOG_ERROR(\"Invalid experiment_type :: %d\", type);\n exit(EXIT_FAILURE);\n }\n\n return \"INVALID\";\n}\n\nstd::string AsynchronousTypeToString(AsynchronousType type) {\n switch (type) {\n case ASYNCHRONOUS_TYPE_INVALID:\n return \"INVALID\";\n\n case ASYNCHRONOUS_TYPE_SYNC:\n return \"SYNC\";\n case ASYNCHRONOUS_TYPE_ASYNC:\n return \"ASYNC\";\n case ASYNCHRONOUS_TYPE_DISABLED:\n return \"DISABLED\";\n\n default:\n LOG_ERROR(\"Invalid asynchronous_mode :: %d\", type);\n exit(EXIT_FAILURE);\n }\n\n return \"INVALID\";\n}\n\n\nstatic void ValidateBenchmarkType(\n const configuration& state) {\n if (state.benchmark_type <= 0 || state.benchmark_type > 3) {\n LOG_ERROR(\"Invalid benchmark_type :: %d\", state.benchmark_type);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"%s : %s\", \"benchmark_type\", BenchmarkTypeToString(state.benchmark_type).c_str());\n}\n\nstatic void ValidateDataFileSize(\n const configuration& state) {\n if (state.data_file_size <= 0) {\n LOG_ERROR(\"Invalid data_file_size :: %lu\", state.data_file_size);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"data_file_size :: %lu\", state.data_file_size);\n}\n\nstatic void ValidateExperimentType(\n const configuration& state) {\n if (state.experiment_type < 0 || state.experiment_type > 4) {\n LOG_ERROR(\"Invalid experiment_type :: %d\", state.experiment_type);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"%s : %s\", \"experiment_type\", ExperimentTypeToString(state.experiment_type).c_str());\n}\n\nstatic void ValidateWaitTimeout(const configuration& state) {\n if (state.wait_timeout < 0) {\n LOG_ERROR(\"Invalid wait_timeout :: %d\", state.wait_timeout);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"wait_timeout :: %d\", state.wait_timeout);\n}\n\nstatic void ValidateFlushMode(\n const configuration& state) {\n if (state.flush_mode <= 0 || state.flush_mode >= 3) {\n LOG_ERROR(\"Invalid flush_mode :: %d\", state.flush_mode);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"flush_mode :: %d\", state.flush_mode);\n}\n\nstatic void ValidateAsynchronousMode(\n const configuration& state) {\n if (state.asynchronous_mode <= ASYNCHRONOUS_TYPE_INVALID ||\n state.asynchronous_mode > ASYNCHRONOUS_TYPE_DISABLED) {\n LOG_ERROR(\"Invalid asynchronous_mode :: %d\", state.asynchronous_mode);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"%s : %s\", \"asynchronous_mode\", AsynchronousTypeToString(state.asynchronous_mode).c_str());\n}\n\nstatic void ValidateNVMLatency(\n const configuration& state) {\n if (state.nvm_latency < 0) {\n LOG_ERROR(\"Invalid nvm_latency :: %d\", state.nvm_latency);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"nvm_latency :: %d\", state.nvm_latency);\n}\n\nstatic void ValidatePCOMMITLatency(\n const configuration& state) {\n if (state.pcommit_latency < 0) {\n LOG_ERROR(\"Invalid pcommit_latency :: %d\", state.pcommit_latency);\n exit(EXIT_FAILURE);\n }\n\n LOG_INFO(\"pcommit_latency :: %d\", state.pcommit_latency);\n}\n\nstatic void ValidateLogFileDir(\n configuration& state) {\n struct stat data_stat;\n\n \/\/ Assign log file dir based on logging type\n switch (state.logging_type) {\n \/\/ Log file on NVM\n case LOGGING_TYPE_NVM_WAL:\n case LOGGING_TYPE_NVM_WBL: {\n int status = stat(NVM_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = NVM_DIR;\n }\n } break;\n\n \/\/ Log file on SSD\n case LOGGING_TYPE_SSD_WAL:\n case LOGGING_TYPE_SSD_WBL: {\n int status = stat(SSD_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = SSD_DIR;\n }\n } break;\n\n \/\/ Log file on HDD\n case LOGGING_TYPE_HDD_WAL:\n case LOGGING_TYPE_HDD_WBL: {\n int status = stat(HDD_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = HDD_DIR;\n }\n } break;\n\n case LOGGING_TYPE_INVALID:\n default: {\n int status = stat(TMP_DIR, &data_stat);\n if (status == 0 && S_ISDIR(data_stat.st_mode)) {\n state.log_file_dir = TMP_DIR;\n } else {\n throw Exception(\"Could not find temp directory : \" +\n std::string(TMP_DIR));\n }\n } break;\n }\n\n LOG_INFO(\"log_file_dir :: %s\", state.log_file_dir.c_str());\n}\n\nvoid ParseArguments(int argc, char* argv[], configuration& state) {\n\n \/\/ Default Logger Values\n state.logging_type = LOGGING_TYPE_NVM_WAL;\n state.log_file_dir = TMP_DIR;\n state.data_file_size = 512;\n\n state.experiment_type = EXPERIMENT_TYPE_THROUGHPUT;\n state.wait_timeout = 200;\n state.benchmark_type = BENCHMARK_TYPE_YCSB;\n state.flush_mode = 2;\n state.nvm_latency = 0;\n state.pcommit_latency = 0;\n state.asynchronous_mode = ASYNCHRONOUS_TYPE_SYNC;\n\n \/\/ Default YCSB Values\n ycsb::state.scale_factor = 1;\n ycsb::state.duration = 1000;\n ycsb::state.column_count = 10;\n ycsb::state.update_ratio = 0.5;\n ycsb::state.backend_count = 2;\n\n \/\/ Default Values\n tpcc::state.warehouse_count = 2; \/\/ 10\n tpcc::state.duration = 1000;\n tpcc::state.backend_count = 2;\n\n \/\/ Parse args\n while (1) {\n int idx = 0;\n \/\/ logger - a:e:f:hl:n:p:v:w:y:\n \/\/ ycsb - b:c:d:k:u:\n \/\/ tpcc - b:d:k:\n int c = getopt_long(argc, argv, \"a:e:f:hl:n:p:v:w:y:b:c:d:k:u:\", opts, &idx);\n\n if (c == -1) break;\n\n switch (c) {\n case 'a':\n state.asynchronous_mode = (AsynchronousType) atoi(optarg);\n break;\n case 'e':\n state.experiment_type = (ExperimentType)atoi(optarg);\n break;\n case 'f':\n state.data_file_size = atoi(optarg);\n break;\n case 'l':\n state.logging_type = (LoggingType)atoi(optarg);\n break;\n case 'n':\n state.nvm_latency = atoi(optarg);\n break;\n case 'p':\n state.pcommit_latency = atoi(optarg);\n break;\n case 'v':\n state.flush_mode = atoi(optarg);\n break;\n case 'w':\n state.wait_timeout = atoi(optarg);\n break;\n case 'y':\n state.benchmark_type = (BenchmarkType)atoi(optarg);\n break;\n\n \/\/ YCSB\n case 'b':\n ycsb::state.backend_count = atoi(optarg);\n tpcc::state.backend_count = atoi(optarg);\n break;\n case 'c':\n ycsb::state.column_count = atoi(optarg);\n break;\n case 'd':\n ycsb::state.duration = atoi(optarg);\n tpcc::state.duration = atoi(optarg);\n break;\n case 'k':\n ycsb::state.scale_factor = atoi(optarg);\n tpcc::state.warehouse_count = atoi(optarg);\n break;\n case 'u':\n ycsb::state.update_ratio = atof(optarg);\n break;\n\n case 'h':\n Usage(stderr);\n ycsb::Usage(stderr);\n exit(EXIT_FAILURE);\n break;\n\n default:\n fprintf(stderr, \"\\nUnknown option: -%c-\\n\", c);\n Usage(stderr);\n exit(EXIT_FAILURE);\n break;\n }\n }\n\n \/\/ Print Logger configuration\n ValidateLoggingType(state);\n ValidateExperimentType(state);\n ValidateAsynchronousMode(state);\n ValidateBenchmarkType(state);\n ValidateDataFileSize(state);\n ValidateLogFileDir(state);\n ValidateWaitTimeout(state);\n ValidateFlushMode(state);\n ValidateNVMLatency(state);\n ValidatePCOMMITLatency(state);\n\n \/\/ Print YCSB configuration\n if(state.benchmark_type == BENCHMARK_TYPE_YCSB) {\n ycsb::ValidateScaleFactor(ycsb::state);\n ycsb::ValidateColumnCount(ycsb::state);\n ycsb::ValidateUpdateRatio(ycsb::state);\n ycsb::ValidateBackendCount(ycsb::state);\n ycsb::ValidateDuration(ycsb::state);\n }\n \/\/ Print TPCC configuration\n else if(state.benchmark_type == BENCHMARK_TYPE_TPCC){\n tpcc::ValidateBackendCount(tpcc::state);\n tpcc::ValidateDuration(tpcc::state);\n tpcc::ValidateWarehouseCount(tpcc::state);\n\n \/\/ Static TPCC parameters\n tpcc::state.item_count = 1000; \/\/ 100000\n tpcc::state.districts_per_warehouse = 2; \/\/ 10\n tpcc::state.customers_per_district = 30; \/\/ 3000\n tpcc::state.new_orders_per_district = 9; \/\/ 900\n\n }\n\n}\n\n} \/\/ namespace logger\n} \/\/ namespace benchmark\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/compiler\/xla\/client\/computation_builder.h\"\n#include \"tensorflow\/compiler\/xla\/client\/local_client.h\"\n#include \"tensorflow\/compiler\/xla\/legacy_flags\/debug_options_flags.h\"\n#include \"tensorflow\/compiler\/xla\/literal_util.h\"\n#include \"tensorflow\/compiler\/xla\/primitive_util.h\"\n#include \"tensorflow\/compiler\/xla\/ptr_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_module.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/shape_util.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/client_library_test_base.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/hlo_test_base.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/literal_test_util.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/test_macros.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/test_utils.h\"\n#include \"tensorflow\/compiler\/xla\/xla_data.pb.h\"\n#include \"tensorflow\/core\/lib\/gtl\/array_slice.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/platform\/test_benchmark.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n\nusing tensorflow::gtl::ArraySlice;\n\nnamespace xla {\nnamespace {\n\nclass MultiOutputFusionTest : public HloTestBase {\n public:\n ErrorSpec error_spec_{0.0001, 1e-2};\n\n protected:\n MultiOutputFusionTest() {}\n void RunTest2D(bool manual_fusion, int64 size) {\n auto builder = HloComputation::Builder(TestName());\n auto hlo_module = CreateNewModule();\n\n const Shape elem_shape0 = ShapeUtil::MakeShape(F32, {});\n const Shape elem_shape2 = ShapeUtil::MakeShape(F32, {size, size});\n\n auto const0 = builder.AddInstruction(\n HloInstruction::CreateConstant(Literal::CreateR0(8.0f)));\n auto param0 = builder.AddInstruction(\n HloInstruction::CreateParameter(0, elem_shape0, \"0\"));\n\n auto add1 = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape0, HloOpcode::kAdd, param0, const0));\n\n HloInstruction* broadcast = builder.AddInstruction(\n HloInstruction::CreateBroadcast(elem_shape2, add1, {0, 1}));\n\n auto param1 = builder.AddInstruction(\n HloInstruction::CreateParameter(1, elem_shape2, \"1\"));\n\n HloInstruction* add2 = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape2, HloOpcode::kAdd, broadcast, param1));\n HloInstruction* sub = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape2, HloOpcode::kSubtract, param1, broadcast));\n HloInstruction* dot = builder.AddInstruction(\n HloInstruction::CreateBinary(elem_shape2, HloOpcode::kDot, sub, add2));\n auto computation = hlo_module->AddEntryComputation(builder.Build(dot));\n\n if (manual_fusion) {\n auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(\n ArraySlice({sub, add2}, 0, 2)));\n computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 0));\n computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 1));\n CHECK_NE(\n computation->CreateFusionInstruction(\n {tuple, sub, add2, broadcast}, HloInstruction::FusionKind::kLoop),\n nullptr);\n }\n\n Literal input;\n input.PopulateWithValue(2.5f, {size, size});\n auto p1 = TransferToDevice(input);\n auto p0 = TransferToDevice(*Literal::CreateR0(-9.0f));\n\n Literal expect;\n expect.PopulateWithValue(size * 1.5f * 3.5f, {size, size});\n auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});\n LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);\n }\n\n void RunTest1D(bool manual_fusion, int size) {\n auto builder = HloComputation::Builder(TestName());\n auto hlo_module = CreateNewModule();\n\n const Shape elem_shape_F32 = ShapeUtil::MakeShape(F32, {size});\n const Shape elem_shape_U8 = ShapeUtil::MakeShape(F64, {size});\n auto param0 = builder.AddInstruction(\n HloInstruction::CreateParameter(0, elem_shape_F32, \"0\"));\n auto param1 = builder.AddInstruction(\n HloInstruction::CreateParameter(1, elem_shape_U8, \"1\"));\n\n HloInstruction* param0_U8 = builder.AddInstruction(\n HloInstruction::CreateConvert(elem_shape_U8, param0));\n HloInstruction* param1_F32 = builder.AddInstruction(\n HloInstruction::CreateConvert(elem_shape_F32, param1));\n HloInstruction* add = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape_F32, HloOpcode::kAdd, param0, param1_F32));\n HloInstruction* sub_U8 =\n builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape_U8, HloOpcode::kSubtract, param0_U8, param1));\n HloInstruction* sub = builder.AddInstruction(\n HloInstruction::CreateConvert(elem_shape_F32, sub_U8));\n\n HloInstruction* reshape =\n builder.AddInstruction(HloInstruction::CreateReshape(\n ShapeUtil::MakeShape(F32, {size, 1}), add));\n HloInstruction* dot = builder.AddInstruction(HloInstruction::CreateBinary(\n ShapeUtil::MakeShape(F32, {}), HloOpcode::kDot, sub, reshape));\n auto computation = hlo_module->AddEntryComputation(builder.Build(dot));\n\n if (manual_fusion) {\n auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(\n ArraySlice({sub_U8, add}, 0, 2)));\n\n computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape_U8, tuple, 0));\n computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape_F32, tuple, 1));\n CHECK_NE(computation->CreateFusionInstruction(\n {tuple, sub_U8, add, param0_U8, param1_F32},\n HloInstruction::FusionKind::kLoop),\n nullptr);\n }\n\n Literal input0, input1;\n input0.PopulateWithValue(2.5f, {size});\n input1.PopulateWithValue(1, {size});\n auto p0 = TransferToDevice(input0);\n auto p1 = TransferToDevice(input1);\n\n Literal expect = *Literal::CreateR0(size * 1.5f * 3.5f);\n auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});\n LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);\n }\n};\n\nXLA_TEST_F(MultiOutputFusionTest, 2DNofusion) { RunTest2D(false, 5); }\nXLA_TEST_F(MultiOutputFusionTest, 2DFusion) { RunTest2D(true, 5); }\nXLA_TEST_F(MultiOutputFusionTest, 2DFusionSize129) { RunTest2D(true, 129); }\nXLA_TEST_F(MultiOutputFusionTest, DiffentTypesNoFusion) { RunTest1D(false, 8); }\nXLA_TEST_F(MultiOutputFusionTest, DiffentTypesFusion) { RunTest1D(true, 8); }\n\n} \/\/ namespace\n} \/\/ namespace xla\n\nint main(int argc, char** argv) {\n std::vector flag_list;\n xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);\n xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);\n const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);\n if (!parse_result) {\n LOG(ERROR) << \"\\n\" << usage;\n return 2;\n }\n testing::InitGoogleTest(&argc, argv);\n if (argc > 1) {\n LOG(ERROR) << \"Unknown argument \" << argv[1] << \"\\n\" << usage;\n return 2;\n }\n\n return RUN_ALL_TESTS();\n}\nFix multioutput fusion test case.\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/compiler\/xla\/client\/computation_builder.h\"\n#include \"tensorflow\/compiler\/xla\/client\/local_client.h\"\n#include \"tensorflow\/compiler\/xla\/legacy_flags\/debug_options_flags.h\"\n#include \"tensorflow\/compiler\/xla\/literal_util.h\"\n#include \"tensorflow\/compiler\/xla\/primitive_util.h\"\n#include \"tensorflow\/compiler\/xla\/ptr_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_module.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/shape_util.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/client_library_test_base.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/hlo_test_base.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/literal_test_util.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/test_macros.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/test_utils.h\"\n#include \"tensorflow\/compiler\/xla\/xla_data.pb.h\"\n#include \"tensorflow\/core\/lib\/gtl\/array_slice.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/protobuf.h\"\n#include \"tensorflow\/core\/platform\/test.h\"\n#include \"tensorflow\/core\/platform\/test_benchmark.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n\nusing tensorflow::gtl::ArraySlice;\n\nnamespace xla {\nnamespace {\n\nclass MultiOutputFusionTest : public HloTestBase {\n public:\n ErrorSpec error_spec_{0.0001, 1e-2};\n\n protected:\n MultiOutputFusionTest() {}\n void RunTest2D(bool manual_fusion, int64 size) {\n auto builder = HloComputation::Builder(TestName());\n auto hlo_module = CreateNewModule();\n\n const Shape elem_shape0 = ShapeUtil::MakeShape(F32, {});\n const Shape elem_shape2 = ShapeUtil::MakeShape(F32, {size, size});\n\n auto const0 = builder.AddInstruction(\n HloInstruction::CreateConstant(Literal::CreateR0(8.0f)));\n auto param0 = builder.AddInstruction(\n HloInstruction::CreateParameter(0, elem_shape0, \"0\"));\n\n auto add1 = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape0, HloOpcode::kAdd, param0, const0));\n\n HloInstruction* broadcast = builder.AddInstruction(\n HloInstruction::CreateBroadcast(elem_shape2, add1, {0, 1}));\n\n auto param1 = builder.AddInstruction(\n HloInstruction::CreateParameter(1, elem_shape2, \"1\"));\n\n HloInstruction* add2 = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape2, HloOpcode::kAdd, broadcast, param1));\n HloInstruction* sub = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape2, HloOpcode::kSubtract, param1, broadcast));\n HloInstruction* dot = builder.AddInstruction(\n HloInstruction::CreateBinary(elem_shape2, HloOpcode::kDot, sub, add2));\n auto computation = hlo_module->AddEntryComputation(builder.Build(dot));\n\n if (manual_fusion) {\n auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(\n ArraySlice({sub, add2}, 0, 2)));\n auto gte0 = computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 0));\n auto gte1 = computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape2, tuple, 1));\n TF_CHECK_OK(dot->ReplaceOperandWith(0, gte0));\n TF_CHECK_OK(dot->ReplaceOperandWith(1, gte1));\n\n CHECK_NE(\n computation->CreateFusionInstruction(\n {tuple, sub, add2, broadcast}, HloInstruction::FusionKind::kLoop),\n nullptr);\n }\n\n Literal input;\n input.PopulateWithValue(2.5f, {size, size});\n auto p1 = TransferToDevice(input);\n auto p0 = TransferToDevice(*Literal::CreateR0(-9.0f));\n\n Literal expect;\n expect.PopulateWithValue(size * 1.5f * 3.5f, {size, size});\n auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});\n LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);\n }\n\n void RunTest1D(bool manual_fusion, int size) {\n auto builder = HloComputation::Builder(TestName());\n auto hlo_module = CreateNewModule();\n\n const Shape elem_shape_F32 = ShapeUtil::MakeShape(F32, {size});\n const Shape elem_shape_U8 = ShapeUtil::MakeShape(F64, {size});\n auto param0 = builder.AddInstruction(\n HloInstruction::CreateParameter(0, elem_shape_F32, \"0\"));\n auto param1 = builder.AddInstruction(\n HloInstruction::CreateParameter(1, elem_shape_U8, \"1\"));\n\n HloInstruction* param0_U8 = builder.AddInstruction(\n HloInstruction::CreateConvert(elem_shape_U8, param0));\n HloInstruction* param1_F32 = builder.AddInstruction(\n HloInstruction::CreateConvert(elem_shape_F32, param1));\n HloInstruction* add = builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape_F32, HloOpcode::kAdd, param0, param1_F32));\n HloInstruction* sub_U8 =\n builder.AddInstruction(HloInstruction::CreateBinary(\n elem_shape_U8, HloOpcode::kSubtract, param0_U8, param1));\n HloInstruction* sub = builder.AddInstruction(\n HloInstruction::CreateConvert(elem_shape_F32, sub_U8));\n\n HloInstruction* reshape =\n builder.AddInstruction(HloInstruction::CreateReshape(\n ShapeUtil::MakeShape(F32, {size, 1}), add));\n HloInstruction* dot = builder.AddInstruction(HloInstruction::CreateBinary(\n ShapeUtil::MakeShape(F32, {}), HloOpcode::kDot, sub, reshape));\n auto computation = hlo_module->AddEntryComputation(builder.Build(dot));\n\n if (manual_fusion) {\n auto tuple = computation->AddInstruction(HloInstruction::CreateTuple(\n ArraySlice({sub_U8, add}, 0, 2)));\n\n auto gte0 = computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape_U8, tuple, 0));\n auto gte1 = computation->AddInstruction(\n HloInstruction::CreateGetTupleElement(elem_shape_F32, tuple, 1));\n TF_CHECK_OK(sub->ReplaceOperandWith(0, gte0));\n TF_CHECK_OK(reshape->ReplaceOperandWith(0, gte1));\n\n CHECK_NE(computation->CreateFusionInstruction(\n {tuple, sub_U8, add, param0_U8, param1_F32},\n HloInstruction::FusionKind::kLoop),\n nullptr);\n }\n\n Literal input0, input1;\n input0.PopulateWithValue(2.5f, {size});\n input1.PopulateWithValue(1, {size});\n auto p0 = TransferToDevice(input0);\n auto p1 = TransferToDevice(input1);\n\n Literal expect = *Literal::CreateR0(size * 1.5f * 3.5f);\n auto actual = ExecuteAndTransfer(std::move(hlo_module), {p0, p1});\n LiteralTestUtil::ExpectNear(expect, *actual, error_spec_);\n }\n};\n\nXLA_TEST_F(MultiOutputFusionTest, 2DNofusion) { RunTest2D(false, 5); }\nXLA_TEST_F(MultiOutputFusionTest, 2DFusion) { RunTest2D(true, 5); }\nXLA_TEST_F(MultiOutputFusionTest, 2DFusionSize129) { RunTest2D(true, 129); }\nXLA_TEST_F(MultiOutputFusionTest, DiffentTypesNoFusion) { RunTest1D(false, 8); }\nXLA_TEST_F(MultiOutputFusionTest, DiffentTypesFusion) { RunTest1D(true, 8); }\n\n} \/\/ namespace\n} \/\/ namespace xla\n\nint main(int argc, char** argv) {\n std::vector flag_list;\n xla::legacy_flags::AppendDebugOptionsFlags(&flag_list);\n xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);\n const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);\n if (!parse_result) {\n LOG(ERROR) << \"\\n\" << usage;\n return 2;\n }\n testing::InitGoogleTest(&argc, argv);\n if (argc > 1) {\n LOG(ERROR) << \"Unknown argument \" << argv[1] << \"\\n\" << usage;\n return 2;\n }\n\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright Renga Software LLC, 2016. All rights reserved.\n\/\/\n\/\/ Renga Software LLC PROVIDES THIS PROGRAM \"AS IS\" AND WITH ALL FAULTS. \n\/\/ Renga Software LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE\n\/\/ UNINTERRUPTED OR ERROR FREE.\n\/\/\n\n#include \"stdafx.h\"\n#include \"PropertyViewBuilder.h\"\n#include \"GuidUtils.h\"\n\n#include \n\n\nPropertyViewBuilder::PropertyViewBuilder(PropertyManagers* pPropertyManagers,\n Renga::IApplicationPtr pApplication,\n Renga::IModelObjectPtr pModelObject) :\n m_pApplication(pApplication),\n m_pPropertyManagers(pPropertyManagers),\n m_pModelObject(pModelObject)\n{\n}\n\nvoid PropertyViewBuilder::createIntegratedParameters(PropertyList& propertyList)\n{\n auto& mngr = m_pPropertyManagers->m_default;\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"name\"), QString::fromWCharArray(m_pModelObject->GetName()));\n\n Renga::ILevelObjectPtr pLevelObject;\n m_pModelObject->QueryInterface(&pLevelObject);\n if (pLevelObject)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"offset\"), pLevelObject->GetOffset());\n\n Renga::IObjectWithMarkPtr pObjectWithMark;\n m_pModelObject->QueryInterface(&pObjectWithMark);\n if (pObjectWithMark)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"mark\"), QString::fromWCharArray(pObjectWithMark->GetMark()));\n\n Renga::IObjectWithMaterialPtr pObjectWithMaterial;\n m_pModelObject->QueryInterface(&pObjectWithMaterial);\n if (pObjectWithMaterial)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"material\"), getMaterialName(pObjectWithMaterial->GetMaterialId()));\n\n Renga::IObjectWithLayeredMaterialPtr pObjectWithLayeredMaterial;\n m_pModelObject->QueryInterface(&pObjectWithLayeredMaterial);\n if (pObjectWithLayeredMaterial)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"material\"), getLayeredMaterialName(pObjectWithLayeredMaterial->GetLayeredMaterialId()));\n}\n\nvoid PropertyViewBuilder::createParameters(PropertyList& propertyList)\n{\n \/\/ block signals before filling properties\n auto& mngr = m_pPropertyManagers->m_parameters;\n mngr.blockSignals(true);\n\n auto pParameters = m_pModelObject->GetParameters();\n auto pIds = pParameters->GetIds();\n for (int i = 0; i < pIds->Count; ++i)\n {\n const auto id = pIds->Get(i);\n\n auto pParameter = pParameters->Get(id);\n auto pDefinition = pParameter->Definition;\n\n QString name = QString::fromStdWString(pDefinition->Name.operator wchar_t *());\n\n switch (pDefinition->GetParameterType())\n {\n case Renga::ParameterType::ParameterType_Angle:\n name += \", \" + QApplication::translate(\"me_mo\", \"angle_dimension\");\n break;\n case Renga::ParameterType::ParameterType_Length:\n name += \", \" + QApplication::translate(\"me_mo\", \"length_dimension\");\n break;\n }\n\n QtProperty* pQtProperty(nullptr);\n if (pParameter->HasValue())\n {\n switch (pParameter->GetValueType())\n {\n case Renga::ParameterValueType::ParameterValueType_Bool:\n pQtProperty = mngr.addValue(propertyList, name, pParameter->GetBoolValue());\n break;\n case Renga::ParameterValueType::ParameterValueType_Int:\n pQtProperty = mngr.addValue(propertyList, name, pParameter->GetIntValue());\n break;\n case Renga::ParameterValueType::ParameterValueType_Double:\n pQtProperty = mngr.addValue(propertyList, name, pParameter->GetDoubleValue());\n break;\n case Renga::ParameterValueType::ParameterValueType_String:\n pQtProperty = mngr.addValue(propertyList, name, QString::fromWCharArray(pParameter->GetStringValue()));\n break;\n }\n }\n else\n {\n pQtProperty = mngr.addValue(propertyList, name, \"\");\n pQtProperty->setEnabled(false);\n }\n\n\n if (pQtProperty)\n {\n pQtProperty->setModified(true);\n\n const auto parameterIdString = QString::fromStdString((GuidToString(id)));\n pQtProperty->setData(parameterIdString);\n }\n }\n\n \/\/ unblock signals\n mngr.blockSignals(false);\n}\n\nvoid PropertyViewBuilder::createQuantities(PropertyList& propertyList)\n{\n using namespace Renga;\n\n auto pQuantities = m_pModelObject->GetQuantities();\n\n PropertyList result;\n\n auto& mngr = m_pPropertyManagers->m_default;\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"overallWidth\"), pQuantities->Get(QuantityIds::OverallWidth));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"overallHeight\"), pQuantities->Get(QuantityIds::OverallHeight));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"overallLength\"), pQuantities->Get(QuantityIds::OverallLength));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"thickness\"), pQuantities->Get(QuantityIds::NominalThickness));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"length\"), pQuantities->Get(QuantityIds::NominalLength));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"width\"), pQuantities->Get(QuantityIds::NominalWidth));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"height\"), pQuantities->Get(QuantityIds::NominalHeight));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"perimeter\"), pQuantities->Get(QuantityIds::Perimeter));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"volume\"), pQuantities->Get(QuantityIds::Volume));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netVolume\"), pQuantities->Get(QuantityIds::NetVolume));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"mass\"), pQuantities->Get(QuantityIds::NetMass));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"crossSectionOverallWidth\"), pQuantities->Get(QuantityIds::CrossSectionOverallWidth));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"crossSectionOverallHeight\"), pQuantities->Get(QuantityIds::CrossSectionOverallHeight));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"crossSectionArea\"), pQuantities->Get(QuantityIds::CrossSectionArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"innerSurfaceArea\"), pQuantities->Get(QuantityIds::InnerSurfaceArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"innerSurfaceInternalArea\"), pQuantities->Get(QuantityIds::InnerSurfaceInternalArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"innerSurfaceExternalArea\"), pQuantities->Get(QuantityIds::InnerSurfaceExternalArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"outerSurfaceArea\"), pQuantities->Get(QuantityIds::OuterSurfaceArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"area\"), pQuantities->Get(QuantityIds::Area));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netArea\"), pQuantities->Get(QuantityIds::NetArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netFloorArea\"), pQuantities->Get(QuantityIds::NetFloorArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netFootprintArea\"), pQuantities->Get(QuantityIds::NetFootprintArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netSideArea\"), pQuantities->Get(QuantityIds::NetSideArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"totalSurfaceArea\"), pQuantities->Get(QuantityIds::TotalSurfaceArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"grossVolume\"), pQuantities->Get(Renga::QuantityIds::GrossVolume));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"grossFloorArea\"), pQuantities->Get(Renga::QuantityIds::GrossFloorArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"grossPerimeter\"), pQuantities->Get(Renga::QuantityIds::GrossPerimeter));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"numberOfRiser\"), pQuantities->Get(QuantityIds::NumberOfRiser));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"numberOfTreads\"), pQuantities->Get(QuantityIds::NumberOfTreads));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"riserHeight\"), pQuantities->Get(QuantityIds::RiserHeight));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"treadLength\"), pQuantities->Get(QuantityIds::TreadLength));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_reinforcement\", \"totalRebarLength\"), pQuantities->Get(QuantityIds::TotalRebarLength));\n mngr.addValue(propertyList, QApplication::translate(\"me_reinforcement\", \"totalRebarMass\"), pQuantities->Get(QuantityIds::TotalRebarMass));\n}\n\nPropertyList PropertyViewBuilder::createProperties()\n{\n PropertyList pResult;\n\n auto pProject = m_pApplication->GetProject();\n auto pPropertyManager = pProject->GetPropertyManager();\n\n \/\/ block signals before filling properties\n auto& mngr = m_pPropertyManagers->m_properties;\n mngr.blockSignals(true);\n\n \/\/ check all attributes\n for (int i = 0; i < pPropertyManager->GetPropertyCount(); ++i)\n {\n auto propertyId = pPropertyManager->GetPropertyId(i);\n\n \/\/ check if objectType has attribute\n if (!pPropertyManager->IsPropertyAssignedToType(propertyId, m_pModelObject->GetObjectType()))\n continue;\n\n auto pProperties = m_pModelObject->GetProperties();\n auto pProperty = pProperties->Get(propertyId);\n\n if (!pProperty)\n continue;\n\n auto propertyDescription = pPropertyManager->GetPropertyDescription(propertyId);\n if (propertyDescription.Type == Renga::PropertyType::PropertyType_Undefined)\n continue;\n\n const auto attributeName = QString::fromWCharArray(propertyDescription.Name);\n const auto propertyIdString = QString::fromStdString((GuidToString(propertyId)));\n\n QtProperty* pQtProperty(nullptr);\n switch (propertyDescription.Type)\n {\n case Renga::PropertyType::PropertyType_Double:\n pQtProperty = mngr.addValue(pResult, attributeName, pProperty->GetDoubleValue());\n break;\n case Renga::PropertyType::PropertyType_String:\n pQtProperty = mngr.addValue(pResult, attributeName, QString::fromWCharArray(pProperty->GetStringValue()));\n break;\n default:\n assert(false);\n }\n pQtProperty->setModified(true);\n pQtProperty->setData(propertyIdString);\n }\n\n \/\/ unblock signals\n mngr.blockSignals(false);\n\n return pResult;\n}\n\nQString PropertyViewBuilder::getMaterialName(const int& materialId)\n{\n auto pProject = m_pApplication->GetProject();\n auto pMaterialManager = pProject->GetMaterialManager();\n auto pMaterial = pMaterialManager->GetMaterial(materialId);\n if (!pMaterial)\n return QString();\n\n return QString::fromWCharArray(pMaterial->GetName());\n}\n\nQString PropertyViewBuilder::getLayeredMaterialName(const int& layeredMaterialId)\n{\n auto pProject = m_pApplication->GetProject();\n auto pLayeredMaterialManager = pProject->GetLayeredMaterialManager();\n auto pLayeredMaterial = pLayeredMaterialManager->GetLayeredMaterial(layeredMaterialId);\n if (!pLayeredMaterial)\n return QString();\n\n return QString::fromWCharArray(pLayeredMaterial->GetName());\n}\nFix for model object parameters with no value\/\/\n\/\/ Copyright Renga Software LLC, 2016. All rights reserved.\n\/\/\n\/\/ Renga Software LLC PROVIDES THIS PROGRAM \"AS IS\" AND WITH ALL FAULTS. \n\/\/ Renga Software LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE\n\/\/ UNINTERRUPTED OR ERROR FREE.\n\/\/\n\n#include \"stdafx.h\"\n#include \"PropertyViewBuilder.h\"\n#include \"GuidUtils.h\"\n\n#include \n\n\nPropertyViewBuilder::PropertyViewBuilder(PropertyManagers* pPropertyManagers,\n Renga::IApplicationPtr pApplication,\n Renga::IModelObjectPtr pModelObject) :\n m_pApplication(pApplication),\n m_pPropertyManagers(pPropertyManagers),\n m_pModelObject(pModelObject)\n{\n}\n\nvoid PropertyViewBuilder::createIntegratedParameters(PropertyList& propertyList)\n{\n auto& mngr = m_pPropertyManagers->m_default;\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"name\"), QString::fromWCharArray(m_pModelObject->GetName()));\n\n Renga::ILevelObjectPtr pLevelObject;\n m_pModelObject->QueryInterface(&pLevelObject);\n if (pLevelObject)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"offset\"), pLevelObject->GetOffset());\n\n Renga::IObjectWithMarkPtr pObjectWithMark;\n m_pModelObject->QueryInterface(&pObjectWithMark);\n if (pObjectWithMark)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"mark\"), QString::fromWCharArray(pObjectWithMark->GetMark()));\n\n Renga::IObjectWithMaterialPtr pObjectWithMaterial;\n m_pModelObject->QueryInterface(&pObjectWithMaterial);\n if (pObjectWithMaterial)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"material\"), getMaterialName(pObjectWithMaterial->GetMaterialId()));\n\n Renga::IObjectWithLayeredMaterialPtr pObjectWithLayeredMaterial;\n m_pModelObject->QueryInterface(&pObjectWithLayeredMaterial);\n if (pObjectWithLayeredMaterial)\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"material\"), getLayeredMaterialName(pObjectWithLayeredMaterial->GetLayeredMaterialId()));\n}\n\nvoid PropertyViewBuilder::createParameters(PropertyList& propertyList)\n{\n \/\/ block signals before filling properties\n auto& mngr = m_pPropertyManagers->m_parameters;\n mngr.blockSignals(true);\n\n auto pParameters = m_pModelObject->GetParameters();\n auto pIds = pParameters->GetIds();\n for (int i = 0; i < pIds->Count; ++i)\n {\n const auto id = pIds->Get(i);\n\n auto pParameter = pParameters->Get(id);\n auto pDefinition = pParameter->Definition;\n\n QString name = QString::fromStdWString(pDefinition->Name.operator wchar_t *());\n\n switch (pDefinition->GetParameterType())\n {\n case Renga::ParameterType::ParameterType_Angle:\n name += \", \" + QApplication::translate(\"me_mo\", \"angle_dimension\");\n break;\n case Renga::ParameterType::ParameterType_Length:\n name += \", \" + QApplication::translate(\"me_mo\", \"length_dimension\");\n break;\n }\n\n QtProperty* pQtProperty(nullptr);\n switch (pParameter->GetValueType())\n {\n case Renga::ParameterValueType::ParameterValueType_Bool:\n pQtProperty = mngr.addValue(propertyList, name, pParameter->GetBoolValue());\n break;\n case Renga::ParameterValueType::ParameterValueType_Int:\n pQtProperty = mngr.addValue(propertyList, name, pParameter->GetIntValue());\n break;\n case Renga::ParameterValueType::ParameterValueType_Double:\n pQtProperty = mngr.addValue(propertyList, name, pParameter->GetDoubleValue());\n break;\n case Renga::ParameterValueType::ParameterValueType_String:\n pQtProperty = mngr.addValue(propertyList, name, QString::fromWCharArray(pParameter->GetStringValue()));\n break;\n }\n\n if (pQtProperty)\n {\n if (!pParameter->HasValue())\n pQtProperty->setEnabled(false);\n\n pQtProperty->setModified(true);\n\n const auto parameterIdString = QString::fromStdString((GuidToString(id)));\n pQtProperty->setData(parameterIdString);\n }\n }\n\n \/\/ unblock signals\n mngr.blockSignals(false);\n}\n\nvoid PropertyViewBuilder::createQuantities(PropertyList& propertyList)\n{\n using namespace Renga;\n\n auto pQuantities = m_pModelObject->GetQuantities();\n\n PropertyList result;\n\n auto& mngr = m_pPropertyManagers->m_default;\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"overallWidth\"), pQuantities->Get(QuantityIds::OverallWidth));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"overallHeight\"), pQuantities->Get(QuantityIds::OverallHeight));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"overallLength\"), pQuantities->Get(QuantityIds::OverallLength));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"thickness\"), pQuantities->Get(QuantityIds::NominalThickness));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"length\"), pQuantities->Get(QuantityIds::NominalLength));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"width\"), pQuantities->Get(QuantityIds::NominalWidth));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"height\"), pQuantities->Get(QuantityIds::NominalHeight));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"perimeter\"), pQuantities->Get(QuantityIds::Perimeter));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"volume\"), pQuantities->Get(QuantityIds::Volume));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netVolume\"), pQuantities->Get(QuantityIds::NetVolume));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"mass\"), pQuantities->Get(QuantityIds::NetMass));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"crossSectionOverallWidth\"), pQuantities->Get(QuantityIds::CrossSectionOverallWidth));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"crossSectionOverallHeight\"), pQuantities->Get(QuantityIds::CrossSectionOverallHeight));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"crossSectionArea\"), pQuantities->Get(QuantityIds::CrossSectionArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"innerSurfaceArea\"), pQuantities->Get(QuantityIds::InnerSurfaceArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"innerSurfaceInternalArea\"), pQuantities->Get(QuantityIds::InnerSurfaceInternalArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"innerSurfaceExternalArea\"), pQuantities->Get(QuantityIds::InnerSurfaceExternalArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"outerSurfaceArea\"), pQuantities->Get(QuantityIds::OuterSurfaceArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"area\"), pQuantities->Get(QuantityIds::Area));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netArea\"), pQuantities->Get(QuantityIds::NetArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netFloorArea\"), pQuantities->Get(QuantityIds::NetFloorArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netFootprintArea\"), pQuantities->Get(QuantityIds::NetFootprintArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"netSideArea\"), pQuantities->Get(QuantityIds::NetSideArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"totalSurfaceArea\"), pQuantities->Get(QuantityIds::TotalSurfaceArea));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"grossVolume\"), pQuantities->Get(Renga::QuantityIds::GrossVolume));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"grossFloorArea\"), pQuantities->Get(Renga::QuantityIds::GrossFloorArea));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"grossPerimeter\"), pQuantities->Get(Renga::QuantityIds::GrossPerimeter));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"numberOfRiser\"), pQuantities->Get(QuantityIds::NumberOfRiser));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"numberOfTreads\"), pQuantities->Get(QuantityIds::NumberOfTreads));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"riserHeight\"), pQuantities->Get(QuantityIds::RiserHeight));\n mngr.addValue(propertyList, QApplication::translate(\"me_mo\", \"treadLength\"), pQuantities->Get(QuantityIds::TreadLength));\n\n mngr.addValue(propertyList, QApplication::translate(\"me_reinforcement\", \"totalRebarLength\"), pQuantities->Get(QuantityIds::TotalRebarLength));\n mngr.addValue(propertyList, QApplication::translate(\"me_reinforcement\", \"totalRebarMass\"), pQuantities->Get(QuantityIds::TotalRebarMass));\n}\n\nPropertyList PropertyViewBuilder::createProperties()\n{\n PropertyList pResult;\n\n auto pProject = m_pApplication->GetProject();\n auto pPropertyManager = pProject->GetPropertyManager();\n\n \/\/ block signals before filling properties\n auto& mngr = m_pPropertyManagers->m_properties;\n mngr.blockSignals(true);\n\n \/\/ check all attributes\n for (int i = 0; i < pPropertyManager->GetPropertyCount(); ++i)\n {\n auto propertyId = pPropertyManager->GetPropertyId(i);\n\n \/\/ check if objectType has attribute\n if (!pPropertyManager->IsPropertyAssignedToType(propertyId, m_pModelObject->GetObjectType()))\n continue;\n\n auto pProperties = m_pModelObject->GetProperties();\n auto pProperty = pProperties->Get(propertyId);\n\n if (!pProperty)\n continue;\n\n auto propertyDescription = pPropertyManager->GetPropertyDescription(propertyId);\n if (propertyDescription.Type == Renga::PropertyType::PropertyType_Undefined)\n continue;\n\n const auto attributeName = QString::fromWCharArray(propertyDescription.Name);\n const auto propertyIdString = QString::fromStdString((GuidToString(propertyId)));\n\n QtProperty* pQtProperty(nullptr);\n switch (propertyDescription.Type)\n {\n case Renga::PropertyType::PropertyType_Double:\n pQtProperty = mngr.addValue(pResult, attributeName, pProperty->GetDoubleValue());\n break;\n case Renga::PropertyType::PropertyType_String:\n pQtProperty = mngr.addValue(pResult, attributeName, QString::fromWCharArray(pProperty->GetStringValue()));\n break;\n default:\n assert(false);\n }\n pQtProperty->setModified(true);\n pQtProperty->setData(propertyIdString);\n }\n\n \/\/ unblock signals\n mngr.blockSignals(false);\n\n return pResult;\n}\n\nQString PropertyViewBuilder::getMaterialName(const int& materialId)\n{\n auto pProject = m_pApplication->GetProject();\n auto pMaterialManager = pProject->GetMaterialManager();\n auto pMaterial = pMaterialManager->GetMaterial(materialId);\n if (!pMaterial)\n return QString();\n\n return QString::fromWCharArray(pMaterial->GetName());\n}\n\nQString PropertyViewBuilder::getLayeredMaterialName(const int& layeredMaterialId)\n{\n auto pProject = m_pApplication->GetProject();\n auto pLayeredMaterialManager = pProject->GetLayeredMaterialManager();\n auto pLayeredMaterial = pLayeredMaterialManager->GetLayeredMaterial(layeredMaterialId);\n if (!pLayeredMaterial)\n return QString();\n\n return QString::fromWCharArray(pLayeredMaterial->GetName());\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/ \n\n\/\/ AliFlowEventCuts:\n\/\/ An event cut class for the flow framework\n\/\/\n\/\/ origin: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch)\n\n#include \n#include \n#include \"TMath.h\"\n#include \"TNamed.h\"\n#include \"AliVVertex.h\"\n#include \"AliVEvent.h\"\n#include \"AliESDEvent.h\"\n#include \"AliCentrality.h\"\n#include \"AliESDVZERO.h\"\n#include \"AliMultiplicity.h\"\n#include \"AliMCEvent.h\"\n#include \"AliFlowEventCuts.h\"\n#include \"AliFlowTrackCuts.h\"\n#include \"AliTriggerAnalysis.h\"\n\nClassImp(AliFlowEventCuts)\n\n\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::AliFlowEventCuts():\n TNamed(),\n fCutNumberOfTracks(kFALSE),\n fNumberOfTracksMax(INT_MAX),\n fNumberOfTracksMin(INT_MIN),\n fCutRefMult(kFALSE),\n fRefMultMethod(kTPConly),\n fRefMultMax(INT_MAX),\n fRefMultMin(INT_MIN),\n fRefMultCuts(NULL),\n fMeanPtCuts(NULL),\n fCutPrimaryVertexX(kFALSE),\n fPrimaryVertexXmax(INT_MAX),\n fPrimaryVertexXmin(INT_MIN),\n fCutPrimaryVertexY(kFALSE),\n fPrimaryVertexYmax(INT_MAX),\n fPrimaryVertexYmin(INT_MIN),\n fCutPrimaryVertexZ(kFALSE),\n fPrimaryVertexZmax(INT_MAX),\n fPrimaryVertexZmin(INT_MIN),\n fCutNContributors(kFALSE),\n fNContributorsMax(INT_MAX),\n fNContributorsMin(INT_MIN),\n fCutMeanPt(kFALSE),\n fMeanPtMax(-DBL_MAX),\n fMeanPtMin(DBL_MAX),\n fCutSPDvertexerAnomaly(kFALSE),\n fCutCentralityPercentile(kFALSE),\n fCentralityPercentileMethod(kTPConly),\n fCentralityPercentileMax(100.),\n fCentralityPercentileMin(0.),\n fCutZDCtiming(kFALSE),\n fTrigAna()\n{\n \/\/constructor \n}\n\n\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::AliFlowEventCuts(const char* name, const char* title):\n TNamed(name, title),\n fCutNumberOfTracks(kFALSE),\n fNumberOfTracksMax(INT_MAX),\n fNumberOfTracksMin(INT_MIN),\n fCutRefMult(kFALSE),\n fRefMultMethod(kTPConly),\n fRefMultMax(INT_MAX),\n fRefMultMin(INT_MIN),\n fRefMultCuts(NULL),\n fMeanPtCuts(NULL),\n fCutPrimaryVertexX(kFALSE),\n fPrimaryVertexXmax(INT_MAX),\n fPrimaryVertexXmin(INT_MIN),\n fCutPrimaryVertexY(kFALSE),\n fPrimaryVertexYmax(INT_MAX),\n fPrimaryVertexYmin(INT_MIN),\n fCutPrimaryVertexZ(kFALSE),\n fPrimaryVertexZmax(INT_MAX),\n fPrimaryVertexZmin(INT_MIN),\n fCutNContributors(kFALSE),\n fNContributorsMax(INT_MAX),\n fNContributorsMin(INT_MIN),\n fCutMeanPt(kFALSE),\n fMeanPtMax(-DBL_MAX),\n fMeanPtMin(DBL_MAX),\n fCutSPDvertexerAnomaly(kTRUE),\n fCutCentralityPercentile(kFALSE),\n fCentralityPercentileMethod(kTPConly),\n fCentralityPercentileMax(100.),\n fCentralityPercentileMin(0.),\n fCutZDCtiming(kFALSE),\n fTrigAna()\n{\n \/\/constructor \n}\n\n\/\/\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::AliFlowEventCuts(const AliFlowEventCuts& that):\n TNamed(that),\n fCutNumberOfTracks(that.fCutNumberOfTracks),\n fNumberOfTracksMax(that.fNumberOfTracksMax),\n fNumberOfTracksMin(that.fNumberOfTracksMin),\n fCutRefMult(that.fCutRefMult),\n fRefMultMethod(that.fRefMultMethod),\n fRefMultMax(that.fRefMultMax),\n fRefMultMin(that.fRefMultMin),\n fRefMultCuts(NULL),\n fMeanPtCuts(NULL),\n fCutPrimaryVertexX(that.fCutPrimaryVertexX),\n fPrimaryVertexXmax(that.fPrimaryVertexXmax),\n fPrimaryVertexXmin(that.fPrimaryVertexXmin),\n fCutPrimaryVertexY(that.fCutPrimaryVertexX),\n fPrimaryVertexYmax(that.fPrimaryVertexYmax),\n fPrimaryVertexYmin(that.fPrimaryVertexYmin),\n fCutPrimaryVertexZ(that.fCutPrimaryVertexX),\n fPrimaryVertexZmax(that.fPrimaryVertexZmax),\n fPrimaryVertexZmin(that.fPrimaryVertexZmin),\n fCutNContributors(that.fCutNContributors),\n fNContributorsMax(that.fNContributorsMax),\n fNContributorsMin(that.fNContributorsMin),\n fCutMeanPt(that.fCutMeanPt),\n fMeanPtMax(that.fMeanPtMax),\n fMeanPtMin(that.fMeanPtMin),\n fCutSPDvertexerAnomaly(that.fCutSPDvertexerAnomaly),\n fCutCentralityPercentile(that.fCutCentralityPercentile),\n fCentralityPercentileMethod(that.fCentralityPercentileMethod),\n fCentralityPercentileMax(that.fCentralityPercentileMax),\n fCentralityPercentileMin(that.fCentralityPercentileMin),\n fCutZDCtiming(that.fCutZDCtiming),\n fTrigAna()\n{\n \/\/copy constructor \n if (that.fRefMultCuts)\n fRefMultCuts = new AliFlowTrackCuts(*(that.fRefMultCuts));\n if (that.fMeanPtCuts)\n fMeanPtCuts = new AliFlowTrackCuts(*(that.fMeanPtCuts));\n}\n\n\/\/\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::~AliFlowEventCuts()\n{\n \/\/dtor\n delete fMeanPtCuts;\n delete fRefMultCuts;\n}\n\n\/\/\/\/-----------------------------------------------------------------------\nAliFlowEventCuts& AliFlowEventCuts::operator=(const AliFlowEventCuts& that)\n{\n \/\/assignment\n fCutNumberOfTracks=that.fCutNumberOfTracks;\n fNumberOfTracksMax=that.fNumberOfTracksMax;\n fNumberOfTracksMin=that.fNumberOfTracksMin;\n fCutRefMult=that.fCutRefMult;\n fRefMultMethod=that.fRefMultMethod;\n fRefMultMax=that.fRefMultMax;\n fRefMultMin=that.fRefMultMin;\n if (that.fRefMultCuts) *fRefMultCuts=*(that.fRefMultCuts);\n if (that.fMeanPtCuts) *fMeanPtCuts=*(that.fMeanPtCuts);\n fCutPrimaryVertexX=that.fCutPrimaryVertexX;\n fPrimaryVertexXmin=that.fPrimaryVertexXmin;\n fPrimaryVertexXmax=that.fPrimaryVertexXmax;\n fPrimaryVertexYmin=that.fPrimaryVertexYmin;\n fPrimaryVertexYmax=that.fPrimaryVertexYmax;\n fPrimaryVertexZmin=that.fPrimaryVertexZmin;\n fPrimaryVertexZmax=that.fPrimaryVertexZmax;\n fCutNContributors=that.fCutNContributors;\n fNContributorsMax=that.fNContributorsMax;\n fNContributorsMin=that.fNContributorsMin;\n fCutMeanPt=that.fCutMeanPt;\n fMeanPtMax=that.fMeanPtMax;\n fMeanPtMin=that.fMeanPtMin;\n fCutSPDvertexerAnomaly=that.fCutSPDvertexerAnomaly;\n fCutCentralityPercentile=that.fCutCentralityPercentile;\n fCentralityPercentileMethod=that.fCentralityPercentileMethod;\n fCentralityPercentileMax=that.fCentralityPercentileMax;\n fCentralityPercentileMin=that.fCentralityPercentileMin;\n return *this;\n}\n\n\/\/----------------------------------------------------------------------- \nBool_t AliFlowEventCuts::IsSelected(TObject* obj)\n{\n \/\/check cuts\n AliVEvent* vevent = dynamic_cast(obj);\n if (vevent) return PassesCuts(vevent);\n return kFALSE; \/\/when passed wrong type of object\n}\n\/\/----------------------------------------------------------------------- \nBool_t AliFlowEventCuts::PassesCuts(AliVEvent *event)\n{\n \/\/\/check if event passes cuts\n AliESDEvent* esdevent = dynamic_cast(event);\n if (fCutCentralityPercentile&&esdevent)\n {\n AliCentrality* centr = esdevent->GetCentrality();\n if (!centr->IsEventInCentralityClass( fCentralityPercentileMin,\n fCentralityPercentileMax,\n CentrMethName(fCentralityPercentileMethod) ))\n {\n return kFALSE;\n }\n }\n if (fCutSPDvertexerAnomaly&&esdevent)\n {\n const AliESDVertex* sdpvertex = esdevent->GetPrimaryVertexSPD();\n if (sdpvertex->GetNContributors()<1) return kFALSE;\n if (sdpvertex->GetDispersion()>0.04) return kFALSE;\n if (sdpvertex->GetZRes()>0.25) return kFALSE;\n const AliESDVertex* tpcvertex = esdevent->GetPrimaryVertexTPC();\n if (tpcvertex->GetNContributors()<1) return kFALSE;\n const AliMultiplicity* tracklets = esdevent->GetMultiplicity();\n if (tpcvertex->GetNContributors()<(-10.0+0.25*tracklets->GetNumberOfITSClusters(0)))\n {\n return kFALSE;\n }\n }\n if (fCutZDCtiming&&esdevent)\n {\n if (!fTrigAna.ZDCTimeTrigger(esdevent))\n {\n return kFALSE;\n }\n }\n if(fCutNumberOfTracks) {if ( event->GetNumberOfTracks() < fNumberOfTracksMin ||\n event->GetNumberOfTracks() >= fNumberOfTracksMax ) return kFALSE;}\n if(fCutRefMult&&esdevent)\n {\n \/\/reference multiplicity still to be defined\n Double_t refMult = RefMult(event);\n if (refMult < fRefMultMin || refMult >= fRefMultMax )\n {\n return kFALSE;\n }\n }\n const AliVVertex* pvtx=event->GetPrimaryVertex();\n Double_t pvtxx = pvtx->GetX();\n Double_t pvtxy = pvtx->GetY();\n Double_t pvtxz = pvtx->GetZ();\n Int_t ncontrib = pvtx->GetNContributors();\n if (fCutNContributors)\n {\n if (ncontrib < fNContributorsMin || ncontrib >= fNContributorsMax)\n return kFALSE;\n }\n if (fCutPrimaryVertexX)\n {\n if (pvtxx < fPrimaryVertexXmin || pvtxx >= fPrimaryVertexXmax)\n return kFALSE;\n }\n if (fCutPrimaryVertexY)\n {\n if (pvtxy < fPrimaryVertexYmin || pvtxy >= fPrimaryVertexYmax)\n return kFALSE;\n }\n if (fCutPrimaryVertexZ)\n {\n if (pvtxz < fPrimaryVertexZmin || pvtxz >= fPrimaryVertexZmax)\n return kFALSE;\n }\n if (fCutMeanPt)\n {\n Float_t meanpt=0.0;\n Int_t ntracks=event->GetNumberOfTracks();\n Int_t nselected=0;\n for (Int_t i=0; iGetTrack(i);\n if (!track) continue;\n Bool_t pass=kTRUE;\n if (fMeanPtCuts) pass=fMeanPtCuts->IsSelected(track);\n if (pass) \n {\n meanpt += track->Pt();\n nselected++;\n }\n }\n meanpt=meanpt\/nselected;\n if (meanpt= fMeanPtMax) return kFALSE;\n }\n return kTRUE;\n}\n\n\/\/----------------------------------------------------------------------- \nconst char* AliFlowEventCuts::CentrMethName(refMultMethod method) const\n{\n \/\/get the string for refmultmethod, for use with AliCentrality in\n \/\/the cut on centrality percentile\n switch (method)\n {\n case kSPDtracklets:\n return \"TKL\";\n case kSPD1clusters:\n return \"CL1\";\n case kTPConly:\n return \"TRK\";\n case kV0:\n return \"V0M\";\n default:\n return \"\";\n }\n}\n\/\/----------------------------------------------------------------------- \nAliFlowEventCuts* AliFlowEventCuts::StandardCuts()\n{\n \/\/make a set of standard event cuts, caller becomes owner\n AliFlowEventCuts* cuts = new AliFlowEventCuts();\n return cuts;\n}\n\n\/\/----------------------------------------------------------------------- \nInt_t AliFlowEventCuts::RefMult(AliVEvent* event)\n{\n \/\/calculate the reference multiplicity, if all fails return 0\n AliESDVZERO* vzero = NULL;\n AliESDEvent* esdevent = dynamic_cast(event);\n\n if (fRefMultMethod==kTPConly && !fRefMultCuts)\n {\n fRefMultCuts = AliFlowTrackCuts::GetStandardTPCOnlyTrackCuts();\n fRefMultCuts->SetEtaRange(-0.8,0.8);\n fRefMultCuts->SetPtMin(0.15);\n }\n else if (fRefMultMethod==kSPDtracklets && !fRefMultCuts)\n {\n fRefMultCuts = new AliFlowTrackCuts(\"tracklet refmult cuts\");\n fRefMultCuts->SetParamType(AliFlowTrackCuts::kESD_SPDtracklet);\n fRefMultCuts->SetEtaRange(-0.8,0.8);\n }\n else if (fRefMultMethod==kV0)\n {\n if (!esdevent) return 0;\n vzero=esdevent->GetVZEROData();\n if (!vzero) return 0;\n return TMath::Nint(vzero->GetMTotV0A()+vzero->GetMTotV0C());\n }\n else if (fRefMultMethod==kSPD1clusters)\n {\n if (!esdevent) return 0;\n const AliMultiplicity* mult = esdevent->GetMultiplicity();\n if (!mult) return 0;\n return mult->GetNumberOfITSClusters(1);\n }\n\n Int_t refmult=0;\n fRefMultCuts->SetEvent(event);\n for (Int_t i=0; iGetNumberOfInputObjects(); i++)\n {\n if (fRefMultCuts->IsSelected(fRefMultCuts->GetInputObject(i),i))\n refmult++;\n }\n return refmult;\n}\ndisable francesco's cut by default\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/ \n\n\/\/ AliFlowEventCuts:\n\/\/ An event cut class for the flow framework\n\/\/\n\/\/ origin: Mikolaj Krzewicki (mikolaj.krzewicki@cern.ch)\n\n#include \n#include \n#include \"TMath.h\"\n#include \"TNamed.h\"\n#include \"AliVVertex.h\"\n#include \"AliVEvent.h\"\n#include \"AliESDEvent.h\"\n#include \"AliCentrality.h\"\n#include \"AliESDVZERO.h\"\n#include \"AliMultiplicity.h\"\n#include \"AliMCEvent.h\"\n#include \"AliFlowEventCuts.h\"\n#include \"AliFlowTrackCuts.h\"\n#include \"AliTriggerAnalysis.h\"\n\nClassImp(AliFlowEventCuts)\n\n\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::AliFlowEventCuts():\n TNamed(),\n fCutNumberOfTracks(kFALSE),\n fNumberOfTracksMax(INT_MAX),\n fNumberOfTracksMin(INT_MIN),\n fCutRefMult(kFALSE),\n fRefMultMethod(kTPConly),\n fRefMultMax(INT_MAX),\n fRefMultMin(INT_MIN),\n fRefMultCuts(NULL),\n fMeanPtCuts(NULL),\n fCutPrimaryVertexX(kFALSE),\n fPrimaryVertexXmax(INT_MAX),\n fPrimaryVertexXmin(INT_MIN),\n fCutPrimaryVertexY(kFALSE),\n fPrimaryVertexYmax(INT_MAX),\n fPrimaryVertexYmin(INT_MIN),\n fCutPrimaryVertexZ(kFALSE),\n fPrimaryVertexZmax(INT_MAX),\n fPrimaryVertexZmin(INT_MIN),\n fCutNContributors(kFALSE),\n fNContributorsMax(INT_MAX),\n fNContributorsMin(INT_MIN),\n fCutMeanPt(kFALSE),\n fMeanPtMax(-DBL_MAX),\n fMeanPtMin(DBL_MAX),\n fCutSPDvertexerAnomaly(kFALSE),\n fCutCentralityPercentile(kFALSE),\n fCentralityPercentileMethod(kTPConly),\n fCentralityPercentileMax(100.),\n fCentralityPercentileMin(0.),\n fCutZDCtiming(kFALSE),\n fTrigAna()\n{\n \/\/constructor \n}\n\n\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::AliFlowEventCuts(const char* name, const char* title):\n TNamed(name, title),\n fCutNumberOfTracks(kFALSE),\n fNumberOfTracksMax(INT_MAX),\n fNumberOfTracksMin(INT_MIN),\n fCutRefMult(kFALSE),\n fRefMultMethod(kTPConly),\n fRefMultMax(INT_MAX),\n fRefMultMin(INT_MIN),\n fRefMultCuts(NULL),\n fMeanPtCuts(NULL),\n fCutPrimaryVertexX(kFALSE),\n fPrimaryVertexXmax(INT_MAX),\n fPrimaryVertexXmin(INT_MIN),\n fCutPrimaryVertexY(kFALSE),\n fPrimaryVertexYmax(INT_MAX),\n fPrimaryVertexYmin(INT_MIN),\n fCutPrimaryVertexZ(kFALSE),\n fPrimaryVertexZmax(INT_MAX),\n fPrimaryVertexZmin(INT_MIN),\n fCutNContributors(kFALSE),\n fNContributorsMax(INT_MAX),\n fNContributorsMin(INT_MIN),\n fCutMeanPt(kFALSE),\n fMeanPtMax(-DBL_MAX),\n fMeanPtMin(DBL_MAX),\n fCutSPDvertexerAnomaly(kFALSE),\n fCutCentralityPercentile(kFALSE),\n fCentralityPercentileMethod(kTPConly),\n fCentralityPercentileMax(100.),\n fCentralityPercentileMin(0.),\n fCutZDCtiming(kFALSE),\n fTrigAna()\n{\n \/\/constructor \n}\n\n\/\/\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::AliFlowEventCuts(const AliFlowEventCuts& that):\n TNamed(that),\n fCutNumberOfTracks(that.fCutNumberOfTracks),\n fNumberOfTracksMax(that.fNumberOfTracksMax),\n fNumberOfTracksMin(that.fNumberOfTracksMin),\n fCutRefMult(that.fCutRefMult),\n fRefMultMethod(that.fRefMultMethod),\n fRefMultMax(that.fRefMultMax),\n fRefMultMin(that.fRefMultMin),\n fRefMultCuts(NULL),\n fMeanPtCuts(NULL),\n fCutPrimaryVertexX(that.fCutPrimaryVertexX),\n fPrimaryVertexXmax(that.fPrimaryVertexXmax),\n fPrimaryVertexXmin(that.fPrimaryVertexXmin),\n fCutPrimaryVertexY(that.fCutPrimaryVertexX),\n fPrimaryVertexYmax(that.fPrimaryVertexYmax),\n fPrimaryVertexYmin(that.fPrimaryVertexYmin),\n fCutPrimaryVertexZ(that.fCutPrimaryVertexX),\n fPrimaryVertexZmax(that.fPrimaryVertexZmax),\n fPrimaryVertexZmin(that.fPrimaryVertexZmin),\n fCutNContributors(that.fCutNContributors),\n fNContributorsMax(that.fNContributorsMax),\n fNContributorsMin(that.fNContributorsMin),\n fCutMeanPt(that.fCutMeanPt),\n fMeanPtMax(that.fMeanPtMax),\n fMeanPtMin(that.fMeanPtMin),\n fCutSPDvertexerAnomaly(that.fCutSPDvertexerAnomaly),\n fCutCentralityPercentile(that.fCutCentralityPercentile),\n fCentralityPercentileMethod(that.fCentralityPercentileMethod),\n fCentralityPercentileMax(that.fCentralityPercentileMax),\n fCentralityPercentileMin(that.fCentralityPercentileMin),\n fCutZDCtiming(that.fCutZDCtiming),\n fTrigAna()\n{\n \/\/copy constructor \n if (that.fRefMultCuts)\n fRefMultCuts = new AliFlowTrackCuts(*(that.fRefMultCuts));\n if (that.fMeanPtCuts)\n fMeanPtCuts = new AliFlowTrackCuts(*(that.fMeanPtCuts));\n}\n\n\/\/\/\/-----------------------------------------------------------------------\nAliFlowEventCuts::~AliFlowEventCuts()\n{\n \/\/dtor\n delete fMeanPtCuts;\n delete fRefMultCuts;\n}\n\n\/\/\/\/-----------------------------------------------------------------------\nAliFlowEventCuts& AliFlowEventCuts::operator=(const AliFlowEventCuts& that)\n{\n \/\/assignment\n fCutNumberOfTracks=that.fCutNumberOfTracks;\n fNumberOfTracksMax=that.fNumberOfTracksMax;\n fNumberOfTracksMin=that.fNumberOfTracksMin;\n fCutRefMult=that.fCutRefMult;\n fRefMultMethod=that.fRefMultMethod;\n fRefMultMax=that.fRefMultMax;\n fRefMultMin=that.fRefMultMin;\n if (that.fRefMultCuts) *fRefMultCuts=*(that.fRefMultCuts);\n if (that.fMeanPtCuts) *fMeanPtCuts=*(that.fMeanPtCuts);\n fCutPrimaryVertexX=that.fCutPrimaryVertexX;\n fPrimaryVertexXmin=that.fPrimaryVertexXmin;\n fPrimaryVertexXmax=that.fPrimaryVertexXmax;\n fPrimaryVertexYmin=that.fPrimaryVertexYmin;\n fPrimaryVertexYmax=that.fPrimaryVertexYmax;\n fPrimaryVertexZmin=that.fPrimaryVertexZmin;\n fPrimaryVertexZmax=that.fPrimaryVertexZmax;\n fCutNContributors=that.fCutNContributors;\n fNContributorsMax=that.fNContributorsMax;\n fNContributorsMin=that.fNContributorsMin;\n fCutMeanPt=that.fCutMeanPt;\n fMeanPtMax=that.fMeanPtMax;\n fMeanPtMin=that.fMeanPtMin;\n fCutSPDvertexerAnomaly=that.fCutSPDvertexerAnomaly;\n fCutCentralityPercentile=that.fCutCentralityPercentile;\n fCentralityPercentileMethod=that.fCentralityPercentileMethod;\n fCentralityPercentileMax=that.fCentralityPercentileMax;\n fCentralityPercentileMin=that.fCentralityPercentileMin;\n return *this;\n}\n\n\/\/----------------------------------------------------------------------- \nBool_t AliFlowEventCuts::IsSelected(TObject* obj)\n{\n \/\/check cuts\n AliVEvent* vevent = dynamic_cast(obj);\n if (vevent) return PassesCuts(vevent);\n return kFALSE; \/\/when passed wrong type of object\n}\n\/\/----------------------------------------------------------------------- \nBool_t AliFlowEventCuts::PassesCuts(AliVEvent *event)\n{\n \/\/\/check if event passes cuts\n AliESDEvent* esdevent = dynamic_cast(event);\n if (fCutCentralityPercentile&&esdevent)\n {\n AliCentrality* centr = esdevent->GetCentrality();\n if (!centr->IsEventInCentralityClass( fCentralityPercentileMin,\n fCentralityPercentileMax,\n CentrMethName(fCentralityPercentileMethod) ))\n {\n return kFALSE;\n }\n }\n if (fCutSPDvertexerAnomaly&&esdevent)\n {\n const AliESDVertex* sdpvertex = esdevent->GetPrimaryVertexSPD();\n if (sdpvertex->GetNContributors()<1) return kFALSE;\n if (sdpvertex->GetDispersion()>0.04) return kFALSE;\n if (sdpvertex->GetZRes()>0.25) return kFALSE;\n const AliESDVertex* tpcvertex = esdevent->GetPrimaryVertexTPC();\n if (tpcvertex->GetNContributors()<1) return kFALSE;\n const AliMultiplicity* tracklets = esdevent->GetMultiplicity();\n if (tpcvertex->GetNContributors()<(-10.0+0.25*tracklets->GetNumberOfITSClusters(0)))\n {\n return kFALSE;\n }\n }\n if (fCutZDCtiming&&esdevent)\n {\n if (!fTrigAna.ZDCTimeTrigger(esdevent))\n {\n return kFALSE;\n }\n }\n if(fCutNumberOfTracks) {if ( event->GetNumberOfTracks() < fNumberOfTracksMin ||\n event->GetNumberOfTracks() >= fNumberOfTracksMax ) return kFALSE;}\n if(fCutRefMult&&esdevent)\n {\n \/\/reference multiplicity still to be defined\n Double_t refMult = RefMult(event);\n if (refMult < fRefMultMin || refMult >= fRefMultMax )\n {\n return kFALSE;\n }\n }\n const AliVVertex* pvtx=event->GetPrimaryVertex();\n Double_t pvtxx = pvtx->GetX();\n Double_t pvtxy = pvtx->GetY();\n Double_t pvtxz = pvtx->GetZ();\n Int_t ncontrib = pvtx->GetNContributors();\n if (fCutNContributors)\n {\n if (ncontrib < fNContributorsMin || ncontrib >= fNContributorsMax)\n return kFALSE;\n }\n if (fCutPrimaryVertexX)\n {\n if (pvtxx < fPrimaryVertexXmin || pvtxx >= fPrimaryVertexXmax)\n return kFALSE;\n }\n if (fCutPrimaryVertexY)\n {\n if (pvtxy < fPrimaryVertexYmin || pvtxy >= fPrimaryVertexYmax)\n return kFALSE;\n }\n if (fCutPrimaryVertexZ)\n {\n if (pvtxz < fPrimaryVertexZmin || pvtxz >= fPrimaryVertexZmax)\n return kFALSE;\n }\n if (fCutMeanPt)\n {\n Float_t meanpt=0.0;\n Int_t ntracks=event->GetNumberOfTracks();\n Int_t nselected=0;\n for (Int_t i=0; iGetTrack(i);\n if (!track) continue;\n Bool_t pass=kTRUE;\n if (fMeanPtCuts) pass=fMeanPtCuts->IsSelected(track);\n if (pass) \n {\n meanpt += track->Pt();\n nselected++;\n }\n }\n meanpt=meanpt\/nselected;\n if (meanpt= fMeanPtMax) return kFALSE;\n }\n return kTRUE;\n}\n\n\/\/----------------------------------------------------------------------- \nconst char* AliFlowEventCuts::CentrMethName(refMultMethod method) const\n{\n \/\/get the string for refmultmethod, for use with AliCentrality in\n \/\/the cut on centrality percentile\n switch (method)\n {\n case kSPDtracklets:\n return \"TKL\";\n case kSPD1clusters:\n return \"CL1\";\n case kTPConly:\n return \"TRK\";\n case kV0:\n return \"V0M\";\n default:\n return \"\";\n }\n}\n\/\/----------------------------------------------------------------------- \nAliFlowEventCuts* AliFlowEventCuts::StandardCuts()\n{\n \/\/make a set of standard event cuts, caller becomes owner\n AliFlowEventCuts* cuts = new AliFlowEventCuts();\n return cuts;\n}\n\n\/\/----------------------------------------------------------------------- \nInt_t AliFlowEventCuts::RefMult(AliVEvent* event)\n{\n \/\/calculate the reference multiplicity, if all fails return 0\n AliESDVZERO* vzero = NULL;\n AliESDEvent* esdevent = dynamic_cast(event);\n\n if (fRefMultMethod==kTPConly && !fRefMultCuts)\n {\n fRefMultCuts = AliFlowTrackCuts::GetStandardTPCOnlyTrackCuts();\n fRefMultCuts->SetEtaRange(-0.8,0.8);\n fRefMultCuts->SetPtMin(0.15);\n }\n else if (fRefMultMethod==kSPDtracklets && !fRefMultCuts)\n {\n fRefMultCuts = new AliFlowTrackCuts(\"tracklet refmult cuts\");\n fRefMultCuts->SetParamType(AliFlowTrackCuts::kESD_SPDtracklet);\n fRefMultCuts->SetEtaRange(-0.8,0.8);\n }\n else if (fRefMultMethod==kV0)\n {\n if (!esdevent) return 0;\n vzero=esdevent->GetVZEROData();\n if (!vzero) return 0;\n return TMath::Nint(vzero->GetMTotV0A()+vzero->GetMTotV0C());\n }\n else if (fRefMultMethod==kSPD1clusters)\n {\n if (!esdevent) return 0;\n const AliMultiplicity* mult = esdevent->GetMultiplicity();\n if (!mult) return 0;\n return mult->GetNumberOfITSClusters(1);\n }\n\n Int_t refmult=0;\n fRefMultCuts->SetEvent(event);\n for (Int_t i=0; iGetNumberOfInputObjects(); i++)\n {\n if (fRefMultCuts->IsSelected(fRefMultCuts->GetInputObject(i),i))\n refmult++;\n }\n return refmult;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkPrincipalAxesResampler.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n\n\/*--------------------------------------------------------------------------\nThis command line program reads an image file, finds its principal\naxes, and resamples the image into principal axes coordinates. It\ntakes two arguments: the names of the input and output image files.\nThe image dimensions are fixed at 192 slices by 256 rows by 256\ncolumns and the data format is fixed at bigendian 16-bit unsigned\ninteger. (But see below for hooks to change these parameters.)\n---------------------------------------------------------------------------*\/\n\n#include \n#include \n\n#include \"itkAffineTransform.h\"\n#include \"itkByteSwapper.h\"\n#include \"itkImage.h\"\n#include \"itkImageMomentsCalculator.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkSimpleImageRegionIterator.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n\nenum {NDimensions = 3};\n\ntypedef unsigned short PixelType;\ntypedef itk::Image ImageType;\ntypedef ImageType::RegionType ImageRegionType;\ntypedef ImageType::SizeType ImageSizeType;\ntypedef ImageType::AffineTransformType AffineTransformType;\n\ntypedef itk::Index ImageIndexType;\ntypedef itk::SimpleImageRegionIterator ImageIteratorType;\ntypedef itk::ImageMomentsCalculator ImageMomentsCalculatorType;\ntypedef itk::LinearInterpolateImageFunction InterpolatorType;\ntypedef itk::Point PointType;\n\n\nint\nmain(int argc, char *argv[])\n{\n \/* Set image and other parameters *\/\n long ImageWidth = 256;\n long ImageHeight = 256;\n long NumberOfSlices = 192;\n int bigend = 1; \/\/ Bigendian data in external files?\n int verbose = 1; \/\/ Show intermediate results?\n\n \/* Get input and output file names from the command line *\/\n if (argc < 2)\n {\n fprintf(stderr, \"You must give input and output file names\\n\");\n exit(EXIT_FAILURE);\n }\n char *filename1 = argv[1];\n char *filename2 = argv[2];\n\n \/* Open image file *\/\n \/* FIXME: Translate into C++ *\/\n FILE *infile = fopen(filename1, \"rb\");\n if (infile == 0) \n {\n fprintf(stderr, \"Unable to open input file\\n\");\n exit(EXIT_FAILURE);\n }\n\n \/* Allocate an image object to store the input file in *\/\n ImageIndexType base = {{0,0,0}};\n ImageSizeType size = {{ImageWidth, ImageHeight, NumberOfSlices}};\n double spacing[3] = {1.0, 1.0, 1.0}; \/\/ Pixel size\n double origin [3] = {0.0, 0.0, 0.0}; \/\/ Location of (0,0,0) pixel\n ImageType::Pointer image = ImageType::New();\n ImageRegionType region;\n region.SetIndex(base);\n region.SetSize(size);\n image->SetLargestPossibleRegion(region);\n image->SetBufferedRegion(region);\n image->SetRequestedRegion(region);\n image->Allocate();\n image->SetOrigin(origin);\n image->SetSpacing(spacing);\n\n \/* Read the image file into an itkImage object *\/\n \/* FIXME: Find or write Insightful tools for this *\/\n std::cout << \"Reading image file.\" << std::endl;\n ImageIndexType index; \/\/ Index to current pixel\n unsigned long point[3]; \/\/ Location of current pixel\n PixelType *buff = new PixelType[ImageWidth]; \/\/ Input\/output buffer\n PixelType maxval = 0; \/\/ Maximum pixel value in image\n size_t count;\n for (long slice = 0; slice < NumberOfSlices; slice++) {\n point[2] = slice;\n for (long row = 0; row < ImageHeight; row++) {\n point[1] = row;\n count = fread(buff, sizeof(PixelType), ImageWidth, infile);\n if (count != (size_t)ImageWidth) {\n fprintf(stderr, \"Error reading input file\\n\");\n exit(EXIT_FAILURE); \n }\n if (bigend)\n itk::ByteSwapper::SwapRangeBE(buff, ImageWidth);\n else\n itk::ByteSwapper::SwapRangeLE(buff, ImageWidth);\n for (long col = 0; col < ImageWidth; col++) {\n point[0] = col;\n index.SetIndex(point);\n image->SetPixel(index, buff[col]);\n if (buff[col] > maxval)\n maxval = buff[col];\n }\n }\n }\n\n \/* Print the maximum pixel value found. (This is useful for detecting\n all-zero images, which confuse the moments calculation.) *\/\n std::cout << \" Max pixel value: \" << maxval << std::endl;\n\n \/* Close the input file *\/\n fclose(infile);\n\n \/* Compute principal moments and axes *\/\n std::cout << \"Computing moments and transformation.\" << std::endl;\n ImageMomentsCalculatorType moments(image);\n double ctm = moments.GetTotalMass();\n itk::Vector\n ccg = moments.GetCenterOfGravity();\n itk::Vector\n cpm = moments.GetPrincipalMoments();\n itk::Matrix\n cpa = moments.GetPrincipalAxes();\n\n \/* Report moments information to the user *\/\n if (verbose) {\n std::cout << \"\\nTotal mass = \" << ctm << std::endl;\n std::cout << \"\\nCenter of gravity = \" << ccg << std::endl;\n std::cout << \"\\nPrincipal moments = \" << cpm << std::endl;\n std::cout << \"\\nPrincipal axes = \\n\";\n std::cout << cpa << \"\\n\";\n }\n\n \/* Compute the transform from principal axes to original axes *\/\n double pi = 3.14159265359;\n AffineTransformType::Pointer trans = AffineTransformType::New();\n itk::Vector center;\n center[0] = -ImageWidth \/ 2.0;\n center[1] = -ImageHeight \/ 2.0;\n center[2] = -NumberOfSlices \/ 2.0;\n trans->Translate(center);\n trans->Rotate(1, 0, pi\/2.0); \/\/ Rotate into radiological orientation\n trans->Rotate(2, 0, -pi\/2.0);\n AffineTransformType::Pointer pa2phys =\n moments.GetPrincipalAxesToPhysicalAxesTransform();\n if (verbose) {\n std::cout << \"Principal axes to physical axes transform\" << std::endl;\n pa2phys->Print( std::cout );\n }\n trans->Compose(pa2phys);\n trans->Compose(image->GetPhysicalToIndexTransform());\n if (verbose) {\n std::cout << \"Backprojection transform:\" << std::endl;\n trans->Print( std::cout );\n }\n\n \/* Create and initialize the interpolator *\/\n InterpolatorType::Pointer interp = InterpolatorType::New();\n interp->SetInputImage(image);\n\n \/* Resample image in principal axes coordinates *\/\n std::cout << \"Resampling the image\" << std::endl;\n itk::ResampleImageFilter< ImageType, ImageType >::Pointer resample;\n resample = itk::ResampleImageFilter< ImageType, ImageType >::New();\n resample->SetInput(image);\n resample->SetSize(size);\n resample->SetTransform(trans);\n resample->SetInterpolator(interp);\n\n \/\/ Run the resampling filter\n resample->Update();\n\n \/\/ Extract the output image\n ImageType::Pointer resamp = resample->GetOutput();\n\n \/* Open the output file *\/\n \/* FIXME: Translate into C++ *\/\n std::cout << \"Writing the output file\" << std::endl;\n FILE *outfile = fopen(filename2, \"wb\");\n if (outfile == 0) \n {\n fprintf(stderr, \"Unable to open output file\\n\");\n exit(EXIT_FAILURE);\n }\n\n \/* Write resampled image to a file *\/\n for (long slice = 0; slice < NumberOfSlices; slice++) {\n point[2] = slice;\n for (long row = 0; row < ImageHeight; row++) {\n point[1] = row;\n for (long col = 0; col < ImageWidth; col++) {\n point[0] = col;\n index.SetIndex(point);\n buff[col] = resamp->GetPixel(index);\n }\n if (bigend)\n itk::ByteSwapper::SwapRangeBE(buff, ImageWidth);\n else\n itk::ByteSwapper::SwapRangeLE(buff, ImageWidth);\n count = fwrite(buff, 2, ImageWidth, outfile);\n if (count != (size_t)ImageWidth) {\n fprintf(stderr, \"Error writing output file\\n\");\n exit(EXIT_FAILURE); }\n }\n }\n fclose(outfile);\n\n delete [] buff;\n return 0;\n}\nENH: index value type.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkPrincipalAxesResampler.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n\n\/*--------------------------------------------------------------------------\nThis command line program reads an image file, finds its principal\naxes, and resamples the image into principal axes coordinates. It\ntakes two arguments: the names of the input and output image files.\nThe image dimensions are fixed at 192 slices by 256 rows by 256\ncolumns and the data format is fixed at bigendian 16-bit unsigned\ninteger. (But see below for hooks to change these parameters.)\n---------------------------------------------------------------------------*\/\n\n#include \n#include \n\n#include \"itkAffineTransform.h\"\n#include \"itkByteSwapper.h\"\n#include \"itkImage.h\"\n#include \"itkImageMomentsCalculator.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkSimpleImageRegionIterator.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n\nenum {NDimensions = 3};\n\ntypedef unsigned short PixelType;\ntypedef itk::Image ImageType;\ntypedef ImageType::IndexValueType ImageIndexValueType;\ntypedef ImageType::RegionType ImageRegionType;\ntypedef ImageType::SizeType ImageSizeType;\ntypedef ImageType::AffineTransformType AffineTransformType;\n\ntypedef itk::Index ImageIndexType;\ntypedef itk::SimpleImageRegionIterator ImageIteratorType;\ntypedef itk::ImageMomentsCalculator ImageMomentsCalculatorType;\ntypedef itk::LinearInterpolateImageFunction InterpolatorType;\ntypedef itk::Point PointType;\n\n\nint\nmain(int argc, char *argv[])\n{\n \/* Set image and other parameters *\/\n long ImageWidth = 256;\n long ImageHeight = 256;\n long NumberOfSlices = 192;\n int bigend = 1; \/\/ Bigendian data in external files?\n int verbose = 1; \/\/ Show intermediate results?\n\n \/* Get input and output file names from the command line *\/\n if (argc < 2)\n {\n fprintf(stderr, \"You must give input and output file names\\n\");\n exit(EXIT_FAILURE);\n }\n char *filename1 = argv[1];\n char *filename2 = argv[2];\n\n \/* Open image file *\/\n \/* FIXME: Translate into C++ *\/\n FILE *infile = fopen(filename1, \"rb\");\n if (infile == 0) \n {\n fprintf(stderr, \"Unable to open input file\\n\");\n exit(EXIT_FAILURE);\n }\n\n \/* Allocate an image object to store the input file in *\/\n ImageIndexType base = {{0,0,0}};\n ImageSizeType size = {{ImageWidth, ImageHeight, NumberOfSlices}};\n double spacing[3] = {1.0, 1.0, 1.0}; \/\/ Pixel size\n double origin [3] = {0.0, 0.0, 0.0}; \/\/ Location of (0,0,0) pixel\n ImageType::Pointer image = ImageType::New();\n ImageRegionType region;\n region.SetIndex(base);\n region.SetSize(size);\n image->SetLargestPossibleRegion(region);\n image->SetBufferedRegion(region);\n image->SetRequestedRegion(region);\n image->Allocate();\n image->SetOrigin(origin);\n image->SetSpacing(spacing);\n\n \/* Read the image file into an itkImage object *\/\n \/* FIXME: Find or write Insightful tools for this *\/\n std::cout << \"Reading image file.\" << std::endl;\n ImageIndexType index; \/\/ Index to current pixel\n ImageIndexValueType point[3]; \/\/ Location of current pixel\n PixelType *buff = new PixelType[ImageWidth]; \/\/ Input\/output buffer\n PixelType maxval = 0; \/\/ Maximum pixel value in image\n size_t count;\n for (long slice = 0; slice < NumberOfSlices; slice++) {\n point[2] = slice;\n for (long row = 0; row < ImageHeight; row++) {\n point[1] = row;\n count = fread(buff, sizeof(PixelType), ImageWidth, infile);\n if (count != (size_t)ImageWidth) {\n fprintf(stderr, \"Error reading input file\\n\");\n exit(EXIT_FAILURE); \n }\n if (bigend)\n itk::ByteSwapper::SwapRangeBE(buff, ImageWidth);\n else\n itk::ByteSwapper::SwapRangeLE(buff, ImageWidth);\n for (long col = 0; col < ImageWidth; col++) {\n point[0] = col;\n index.SetIndex(point);\n image->SetPixel(index, buff[col]);\n if (buff[col] > maxval)\n maxval = buff[col];\n }\n }\n }\n\n \/* Print the maximum pixel value found. (This is useful for detecting\n all-zero images, which confuse the moments calculation.) *\/\n std::cout << \" Max pixel value: \" << maxval << std::endl;\n\n \/* Close the input file *\/\n fclose(infile);\n\n \/* Compute principal moments and axes *\/\n std::cout << \"Computing moments and transformation.\" << std::endl;\n ImageMomentsCalculatorType moments(image);\n double ctm = moments.GetTotalMass();\n itk::Vector\n ccg = moments.GetCenterOfGravity();\n itk::Vector\n cpm = moments.GetPrincipalMoments();\n itk::Matrix\n cpa = moments.GetPrincipalAxes();\n\n \/* Report moments information to the user *\/\n if (verbose) {\n std::cout << \"\\nTotal mass = \" << ctm << std::endl;\n std::cout << \"\\nCenter of gravity = \" << ccg << std::endl;\n std::cout << \"\\nPrincipal moments = \" << cpm << std::endl;\n std::cout << \"\\nPrincipal axes = \\n\";\n std::cout << cpa << \"\\n\";\n }\n\n \/* Compute the transform from principal axes to original axes *\/\n double pi = 3.14159265359;\n AffineTransformType::Pointer trans = AffineTransformType::New();\n itk::Vector center;\n center[0] = -ImageWidth \/ 2.0;\n center[1] = -ImageHeight \/ 2.0;\n center[2] = -NumberOfSlices \/ 2.0;\n trans->Translate(center);\n trans->Rotate(1, 0, pi\/2.0); \/\/ Rotate into radiological orientation\n trans->Rotate(2, 0, -pi\/2.0);\n AffineTransformType::Pointer pa2phys =\n moments.GetPrincipalAxesToPhysicalAxesTransform();\n if (verbose) {\n std::cout << \"Principal axes to physical axes transform\" << std::endl;\n pa2phys->Print( std::cout );\n }\n trans->Compose(pa2phys);\n trans->Compose(image->GetPhysicalToIndexTransform());\n if (verbose) {\n std::cout << \"Backprojection transform:\" << std::endl;\n trans->Print( std::cout );\n }\n\n \/* Create and initialize the interpolator *\/\n InterpolatorType::Pointer interp = InterpolatorType::New();\n interp->SetInputImage(image);\n\n \/* Resample image in principal axes coordinates *\/\n std::cout << \"Resampling the image\" << std::endl;\n itk::ResampleImageFilter< ImageType, ImageType >::Pointer resample;\n resample = itk::ResampleImageFilter< ImageType, ImageType >::New();\n resample->SetInput(image);\n resample->SetSize(size);\n resample->SetTransform(trans);\n resample->SetInterpolator(interp);\n\n \/\/ Run the resampling filter\n resample->Update();\n\n \/\/ Extract the output image\n ImageType::Pointer resamp = resample->GetOutput();\n\n \/* Open the output file *\/\n \/* FIXME: Translate into C++ *\/\n std::cout << \"Writing the output file\" << std::endl;\n FILE *outfile = fopen(filename2, \"wb\");\n if (outfile == 0) \n {\n fprintf(stderr, \"Unable to open output file\\n\");\n exit(EXIT_FAILURE);\n }\n\n \/* Write resampled image to a file *\/\n for (long slice = 0; slice < NumberOfSlices; slice++) {\n point[2] = slice;\n for (long row = 0; row < ImageHeight; row++) {\n point[1] = row;\n for (long col = 0; col < ImageWidth; col++) {\n point[0] = col;\n index.SetIndex(point);\n buff[col] = resamp->GetPixel(index);\n }\n if (bigend)\n itk::ByteSwapper::SwapRangeBE(buff, ImageWidth);\n else\n itk::ByteSwapper::SwapRangeLE(buff, ImageWidth);\n count = fwrite(buff, 2, ImageWidth, outfile);\n if (count != (size_t)ImageWidth) {\n fprintf(stderr, \"Error writing output file\\n\");\n exit(EXIT_FAILURE); }\n }\n }\n fclose(outfile);\n\n delete [] buff;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"LightRenderSystem.h\"\n\n#include \"GraphicsBackendSystem.h\"\n#include \n#include \n#include \n#include \n#include \n\nLightRenderSystem::LightRenderSystem( GraphicsBackendSystem* p_gfxBackend )\n\t: EntitySystem( SystemType::LightRenderSystem )\n{\n\tm_gfxBackend = p_gfxBackend;\n\n\tm_box = NULL;\n}\n\n\nLightRenderSystem::~LightRenderSystem()\n{\n\tdelete m_box;\n}\n\nvoid LightRenderSystem::initialize()\n{\n\tGraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();\n\n\tBufferFactory* bufferFactory = new BufferFactory( gfxWrapper->getDevice(),\n\t\tgfxWrapper->getDeviceContext() );\n\n\tm_box = bufferFactory->createLightBoxMesh();\n\tdelete bufferFactory;\n}\n\nvoid LightRenderSystem::processEntities( const vector& p_entities )\n{\n\tGraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();\n\t\n\tgfxWrapper->beginLightPass();\t\t\t \/\/ finalize, draw to back buffer\n\t\/\/gfxWrapper->renderLights( NULL, NULL );\n\n\tstatic float range = 10.0f;\n\tAntTweakBarWrapper::getInstance()->addWriteVariable(AntTweakBarWrapper::GRAPHICS, \"lightCubeWidth\", TwType::TW_TYPE_FLOAT, &range,\"\");\n\n\tAglMatrix mat = AglMatrix::identityMatrix();\n\tmat[0] = mat[5] = mat[10] = range \/ 2.0f; \/\/ The cube is 2.0f wide, therefore 2 and not 1\n\t\n\tLightInstanceData instData;\n\tinstData.range = range; \/\/ Should be synced with wolrdTransform\n\tfor( int i=0; i<16; i++ ){\n\t\tinstData.worldTransform[i] = mat[i];\n\t}\n\n\tinstData.lightDir[0] = 1.0f;\n\tinstData.lightDir[1] = 0.0f;\n\tinstData.lightDir[2] = 0.0f;\n\n\tinstData.attenuation[0] = 1.1f;\n\tinstData.attenuation[1] = 0.01f;\n\tinstData.attenuation[2] = 0.1f;\n\tinstData.spotPower = 100.0f;\n\n\tinstData.ambient[0] = 0.01f;\n\tinstData.ambient[1] = 0.01f;\n\tinstData.ambient[2] = 0.01f;\n\tinstData.ambient[3] = 1.01f;\n\n\tinstData.diffuse[0] = 0.0f;\n\tinstData.diffuse[1] = 0.5f;\n\tinstData.diffuse[2] = 0.0f;\n\tinstData.diffuse[3] = 1.0f;\n\n\tinstData.specular[0] = 0.5f;\n\tinstData.specular[1] = 0.1f;\n\tinstData.specular[2] = 0.0f;\n\tinstData.specular[3] = 1.0f;\n\n\tinstData.enabled = true;\n\tinstData.type = LightTypes::E_LightTypes_POINT;\n\n\tvector instDatas;\n\tfor( int x=0; x<5; x++ )\n\t{\n\t\tinstData.worldTransform[3] = x * (range+1.0f) - 25.0f;\n\t\tinstData.diffuse[1] += 0.1f;\n\t\tfor( int y=0; y<5; y++ )\n\t\t{\n\t\t\tinstData.worldTransform[7] = y * (range+1.0f) - 25.0f;\n\t\t\tinstData.diffuse[2] += 0.1f;\n\t\t\tfor( int z=0; z<5; z++ )\n\t\t\t{\n\t\t\t\tinstData.worldTransform[11] = z * (range+1.0f) - 25.0f;\n\t\t\t\tinstData.diffuse[3] += 0.1f;\n\t\t\t\tinstDatas.push_back( instData );\n\t\t\t}\n\t\t}\n\t}\n\n\tgfxWrapper->renderLights( m_box, &instDatas );\n\t \n\tgfxWrapper->endLightPass();\n}\nRemoved AntTweakBar errors from the output.#include \"LightRenderSystem.h\"\n\n#include \"GraphicsBackendSystem.h\"\n#include \n#include \n#include \n#include \n#include \n\nLightRenderSystem::LightRenderSystem( GraphicsBackendSystem* p_gfxBackend )\n\t: EntitySystem( SystemType::LightRenderSystem )\n{\n\tm_gfxBackend = p_gfxBackend;\n\n\tm_box = NULL;\n}\n\n\nLightRenderSystem::~LightRenderSystem()\n{\n\tdelete m_box;\n}\n\nvoid LightRenderSystem::initialize()\n{\n\tGraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();\n\n\tBufferFactory* bufferFactory = new BufferFactory( gfxWrapper->getDevice(),\n\t\tgfxWrapper->getDeviceContext() );\n\n\tm_box = bufferFactory->createLightBoxMesh();\n\tdelete bufferFactory;\n}\n\nvoid LightRenderSystem::processEntities( const vector& p_entities )\n{\n\tGraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();\n\t\n\tgfxWrapper->beginLightPass();\t\t\t \/\/ finalize, draw to back buffer\n\t\/\/gfxWrapper->renderLights( NULL, NULL );\n\n\tstatic float range = 10.0f;\n\n\tAglMatrix mat = AglMatrix::identityMatrix();\n\tmat[0] = mat[5] = mat[10] = range \/ 2.0f; \/\/ The cube is 2.0f wide, therefore 2 and not 1\n\t\n\tLightInstanceData instData;\n\tinstData.range = range; \/\/ Should be synced with wolrdTransform\n\tfor( int i=0; i<16; i++ ){\n\t\tinstData.worldTransform[i] = mat[i];\n\t}\n\n\tinstData.lightDir[0] = 1.0f;\n\tinstData.lightDir[1] = 0.0f;\n\tinstData.lightDir[2] = 0.0f;\n\n\tinstData.attenuation[0] = 1.1f;\n\tinstData.attenuation[1] = 0.01f;\n\tinstData.attenuation[2] = 0.1f;\n\tinstData.spotPower = 100.0f;\n\n\tinstData.ambient[0] = 0.01f;\n\tinstData.ambient[1] = 0.01f;\n\tinstData.ambient[2] = 0.01f;\n\tinstData.ambient[3] = 1.01f;\n\n\tinstData.diffuse[0] = 0.0f;\n\tinstData.diffuse[1] = 0.5f;\n\tinstData.diffuse[2] = 0.0f;\n\tinstData.diffuse[3] = 1.0f;\n\n\tinstData.specular[0] = 0.5f;\n\tinstData.specular[1] = 0.1f;\n\tinstData.specular[2] = 0.0f;\n\tinstData.specular[3] = 1.0f;\n\n\tinstData.enabled = true;\n\tinstData.type = LightTypes::E_LightTypes_POINT;\n\n\tvector instDatas;\n\tfor( int x=0; x<5; x++ )\n\t{\n\t\tinstData.worldTransform[3] = x * (range+1.0f) - 25.0f;\n\t\tinstData.diffuse[1] += 0.1f;\n\t\tfor( int y=0; y<5; y++ )\n\t\t{\n\t\t\tinstData.worldTransform[7] = y * (range+1.0f) - 25.0f;\n\t\t\tinstData.diffuse[2] += 0.1f;\n\t\t\tfor( int z=0; z<5; z++ )\n\t\t\t{\n\t\t\t\tinstData.worldTransform[11] = z * (range+1.0f) - 25.0f;\n\t\t\t\tinstData.diffuse[3] += 0.1f;\n\t\t\t\tinstDatas.push_back( instData );\n\t\t\t}\n\t\t}\n\t}\n\n\tgfxWrapper->renderLights( m_box, &instDatas );\n\t \n\tgfxWrapper->endLightPass();\n}\n<|endoftext|>"} {"text":"\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n\/\/\n\/\/ Code that is used by both the Unix corerun and coreconsole.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"coreruncommon.h\"\n#include \n\n#define SUCCEEDED(Status) ((Status) >= 0)\n\n\/\/ Name of the environment variable controlling server GC.\n\/\/ If set to 1, server GC is enabled on startup. If 0, server GC is\n\/\/ disabled. Server GC is off by default.\nstatic const char* serverGcVar = \"CORECLR_SERVER_GC\";\n\n\/\/ Name of the environment variable controlling concurrent GC,\n\/\/ used in the same way as serverGcVar. Concurrent GC is on by default.\nstatic const char* concurrentGcVar = \"CORECLR_CONCURRENT_GC\";\n\n\/\/ Prototype of the coreclr_initialize function from the libcoreclr.so\ntypedef int (*InitializeCoreCLRFunction)(\n const char* exePath,\n const char* appDomainFriendlyName,\n int propertyCount,\n const char** propertyKeys,\n const char** propertyValues,\n void** hostHandle,\n unsigned int* domainId);\n\n\/\/ Prototype of the coreclr_shutdown function from the libcoreclr.so\ntypedef int (*ShutdownCoreCLRFunction)(\n void* hostHandle,\n unsigned int domainId);\n\n\/\/ Prototype of the coreclr_execute_assembly function from the libcoreclr.so\ntypedef int (*ExecuteAssemblyFunction)(\n void* hostHandle,\n unsigned int domainId,\n int argc,\n const char** argv,\n const char* managedAssemblyPath,\n unsigned int* exitCode);\n\n#if defined(__LINUX__)\n#define symlinkEntrypointExecutable \"\/proc\/self\/exe\"\n#elif !defined(__APPLE__)\n#define symlinkEntrypointExecutable \"\/proc\/curproc\/exe\"\n#endif\n\nbool GetEntrypointExecutableAbsolutePath(std::string& entrypointExecutable)\n{\n bool result = false;\n \n entrypointExecutable.clear();\n\n \/\/ Get path to the executable for the current process using\n \/\/ platform specific means.\n#if defined(__LINUX__)\n \/\/ On Linux, fetch the entry point EXE absolute path, inclusive of filename.\n char exe[PATH_MAX];\n ssize_t res = readlink(symlinkEntrypointExecutable, exe, PATH_MAX - 1);\n if (res != -1)\n {\n exe[res] = '\\0';\n entrypointExecutable.assign(exe);\n result = true;\n }\n else\n {\n result = false;\n }\n#elif defined(__APPLE__)\n \n \/\/ On Mac, we ask the OS for the absolute path to the entrypoint executable\n uint32_t lenActualPath = 0;\n if (_NSGetExecutablePath(nullptr, &lenActualPath) == -1)\n {\n \/\/ OSX has placed the actual path length in lenActualPath,\n \/\/ so re-attempt the operation\n std::string resizedPath(lenActualPath, '\\0');\n char *pResizedPath = const_cast(resizedPath.c_str());\n if (_NSGetExecutablePath(pResizedPath, &lenActualPath) == 0)\n {\n entrypointExecutable.assign(pResizedPath);\n result = true;\n }\n }\n#else\n \/\/ On non-Mac OS, return the symlink that will be resolved by GetAbsolutePath\n \/\/ to fetch the entrypoint EXE absolute path, inclusive of filename.\n entrypointExecutable.assign(symlinkEntrypointExecutable);\n result = true;\n#endif \n\n return result;\n}\n\nbool GetAbsolutePath(const char* path, std::string& absolutePath)\n{\n bool result = false;\n\n char realPath[PATH_MAX];\n if (realpath(path, realPath) != nullptr && realPath[0] != '\\0')\n {\n absolutePath.assign(realPath);\n \/\/ realpath should return canonicalized path without the trailing slash\n assert(absolutePath.back() != '\/');\n\n result = true;\n }\n\n return result;\n}\n\nbool GetDirectory(const char* absolutePath, std::string& directory)\n{\n directory.assign(absolutePath);\n size_t lastSlash = directory.rfind('\/');\n if (lastSlash != std::string::npos)\n {\n directory.erase(lastSlash);\n return true;\n }\n\n return false;\n}\n\nbool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)\n{\n std::string clrFilesRelativePath;\n const char* clrFilesPathLocal = clrFilesPath;\n if (clrFilesPathLocal == nullptr)\n {\n \/\/ There was no CLR files path specified, use the folder of the corerun\/coreconsole\n if (!GetDirectory(currentExePath, clrFilesRelativePath))\n {\n perror(\"Failed to get directory from argv[0]\");\n return false;\n }\n\n clrFilesPathLocal = clrFilesRelativePath.c_str();\n\n \/\/ TODO: consider using an env variable (if defined) as a fall-back.\n \/\/ The windows version of the corerun uses core_root env variable\n }\n\n if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))\n {\n perror(\"Failed to convert CLR files path to absolute path\");\n return false;\n }\n\n return true;\n}\n\nvoid AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)\n{\n const char * const tpaExtensions[] = {\n \".ni.dll\", \/\/ Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir\n \".dll\",\n \".ni.exe\",\n \".exe\",\n };\n \n DIR* dir = opendir(directory);\n if (dir == nullptr)\n {\n return;\n }\n\n std::set addedAssemblies;\n\n \/\/ Walk the directory for each extension separately so that we first get files with .ni.dll extension,\n \/\/ then files with .dll extension, etc.\n for (int extIndex = 0; extIndex < sizeof(tpaExtensions) \/ sizeof(tpaExtensions[0]); extIndex++)\n {\n const char* ext = tpaExtensions[extIndex];\n int extLength = strlen(ext);\n\n struct dirent* entry;\n\n \/\/ For all entries in the directory\n while ((entry = readdir(dir)) != nullptr)\n {\n \/\/ We are interested in files only\n switch (entry->d_type)\n {\n case DT_REG:\n break;\n\n \/\/ Handle symlinks and file systems that do not support d_type\n case DT_LNK:\n case DT_UNKNOWN:\n {\n std::string fullFilename;\n\n fullFilename.append(directory);\n fullFilename.append(\"\/\");\n fullFilename.append(entry->d_name);\n\n struct stat sb;\n if (stat(fullFilename.c_str(), &sb) == -1)\n {\n continue;\n }\n\n if (!S_ISREG(sb.st_mode))\n {\n continue;\n }\n }\n break;\n\n default:\n continue;\n }\n\n std::string filename(entry->d_name);\n\n \/\/ Check if the extension matches the one we are looking for\n int extPos = filename.length() - extLength;\n if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))\n {\n continue;\n }\n\n std::string filenameWithoutExt(filename.substr(0, extPos));\n\n \/\/ Make sure if we have an assembly with multiple extensions present,\n \/\/ we insert only one version of it.\n if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())\n {\n addedAssemblies.insert(filenameWithoutExt);\n\n tpaList.append(directory);\n tpaList.append(\"\/\");\n tpaList.append(filename);\n tpaList.append(\":\");\n }\n }\n \n \/\/ Rewind the directory stream to be able to iterate over it for the next extension\n rewinddir(dir);\n }\n \n closedir(dir);\n}\n\nint ExecuteManagedAssembly(\n const char* currentExeAbsolutePath,\n const char* clrFilesAbsolutePath,\n const char* managedAssemblyAbsolutePath,\n int managedAssemblyArgc,\n const char** managedAssemblyArgv)\n{\n \/\/ Indicates failure\n int exitCode = -1;\n\n std::string coreClrDllPath(clrFilesAbsolutePath);\n coreClrDllPath.append(\"\/\");\n coreClrDllPath.append(coreClrDll);\n\n if (coreClrDllPath.length() >= PATH_MAX)\n {\n fprintf(stderr, \"Absolute path to libcoreclr.so too long\\n\");\n return -1;\n }\n\n \/\/ Get just the path component of the managed assembly path\n std::string appPath;\n GetDirectory(managedAssemblyAbsolutePath, appPath);\n\n std::string nativeDllSearchDirs(appPath);\n nativeDllSearchDirs.append(\":\");\n nativeDllSearchDirs.append(clrFilesAbsolutePath);\n\n std::string tpaList;\n AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);\n\n void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);\n if (coreclrLib != nullptr)\n {\n InitializeCoreCLRFunction initializeCoreCLR = (InitializeCoreCLRFunction)dlsym(coreclrLib, \"coreclr_initialize\");\n ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, \"coreclr_execute_assembly\");\n ShutdownCoreCLRFunction shutdownCoreCLR = (ShutdownCoreCLRFunction)dlsym(coreclrLib, \"coreclr_shutdown\");\n\n if (initializeCoreCLR == nullptr)\n {\n fprintf(stderr, \"Function coreclr_initialize not found in the libcoreclr.so\\n\");\n }\n else if (executeAssembly == nullptr)\n {\n fprintf(stderr, \"Function coreclr_execute_assembly not found in the libcoreclr.so\\n\");\n }\n else if (shutdownCoreCLR == nullptr)\n {\n fprintf(stderr, \"Function coreclr_shutdown not found in the libcoreclr.so\\n\");\n }\n else\n {\n \/\/ check if we are enabling server GC or concurrent GC.\n \/\/ Server GC is off by default, while concurrent GC is on by default.\n \/\/ Actual checking of these string values is done in coreclr_initialize.\n const char* useServerGc = std::getenv(serverGcVar);\n if (useServerGc == nullptr)\n {\n useServerGc = \"0\";\n }\n \n const char* useConcurrentGc = std::getenv(concurrentGcVar);\n if (useConcurrentGc == nullptr)\n {\n useConcurrentGc = \"1\";\n }\n \n \/\/ Allowed property names:\n \/\/ APPBASE\n \/\/ - The base path of the application from which the exe and other assemblies will be loaded\n \/\/\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n \/\/ - The list of complete paths to each of the fully trusted assemblies\n \/\/\n \/\/ APP_PATHS\n \/\/ - The list of paths which will be probed by the assembly loader\n \/\/\n \/\/ APP_NI_PATHS\n \/\/ - The list of additional paths that the assembly loader will probe for ngen images\n \/\/\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n \/\/ - The list of paths that will be probed for native DLLs called by PInvoke\n \/\/\n const char *propertyKeys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\",\n \"AppDomainCompatSwitch\",\n \"SERVER_GC\",\n \"CONCURRENT_GC\"\n };\n const char *propertyValues[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpaList.c_str(),\n \/\/ APP_PATHS\n appPath.c_str(),\n \/\/ APP_NI_PATHS\n appPath.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n nativeDllSearchDirs.c_str(),\n \/\/ AppDomainCompatSwitch\n \"UseLatestBehaviorWhenTFMNotSpecified\",\n \/\/ SERVER_GC\n useServerGc,\n \/\/ CONCURRENT_GC\n useConcurrentGc\n };\n\n void* hostHandle;\n unsigned int domainId;\n\n int st = initializeCoreCLR(\n currentExeAbsolutePath, \n \"unixcorerun\", \n sizeof(propertyKeys) \/ sizeof(propertyKeys[0]), \n propertyKeys, \n propertyValues, \n &hostHandle, \n &domainId);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"coreclr_initialize failed - status: 0x%08x\\n\", st);\n exitCode = -1;\n }\n else \n {\n st = executeAssembly(\n hostHandle,\n domainId,\n managedAssemblyArgc,\n managedAssemblyArgv,\n managedAssemblyAbsolutePath,\n (unsigned int*)&exitCode);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"coreclr_execute_assembly failed - status: 0x%08x\\n\", st);\n exitCode = -1;\n }\n\n st = shutdownCoreCLR(hostHandle, domainId);\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"coreclr_shutdown failed - status: 0x%08x\\n\", st);\n exitCode = -1;\n }\n }\n }\n\n if (dlclose(coreclrLib) != 0)\n {\n fprintf(stderr, \"Warning - dlclose failed\\n\");\n }\n }\n else\n {\n char* error = dlerror();\n fprintf(stderr, \"dlopen failed to open the libcoreclr.so with error %s\\n\", error);\n }\n\n return exitCode;\n}\nFix Stack Unwind Behavior of Libunwind-ARM\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n\/\/\n\/\/ Code that is used by both the Unix corerun and coreconsole.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"coreruncommon.h\"\n#include \n\n#define SUCCEEDED(Status) ((Status) >= 0)\n\n\/\/ Name of the environment variable controlling server GC.\n\/\/ If set to 1, server GC is enabled on startup. If 0, server GC is\n\/\/ disabled. Server GC is off by default.\nstatic const char* serverGcVar = \"CORECLR_SERVER_GC\";\n\n\/\/ Name of the environment variable controlling concurrent GC,\n\/\/ used in the same way as serverGcVar. Concurrent GC is on by default.\nstatic const char* concurrentGcVar = \"CORECLR_CONCURRENT_GC\";\n\n\/\/ Prototype of the coreclr_initialize function from the libcoreclr.so\ntypedef int (*InitializeCoreCLRFunction)(\n const char* exePath,\n const char* appDomainFriendlyName,\n int propertyCount,\n const char** propertyKeys,\n const char** propertyValues,\n void** hostHandle,\n unsigned int* domainId);\n\n\/\/ Prototype of the coreclr_shutdown function from the libcoreclr.so\ntypedef int (*ShutdownCoreCLRFunction)(\n void* hostHandle,\n unsigned int domainId);\n\n\/\/ Prototype of the coreclr_execute_assembly function from the libcoreclr.so\ntypedef int (*ExecuteAssemblyFunction)(\n void* hostHandle,\n unsigned int domainId,\n int argc,\n const char** argv,\n const char* managedAssemblyPath,\n unsigned int* exitCode);\n\n#if defined(__LINUX__)\n#define symlinkEntrypointExecutable \"\/proc\/self\/exe\"\n#elif !defined(__APPLE__)\n#define symlinkEntrypointExecutable \"\/proc\/curproc\/exe\"\n#endif\n\nbool GetEntrypointExecutableAbsolutePath(std::string& entrypointExecutable)\n{\n bool result = false;\n \n entrypointExecutable.clear();\n\n \/\/ Get path to the executable for the current process using\n \/\/ platform specific means.\n#if defined(__LINUX__)\n \/\/ On Linux, fetch the entry point EXE absolute path, inclusive of filename.\n char exe[PATH_MAX];\n ssize_t res = readlink(symlinkEntrypointExecutable, exe, PATH_MAX - 1);\n if (res != -1)\n {\n exe[res] = '\\0';\n entrypointExecutable.assign(exe);\n result = true;\n }\n else\n {\n result = false;\n }\n#elif defined(__APPLE__)\n \n \/\/ On Mac, we ask the OS for the absolute path to the entrypoint executable\n uint32_t lenActualPath = 0;\n if (_NSGetExecutablePath(nullptr, &lenActualPath) == -1)\n {\n \/\/ OSX has placed the actual path length in lenActualPath,\n \/\/ so re-attempt the operation\n std::string resizedPath(lenActualPath, '\\0');\n char *pResizedPath = const_cast(resizedPath.c_str());\n if (_NSGetExecutablePath(pResizedPath, &lenActualPath) == 0)\n {\n entrypointExecutable.assign(pResizedPath);\n result = true;\n }\n }\n#else\n \/\/ On non-Mac OS, return the symlink that will be resolved by GetAbsolutePath\n \/\/ to fetch the entrypoint EXE absolute path, inclusive of filename.\n entrypointExecutable.assign(symlinkEntrypointExecutable);\n result = true;\n#endif \n\n return result;\n}\n\nbool GetAbsolutePath(const char* path, std::string& absolutePath)\n{\n bool result = false;\n\n char realPath[PATH_MAX];\n if (realpath(path, realPath) != nullptr && realPath[0] != '\\0')\n {\n absolutePath.assign(realPath);\n \/\/ realpath should return canonicalized path without the trailing slash\n assert(absolutePath.back() != '\/');\n\n result = true;\n }\n\n return result;\n}\n\nbool GetDirectory(const char* absolutePath, std::string& directory)\n{\n directory.assign(absolutePath);\n size_t lastSlash = directory.rfind('\/');\n if (lastSlash != std::string::npos)\n {\n directory.erase(lastSlash);\n return true;\n }\n\n return false;\n}\n\nbool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)\n{\n std::string clrFilesRelativePath;\n const char* clrFilesPathLocal = clrFilesPath;\n if (clrFilesPathLocal == nullptr)\n {\n \/\/ There was no CLR files path specified, use the folder of the corerun\/coreconsole\n if (!GetDirectory(currentExePath, clrFilesRelativePath))\n {\n perror(\"Failed to get directory from argv[0]\");\n return false;\n }\n\n clrFilesPathLocal = clrFilesRelativePath.c_str();\n\n \/\/ TODO: consider using an env variable (if defined) as a fall-back.\n \/\/ The windows version of the corerun uses core_root env variable\n }\n\n if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))\n {\n perror(\"Failed to convert CLR files path to absolute path\");\n return false;\n }\n\n return true;\n}\n\nvoid AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)\n{\n const char * const tpaExtensions[] = {\n \".ni.dll\", \/\/ Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir\n \".dll\",\n \".ni.exe\",\n \".exe\",\n };\n \n DIR* dir = opendir(directory);\n if (dir == nullptr)\n {\n return;\n }\n\n std::set addedAssemblies;\n\n \/\/ Walk the directory for each extension separately so that we first get files with .ni.dll extension,\n \/\/ then files with .dll extension, etc.\n for (int extIndex = 0; extIndex < sizeof(tpaExtensions) \/ sizeof(tpaExtensions[0]); extIndex++)\n {\n const char* ext = tpaExtensions[extIndex];\n int extLength = strlen(ext);\n\n struct dirent* entry;\n\n \/\/ For all entries in the directory\n while ((entry = readdir(dir)) != nullptr)\n {\n \/\/ We are interested in files only\n switch (entry->d_type)\n {\n case DT_REG:\n break;\n\n \/\/ Handle symlinks and file systems that do not support d_type\n case DT_LNK:\n case DT_UNKNOWN:\n {\n std::string fullFilename;\n\n fullFilename.append(directory);\n fullFilename.append(\"\/\");\n fullFilename.append(entry->d_name);\n\n struct stat sb;\n if (stat(fullFilename.c_str(), &sb) == -1)\n {\n continue;\n }\n\n if (!S_ISREG(sb.st_mode))\n {\n continue;\n }\n }\n break;\n\n default:\n continue;\n }\n\n std::string filename(entry->d_name);\n\n \/\/ Check if the extension matches the one we are looking for\n int extPos = filename.length() - extLength;\n if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))\n {\n continue;\n }\n\n std::string filenameWithoutExt(filename.substr(0, extPos));\n\n \/\/ Make sure if we have an assembly with multiple extensions present,\n \/\/ we insert only one version of it.\n if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())\n {\n addedAssemblies.insert(filenameWithoutExt);\n\n tpaList.append(directory);\n tpaList.append(\"\/\");\n tpaList.append(filename);\n tpaList.append(\":\");\n }\n }\n \n \/\/ Rewind the directory stream to be able to iterate over it for the next extension\n rewinddir(dir);\n }\n \n closedir(dir);\n}\n\nint ExecuteManagedAssembly(\n const char* currentExeAbsolutePath,\n const char* clrFilesAbsolutePath,\n const char* managedAssemblyAbsolutePath,\n int managedAssemblyArgc,\n const char** managedAssemblyArgv)\n{\n \/\/ Indicates failure\n int exitCode = -1;\n\n#ifdef _ARM_\n \/\/ LIBUNWIND-ARM has a bug of side effect with DWARF mode\n \/\/ Ref: https:\/\/github.com\/dotnet\/coreclr\/issues\/3462\n \/\/ This is why Fedora is disabling it by default as well.\n \/\/ Assuming that we cannot enforce the user to set\n \/\/ environmental variables for third party packages,\n \/\/ we set the environmental variable of libunwind locally here.\n\n \/\/ Without this, any exception handling will fail, so let's do this\n \/\/ as early as possible.\n \/\/ 0x1: DWARF \/ 0x2: FRAME \/ 0x4: EXIDX\n putenv(\"UNW_ARM_UNWIND_METHOD=6\");\n#endif \/\/ _ARM_\n\n std::string coreClrDllPath(clrFilesAbsolutePath);\n coreClrDllPath.append(\"\/\");\n coreClrDllPath.append(coreClrDll);\n\n if (coreClrDllPath.length() >= PATH_MAX)\n {\n fprintf(stderr, \"Absolute path to libcoreclr.so too long\\n\");\n return -1;\n }\n\n \/\/ Get just the path component of the managed assembly path\n std::string appPath;\n GetDirectory(managedAssemblyAbsolutePath, appPath);\n\n std::string nativeDllSearchDirs(appPath);\n nativeDllSearchDirs.append(\":\");\n nativeDllSearchDirs.append(clrFilesAbsolutePath);\n\n std::string tpaList;\n AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);\n\n void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);\n if (coreclrLib != nullptr)\n {\n InitializeCoreCLRFunction initializeCoreCLR = (InitializeCoreCLRFunction)dlsym(coreclrLib, \"coreclr_initialize\");\n ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, \"coreclr_execute_assembly\");\n ShutdownCoreCLRFunction shutdownCoreCLR = (ShutdownCoreCLRFunction)dlsym(coreclrLib, \"coreclr_shutdown\");\n\n if (initializeCoreCLR == nullptr)\n {\n fprintf(stderr, \"Function coreclr_initialize not found in the libcoreclr.so\\n\");\n }\n else if (executeAssembly == nullptr)\n {\n fprintf(stderr, \"Function coreclr_execute_assembly not found in the libcoreclr.so\\n\");\n }\n else if (shutdownCoreCLR == nullptr)\n {\n fprintf(stderr, \"Function coreclr_shutdown not found in the libcoreclr.so\\n\");\n }\n else\n {\n \/\/ check if we are enabling server GC or concurrent GC.\n \/\/ Server GC is off by default, while concurrent GC is on by default.\n \/\/ Actual checking of these string values is done in coreclr_initialize.\n const char* useServerGc = std::getenv(serverGcVar);\n if (useServerGc == nullptr)\n {\n useServerGc = \"0\";\n }\n \n const char* useConcurrentGc = std::getenv(concurrentGcVar);\n if (useConcurrentGc == nullptr)\n {\n useConcurrentGc = \"1\";\n }\n \n \/\/ Allowed property names:\n \/\/ APPBASE\n \/\/ - The base path of the application from which the exe and other assemblies will be loaded\n \/\/\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n \/\/ - The list of complete paths to each of the fully trusted assemblies\n \/\/\n \/\/ APP_PATHS\n \/\/ - The list of paths which will be probed by the assembly loader\n \/\/\n \/\/ APP_NI_PATHS\n \/\/ - The list of additional paths that the assembly loader will probe for ngen images\n \/\/\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n \/\/ - The list of paths that will be probed for native DLLs called by PInvoke\n \/\/\n const char *propertyKeys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\",\n \"AppDomainCompatSwitch\",\n \"SERVER_GC\",\n \"CONCURRENT_GC\"\n };\n const char *propertyValues[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpaList.c_str(),\n \/\/ APP_PATHS\n appPath.c_str(),\n \/\/ APP_NI_PATHS\n appPath.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n nativeDllSearchDirs.c_str(),\n \/\/ AppDomainCompatSwitch\n \"UseLatestBehaviorWhenTFMNotSpecified\",\n \/\/ SERVER_GC\n useServerGc,\n \/\/ CONCURRENT_GC\n useConcurrentGc\n };\n\n void* hostHandle;\n unsigned int domainId;\n\n int st = initializeCoreCLR(\n currentExeAbsolutePath, \n \"unixcorerun\", \n sizeof(propertyKeys) \/ sizeof(propertyKeys[0]), \n propertyKeys, \n propertyValues, \n &hostHandle, \n &domainId);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"coreclr_initialize failed - status: 0x%08x\\n\", st);\n exitCode = -1;\n }\n else \n {\n st = executeAssembly(\n hostHandle,\n domainId,\n managedAssemblyArgc,\n managedAssemblyArgv,\n managedAssemblyAbsolutePath,\n (unsigned int*)&exitCode);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"coreclr_execute_assembly failed - status: 0x%08x\\n\", st);\n exitCode = -1;\n }\n\n st = shutdownCoreCLR(hostHandle, domainId);\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"coreclr_shutdown failed - status: 0x%08x\\n\", st);\n exitCode = -1;\n }\n }\n }\n\n if (dlclose(coreclrLib) != 0)\n {\n fprintf(stderr, \"Warning - dlclose failed\\n\");\n }\n }\n else\n {\n char* error = dlerror();\n fprintf(stderr, \"dlopen failed to open the libcoreclr.so with error %s\\n\", error);\n }\n\n return exitCode;\n}\n<|endoftext|>"} {"text":"#include \"Mesh.h\"\n#include \"Director.h\"\n\/\/#include \"TransformPipelineParam.h\"\n\nnamespace Rendering\n{\n\tusing namespace Manager;\n\tnamespace Mesh\n\t{\n\t\tMesh::Mesh() : \n\t\t\t_filter(nullptr), _renderer(nullptr), \n\t\t\t_selectMaterialIndex(0), _transformConstBuffer(nullptr)\n\t\t{\n\t\t\t_updateType = MaterialUpdateType::All;\n\t\t}\n\n\t\tMesh::~Mesh()\n\t\t{\n\t\t\tOnDestroy();\n\t\t}\n\n\t\tbool Mesh::Initialize(const CreateFuncArguments& args)\n\t\t{\n\t\t\t_filter = new MeshFilter;\n\t\t\tif(_filter->CreateBuffer(args) == false)\n\t\t\t{\n\t\t\t\tASSERT_MSG(\"Error, filter->cratebuffer\");\n\t\t\t\tSAFE_DELETE(_filter);\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t_renderer = new MeshRenderer;\n\t\t\tif(_renderer->AddMaterial(args.material) == false)\n\t\t\t{\n\t\t\t\tASSERT_MSG(\"Error, renderer addmaterial\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t_transformConstBuffer = new Buffer::ConstBuffer;\n\t\t\tif(_transformConstBuffer->Initialize(sizeof(Core::TransformPipelineShaderInput)) == false)\n\t\t\t{\n\t\t\t\tASSERT_MSG(\"Error, transformBuffer->Initialize\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tClassifyRenderMeshType();\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid Mesh::OnInitialize()\n\t\t{\n\t\t}\n\n\t\tvoid Mesh::OnUpdate(float deltaTime)\n\t\t{\n\t\t}\n\n\t\tvoid Mesh::OnUpdateTransformCB(const Core::TransformPipelineShaderInput& transpose_Transform)\n\t\t{\n\t\t\t\/\/Ʈ δ, Object Ǵ\n\t\t\tID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();\n\t\t\t_transformConstBuffer->UpdateSubResource(context, &transpose_Transform);\n\t\t}\n\n\t\tvoid Mesh::OnDestroy()\n\t\t{\n\t\t\tSAFE_DELETE(_filter);\n\t\t\tSAFE_DELETE(_renderer);\n\t\t\tSAFE_DELETE(_transformConstBuffer);\n\t\t}\n\n\t\tvoid Mesh::ClassifyRenderMeshType()\n\t\t{\n\t\t\tManager::RenderManager* renderMgr = Device::Director::GetInstance()->GetCurrentScene()->GetRenderManager();\n\t\t\tif(_renderer)\n\t\t\t{\n\t\t\t\tbool isTransparentMesh = _renderer->IsTransparent();\n\t\t\t\tRenderManager::MeshType type = isTransparentMesh ? \n\t\t\t\t\tRenderManager::MeshType::Transparent : RenderManager::MeshType::Opaque;\n\n\t\t\t\trenderMgr->UpdateRenderList(this, type);\n\t\t\t}\n\t\t}\n\n\t\tvoid Mesh::OnRenderPreview()\n\t\t{\n\t\t\tClassifyRenderMeshType();\n\t\t}\n\n\t\tCore::Component* Mesh::Clone() const\n\t\t{\n\t\t\tMesh* newMesh = new Mesh;\n\t\t\t{\n\t\t\t\tnewMesh->_filter = new MeshFilter(*_filter);\n\t\t\t\tnewMesh->_renderer = new MeshRenderer(*_renderer);\n\t\t\t\tnewMesh->_transformConstBuffer = new Buffer::ConstBuffer;\n\t\t\t\tnewMesh->_transformConstBuffer->Initialize(sizeof(Core::TransformPipelineShaderInput));\n\t\t\t\tnewMesh->ClassifyRenderMeshType();\n\n\t\t\t\tnewMesh->_owner = _owner;\n\t\t\t}\n\n\t\t\treturn newMesh;\n\t\t}\n\t}\n}Mesh - 코드 정리 #64#include \"Mesh.h\"\n#include \"Director.h\"\n\/\/#include \"TransformPipelineParam.h\"\n\nusing namespace Rendering::Manager;\nusing namespace Rendering::Mesh;\n\nMesh::Mesh() : \n\t_filter(nullptr), _renderer(nullptr), \n\t_selectMaterialIndex(0), _transformConstBuffer(nullptr)\n{\n\t_updateType = MaterialUpdateType::All;\n}\n\nMesh::~Mesh()\n{\n\tOnDestroy();\n}\n\nbool Mesh::Initialize(const CreateFuncArguments& args)\n{\n\t_filter = new MeshFilter;\n\tif(_filter->CreateBuffer(args) == false)\n\t{\n\t\tASSERT_MSG(\"Error, filter->cratebuffer\");\n\t\tSAFE_DELETE(_filter);\n\t\treturn false;\n\t}\n\n\t_renderer = new MeshRenderer;\n\tif(_renderer->AddMaterial(args.material) == false)\n\t{\n\t\tASSERT_MSG(\"Error, renderer addmaterial\");\n\t\treturn false;\n\t}\n\n\t_transformConstBuffer = new Buffer::ConstBuffer;\n\tif(_transformConstBuffer->Initialize(sizeof(Core::TransformPipelineShaderInput)) == false)\n\t{\n\t\tASSERT_MSG(\"Error, transformBuffer->Initialize\");\n\t\treturn false;\n\t}\n\n\tClassifyRenderMeshType();\n\treturn true;\n}\n\nvoid Mesh::OnInitialize()\n{\n}\n\nvoid Mesh::OnUpdate(float deltaTime)\n{\n}\n\nvoid Mesh::OnUpdateTransformCB(const Core::TransformPipelineShaderInput& transpose_Transform)\n{\n\t\/\/Ʈ δ, Object Ǵ\n\tID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();\n\t_transformConstBuffer->UpdateSubResource(context, &transpose_Transform);\n}\n\nvoid Mesh::OnDestroy()\n{\n\tSAFE_DELETE(_filter);\n\tSAFE_DELETE(_renderer);\n\tSAFE_DELETE(_transformConstBuffer);\n}\n\nvoid Mesh::ClassifyRenderMeshType()\n{\n\tManager::RenderManager* renderMgr = Device::Director::GetInstance()->GetCurrentScene()->GetRenderManager();\n\tif(_renderer)\n\t{\n\t\tbool isTransparentMesh = _renderer->IsTransparent();\n\t\tRenderManager::MeshType type = isTransparentMesh ? \n\t\t\tRenderManager::MeshType::Transparent : RenderManager::MeshType::Opaque;\n\n\t\trenderMgr->UpdateRenderList(this, type);\n\t}\n}\n\nvoid Mesh::OnRenderPreview()\n{\n\tClassifyRenderMeshType();\n}\n\nCore::Component* Mesh::Clone() const\n{\n\tMesh* newMesh = new Mesh;\n\t{\n\t\tnewMesh->_filter = new MeshFilter(*_filter);\n\t\tnewMesh->_renderer = new MeshRenderer(*_renderer);\n\t\tnewMesh->_transformConstBuffer = new Buffer::ConstBuffer;\n\t\tnewMesh->_transformConstBuffer->Initialize(sizeof(Core::TransformPipelineShaderInput));\n\t\tnewMesh->ClassifyRenderMeshType();\n\n\t\tnewMesh->_owner = _owner;\n\t}\n\n\treturn newMesh;\n}\n<|endoftext|>"} {"text":"#include \"Light.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\n\nvoid TurnOn(int pin){\n\tint Value=0;\n\twhile(Value<100){\n\t\tValue+=1;\n\t\tsoftPwmWrite(pin,Value);\n\t\tthis_thread::sleep_for(chrono::milliseconds(20));\n\t}\n\treturn;\n}\n\nvoid TurnOff(int pin){\n\tint Value=100;\n\twhile(Value>0){\n\t\tValue-=1;\n\t\tsoftPwmWrite(pin,Value);\n\t\tthis_thread::sleep_for(chrono::milliseconds(20));\n\t}\n\treturn;\n}\n\n\n\nLight::Light(int pin):Pin(pin){\n\n\tsoftPwmCreate(pin,0,100);\n\n}\n\nbool Light::Check(){\n\tif((time(0) > Timer)&&(Active)){\n\t\tActive=false;\n\t\tthread turnoff(TurnOff, Pin);\n\t\tturnoff.detach();\n\t\treturn 0;\n\t}\n\telse if(Active)\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\nvoid Light::Set_Light(bool x){\n\tif((x) && (!Active)){\n\t\tTimer = time(0) + TimeOut;\n\t\tActive=true;\n\t\tthread turnon(TurnOn, Pin);\n\t\tturnon.detach();\n\t}\n\telse if(!x)\n\t\tTimer=time(0)+3; \/\/3 seconds till lights turn off\n}Update Light.cpp#include \"Light.h\"\n#include \n#include \n#include \n#include \n#include \n\n\/* Program runs on the principle of a dead-timer\n Once the dead timer is reached, the lights turn off\n Once motion is detected, the timers will update itself. \n*\/ \n\nusing namespace std;\n\n\n\nvoid TurnOn(int pin){\t\/\/ Turn on Light on pin\n\tint Value=0;\n\twhile(Value<100){ \/\/ Fade in lights with a 100 x 20ms loop. Meaning over 2 seconds the light will fade in\n\t\tValue+=1;\n\t\tsoftPwmWrite(pin,Value); \/\/ PWM write to slowly increase brightness\n\t\tthis_thread::sleep_for(chrono::milliseconds(20)); \/\/ time-delay (20ms)\n\t}\n\treturn;\n}\n\nvoid TurnOff(int pin) { \/\/ Turn off Light on pin\n\tint Value=100;\n\twhile(Value>0){ \/\/ Fade out lights with a 100 x 20ms loop. Meaning the light will fade out over the span of 2 seconds\n\t\tValue-=1;\n\t\tsoftPwmWrite(pin,Value); \/\/ PWM write to slowly decrease brightness\n\t\tthis_thread::sleep_for(chrono::milliseconds(20)); \/\/ time-delay (20ms)\n\t}\n\treturn;\n}\n\n\n\nLight::Light(int pin):Pin(pin){\n\tsoftPwmCreate(pin,0,100); \/\/ Create a PWM instance for pin with a value between 0 and 100\n}\n\nbool Light::Check(){\n\tif((time(0) > Timer)&&(Active)){ \/\/ if the current time is less than the Timer (for expiry)\n\t\tActive=false; \/\/(meaning the dead-timer for the light has expired) and the Light is still active.\n\t\tthread turnoff(TurnOff, Pin); \/\/ Turn off the lights. \n\t\tturnoff.detach();\n\t\treturn 0; \/\/ Return 0 because the timer expired.\n\t}\n\telse if(Active) {\n\t\treturn 1; \/\/ If light is still active (and on), return a 1\n\t}\n\telse\n\t\treturn 0; \/\/ If the light is out, return 0\n}\n\nvoid Light::Set_Light(bool x) { \n\tif((x) && (!Active)) { \/\/ If x is true and the lights are off. Turn on the lights\n\t\tTimer = time(0) + TimeOut; \/\/ current time + the time after which the lights will turn off sets the dead-time\n\t\tActive=true;\n\t\tthread turnon(TurnOn, Pin);\n\t\tturnon.detach();\n\t}\n\telse if((x) && (Active)) { \/\/ If x is true and the lights are on. Update the dead-timer (if lights are on, no need to turn them on)\n\t\tTimer = time(0) + TimeOut; \/\/ current time + the time after which the lights will turn off sets the dead-time\n\t}\n\telse if(!x)\n\t\tTimer=time(0)+3; \/\/ 3 seconds till lights turn off\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts, clang::LangAS::Map& address_spaces) {\n\n clang::CompilerInstance c;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw error(CL_INVALID_BUILD_OPTIONS);\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n c.getPreprocessorOpts().addMacroDef(\"cl_khr_fp64\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Setting this attribute tells clang to link this file before\n \/\/ performing any optimizations. This is required so that\n \/\/ we can replace calls to the OpenCL C barrier() builtin\n \/\/ with calls to target intrinsics that have the noduplicate\n \/\/ attribute. This attribute will prevent Clang from creating\n \/\/ illegal uses of barrier() (e.g. Moving barrier() inside a conditional\n \/\/ that is no executed by all threads) during its optimizaton passes.\n c.getCodeGenOpts().LinkBitcodeFile = libclc_path;\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n \/\/ Get address spaces map to be able to find kernel argument address space\n memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), \n sizeof(address_spaces));\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n \/\/ This means there are no kernels in the program. The spec does not\n \/\/ require that we return an error here, but there will be an error if\n \/\/ the user tries to pass this program to a clCreateKernel() call.\n if (!kernel_node) {\n return;\n }\n\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n internalize_functions(llvm::Module *mod,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels,\n clang::LangAS::Map& address_spaces) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#elif HAVE_LLVM < 0x0304\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#else\n llvm::DataLayout TD(mod);\n#endif\n\n llvm::Type *arg_type = arg.getType();\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n llvm::Type *target_type = arg_type->isIntegerTy() ?\n TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) :\n arg_type;\n unsigned target_size = TD.getTypeStoreSize(target_type);\n unsigned target_align = TD.getABITypeAlignment(target_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n if (address_space == address_spaces[clang::LangAS::opencl_local\n - clang::LangAS::Offset]) {\n args.push_back(module::argument(module::argument::local,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n } else {\n \/\/ XXX: Correctly handle constant address space. There is no\n \/\/ way for r600g to pass a handle for constant buffers back\n \/\/ to clover like it can for global buffers, so\n \/\/ creating constant arguements will break r600g. For now,\n \/\/ continue treating constant buffers as global buffers\n \/\/ until we can come up with a way to create handles for\n \/\/ constant buffers.\n args.push_back(module::argument(module::argument::global,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n }\n\n } else {\n llvm::AttributeSet attrs = kernel_func->getAttributes();\n enum module::argument::ext_type ext_type =\n (attrs.hasAttribute(arg.getArgNo() + 1,\n llvm::Attribute::SExt) ?\n module::argument::sign_ext :\n module::argument::zero_ext);\n\n args.push_back(\n module::argument(module::argument::scalar, arg_size,\n target_size, target_align, ext_type));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n clang::LangAS::Map address_spaces;\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts,\n address_spaces);\n\n find_kernels(mod, kernels);\n\n internalize_functions(mod, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels, address_spaces);\n }\n}\nRevert \"Merge branch 'master' of git+ssh:\/\/git.freedesktop.org\/git\/mesa\/mesa\"\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts, clang::LangAS::Map& address_spaces) {\n\n clang::CompilerInstance c;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw error(CL_INVALID_BUILD_OPTIONS);\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n c.getPreprocessorOpts().addMacroDef(\"cl_khr_fp64\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Setting this attribute tells clang to link this file before\n \/\/ performing any optimizations. This is required so that\n \/\/ we can replace calls to the OpenCL C barrier() builtin\n \/\/ with calls to target intrinsics that have the noduplicate\n \/\/ attribute. This attribute will prevent Clang from creating\n \/\/ illegal uses of barrier() (e.g. Moving barrier() inside a conditional\n \/\/ that is no executed by all threads) during its optimizaton passes.\n c.getCodeGenOpts().LinkBitcodeFile = libclc_path;\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n \/\/ Get address spaces map to be able to find kernel argument address space\n memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), \n sizeof(address_spaces));\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n \/\/ This means there are no kernels in the program. The spec does not\n \/\/ require that we return an error here, but there will be an error if\n \/\/ the user tries to pass this program to a clCreateKernel() call.\n if (!kernel_node) {\n return;\n }\n\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n internalize_functions(llvm::Module *mod,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels,\n clang::LangAS::Map& address_spaces) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#else\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#endif\n\n llvm::Type *arg_type = arg.getType();\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n llvm::Type *target_type = arg_type->isIntegerTy() ?\n TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) :\n arg_type;\n unsigned target_size = TD.getTypeStoreSize(target_type);\n unsigned target_align = TD.getABITypeAlignment(target_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n if (address_space == address_spaces[clang::LangAS::opencl_local\n - clang::LangAS::Offset]) {\n args.push_back(module::argument(module::argument::local,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n } else {\n \/\/ XXX: Correctly handle constant address space. There is no\n \/\/ way for r600g to pass a handle for constant buffers back\n \/\/ to clover like it can for global buffers, so\n \/\/ creating constant arguements will break r600g. For now,\n \/\/ continue treating constant buffers as global buffers\n \/\/ until we can come up with a way to create handles for\n \/\/ constant buffers.\n args.push_back(module::argument(module::argument::global,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n }\n\n } else {\n llvm::AttributeSet attrs = kernel_func->getAttributes();\n enum module::argument::ext_type ext_type =\n (attrs.hasAttribute(arg.getArgNo() + 1,\n llvm::Attribute::SExt) ?\n module::argument::sign_ext :\n module::argument::zero_ext);\n\n args.push_back(\n module::argument(module::argument::scalar, arg_size,\n target_size, target_align, ext_type));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n clang::LangAS::Map address_spaces;\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts,\n address_spaces);\n\n find_kernels(mod, kernels);\n\n internalize_functions(mod, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels, address_spaces);\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts, clang::LangAS::Map& address_spaces) {\n\n clang::CompilerInstance c;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw error(CL_INVALID_BUILD_OPTIONS);\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n c.getPreprocessorOpts().addMacroDef(\"cl_khr_fp64\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Setting this attribute tells clang to link this file before\n \/\/ performing any optimizations. This is required so that\n \/\/ we can replace calls to the OpenCL C barrier() builtin\n \/\/ with calls to target intrinsics that have the noduplicate\n \/\/ attribute. This attribute will prevent Clang from creating\n \/\/ illegal uses of barrier() (e.g. Moving barrier() inside a conditional\n \/\/ that is no executed by all threads) during its optimizaton passes.\n c.getCodeGenOpts().LinkBitcodeFile = libclc_path;\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n \/\/ Get address spaces map to be able to find kernel argument address space\n memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), \n sizeof(address_spaces));\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n \/\/ This means there are no kernels in the program. The spec does not\n \/\/ require that we return an error here, but there will be an error if\n \/\/ the user tries to pass this program to a clCreateKernel() call.\n if (!kernel_node) {\n return;\n }\n\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n internalize_functions(llvm::Module *mod,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels,\n clang::LangAS::Map& address_spaces) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#else\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#endif\n\n llvm::Type *arg_type = arg.getType();\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n llvm::Type *target_type = arg_type->isIntegerTy() ?\n TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) :\n arg_type;\n unsigned target_size = TD.getTypeStoreSize(target_type);\n unsigned target_align = TD.getABITypeAlignment(target_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n if (address_space == address_spaces[clang::LangAS::opencl_local\n - clang::LangAS::Offset]) {\n args.push_back(module::argument(module::argument::local,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n } else {\n \/\/ XXX: Correctly handle constant address space. There is no\n \/\/ way for r600g to pass a handle for constant buffers back\n \/\/ to clover like it can for global buffers, so\n \/\/ creating constant arguements will break r600g. For now,\n \/\/ continue treating constant buffers as global buffers\n \/\/ until we can come up with a way to create handles for\n \/\/ constant buffers.\n args.push_back(module::argument(module::argument::global,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n }\n\n } else {\n llvm::AttributeSet attrs = kernel_func->getAttributes();\n enum module::argument::ext_type ext_type =\n (attrs.hasAttribute(arg.getArgNo() + 1,\n llvm::Attribute::SExt) ?\n module::argument::sign_ext :\n module::argument::zero_ext);\n\n args.push_back(\n module::argument(module::argument::scalar, arg_size,\n target_size, target_align, ext_type));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n clang::LangAS::Map address_spaces;\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts,\n address_spaces);\n\n find_kernels(mod, kernels);\n\n internalize_functions(mod, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels, address_spaces);\n }\n}\nRe-commit 'clover: Fix build with LLVM 3.5'\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts, clang::LangAS::Map& address_spaces) {\n\n clang::CompilerInstance c;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw error(CL_INVALID_BUILD_OPTIONS);\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n c.getPreprocessorOpts().addMacroDef(\"cl_khr_fp64\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Setting this attribute tells clang to link this file before\n \/\/ performing any optimizations. This is required so that\n \/\/ we can replace calls to the OpenCL C barrier() builtin\n \/\/ with calls to target intrinsics that have the noduplicate\n \/\/ attribute. This attribute will prevent Clang from creating\n \/\/ illegal uses of barrier() (e.g. Moving barrier() inside a conditional\n \/\/ that is no executed by all threads) during its optimizaton passes.\n c.getCodeGenOpts().LinkBitcodeFile = libclc_path;\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n \/\/ Get address spaces map to be able to find kernel argument address space\n memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), \n sizeof(address_spaces));\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n \/\/ This means there are no kernels in the program. The spec does not\n \/\/ require that we return an error here, but there will be an error if\n \/\/ the user tries to pass this program to a clCreateKernel() call.\n if (!kernel_node) {\n return;\n }\n\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n internalize_functions(llvm::Module *mod,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels,\n clang::LangAS::Map& address_spaces) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#elif HAVE_LLVM < 0x0304\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#else\n llvm::DataLayout TD(mod);\n#endif\n\n llvm::Type *arg_type = arg.getType();\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n llvm::Type *target_type = arg_type->isIntegerTy() ?\n TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) :\n arg_type;\n unsigned target_size = TD.getTypeStoreSize(target_type);\n unsigned target_align = TD.getABITypeAlignment(target_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n if (address_space == address_spaces[clang::LangAS::opencl_local\n - clang::LangAS::Offset]) {\n args.push_back(module::argument(module::argument::local,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n } else {\n \/\/ XXX: Correctly handle constant address space. There is no\n \/\/ way for r600g to pass a handle for constant buffers back\n \/\/ to clover like it can for global buffers, so\n \/\/ creating constant arguements will break r600g. For now,\n \/\/ continue treating constant buffers as global buffers\n \/\/ until we can come up with a way to create handles for\n \/\/ constant buffers.\n args.push_back(module::argument(module::argument::global,\n arg_size, target_size,\n target_align,\n module::argument::zero_ext));\n }\n\n } else {\n llvm::AttributeSet attrs = kernel_func->getAttributes();\n enum module::argument::ext_type ext_type =\n (attrs.hasAttribute(arg.getArgNo() + 1,\n llvm::Attribute::SExt) ?\n module::argument::sign_ext :\n module::argument::zero_ext);\n\n args.push_back(\n module::argument(module::argument::scalar, arg_size,\n target_size, target_align, ext_type));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n clang::LangAS::Map address_spaces;\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts,\n address_spaces);\n\n find_kernels(mod, kernels);\n\n internalize_functions(mod, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels, address_spaces);\n }\n}\n<|endoftext|>"} {"text":"\/\/ #include guards\n#ifndef ICEFIELD_H\n#define ICEFIELD_H\n\n\/\/ Used for overloading << operator with an ostream\n#include \n\n\/* A class representing an ice rink that, like in Pac-Man and\n * Final Fantasy, has wraparound geography and finite dimensions.\n *\/\nclass IceField {\npublic:\n \n \/* Creates a new IceField object\n * PARAMS\n **** rows: number of rows on the IceField\n **** cols: number of columns on the IceField\n **** startRow: initial row number of the zamboni, zero-indexed\n **** startCol: initial column number of the zamboni, zero-indexed\n **** numMoves: number of time the zamboni moves and changes color\n * RETURN\n **** IceField object created with the given parameters\n *\/\n IceField(int rows, int cols, int startRow, int startCol, int numMoves);\n \n \/* Safely destroys the IceField object.\n *\/\n ~IceField();\n \n \/* Cleans the ice according to the Pac-Man algorithm:\n * stepSize := 1\n * loop numMoves times\n * Move stepSize steps in the current direction\n * Rotate the direction of the zamboni 90 degrees clockwise\n * Switch to the next color\n * stepSize := stepSize + 1\n * end loop\n * The zamboni starts by facing up.\n *\/\n clean();\n \n \/* Outputs a visual representation of the ice field, with\n * the letters A-Z representing the different colors, the\n * character '.' representing white ice, and the character\n * '@' representing the current location of the Zamboni. \n *\/\n friend std::ostream& operator<<(std::ostream& o, const IceField ice);\n \nprivate:\n \n \/* The number of colors the zamboni can paint. Since each\n * letter of the alphabet represents a different color,\n * there are 26 possible colors.\n *\/\n static const int NUMBER_OF_COLORS = 26;\n \n \/* The character that represents the first color the zamboni\n * will paint. This is used to the field currentColor into\n * a character, since the expressions ZERO_COLOR + 0,\n * ZERO_COLOR + 1, and ZERO_COLOR + 2 will have the values\n * 'A', 'B', and 'C', respectively, and so on.\n *\/\n static const char ZERO_COLOR = 'A';\n \n \/* Constants that represent the four directions in which the\n * zamboni can move.\n *\/\n static const int NORTH = 0;\n static const int EAST = 1;\n static const int SOUTH = 2;\n static const int WEST = 3;\n \n \/* Number of rows in the ice field.\n *\/\n int rows;\n \n \/* Number of columns in the ice field\n *\/\n int cols;\n \n \/* Initial row number of the zamboni, zero-indexed\n *\/\n int startRow;\n \n \/* Initial column number of the zamboni, zero-indexed\n *\/\n int startCol;\n \n \/* Number of times the zamboni moves and changes color.\n *\/\n int numMoves;\n \n \/* Distance the zamboni should move in the next direction.\n *\/\n int stepSize;\n \n \/* A 2D array that contains the colors of every square on the\n * ice field, with '.' representing white, A-Z representing colors,\n * and '@' representing the current location of the zamboni.\n *\/\n char** grid;\n \n \/* An integer representing the color the zamboni is painting.\n * Always meets the condition 0 <= currentColor < NUMBER_OF_COLORS.\n * To guarantee this, it should always be modded by NUMBER_OF_COLORS\n * after incrementing.\n *\/\n int currentColor = 0;\n \n \/* An integer representing the direction in which the zamboni is\n * moving. It should always have the value NORTH, EAST, SOUTH, or\n * WEST.\n *\/\n int currentDirection;\n \n \/* Moves the zamboni in its current direction, coloring every square\n * it passes over, including the square it starts from, and not\n * including the square it finishes on. If it moves across one edge,\n * it wraps around to the opposite edge.\n *\/\n void moveZamboni(int distance);\n \n \/* Turns the zamboni clockwise.\n *\/\n void turnZamboni();\n};\n\n\/\/ Closes #include guard.\n#endifFixed #include guard to match the header file name\/\/ #include guards\n#ifndef ICEFIELD_HPP\n#define ICEFIELD_HPP\n\n\/\/ Used for overloading << operator with an ostream\n#include \n\n\/* A class representing an ice rink that, like in Pac-Man and\n * Final Fantasy, has wraparound geography and finite dimensions.\n *\/\nclass IceField {\npublic:\n \n \/* Creates a new IceField object\n * PARAMS\n **** rows: number of rows on the IceField\n **** cols: number of columns on the IceField\n **** startRow: initial row number of the zamboni, zero-indexed\n **** startCol: initial column number of the zamboni, zero-indexed\n **** numMoves: number of time the zamboni moves and changes color\n * RETURN\n **** IceField object created with the given parameters\n *\/\n IceField(int rows, int cols, int startRow, int startCol, int numMoves);\n \n \/* Safely destroys the IceField object.\n *\/\n ~IceField();\n \n \/* Cleans the ice according to the Pac-Man algorithm:\n * stepSize := 1\n * loop numMoves times\n * Move stepSize steps in the current direction\n * Rotate the direction of the zamboni 90 degrees clockwise\n * Switch to the next color\n * stepSize := stepSize + 1\n * end loop\n * The zamboni starts by facing up.\n *\/\n clean();\n \n \/* Outputs a visual representation of the ice field, with\n * the letters A-Z representing the different colors, the\n * character '.' representing white ice, and the character\n * '@' representing the current location of the Zamboni. \n *\/\n friend std::ostream& operator<<(std::ostream& o, const IceField ice);\n \nprivate:\n \n \/* The number of colors the zamboni can paint. Since each\n * letter of the alphabet represents a different color,\n * there are 26 possible colors.\n *\/\n static const int NUMBER_OF_COLORS = 26;\n \n \/* The character that represents the first color the zamboni\n * will paint. This is used to the field currentColor into\n * a character, since the expressions ZERO_COLOR + 0,\n * ZERO_COLOR + 1, and ZERO_COLOR + 2 will have the values\n * 'A', 'B', and 'C', respectively, and so on.\n *\/\n static const char ZERO_COLOR = 'A';\n \n \/* Constants that represent the four directions in which the\n * zamboni can move.\n *\/\n static const int NORTH = 0;\n static const int EAST = 1;\n static const int SOUTH = 2;\n static const int WEST = 3;\n \n \/* Number of rows in the ice field.\n *\/\n int rows;\n \n \/* Number of columns in the ice field\n *\/\n int cols;\n \n \/* Initial row number of the zamboni, zero-indexed\n *\/\n int startRow;\n \n \/* Initial column number of the zamboni, zero-indexed\n *\/\n int startCol;\n \n \/* Number of times the zamboni moves and changes color.\n *\/\n int numMoves;\n \n \/* Distance the zamboni should move in the next direction.\n *\/\n int stepSize;\n \n \/* A 2D array that contains the colors of every square on the\n * ice field, with '.' representing white, A-Z representing colors,\n * and '@' representing the current location of the zamboni.\n *\/\n char** grid;\n \n \/* An integer representing the color the zamboni is painting.\n * Always meets the condition 0 <= currentColor < NUMBER_OF_COLORS.\n * To guarantee this, it should always be modded by NUMBER_OF_COLORS\n * after incrementing.\n *\/\n int currentColor = 0;\n \n \/* An integer representing the direction in which the zamboni is\n * moving. It should always have the value NORTH, EAST, SOUTH, or\n * WEST.\n *\/\n int currentDirection;\n \n \/* Moves the zamboni in its current direction, coloring every square\n * it passes over, including the square it starts from, and not\n * including the square it finishes on. If it moves across one edge,\n * it wraps around to the opposite edge.\n *\/\n void moveZamboni(int distance);\n \n \/* Turns the zamboni clockwise.\n *\/\n void turnZamboni();\n};\n\n\/\/ Closes #include guard.\n#endif<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2008-2017 the Urho3D project.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"HelloWorld.h\"\n\n#include \n\n\/\/ Expands to this example's entry-point\nURHO3D_DEFINE_APPLICATION_MAIN(HelloWorld)\n\nHelloWorld::HelloWorld(Context* context) :\n Sample(context)\n{\n}\n\nvoid HelloWorld::Start()\n{\n \/\/ Execute base class startup\n Sample::Start();\n\n \/\/ Create \"Hello World\" Text\n CreateText();\n\n \/\/ Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events\n \/\/ like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we\n \/\/ could subscribe in the constructor instead.\n SubscribeToEvents();\n\n \/\/ Set the mouse mode to use in the sample\n Sample::InitMouseMode(MM_FREE);\n}\n\nvoid HelloWorld::CreateText()\n{\n ResourceCache* cache = GetSubsystem();\n\n \/\/ Construct new Text object\n SharedPtr helloText(new Text(context_));\n\n \/\/ Set String to display\n helloText->SetText(\"Hello World from Urho3D!\");\n\n \/\/ Set font and text color\n helloText->SetFont(cache->GetResource(\"Fonts\/Anonymous Pro.ttf\"), 30);\n helloText->SetColor(Color(0.0f, 1.0f, 0.0f));\n\n \/\/ Align Text center-screen\n helloText->SetHorizontalAlignment(HA_CENTER);\n helloText->SetVerticalAlignment(VA_CENTER);\n\n \/\/ Add Text instance to the UI root element\n GetSubsystem()->GetRoot()->AddChild(helloText);\n}\n\nvoid HelloWorld::SubscribeToEvents()\n{\n \/\/ Subscribe HandleUpdate() function for processing update events\n SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HelloWorld, HandleUpdate));\n}\n\nvoid HelloWorld::HandleUpdate(StringHash eventType, VariantMap& eventData)\n{\n \/\/ Do nothing for now, could be extended to eg. animate the display\n}\nTemporarily add serialization test code.\/\/\n\/\/ Copyright (c) 2008-2017 the Urho3D project.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ TO BE REMOVED\n\n#include \"HelloWorld.h\"\n\n#include \n\n\/\/ Expands to this example's entry-point\nURHO3D_DEFINE_APPLICATION_MAIN(HelloWorld)\n\n\/\/ TO BE REMOVED\n\/\/ @{\nstatic const char* enumNames[] =\n{\n \"Enum1\",\n \"Enum2\",\n \"Enum3\"\n};\n\nenum class TestEnum\n{\n Enum1,\n Enum2,\n Enum3,\n};\n\nclass TestSerializable : public Serializable\n{\n URHO3D_OBJECT(TestSerializable, Serializable);\n\npublic:\n TestSerializable(Context* context) : Serializable(context) { }\n\n static void RegisterObject(Context* context)\n {\n context->RegisterFactory();\n URHO3D_ATTRIBUTE(\"attribute\", String, attribute_, \"attribute\", AM_DEFAULT);\n URHO3D_ATTRIBUTE_EX(\"attributeEx\", String, attributeEx_, OnAttributeExSet, \"attributeEx\", AM_DEFAULT);\n URHO3D_ENUM_ATTRIBUTE(\"enumAttribute\", enumAttribute_, enumNames, TestEnum::Enum2, AM_DEFAULT);\n URHO3D_ENUM_ATTRIBUTE_EX(\"enumAttributeEx\", enumAttributeEx_, OnEnumAttributeExSet, enumNames, TestEnum::Enum2, AM_DEFAULT);\n URHO3D_ACCESSOR_ATTRIBUTE(\"accessorAttribute\", GetAccessorAttribute, SetAccessorAttribute, String, \"accessorAttribute\", AM_DEFAULT);\n URHO3D_ENUM_ACCESSOR_ATTRIBUTE(\"enumAccessorAttribute\", GetEnumAccessorAttribute, SetEnumAccessorAttribute, TestEnum, enumNames, TestEnum::Enum3, AM_DEFAULT);\n URHO3D_MIXED_ACCESSOR_ATTRIBUTE(\"mixedAccessorAttribute\", GetMixedAccessorAttribute, SetMixedAccessorAttribute, String, \"mixedAccessorAttribute\", AM_DEFAULT);\n\n {\n String suffix = \"_temp\";\n auto getter = [=](const TestSerializable& self, Variant& value)\n {\n value = self.customAttribute_ + suffix;\n };\n auto setter = [=](TestSerializable& self, const Variant& value)\n {\n self.customAttribute_ = value.GetString() + suffix;\n };\n URHO3D_CUSTOM_ATTRIBUTE(\"customAttribute\", getter, setter, String, \"customAttribute\", AM_DEFAULT);\n }\n\n {\n auto getter = [=](const TestSerializable& self, Variant& value)\n {\n value = static_cast(self.customEnumAttribute_);\n };\n auto setter = [=](TestSerializable& self, const Variant& value)\n {\n self.customEnumAttribute_ = static_cast(value.GetInt());\n };\n URHO3D_CUSTOM_ENUM_ATTRIBUTE(\"customAttribute\", getter, setter, enumNames, TestEnum::Enum1, AM_DEFAULT);\n }\n }\n\n String attribute_;\n String attributeEx_;\n void OnAttributeExSet()\n {\n attributeEx_ = attributeEx_.ToUpper();\n }\n TestEnum enumAttribute_ = TestEnum::Enum1;\n TestEnum enumAttributeEx_ = TestEnum::Enum1;\n void OnEnumAttributeExSet()\n {\n enumAttributeEx_ = static_cast(static_cast(enumAttributeEx_) + 1);\n }\n\n String accessorAttribute_;\n const String& GetAccessorAttribute() const { return accessorAttribute_; }\n void SetAccessorAttribute(const String& value) { accessorAttribute_ = value; }\n\n TestEnum enumAccessorAttribute_ = TestEnum::Enum1;\n TestEnum GetEnumAccessorAttribute() const { return enumAccessorAttribute_; }\n void SetEnumAccessorAttribute(TestEnum value) { enumAccessorAttribute_ = value; }\n\n String mixedAccessorAttribute_;\n String GetMixedAccessorAttribute() const { return mixedAccessorAttribute_; }\n void SetMixedAccessorAttribute(const String& value) { mixedAccessorAttribute_ = value; }\n\n String customAttribute_;\n TestEnum customEnumAttribute_ = TestEnum::Enum1;\n};\n\/\/ @}\n\nHelloWorld::HelloWorld(Context* context) :\n Sample(context)\n{\n \/\/ TO BE REMOVED\n \/\/ @{\n TestSerializable::RegisterObject(context);\n auto obj = MakeShared(context_);\n obj->ResetToDefault();\n\n VectorBuffer buf;\n XMLFile xml(context_);\n obj->SaveXML(xml.CreateRoot(\"test\"));\n xml.Save(buf);\n String text;\n text.Append(reinterpret_cast(buf.GetData()), buf.GetSize());\n obj.Reset();\n \/\/ @}\n}\n\nvoid HelloWorld::Start()\n{\n \/\/ Execute base class startup\n Sample::Start();\n\n \/\/ Create \"Hello World\" Text\n CreateText();\n\n \/\/ Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events\n \/\/ like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we\n \/\/ could subscribe in the constructor instead.\n SubscribeToEvents();\n\n \/\/ Set the mouse mode to use in the sample\n Sample::InitMouseMode(MM_FREE);\n}\n\nvoid HelloWorld::CreateText()\n{\n ResourceCache* cache = GetSubsystem();\n\n \/\/ Construct new Text object\n SharedPtr helloText(new Text(context_));\n\n \/\/ Set String to display\n helloText->SetText(\"Hello World from Urho3D!\");\n\n \/\/ Set font and text color\n helloText->SetFont(cache->GetResource(\"Fonts\/Anonymous Pro.ttf\"), 30);\n helloText->SetColor(Color(0.0f, 1.0f, 0.0f));\n\n \/\/ Align Text center-screen\n helloText->SetHorizontalAlignment(HA_CENTER);\n helloText->SetVerticalAlignment(VA_CENTER);\n\n \/\/ Add Text instance to the UI root element\n GetSubsystem()->GetRoot()->AddChild(helloText);\n}\n\nvoid HelloWorld::SubscribeToEvents()\n{\n \/\/ Subscribe HandleUpdate() function for processing update events\n SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(HelloWorld, HandleUpdate));\n}\n\nvoid HelloWorld::HandleUpdate(StringHash eventType, VariantMap& eventData)\n{\n \/\/ Do nothing for now, could be extended to eg. animate the display\n}\n<|endoftext|>"} {"text":"\/\/ 837 Studios - 2016 - Michael Gaskin (teak421) -- MIT License\n\n#include \"SmoothZoomPrivatePCH.h\"\n#include \"SmoothZoom.h\"\n#include \"AC_SmoothZoom.h\"\n\nDEFINE_LOG_CATEGORY(ZoomLog);\n\nUAC_SmoothZoom::UAC_SmoothZoom()\n{\n\tPrimaryComponentTick.bCanEverTick = true;\n\t\/\/ Default Values\n\tCurrentVersion = 1.3f;\n\tMinTargetLength = 150.0f;\n\tMaxTargetLength = 1500.0f;\n\tZoomUnits = 125.0f;\n\tZoomSmoothness = 9.0f;\n}\n\nvoid UAC_SmoothZoom::BeginPlay() { \tSuper::BeginPlay(); }\n\nvoid UAC_SmoothZoom::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )\n{\n\tSuper::TickComponent(DeltaTime, TickType, ThisTickFunction);\n\n\t\/\/ Only call when need to, saves ms's \n\tif (SpringArm->TargetArmLength != DesiredArmLength)\n\t{\n\t\tSpringArm->TargetArmLength = FMath::FInterpTo(SpringArm->TargetArmLength, DesiredArmLength, DeltaTime, ZoomSmoothness);\n\t}\n}\n\n\/\/ Assigns the SpringArm component\nvoid UAC_SmoothZoom::SetSpringArmComponent(UPARAM(ref)USpringArmComponent* AssignedSpringArm)\n{\n\tDesiredArmLength = AssignedSpringArm->TargetArmLength;\n\tSpringArm = AssignedSpringArm;\n}\n\n\/\/ Sets the DesiredArmLength\nvoid UAC_SmoothZoom::SmoothCameraZoom(bool bZoomOut)\n{\n\tDesiredArmLength = bZoomOut ? SpringArm->TargetArmLength + ZoomUnits\n\t\t: SpringArm->TargetArmLength + (ZoomUnits * -1);\n\tif (DesiredArmLength > MaxTargetLength || DesiredArmLength < MinTargetLength)\n\t{\n\t\tDesiredArmLength = FMath::Min(FMath::Max(DesiredArmLength, MinTargetLength), MaxTargetLength);\n\t}\n\n\tif (bDebug) { SmoothZoomLog(); }\n}\n\nvoid UAC_SmoothZoom::SmoothZoomLog()\n{\n\tUE_LOG(ZoomLog, Log, TEXT(\"ArmLength: %f, Min: %f Max: %f, ZUnits: %f, Smoothness: %f\"),\n\t\tDesiredArmLength, MinTargetLength, MaxTargetLength, ZoomUnits, ZoomSmoothness)\n}\n\nImprovement in how checking occurs in the tick function. Will reduce calls. Thanks to dc5ala.\/\/ 837 Studios - 2016 - Michael Gaskin (teak421) -- MIT License\n\n#include \"SmoothZoomPrivatePCH.h\"\n#include \"SmoothZoom.h\"\n#include \"AC_SmoothZoom.h\"\n\nDEFINE_LOG_CATEGORY(ZoomLog);\n\nUAC_SmoothZoom::UAC_SmoothZoom()\n{\n\tPrimaryComponentTick.bCanEverTick = true;\n\t\/\/ Default Values\n\tCurrentVersion = 1.31f;\n\tMinTargetLength = 150.0f;\n\tMaxTargetLength = 1500.0f;\n\tZoomUnits = 125.0f;\n\tZoomSmoothness = 9.0f;\n}\n\nvoid UAC_SmoothZoom::BeginPlay() { \tSuper::BeginPlay(); }\n\nvoid UAC_SmoothZoom::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )\n{\n\tSuper::TickComponent(DeltaTime, TickType, ThisTickFunction);\n\n\t\/\/ Only call when need to, saves ms's \n\tif (!FMath::IsNearlyEqual(SpringArm->TargetArmLength, DesiredArmLength, 0.5f))\n\t{\n\t\tSpringArm->TargetArmLength = FMath::FInterpTo(SpringArm->TargetArmLength, DesiredArmLength, DeltaTime, ZoomSmoothness);\n\t}\n}\n\n\/\/ Assigns the SpringArm component\nvoid UAC_SmoothZoom::SetSpringArmComponent(UPARAM(ref)USpringArmComponent* AssignedSpringArm)\n{\n\tDesiredArmLength = AssignedSpringArm->TargetArmLength;\n\tSpringArm = AssignedSpringArm;\n}\n\n\/\/ Sets the DesiredArmLength\nvoid UAC_SmoothZoom::SmoothCameraZoom(bool bZoomOut)\n{\n\tDesiredArmLength = bZoomOut ? SpringArm->TargetArmLength + ZoomUnits\n\t\t: SpringArm->TargetArmLength + (ZoomUnits * -1);\n\tif (DesiredArmLength > MaxTargetLength || DesiredArmLength < MinTargetLength)\n\t{\n\t\tDesiredArmLength = FMath::Min(FMath::Max(DesiredArmLength, MinTargetLength), MaxTargetLength);\n\t}\n\n\tif (bDebug) { SmoothZoomLog(); }\n}\n\nvoid UAC_SmoothZoom::SmoothZoomLog()\n{\n\tUE_LOG(ZoomLog, Log, TEXT(\"ArmLength: %f, Min: %f Max: %f, ZUnits: %f, Smoothness: %f\"),\n\t\tDesiredArmLength, MinTargetLength, MaxTargetLength, ZoomUnits, ZoomSmoothness)\n}\n\n<|endoftext|>"} {"text":"\/**\n * This file is part of TelepathyQt4\n *\n * @copyright Copyright (C) 2011 Collabora Ltd. \n * @copyright Copyright (C) 2011 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"TelepathyQt4\/simple-stream-tube-handler.h\"\n\n#include \"TelepathyQt4\/_gen\/simple-stream-tube-handler.moc.hpp\"\n\n#include \"TelepathyQt4\/debug-internal.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Tp\n{\n\nnamespace\n{\n ChannelClassSpecList buildFilter(const QStringList &p2pServices,\n const QStringList &roomServices, bool requested)\n {\n ChannelClassSpecList filter;\n\n foreach (const QString &service, p2pServices)\n {\n filter.append(requested ?\n ChannelClassSpec::outgoingStreamTube(service) :\n ChannelClassSpec::incomingStreamTube(service));\n }\n\n foreach (const QString &service, roomServices)\n {\n filter.append(requested ?\n ChannelClassSpec::outgoingRoomStreamTube(service) :\n ChannelClassSpec::incomingRoomStreamTube(service));\n }\n\n return filter;\n }\n}\n\nSharedPtr SimpleStreamTubeHandler::create(\n const QStringList &p2pServices,\n const QStringList &roomServices,\n bool requested,\n bool monitorConnections,\n bool bypassApproval)\n{\n return SharedPtr(\n new SimpleStreamTubeHandler(\n p2pServices,\n roomServices,\n requested,\n monitorConnections,\n bypassApproval));\n}\n\nSimpleStreamTubeHandler::SimpleStreamTubeHandler(\n const QStringList &p2pServices,\n const QStringList &roomServices,\n bool requested,\n bool monitorConnections,\n bool bypassApproval)\n : AbstractClient(),\n AbstractClientHandler(buildFilter(p2pServices, roomServices, requested)),\n mMonitorConnections(monitorConnections),\n mBypassApproval(bypassApproval)\n{\n}\n\nSimpleStreamTubeHandler::~SimpleStreamTubeHandler()\n{\n if (!mTubes.empty()) {\n debug() << \"~SSTubeHandler(): Closing\" << mTubes.size() << \"leftover tubes\";\n\n foreach (const StreamTubeChannelPtr &tube, mTubes.keys()) {\n tube->requestClose();\n }\n }\n}\n\nvoid SimpleStreamTubeHandler::handleChannels(\n const MethodInvocationContextPtr<> &context,\n const AccountPtr &account,\n const ConnectionPtr &connection,\n const QList &channels,\n const QList &requestsSatisfied,\n const QDateTime &userActionTime,\n const HandlerInfo &handlerInfo)\n{\n debug() << \"SimpleStreamTubeHandler::handleChannels() invoked for \" <<\n channels.size() << \"channels on account\" << account->objectPath();\n\n SharedPtr invocation(new InvocationData());\n QList readyOps;\n\n foreach (const ChannelPtr &chan, channels) {\n StreamTubeChannelPtr tube = StreamTubeChannelPtr::qObjectCast(chan);\n\n if (!tube) {\n \/\/ TODO: if Channel ever starts utilizing its immutable props for the immutable\n \/\/ accessors, use Channel::channelType() here\n const QString channelType =\n chan->immutableProperties()[QLatin1String(\n TELEPATHY_INTERFACE_CHANNEL \".ChannelType\")].toString();\n\n if (channelType != TP_QT4_IFACE_CHANNEL_TYPE_STREAM_TUBE) {\n debug() << \"We got a non-StreamTube channel\" << chan->objectPath() <<\n \"of type\" << channelType << \", ignoring\";\n } else {\n warning() << \"The channel factory used for a simple StreamTube handler must\" <<\n \"construct StreamTubeChannel subclasses for stream tubes\";\n }\n continue;\n }\n\n Features features = StreamTubeChannel::FeatureStreamTube;\n if (mMonitorConnections) {\n features.insert(StreamTubeChannel::FeatureConnectionMonitoring);\n }\n readyOps.append(tube->becomeReady(features));\n\n invocation->tubes.append(tube);\n }\n\n invocation->ctx = context;\n invocation->acc = account;\n invocation->time = userActionTime;\n\n if (!requestsSatisfied.isEmpty()) {\n invocation->hints = requestsSatisfied.first()->hints();\n }\n\n mInvocations.append(invocation);\n\n if (invocation->tubes.isEmpty()) {\n warning() << \"SSTH::HandleChannels got no suitable channels, admitting we're Confused\";\n invocation->readyOp = 0;\n invocation->error = TP_QT4_ERROR_CONFUSED;\n invocation->message = QLatin1String(\"Got no suitable channels\");\n onReadyOpFinished(0);\n } else {\n invocation->readyOp = new PendingComposite(readyOps, SharedPtr(this));\n connect(invocation->readyOp,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onReadyOpFinished(Tp::PendingOperation*)));\n }\n}\n\nvoid SimpleStreamTubeHandler::onReadyOpFinished(Tp::PendingOperation *op)\n{\n Q_ASSERT(!mInvocations.isEmpty());\n Q_ASSERT(!op || op->isFinished());\n\n for (QLinkedList >::iterator i = mInvocations.begin();\n op != 0 && i != mInvocations.end(); ++i) {\n if ((*i)->readyOp != op) {\n continue;\n }\n\n (*i)->readyOp = 0;\n\n if (op->isError()) {\n warning() << \"Preparing proxies for SSTubeHandler failed with\" << op->errorName()\n << op->errorMessage();\n (*i)->error = op->errorName();\n (*i)->message = op->errorMessage();\n }\n\n break;\n }\n\n while (!mInvocations.isEmpty() && !mInvocations.first()->readyOp) {\n SharedPtr invocation = mInvocations.takeFirst();\n\n if (!invocation->error.isEmpty()) {\n \/\/ We guarantee that the proxies were ready - so we can't invoke the client if they\n \/\/ weren't made ready successfully. Fix the introspection code if this happens :)\n invocation->ctx->setFinishedWithError(invocation->error, invocation->message);\n continue;\n }\n\n debug() << \"Emitting SSTubeHandler::invokedForTube for\" << invocation->tubes.size()\n << \"tubes\";\n\n foreach (const StreamTubeChannelPtr &tube, invocation->tubes) {\n if (!tube->isValid()) {\n debug() << \"Skipping already invalidated tube\" << tube->objectPath();\n continue;\n }\n\n if (!mTubes.contains(tube)) {\n connect(tube.data(),\n SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),\n SLOT(onTubeInvalidated(Tp::DBusProxy*,QString,QString)));\n\n mTubes.insert(tube, invocation->acc);\n }\n\n emit invokedForTube(\n invocation->acc,\n tube,\n invocation->time,\n invocation->hints);\n }\n\n invocation->ctx->setFinished();\n }\n}\n\nvoid SimpleStreamTubeHandler::onTubeInvalidated(DBusProxy *proxy,\n const QString &errorName, const QString &errorMessage)\n{\n StreamTubeChannelPtr tube(qobject_cast(proxy));\n\n Q_ASSERT(!tube.isNull());\n Q_ASSERT(mTubes.contains(tube));\n\n debug() << \"Tube\" << tube->objectPath() << \"invalidated - \" << errorName << ':' << errorMessage;\n\n AccountPtr acc = mTubes.value(tube);\n mTubes.remove(tube);\n\n emit tubeInvalidated(\n acc,\n tube,\n errorName,\n errorMessage);\n}\n\n} \/\/ Tp\nSimpleStreamTubeHandler: Weed out duplicate services when building filter\/**\n * This file is part of TelepathyQt4\n *\n * @copyright Copyright (C) 2011 Collabora Ltd. \n * @copyright Copyright (C) 2011 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"TelepathyQt4\/simple-stream-tube-handler.h\"\n\n#include \"TelepathyQt4\/_gen\/simple-stream-tube-handler.moc.hpp\"\n\n#include \"TelepathyQt4\/debug-internal.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Tp\n{\n\nnamespace\n{\n ChannelClassSpecList buildFilter(const QStringList &p2pServices,\n const QStringList &roomServices, bool requested)\n {\n ChannelClassSpecList filter;\n\n \/\/ Convert to QSet to weed out duplicates\n foreach (const QString &service, p2pServices.toSet())\n {\n filter.append(requested ?\n ChannelClassSpec::outgoingStreamTube(service) :\n ChannelClassSpec::incomingStreamTube(service));\n }\n\n \/\/ Convert to QSet to weed out duplicates\n foreach (const QString &service, roomServices.toSet())\n {\n filter.append(requested ?\n ChannelClassSpec::outgoingRoomStreamTube(service) :\n ChannelClassSpec::incomingRoomStreamTube(service));\n }\n\n return filter;\n }\n}\n\nSharedPtr SimpleStreamTubeHandler::create(\n const QStringList &p2pServices,\n const QStringList &roomServices,\n bool requested,\n bool monitorConnections,\n bool bypassApproval)\n{\n return SharedPtr(\n new SimpleStreamTubeHandler(\n p2pServices,\n roomServices,\n requested,\n monitorConnections,\n bypassApproval));\n}\n\nSimpleStreamTubeHandler::SimpleStreamTubeHandler(\n const QStringList &p2pServices,\n const QStringList &roomServices,\n bool requested,\n bool monitorConnections,\n bool bypassApproval)\n : AbstractClient(),\n AbstractClientHandler(buildFilter(p2pServices, roomServices, requested)),\n mMonitorConnections(monitorConnections),\n mBypassApproval(bypassApproval)\n{\n}\n\nSimpleStreamTubeHandler::~SimpleStreamTubeHandler()\n{\n if (!mTubes.empty()) {\n debug() << \"~SSTubeHandler(): Closing\" << mTubes.size() << \"leftover tubes\";\n\n foreach (const StreamTubeChannelPtr &tube, mTubes.keys()) {\n tube->requestClose();\n }\n }\n}\n\nvoid SimpleStreamTubeHandler::handleChannels(\n const MethodInvocationContextPtr<> &context,\n const AccountPtr &account,\n const ConnectionPtr &connection,\n const QList &channels,\n const QList &requestsSatisfied,\n const QDateTime &userActionTime,\n const HandlerInfo &handlerInfo)\n{\n debug() << \"SimpleStreamTubeHandler::handleChannels() invoked for \" <<\n channels.size() << \"channels on account\" << account->objectPath();\n\n SharedPtr invocation(new InvocationData());\n QList readyOps;\n\n foreach (const ChannelPtr &chan, channels) {\n StreamTubeChannelPtr tube = StreamTubeChannelPtr::qObjectCast(chan);\n\n if (!tube) {\n \/\/ TODO: if Channel ever starts utilizing its immutable props for the immutable\n \/\/ accessors, use Channel::channelType() here\n const QString channelType =\n chan->immutableProperties()[QLatin1String(\n TELEPATHY_INTERFACE_CHANNEL \".ChannelType\")].toString();\n\n if (channelType != TP_QT4_IFACE_CHANNEL_TYPE_STREAM_TUBE) {\n debug() << \"We got a non-StreamTube channel\" << chan->objectPath() <<\n \"of type\" << channelType << \", ignoring\";\n } else {\n warning() << \"The channel factory used for a simple StreamTube handler must\" <<\n \"construct StreamTubeChannel subclasses for stream tubes\";\n }\n continue;\n }\n\n Features features = StreamTubeChannel::FeatureStreamTube;\n if (mMonitorConnections) {\n features.insert(StreamTubeChannel::FeatureConnectionMonitoring);\n }\n readyOps.append(tube->becomeReady(features));\n\n invocation->tubes.append(tube);\n }\n\n invocation->ctx = context;\n invocation->acc = account;\n invocation->time = userActionTime;\n\n if (!requestsSatisfied.isEmpty()) {\n invocation->hints = requestsSatisfied.first()->hints();\n }\n\n mInvocations.append(invocation);\n\n if (invocation->tubes.isEmpty()) {\n warning() << \"SSTH::HandleChannels got no suitable channels, admitting we're Confused\";\n invocation->readyOp = 0;\n invocation->error = TP_QT4_ERROR_CONFUSED;\n invocation->message = QLatin1String(\"Got no suitable channels\");\n onReadyOpFinished(0);\n } else {\n invocation->readyOp = new PendingComposite(readyOps, SharedPtr(this));\n connect(invocation->readyOp,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(onReadyOpFinished(Tp::PendingOperation*)));\n }\n}\n\nvoid SimpleStreamTubeHandler::onReadyOpFinished(Tp::PendingOperation *op)\n{\n Q_ASSERT(!mInvocations.isEmpty());\n Q_ASSERT(!op || op->isFinished());\n\n for (QLinkedList >::iterator i = mInvocations.begin();\n op != 0 && i != mInvocations.end(); ++i) {\n if ((*i)->readyOp != op) {\n continue;\n }\n\n (*i)->readyOp = 0;\n\n if (op->isError()) {\n warning() << \"Preparing proxies for SSTubeHandler failed with\" << op->errorName()\n << op->errorMessage();\n (*i)->error = op->errorName();\n (*i)->message = op->errorMessage();\n }\n\n break;\n }\n\n while (!mInvocations.isEmpty() && !mInvocations.first()->readyOp) {\n SharedPtr invocation = mInvocations.takeFirst();\n\n if (!invocation->error.isEmpty()) {\n \/\/ We guarantee that the proxies were ready - so we can't invoke the client if they\n \/\/ weren't made ready successfully. Fix the introspection code if this happens :)\n invocation->ctx->setFinishedWithError(invocation->error, invocation->message);\n continue;\n }\n\n debug() << \"Emitting SSTubeHandler::invokedForTube for\" << invocation->tubes.size()\n << \"tubes\";\n\n foreach (const StreamTubeChannelPtr &tube, invocation->tubes) {\n if (!tube->isValid()) {\n debug() << \"Skipping already invalidated tube\" << tube->objectPath();\n continue;\n }\n\n if (!mTubes.contains(tube)) {\n connect(tube.data(),\n SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),\n SLOT(onTubeInvalidated(Tp::DBusProxy*,QString,QString)));\n\n mTubes.insert(tube, invocation->acc);\n }\n\n emit invokedForTube(\n invocation->acc,\n tube,\n invocation->time,\n invocation->hints);\n }\n\n invocation->ctx->setFinished();\n }\n}\n\nvoid SimpleStreamTubeHandler::onTubeInvalidated(DBusProxy *proxy,\n const QString &errorName, const QString &errorMessage)\n{\n StreamTubeChannelPtr tube(qobject_cast(proxy));\n\n Q_ASSERT(!tube.isNull());\n Q_ASSERT(mTubes.contains(tube));\n\n debug() << \"Tube\" << tube->objectPath() << \"invalidated - \" << errorName << ':' << errorMessage;\n\n AccountPtr acc = mTubes.value(tube);\n mTubes.remove(tube);\n\n emit tubeInvalidated(\n acc,\n tube,\n errorName,\n errorMessage);\n}\n\n} \/\/ Tp\n<|endoftext|>"} {"text":"\/\/\n\/\/ Name: UtilDlg.cpp\n\/\/\n\/\/ Copyright (c) 2002-2006 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"UtilDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Route.h\"\n#include \"UtilDlg.h\"\n#include \"EnviroGUI.h\"\n\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ UtilDlg\n\/\/----------------------------------------------------------------------------\n\n\/\/ WDR: event table for UtilDlg\n\nBEGIN_EVENT_TABLE(UtilDlg,AutoDialog)\n\tEVT_INIT_DIALOG (UtilDlg::OnInitDialog)\n\tEVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )\nEND_EVENT_TABLE()\n\nUtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\tAutoDialog( parent, id, title, position, size, style )\n{\n\tUtilDialogFunc( this, TRUE );\n\n\tm_pChoice = GetStructtype();\n\tm_iType = 0;\n\n\tAddValidator(ID_STRUCTTYPE, &m_iType);\n}\n\n\/\/ WDR: handler implementations for UtilDlg\n\nvoid UtilDlg::OnStructType( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\twxString val = m_pChoice->GetStringSelection();\n\tg_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));\n\tg_App.start_new_fence();\n}\n\nvoid UtilDlg::OnInitDialog(wxInitDialogEvent& event)\n{\n\tvtContentManager &mng = vtGetContent();\n\n\tm_pChoice->Clear();\n\tfor (unsigned int i = 0; i < mng.NumItems(); i++)\n\t{\n\t\tvtString str;\n\t\tvtItem *item = mng.GetItem(i);\n\t\tif (item->GetValueString(\"type\", str))\n\t\t{\n\t\t\tif (str == \"utility pole\")\n\t\t\t\tm_pChoice->Append(wxString::FromAscii(item->m_name));\n\t\t}\n\t}\n\tTransferDataToWindow();\n\n\twxString val = m_pChoice->GetStringSelection();\n\tg_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));\n}\n\nadded logging\/\/\n\/\/ Name: UtilDlg.cpp\n\/\/\n\/\/ Copyright (c) 2002-2008 Virtual Terrain Project\n\/\/ Free for all uses, see license.txt for details.\n\/\/\n\n#ifdef __GNUG__\n\t#pragma implementation \"UtilDlg.cpp\"\n#endif\n\n\/\/ For compilers that support precompilation, includes \"wx\/wx.h\".\n#include \"wx\/wxprec.h\"\n\n#include \"vtlib\/vtlib.h\"\n#include \"vtlib\/core\/Route.h\"\n#include \"UtilDlg.h\"\n#include \"EnviroGUI.h\"\n#include \"vtdata\/vtLog.h\"\n\n\n\/\/ WDR: class implementations\n\n\/\/----------------------------------------------------------------------------\n\/\/ UtilDlg\n\/\/----------------------------------------------------------------------------\n\n\/\/ WDR: event table for UtilDlg\n\nBEGIN_EVENT_TABLE(UtilDlg,AutoDialog)\n\tEVT_INIT_DIALOG (UtilDlg::OnInitDialog)\n\tEVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )\nEND_EVENT_TABLE()\n\nUtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,\n\tconst wxPoint &position, const wxSize& size, long style ) :\n\tAutoDialog( parent, id, title, position, size, style )\n{\n\tUtilDialogFunc( this, TRUE );\n\n\tm_pChoice = GetStructtype();\n\tm_iType = 0;\n\n\tAddValidator(ID_STRUCTTYPE, &m_iType);\n}\n\n\/\/ WDR: handler implementations for UtilDlg\n\nvoid UtilDlg::OnStructType( wxCommandEvent &event )\n{\n\tTransferDataFromWindow();\n\twxString val = m_pChoice->GetStringSelection();\n\tg_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));\n\tg_App.start_new_fence();\n}\n\nvoid UtilDlg::OnInitDialog(wxInitDialogEvent& event)\n{\n\tVTLOG(\"UtilDlg looking for items of type utility pole.\\n\");\n\tvtContentManager &mng = vtGetContent();\n\n\tint found = 0;\n\tm_pChoice->Clear();\n\tfor (unsigned int i = 0; i < mng.NumItems(); i++)\n\t{\n\t\tvtString str;\n\t\tvtItem *item = mng.GetItem(i);\n\t\tif (item->GetValueString(\"type\", str))\n\t\t{\n\t\t\tif (str == \"utility pole\")\n\t\t\t{\n\t\t\t\tm_pChoice->Append(wxString::FromAscii(item->m_name));\n\t\t\t\tfound++;\n\t\t\t}\n\t\t}\n\t}\n\tTransferDataToWindow();\n\n\tVTLOG(\"\\t%d items, %d found.\\n\", mng.NumItems(), found);\n\n\twxString val = m_pChoice->GetStringSelection();\n\tg_App.SetRouteOptions((const char *) val.mb_str(wxConvUTF8));\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nint testMetaImage(int argc, char *argv[])\n {\n\n MetaImage tIm(8, 8, 1, 2, MET_CHAR);\n\n int i;\n for(i=0; i<64; i++)\n tIm.ElementData(i, i);\n\n for(i=0; i<64; i++)\n {\n if(i != tIm.ElementData(i))\n {\n std::cout << \"Assigned Element Values Maintained: FAIL\" << std::endl;\n return 1;\n }\n }\n\n tIm.Write(\"test.mha\");\n tIm.PrintInfo();\n\n MetaImage tIm2(\"test.mha\");\n tIm2.PrintInfo();\n for(i=0; i<64; i++)\n {\n if(i != tIm.ElementData(i))\n {\n std::cout << \"Read Element Values: FAIL\" << std::endl;\n return 1;\n }\n }\n\n\n return 0;\n }\nSTYLE: Added end of test#include \n#include \n#include \n\nint testMetaImage(int argc, char *argv[])\n {\n\n MetaImage tIm(8, 8, 1, 2, MET_CHAR);\n\n int i;\n for(i=0; i<64; i++)\n tIm.ElementData(i, i);\n\n for(i=0; i<64; i++)\n {\n if(i != tIm.ElementData(i))\n {\n std::cout << \"Assigned Element Values Maintained: FAIL\" << std::endl;\n return 1;\n }\n }\n\n tIm.Write(\"test.mha\");\n tIm.PrintInfo();\n\n MetaImage tIm2(\"test.mha\");\n tIm2.PrintInfo();\n for(i=0; i<64; i++)\n {\n if(i != tIm.ElementData(i))\n {\n std::cout << \"Read Element Values: FAIL\" << std::endl;\n return 1;\n }\n }\n\n std::cout << \"[DONE]\" << std::endl;\n return 0;\n }\n<|endoftext|>"} {"text":"\/*\n * FstAligner.cpp\n *\n * align hypothesis fst to reference fst, produce WER\n *\n * Created on: 2010-12-6\n * Author: freqyifan@gmail.com\n *\/\n\n#include \"FstAligner.h\"\n\n#include \n#include \n#include \n#include \n\nFstAligner::FstAligner() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nFstAligner::~FstAligner() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid drawFstToFile(fst::StdVectorFst &fstToDraw, const fst::SymbolTable &symbol, const std::string &name) {\n\tstd::ofstream stream(name.c_str());\n\tif (stream.is_open()) {\n\t\tfst::script::FstClass object(&fstToDraw);\n\t\tfst::script::DrawFst(object, &symbol, &symbol, 0, false,\n\t\t\t\t\t\t\tname, 8.5, 11, false, false, 0.40, 0.25, 14, 5,\n\t\t\t\t\t\t\tfalse, &stream, name);\n\t}\n\tstream.close();\n}\n\nvoid FstAligner::align(const FstAlignOption & option,\n\t\tconst FstLoader &refLoader, const FstLoader &hypLoader,\n\t\tFstAlignResult &result) {\n\tfst::SymbolTable symbol(\"symbol\");\n\n\tsymbol.AddSymbol(option.symEps);\n\tsymbol.AddSymbol(option.symOov);\n\tsymbol.AddSymbol(option.symIns);\n\tsymbol.AddSymbol(option.symDel);\n\tsymbol.AddSymbol(option.symSub);\n\n\trefLoader.addToSymbolTable(symbol);\n\thypLoader.addToSymbolTable(symbol);\n\tfst::StdVectorFst refFst = refLoader.convertToFst(symbol);\n\tfst::StdVectorFst hypFst = hypLoader.convertToFst(symbol);\n\n\tsymbol.WriteText(\"symbol\");\n\n\tassert(refFst.NumStates() > 1);\n\tassert(hypFst.NumStates() > 1);\n\n\t\/\/ add possible insertion\/deletion\/substitution to reference\n\tint nstate = refFst.NumStates();\n\n\tif (option.bForceEnterAndExit == false) {\n\t\trefFst.AddArc(0, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),\n\t\t\t\t\t\t\t\t\t\toption.insCost, 0));\n\t\trefFst.AddArc(nstate-1, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),\n\t\t\t\t\t\t\t\t\t\toption.insCost, nstate-1));\n\t}\n\telse {\n\t\tnstate --;\n\t}\n\n\tfor (int i=1; i >RM;\n\tfst::ComposeFstOptions opts;\n\topts.gc_limit = 0;\n\topts.matcher1 = new RM(hypFst, fst::MATCH_NONE, fst::kNoLabel);\n\topts.matcher2 = new RM(refFst, fst::MATCH_INPUT, symbol.Find(option.symOov));\n\n\tfst::StdComposeFst cFst(hypFst, refFst, opts);\n\tfst::StdVectorFst composedFst(cFst);\n\n\tif (option.saveCompositionDot != \"\")\n\t\tdrawFstToFile(composedFst, symbol, option.saveCompositionDot);\n\n\tfst::StdVectorFst pathFst;\n\tfst::ShortestPath(composedFst, &pathFst);\n\tif (option.saveShortestPathDot != \"\")\n\t\tdrawFstToFile(pathFst, symbol, option.saveShortestPathDot);\n\n\tfst::StdVectorFst::StateId state = pathFst.Start();\n\twhile (state > 0) {\n\t\tfst::ArcIterator aiter(pathFst, state);\n\t\tconst fst::StdArc &arc = aiter.Value();\n\t\tresult.alignment.push_back(std::make_pair(symbol.Find(arc.ilabel), symbol.Find(arc.olabel)));\n\t\tstate = arc.nextstate;\n\t}\n\n\tresult.update(option);\n}\n\/ bugfix: added missing insertions on all reference states\/*\n * FstAligner.cpp\n *\n * align hypothesis fst to reference fst, produce WER\n *\n * Created on: 2010-12-6\n * Author: freqyifan@gmail.com\n *\/\n\n#include \"FstAligner.h\"\n\n#include \n#include \n#include \n#include \n\nFstAligner::FstAligner() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nFstAligner::~FstAligner() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nvoid drawFstToFile(fst::StdVectorFst &fstToDraw, const fst::SymbolTable &symbol, const std::string &name) {\n\tstd::ofstream stream(name.c_str());\n\tif (stream.is_open()) {\n\t\tfst::script::FstClass object(&fstToDraw);\n\t\tfst::script::DrawFst(object, &symbol, &symbol, 0, false,\n\t\t\t\t\t\t\tname, 8.5, 11, false, false, 0.40, 0.25, 14, 5,\n\t\t\t\t\t\t\tfalse, &stream, name);\n\t}\n\tstream.close();\n}\n\nvoid FstAligner::align(const FstAlignOption & option,\n\t\tconst FstLoader &refLoader, const FstLoader &hypLoader,\n\t\tFstAlignResult &result) {\n\tfst::SymbolTable symbol(\"symbol\");\n\n\tsymbol.AddSymbol(option.symEps);\n\tsymbol.AddSymbol(option.symOov);\n\tsymbol.AddSymbol(option.symIns);\n\tsymbol.AddSymbol(option.symDel);\n\tsymbol.AddSymbol(option.symSub);\n\n\trefLoader.addToSymbolTable(symbol);\n\thypLoader.addToSymbolTable(symbol);\n\tfst::StdVectorFst refFst = refLoader.convertToFst(symbol);\n\tfst::StdVectorFst hypFst = hypLoader.convertToFst(symbol);\n\n\tsymbol.WriteText(\"symbol\");\n\n\tassert(refFst.NumStates() > 1);\n\tassert(hypFst.NumStates() > 1);\n\n\t\/\/ add possible insertion\/deletion\/substitution to reference\n\tint nstate = refFst.NumStates();\n\n\tif (option.bForceEnterAndExit == false) {\n\t\trefFst.AddArc(0, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),\n\t\t\t\t\t\t\t\t\t\toption.insCost, 0));\n\t\trefFst.AddArc(nstate-1, fst::StdArc(symbol.Find(option.symOov), symbol.Find(option.symIns),\n\t\t\t\t\t\t\t\t\t\toption.insCost, nstate-1));\n\t}\n\telse {\n\t\tnstate --;\n\t}\n\n\tfor (int i=1; i >RM;\n\tfst::ComposeFstOptions opts;\n\topts.gc_limit = 0;\n\topts.matcher1 = new RM(hypFst, fst::MATCH_NONE, fst::kNoLabel);\n\topts.matcher2 = new RM(refFst, fst::MATCH_INPUT, symbol.Find(option.symOov));\n\n\tfst::StdComposeFst cFst(hypFst, refFst, opts);\n\tfst::StdVectorFst composedFst(cFst);\n\n\tif (option.saveCompositionDot != \"\")\n\t\tdrawFstToFile(composedFst, symbol, option.saveCompositionDot);\n\n\tfst::StdVectorFst pathFst;\n\tfst::ShortestPath(composedFst, &pathFst);\n\tif (option.saveShortestPathDot != \"\")\n\t\tdrawFstToFile(pathFst, symbol, option.saveShortestPathDot);\n\n\tfst::StdVectorFst::StateId state = pathFst.Start();\n\twhile (state > 0) {\n\t\tfst::ArcIterator aiter(pathFst, state);\n\t\tconst fst::StdArc &arc = aiter.Value();\n\t\tresult.alignment.push_back(std::make_pair(symbol.Find(arc.ilabel), symbol.Find(arc.olabel)));\n\t\tstate = arc.nextstate;\n\t}\n\n\tresult.update(option);\n}\n<|endoftext|>"} {"text":"#include \"GPS.h\"\n#include \"Battery.h\"\n\nchar* parse_token(char* data, char* dest)\n{\n int i = 0;\n while(data[i] != ',' && data[i] != 0)\n ++i;\n if( dest != NULL)\n strncpy(dest, data, i);\n if(data[i])\n ++i;\n return data + i;\n}\n\nvoid GPSTracker::localize()\n{\n \/\/Read data from GPS\n LGPS.getData(&gps_info);\n char* data = (char*)gps_info.GPGGA;\n Serial.println(data);\n char buff[20];\n data = parse_token(data, NULL); \/\/ $GPGGA\n data = parse_token(data, buff); \/\/ Time\n gps_data[cache_gps].date_time = atof(buff);\n \n data = parse_token(data, buff); \/\/ Latitude\n double tmp = atof(buff);\n gps_data[cache_gps].latitude = ((int)tmp) \/ 100; \n tmp -= (gps_data[cache_gps].latitude * 100);\n tmp \/= 60.0;\n gps_data[cache_gps].latitude += tmp;\n\n data = parse_token(data, buff); \/\/ North\/South\n if(buff[0] == 'S' || buff[0] == 's')\n gps_data[cache_gps].latitude *= -1;\n\n data = parse_token(data, buff); \/\/ Longitude\n tmp = atof(buff);\n gps_data[cache_gps].longitude = ((int)tmp) \/ 100; \n tmp -= (gps_data[cache_gps].longitude * 100);\n tmp \/= 60.0;\n gps_data[cache_gps].longitude += tmp; \n \n data = parse_token(data, buff); \/\/ West\/East\n if(buff[0] == 'W' || buff[0] == 'w')\n gps_data[cache_gps].longitude *= -1;\n\n data = parse_token(data, buff); \/\/ Fix bit\n if(buff[0] != '0')\n {\n data = parse_token(data, buff);\n gps_data[cache_gps].num_satelites = (int)atof(buff);\n }\n else\n {\n data = parse_token(data, NULL); \/\/ flush the empty number of satelites\n gps_data[cache_gps].num_satelites = 0;\n }\n data = parse_token(data, NULL); \/\/ flush the horizontal dilutoion of position\n data = parse_token(data, buff); \/\/ get the Altitude\n gps_data[cache_gps].altitude = atof(buff);\n data = parse_token(data, NULL); \/\/ flush the measurment system of altitude\n data = parse_token(data, buff); \/\/ get the height of geoid\n gps_data[cache_gps].altitude -= atof(buff); \n Serial.println(\"The location was localized\");\n Serial.print(gps_data[cache_gps].latitude, 6);\n Serial.print(\" \");\n Serial.print(gps_data[cache_gps].longitude, 6);\n Serial.print(\" #sats \");\n Serial.println(gps_data[cache_gps].num_satelites);\n\n}\n\nvoid GPSTracker::submitToServer()\n{\n int i;\n for (i = 0; i < 3; ++i)\n {\n if (client.connect(site_url, site_port))\n {\n break;\n } \n }\n if (i == 3)\n {\n return;\n }\n char buff[256];\n client.println(\"GET \/ HTTP\/1.1\");\n client.print(\"Host: \");\n client.print(site_url);\n client.print(\":\");\n client.println(site_port);\n client.print(\"Latitude: \");\n sprintf(buff, \"%.6f\", gps_data[cache_gps].latitude);\n client.println(buff);\n client.print(\"Longitude: \");\n sprintf(buff, \"%.6f\", gps_data[cache_gps].longitude);\n client.println(buff);\n client.print(\"Altitude: \");\n client.println(gps_data[cache_gps].altitude);\n client.print(\"Satelites_Count: \");\n client.println(gps_data[cache_gps].num_satelites);\n client.print(\"Localization_Time: \");\n client.println(gps_data[cache_gps].date_time);\n client.print(\"Battery_Rate: \");\n client.println(get_battery_rate());\n client.println();\n\n \/\/ get the response\n int response;\n while (client.available())\n {\n response = client.read(); \/\/ TODO: Read the response on larger batches, not byte by byte\n if (response < 0)\n break;\n }\n Serial.println(\"Data is submitted to server\");\n}\n\nvoid GPSTracker::updateTimeInterval()\n{\n if (haveWeMoved())\n {\n if (time_interval > 32000)\n time_interval \/= 4;\n else if (time_interval > LOWER_TIME_LIMIT)\n time_interval \/= 2;\n time_interval = max(time_interval, LOWER_TIME_LIMIT);\n }\n else\n {\n if (time_interval < 32000)\n time_interval *= 4;\n else if (time_interval < UPPER_TIME_LIMIT)\n time_interval *= 2;\n time_interval = min(time_interval, UPPER_TIME_LIMIT);\n }\n}\n\nvoid GPSTracker::setUrl(const char* new_url)\n{\n strncpy(site_url, new_url, SITE_URL_LENGTH - 1);\n}\n\nGPSTracker::GPSTracker()\n{\n client = LGPRSClient();\n time_interval = (UPPER_TIME_LIMIT + LOWER_TIME_LIMIT) \/ 16;\n setUrl(\"\"); \/\/ TODO: Enter valid URL\/IP\n site_port = 80;\n lastRun = millis();\n Wifi_enabled = false;\n GPS_enabled = false;\n cache_gps = 0;\n Serial.println(\"GPS_Tracker is init\");\n}\n\nvoid GPSTracker::initModules()\n{\n Serial.println(\"In initModules\");\n startGps();\n startGPRS();\n for(int i = 0; i < CACHE_COUNT; ++i)\n gps_data[i].longitude = gps_data[i].latitude = 0.0;\n}\n\nvoid GPSTracker::startGps()\n{\n LGPS.powerOn();\n delay(1000);\n GPS_enabled = true;\n Serial.println(\"GPS is started\");\n}\n\nvoid GPSTracker::stopGps()\n{\n LGPS.powerOff();\n GPS_enabled = false;\n Serial.println(\"GPS is stopped\");\n}\n\nvoid GPSTracker::startGPRS()\n{\n while (!LGPRS.attachGPRS(\"telenorbg\", \"telenor\", \"\")) \/\/ TODO: Enter valid values for your telecom operator.\n {\n delay(2000);\n }\n Serial.println(\"GSM\/GPRS is started\");\n}\n\nvoid GPSTracker::disableModules()\n{\n stopGps();\n}\n\nvoid GPSTracker::run()\n{\n unsigned long current_lapsed_time;\n int tries = 0;\n current_lapsed_time = millis();\n if (current_lapsed_time - lastRun > time_interval)\n {\n Serial.println(\"Start another instance of the MaiN LOOP\");\n \/\/ here we have to get the location and submit it\n \/\/ also update lastRun, check the movement in the last positions\n \/\/ the sum of the coordinates devided by the number of points\n \/\/ give us the center of gravity\n \/\/ if we were stationary, then the distance between all points will be very small\n \/\/ if we start to move, then tha last point will move the center of gravity\n \/\/ enough, that it will get away from most of the points\n if(GPS_enabled == false)\n startGps();\n tries = 0;\n do\n {\n localize();\n ++tries;\n }while(gps_data[cache_gps].num_satelites < 4 && tries < 16);\n if(tries < 16 )\n {\n submitToServer();\n updateTimeInterval();\n if (Wifi_enabled)\n {\n \/\/ submit localization to WI-FI module\n this->serve_on_wifi();\n }\n \/\/ increase cache_gps\n cache_gps = (cache_gps+1) % CACHE_COUNT;\n }\n lastRun = millis();\n if (time_interval > 32000)\n stopGps();\n }\n delay(time_interval);\n}\n\nbool GPSTracker::haveWeMoved() const\n{\n double longi=0.0f, lati=0.0f;\n for (int i = 0; i < CACHE_COUNT; ++i)\n {\n longi += gps_data[i].longitude;\n lati += gps_data[i].latitude;\n }\n longi \/= CACHE_COUNT;\n lati \/= CACHE_COUNT;\n if( abs(longi - gps_data[cache_gps].longitude) + \n abs(lati - gps_data[cache_gps].latitude) < MOVEMENT_TRESHHOLD)\n return false;\n return true;\n}\n\nvoid GPSTracker::serve_on_wifi() const\n{\n LWiFi.begin();\n LWiFi.connect(\"GPS_Tracker\");\n LWiFiClient client;\n client.connect(\"server\", 80);\n \n char buff[256];\n sprintf(buff, \"%.6f\", gps_data[cache_gps].latitude);\n client.print(buff);\n client.print(\" \");\n sprintf(buff, \"%.6f\", gps_data[cache_gps].longitude);\n client.print(buff);\n client.println();\n\n LWiFi.end();\n}\nFix reading number of satelites Add some delay between consequent invokes of 'localize' Add some debug logs Move delay in run method#include \"GPS.h\"\n#include \"Battery.h\"\n\nchar* parse_token(char* data, char* dest)\n{\n int i = 0;\n while(data[i] != ',' && data[i] != 0)\n ++i;\n if (dest != NULL)\n {\n strncpy(dest, data, i);\n dest[i] = '\\0';\n }\n if(data[i])\n ++i;\n return data + i;\n}\n\nvoid GPSTracker::localize()\n{\n \/\/Read data from GPS\n LGPS.getData(&gps_info);\n char* data = (char*)gps_info.GPGGA;\n Serial.println(data);\n char buff[20];\n data = parse_token(data, NULL); \/\/ $GPGGA\n data = parse_token(data, buff); \/\/ Time\n gps_data[cache_gps].date_time = atof(buff);\n \n data = parse_token(data, buff); \/\/ Latitude\n double tmp = atof(buff);\n gps_data[cache_gps].latitude = ((int)tmp) \/ 100; \n tmp -= (gps_data[cache_gps].latitude * 100);\n tmp \/= 60.0;\n gps_data[cache_gps].latitude += tmp;\n\n data = parse_token(data, buff); \/\/ North\/South\n if(buff[0] == 'S' || buff[0] == 's')\n gps_data[cache_gps].latitude *= -1;\n\n data = parse_token(data, buff); \/\/ Longitude\n tmp = atof(buff);\n gps_data[cache_gps].longitude = ((int)tmp) \/ 100; \n tmp -= (gps_data[cache_gps].longitude * 100);\n tmp \/= 60.0;\n gps_data[cache_gps].longitude += tmp; \n \n data = parse_token(data, buff); \/\/ West\/East\n if(buff[0] == 'W' || buff[0] == 'w')\n gps_data[cache_gps].longitude *= -1;\n\n data = parse_token(data, buff); \/\/ Fix bit\n if(buff[0] != '0')\n {\n data = parse_token(data, buff);\n gps_data[cache_gps].num_satelites = atoi(buff);\n }\n else\n {\n data = parse_token(data, NULL); \/\/ flush the empty number of satelites\n gps_data[cache_gps].num_satelites = 0;\n }\n data = parse_token(data, NULL); \/\/ flush the horizontal dilutoion of position\n data = parse_token(data, buff); \/\/ get the Altitude\n gps_data[cache_gps].altitude = atof(buff);\n data = parse_token(data, NULL); \/\/ flush the measurment system of altitude\n data = parse_token(data, buff); \/\/ get the height of geoid\n gps_data[cache_gps].altitude -= atof(buff); \n Serial.println(\"The location was localized\");\n Serial.print(gps_data[cache_gps].latitude, 6);\n Serial.print(\" \");\n Serial.print(gps_data[cache_gps].longitude, 6);\n Serial.print(\" #sats \");\n Serial.println(gps_data[cache_gps].num_satelites);\n delay(1000);\n\n}\n\nvoid GPSTracker::submitToServer()\n{\n Serial.println(\"In submitToServer\");\n int i;\n for (i = 0; i < 3; ++i)\n {\n Serial.print(\"connect to server, attempt <-- \");\n Serial.println(i + 1);\n if (client.connect(site_url, site_port))\n {\n break;\n } \n }\n if (i == 3)\n {\n Serial.println(\"Failed to connecto to site_url\");\n return;\n }\n char buff[256];\n client.println(\"GET \/ HTTP\/1.1\");\n client.print(\"Host: \");\n client.print(site_url);\n client.print(\":\");\n client.println(site_port);\n client.print(\"Latitude: \");\n sprintf(buff, \"%.6f\", gps_data[cache_gps].latitude);\n client.println(buff);\n client.print(\"Longitude: \");\n sprintf(buff, \"%.6f\", gps_data[cache_gps].longitude);\n client.println(buff);\n client.print(\"Altitude: \");\n client.println(gps_data[cache_gps].altitude);\n client.print(\"Satelites_Count: \");\n client.println(gps_data[cache_gps].num_satelites);\n client.print(\"Localization_Time: \");\n client.println(gps_data[cache_gps].date_time);\n client.print(\"Battery_Rate: \");\n client.println(get_battery_rate());\n client.println();\n\n Serial.println(\"The data is sent to server, now gets the response\");\n \/\/ get the response\n int response;\n while (client.available())\n {\n response = client.read(); \/\/ TODO: Read the response on larger batches, not byte by byte\n if (response < 0)\n break;\n }\n Serial.println(\"Response arrived\");\n}\n\nvoid GPSTracker::updateTimeInterval()\n{\n if (haveWeMoved())\n {\n if (time_interval > 32000)\n time_interval \/= 4;\n else if (time_interval > LOWER_TIME_LIMIT)\n time_interval \/= 2;\n time_interval = max(time_interval, LOWER_TIME_LIMIT);\n }\n else\n {\n if (time_interval < 32000)\n time_interval *= 4;\n else if (time_interval < UPPER_TIME_LIMIT)\n time_interval *= 2;\n time_interval = min(time_interval, UPPER_TIME_LIMIT);\n }\n}\n\nvoid GPSTracker::setUrl(const char* new_url)\n{\n strncpy(site_url, new_url, SITE_URL_LENGTH - 1);\n}\n\nGPSTracker::GPSTracker()\n{\n client = LGPRSClient();\n time_interval = (UPPER_TIME_LIMIT + LOWER_TIME_LIMIT) \/ 16;\n setUrl(\"\", SET_URL_COMPILE_ERROR); \/\/ TODO: Enter valid URL\/IP\n site_port = 80;\n lastRun = millis();\n Wifi_enabled = false;\n GPS_enabled = false;\n cache_gps = 0;\n Serial.println(\"GPS_Tracker is init\");\n}\n\nvoid GPSTracker::initModules()\n{\n Serial.println(\"In initModules\");\n startGps();\n startGPRS();\n for(int i = 0; i < CACHE_COUNT; ++i)\n gps_data[i].longitude = gps_data[i].latitude = 0.0;\n}\n\nvoid GPSTracker::startGps()\n{\n LGPS.powerOn();\n delay(1000);\n GPS_enabled = true;\n Serial.println(\"GPS is started\");\n}\n\nvoid GPSTracker::stopGps()\n{\n LGPS.powerOff();\n GPS_enabled = false;\n Serial.println(\"GPS is stopped\");\n}\n\nvoid GPSTracker::startGPRS()\n{\n while (!LGPRS.attachGPRS(\"telenorbg\", \"telenor\", \"\")) \/\/ TODO: Enter valid values for your telecom operator.\n {\n delay(2000);\n }\n Serial.println(\"GSM\/GPRS is started\");\n}\n\nvoid GPSTracker::disableModules()\n{\n stopGps();\n}\n\nvoid GPSTracker::run()\n{\n unsigned long current_lapsed_time;\n int tries = 0;\n current_lapsed_time = millis();\n if (current_lapsed_time - lastRun > time_interval)\n {\n Serial.println(\"Start another instance of the MaiN LOOP\");\n \/\/ here we have to get the location and submit it\n \/\/ also update lastRun, check the movement in the last positions\n \/\/ the sum of the coordinates devided by the number of points\n \/\/ give us the center of gravity\n \/\/ if we were stationary, then the distance between all points will be very small\n \/\/ if we start to move, then tha last point will move the center of gravity\n \/\/ enough, that it will get away from most of the points\n if(GPS_enabled == false)\n startGps();\n tries = 0;\n do\n {\n Serial.println(\"In do-while loop\");\n localize();\n ++tries;\n }while(gps_data[cache_gps].num_satelites < 4 && tries < 16);\n Serial.println(\"Out of do-while loop\");\n Serial.print(\"attempts= \");\n Serial.println(tries);\n if(tries < 16 )\n {\n submitToServer();\n updateTimeInterval();\n if (Wifi_enabled)\n {\n \/\/ submit localization to WI-FI module\n this->serve_on_wifi();\n }\n \/\/ increase cache_gps\n cache_gps = (cache_gps+1) % CACHE_COUNT;\n }\n lastRun = millis();\n if (time_interval > 32000)\n stopGps();\n delay(time_interval);\n }\n}\n\nbool GPSTracker::haveWeMoved() const\n{\n double longi=0.0f, lati=0.0f;\n for (int i = 0; i < CACHE_COUNT; ++i)\n {\n longi += gps_data[i].longitude;\n lati += gps_data[i].latitude;\n }\n longi \/= CACHE_COUNT;\n lati \/= CACHE_COUNT;\n if( abs(longi - gps_data[cache_gps].longitude) + \n abs(lati - gps_data[cache_gps].latitude) < MOVEMENT_TRESHHOLD)\n return false;\n return true;\n}\n\nvoid GPSTracker::serve_on_wifi() const\n{\n LWiFi.begin();\n LWiFi.connect(\"GPS_Tracker\");\n LWiFiClient client;\n client.connect(\"server\", 80);\n \n char buff[256];\n sprintf(buff, \"%.6f\", gps_data[cache_gps].latitude);\n client.print(buff);\n client.print(\" \");\n sprintf(buff, \"%.6f\", gps_data[cache_gps].longitude);\n client.print(buff);\n client.println();\n\n LWiFi.end();\n}\r\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010 MQWeb - Franky Braem\n *\n * Licensed under the EUPL, Version 1.1 or – as soon they\n * will be approved by the European Commission - subsequent\n * versions of the EUPL (the \"Licence\");\n * You may not use this work except in compliance with the\n * Licence.\n * You may obtain a copy of the Licence at:\n *\n * http:\/\/joinup.ec.europa.eu\/software\/page\/eupl\n *\n * Unless required by applicable law or agreed to in\n * writing, software distributed under the Licence is\n * distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied.\n * See the Licence for the specific language governing\n * permissions and limitations under the Licence.\n *\/\n#include \/\/ For memcpy\n#include \n\n#include \"Poco\/DateTimeParser.h\"\n#include \"MQ\/PCF.h\"\n\nnamespace MQ\n{\n\nPCF::PCF(bool zos)\n\t: Message()\n\t, _zos(zos)\n{\n}\n\n\nPCF::PCF(int cmd, bool zos)\n\t: Message()\n\t, _zos(zos)\n{\n\tsetFormat(MQFMT_ADMIN);\n\tsetType(MQMT_REQUEST);\n\tsetPersistence(MQPER_NOT_PERSISTENT);\n\tbuffer().resize(MQCFH_STRUC_LENGTH);\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &buffer()[0];\n\theader->StrucLength = MQCFH_STRUC_LENGTH;\n\tif ( _zos )\n\t{\n\t\theader->Type = MQCFT_COMMAND_XR;\n\t\theader->Version = MQCFH_VERSION_3;\n\t}\n\telse\n\t{\n\t\theader->Type = (MQLONG) MQCFT_COMMAND;\n\t\theader->Version = MQCFH_VERSION_1;\n\t}\n\theader->Command = cmd;\n\theader->MsgSeqNumber = MQCFC_LAST;\n\theader->Control = MQCFC_LAST;\n\theader->ParameterCount = 0;\n}\n\n\nPCF::~PCF()\n{\n}\n\n\nvoid PCF::init()\n{\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);\n\tint pos = MQCFH_STRUC_LENGTH;\n\tfor(int i = 0; i < header->ParameterCount; i++)\n\t{\n\t\tMQLONG *pcfType = (MQLONG*) &buffer()[pos];\n\t\t_pointers[pcfType[2]] = pos;\n\t\tpos += pcfType[1];\n\t}\n}\n\n\nstd::string PCF::getParameterString(MQLONG parameter) const\n{\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_STRING )\n\t{\n\t\tMQCFST* pcfParam = (MQCFST*) &buffer()[it->second];\n\t\tstd::string result(pcfParam->String, pcfParam->StringLength);\n\t\treturn Poco::trimRightInPlace(result);\n\t}\n\telse if ( *pcfType == MQCFT_BYTE_STRING )\n\t{\n\t\tMQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];\n\t\treturn Message::getBufferAsHex(pcfParam->String, pcfParam->StringLength);\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nBufferPtr PCF::getParameterByteString(MQLONG parameter) const\n{\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_BYTE_STRING )\n\t{\n\t\tMQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];\n\t\treturn new Buffer(pcfParam->String, pcfParam->StringLength);\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nstd::string PCF::optParameterString(MQLONG parameter, const std::string& def) const\n{\n\tstd::string result = def;\n\n\ttry\n\t{\n\t\tresult = getParameterString(parameter);\n\t}\n\tcatch(...)\n\t{\n\t}\n\n\treturn result;\n}\n\nPoco::DateTime PCF::getParameterDate(MQLONG dateParameter, MQLONG timeParameter) const\n{\n\tstd::string dateValue = getParameterString(dateParameter);\n\tPoco::trimRightInPlace(dateValue);\n\tstd::string timeValue = getParameterString(timeParameter);\n\tPoco::trimRightInPlace(timeValue);\n\tdateValue += timeValue;\n\tif ( ! dateValue.empty() )\n\t{\n\t\tPoco::DateTime dateTime;\n\t\tint timeZone;\n\t\tPoco::DateTimeParser::parse(\"%Y%n%e%H%M%S\", dateValue, dateTime, timeZone);\n\t\treturn dateTime;\n\t}\n\treturn Poco::DateTime();\n}\n\n\nMQLONG PCF::getParameterNum(MQLONG parameter) const\n{\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_INTEGER )\n\t{\n\t\tMQCFIN* pcfParam = (MQCFIN*) &buffer()[it->second];\n\t\treturn pcfParam->Value;\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nstd::vector PCF::getParameterNumList(MQLONG parameter) const\n{\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_INTEGER_LIST )\n\t{\n\t\tstd::vector list;\n\t\tMQCFIL* pcfParam = (MQCFIL*) &buffer()[it->second];\n\t\tfor(int i = 0; i < pcfParam->Count; ++i)\n\t\t{\n\t\t\tlist.push_back(pcfParam->Values[i]);\n\t\t}\n\t\treturn list;\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nstd::vector PCF::getParameterStringList(MQLONG parameter) const\n{\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_STRING_LIST )\n\t{\n\t\tstd::vector list;\n\t\tMQCFSL* pcfParam = (MQCFSL*) &buffer()[it->second];\n\t\tfor(int i = 0; i < pcfParam->Count; ++i)\n\t\t{\n\t\t\tstd::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength);\n\t\t\tPoco::trimRightInPlace(result);\n\t\t\tlist.push_back(result);\n\t\t}\n\t\treturn list;\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nMQLONG PCF::optParameterNum(MQLONG parameter, MQLONG def) const\n{\n\tMQLONG result = def;\n\ttry\n\t{\n\t\tresult = getParameterNum(parameter);\n\t}\n\tcatch(...)\n\t{\n\t}\n\treturn result;\n}\n\n\nvoid PCF::addParameter(MQLONG parameter, const std::string& value)\n{\n\tMQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value.length()) \/ 4 + 1) * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + structLength);\n\tMQCFST* pcfParam = (MQCFST*) &buffer()[_pointers[parameter]];\n\tpcfParam->Type = MQCFT_STRING;\n\tpcfParam->StrucLength = structLength;\n\tpcfParam->Parameter = parameter;\n\tpcfParam->CodedCharSetId = MQCCSI_DEFAULT;\n\tpcfParam->StringLength = value.length();\n\tmemcpy(pcfParam->String, value.c_str(), pcfParam->StringLength);\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nvoid PCF::addParameter(MQLONG parameter, MQLONG value)\n{\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + MQCFIN_STRUC_LENGTH);\n\tMQCFIN* pcfParam = (MQCFIN*) &buffer()[_pointers[parameter]];\n\tpcfParam->Type = MQCFT_INTEGER;\n\tpcfParam->StrucLength = MQCFIN_STRUC_LENGTH;\n\tpcfParam->Parameter = parameter;\n\tpcfParam->Value = value;\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\nvoid PCF::addParameter(MQLONG parameter, BufferPtr value)\n{\n\tMQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value->sizeBytes()) \/ 4 + 1) * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + structLength);\n\tMQCFBS* pcfParam = (MQCFBS*) &buffer()[_pointers[parameter]];\n\tpcfParam->Type = MQCFT_BYTE_STRING;\n\tpcfParam->StrucLength = structLength;\n\tpcfParam->Parameter = parameter;\n\tpcfParam->StringLength = value->sizeBytes();\n\tmemcpy(pcfParam->String, value->begin(), pcfParam->StringLength);\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\nvoid PCF::addParameterList(MQLONG parameter, MQLONG *values)\n{\n\tint count = (sizeof values \/ sizeof values[0]);\n\tint strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + strucLength);\n\tMQCFIL *pcfIntegerList = (MQCFIL *) &buffer()[_pointers[parameter]];\n\tpcfIntegerList->Count = count;\n\tpcfIntegerList->Type = MQCFT_INTEGER_LIST;\n\tpcfIntegerList->StrucLength = strucLength;\n\tpcfIntegerList->Parameter = parameter;\n\tpcfIntegerList->Values[0] = *values;\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nvoid PCF::addFilter(MQLONG parameter, MQLONG op, const std::string& value)\n{\n\tMQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + value.length()) \/ 4 + 1) * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + strucLength);\n\tMQCFSF* pcfFilter = (MQCFSF*) &buffer()[_pointers[parameter]];\n\tpcfFilter->Type = MQCFT_STRING_FILTER;\n\tpcfFilter->StrucLength = strucLength;\n\tpcfFilter->Parameter = parameter;\n\tpcfFilter->Operator = op;\n\tpcfFilter->CodedCharSetId = MQCCSI_DEFAULT;\n\tpcfFilter->FilterValueLength = value.length();\n\tmemcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength);\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nvoid PCF::addFilter(MQLONG parameter, MQLONG op, MQLONG value)\n{\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + MQCFIF_STRUC_LENGTH);\n\tMQCFIF* pcfFilter = (MQCFIF*) &buffer()[_pointers[parameter]];\n\tpcfFilter->Type = MQCFT_INTEGER_FILTER;\n\tpcfFilter->StrucLength = MQCFIF_STRUC_LENGTH;\n\tpcfFilter->Parameter = parameter;\n\tpcfFilter->Operator = op;\n\tpcfFilter->FilterValue = value;\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nstd::vector PCF::getParameters() const\n{\n\tstd::vector parameters;\n\tfor(std::map::const_iterator it = _pointers.begin(); it != _pointers.end(); it++)\n\t{\n\t\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\t\tparameters.push_back(pcfType[2]);\n\t}\n\treturn parameters;\n}\n\n} \/\/ Namespace MQ\nAdd count argument to addParameterList\/*\n * Copyright 2010 MQWeb - Franky Braem\n *\n * Licensed under the EUPL, Version 1.1 or – as soon they\n * will be approved by the European Commission - subsequent\n * versions of the EUPL (the \"Licence\");\n * You may not use this work except in compliance with the\n * Licence.\n * You may obtain a copy of the Licence at:\n *\n * http:\/\/joinup.ec.europa.eu\/software\/page\/eupl\n *\n * Unless required by applicable law or agreed to in\n * writing, software distributed under the Licence is\n * distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied.\n * See the Licence for the specific language governing\n * permissions and limitations under the Licence.\n *\/\n#include \/\/ For memcpy\n#include \n\n#include \"Poco\/DateTimeParser.h\"\n#include \"MQ\/PCF.h\"\n\nnamespace MQ\n{\n\nPCF::PCF(bool zos)\n\t: Message()\n\t, _zos(zos)\n{\n}\n\n\nPCF::PCF(int cmd, bool zos)\n\t: Message()\n\t, _zos(zos)\n{\n\tsetFormat(MQFMT_ADMIN);\n\tsetType(MQMT_REQUEST);\n\tsetPersistence(MQPER_NOT_PERSISTENT);\n\tbuffer().resize(MQCFH_STRUC_LENGTH);\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &buffer()[0];\n\theader->StrucLength = MQCFH_STRUC_LENGTH;\n\tif ( _zos )\n\t{\n\t\theader->Type = MQCFT_COMMAND_XR;\n\t\theader->Version = MQCFH_VERSION_3;\n\t}\n\telse\n\t{\n\t\theader->Type = (MQLONG) MQCFT_COMMAND;\n\t\theader->Version = MQCFH_VERSION_1;\n\t}\n\theader->Command = cmd;\n\theader->MsgSeqNumber = MQCFC_LAST;\n\theader->Control = MQCFC_LAST;\n\theader->ParameterCount = 0;\n}\n\n\nPCF::~PCF()\n{\n}\n\n\nvoid PCF::init()\n{\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);\n\tint pos = MQCFH_STRUC_LENGTH;\n\tfor(int i = 0; i < header->ParameterCount; i++)\n\t{\n\t\tMQLONG *pcfType = (MQLONG*) &buffer()[pos];\n\t\t_pointers[pcfType[2]] = pos;\n\t\tpos += pcfType[1];\n\t}\n}\n\n\nstd::string PCF::getParameterString(MQLONG parameter) const\n{\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_STRING )\n\t{\n\t\tMQCFST* pcfParam = (MQCFST*) &buffer()[it->second];\n\t\tstd::string result(pcfParam->String, pcfParam->StringLength);\n\t\treturn Poco::trimRightInPlace(result);\n\t}\n\telse if ( *pcfType == MQCFT_BYTE_STRING )\n\t{\n\t\tMQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];\n\t\treturn Message::getBufferAsHex(pcfParam->String, pcfParam->StringLength);\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nBufferPtr PCF::getParameterByteString(MQLONG parameter) const\n{\n\tMQCFH* header = (MQCFH*)(MQBYTE*) &(buffer()[0]);\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_BYTE_STRING )\n\t{\n\t\tMQCFBS* pcfParam = (MQCFBS*) &buffer()[it->second];\n\t\treturn new Buffer(pcfParam->String, pcfParam->StringLength);\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nstd::string PCF::optParameterString(MQLONG parameter, const std::string& def) const\n{\n\tstd::string result = def;\n\n\ttry\n\t{\n\t\tresult = getParameterString(parameter);\n\t}\n\tcatch(...)\n\t{\n\t}\n\n\treturn result;\n}\n\nPoco::DateTime PCF::getParameterDate(MQLONG dateParameter, MQLONG timeParameter) const\n{\n\tstd::string dateValue = getParameterString(dateParameter);\n\tPoco::trimRightInPlace(dateValue);\n\tstd::string timeValue = getParameterString(timeParameter);\n\tPoco::trimRightInPlace(timeValue);\n\tdateValue += timeValue;\n\tif ( ! dateValue.empty() )\n\t{\n\t\tPoco::DateTime dateTime;\n\t\tint timeZone;\n\t\tPoco::DateTimeParser::parse(\"%Y%n%e%H%M%S\", dateValue, dateTime, timeZone);\n\t\treturn dateTime;\n\t}\n\treturn Poco::DateTime();\n}\n\n\nMQLONG PCF::getParameterNum(MQLONG parameter) const\n{\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_INTEGER )\n\t{\n\t\tMQCFIN* pcfParam = (MQCFIN*) &buffer()[it->second];\n\t\treturn pcfParam->Value;\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nstd::vector PCF::getParameterNumList(MQLONG parameter) const\n{\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_INTEGER_LIST )\n\t{\n\t\tstd::vector list;\n\t\tMQCFIL* pcfParam = (MQCFIL*) &buffer()[it->second];\n\t\tfor(int i = 0; i < pcfParam->Count; ++i)\n\t\t{\n\t\t\tlist.push_back(pcfParam->Values[i]);\n\t\t}\n\t\treturn list;\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nstd::vector PCF::getParameterStringList(MQLONG parameter) const\n{\n\tstd::map::const_iterator it = _pointers.find(parameter);\n\tif ( it == _pointers.end() )\n\t\tthrow Poco::NotFoundException(parameter);\n\n\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\tif ( *pcfType == MQCFT_STRING_LIST )\n\t{\n\t\tstd::vector list;\n\t\tMQCFSL* pcfParam = (MQCFSL*) &buffer()[it->second];\n\t\tfor(int i = 0; i < pcfParam->Count; ++i)\n\t\t{\n\t\t\tstd::string result(pcfParam->Strings, i * pcfParam->StringLength, pcfParam->StringLength);\n\t\t\tPoco::trimRightInPlace(result);\n\t\t\tlist.push_back(result);\n\t\t}\n\t\treturn list;\n\t}\n\n\tthrow Poco::BadCastException(parameter);\n}\n\nMQLONG PCF::optParameterNum(MQLONG parameter, MQLONG def) const\n{\n\tMQLONG result = def;\n\ttry\n\t{\n\t\tresult = getParameterNum(parameter);\n\t}\n\tcatch(...)\n\t{\n\t}\n\treturn result;\n}\n\n\nvoid PCF::addParameter(MQLONG parameter, const std::string& value)\n{\n\tMQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value.length()) \/ 4 + 1) * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + structLength);\n\tMQCFST* pcfParam = (MQCFST*) &buffer()[_pointers[parameter]];\n\tpcfParam->Type = MQCFT_STRING;\n\tpcfParam->StrucLength = structLength;\n\tpcfParam->Parameter = parameter;\n\tpcfParam->CodedCharSetId = MQCCSI_DEFAULT;\n\tpcfParam->StringLength = value.length();\n\tmemcpy(pcfParam->String, value.c_str(), pcfParam->StringLength);\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nvoid PCF::addParameter(MQLONG parameter, MQLONG value)\n{\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + MQCFIN_STRUC_LENGTH);\n\tMQCFIN* pcfParam = (MQCFIN*) &buffer()[_pointers[parameter]];\n\tpcfParam->Type = MQCFT_INTEGER;\n\tpcfParam->StrucLength = MQCFIN_STRUC_LENGTH;\n\tpcfParam->Parameter = parameter;\n\tpcfParam->Value = value;\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\nvoid PCF::addParameter(MQLONG parameter, BufferPtr value)\n{\n\tMQLONG structLength = ((MQCFST_STRUC_LENGTH_FIXED + value->sizeBytes()) \/ 4 + 1) * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + structLength);\n\tMQCFBS* pcfParam = (MQCFBS*) &buffer()[_pointers[parameter]];\n\tpcfParam->Type = MQCFT_BYTE_STRING;\n\tpcfParam->StrucLength = structLength;\n\tpcfParam->Parameter = parameter;\n\tpcfParam->StringLength = value->sizeBytes();\n\tmemcpy(pcfParam->String, value->begin(), pcfParam->StringLength);\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\nvoid PCF::addParameterList(MQLONG parameter, MQLONG *values, unsigned int count)\n{\n\tint strucLength = MQCFIL_STRUC_LENGTH_FIXED + count * sizeof(MQLONG);\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + strucLength);\n\tMQCFIL *pcfIntegerList = (MQCFIL *) &buffer()[_pointers[parameter]];\n\tpcfIntegerList->Count = count;\n\tpcfIntegerList->Type = MQCFT_INTEGER_LIST;\n\tpcfIntegerList->StrucLength = strucLength;\n\tpcfIntegerList->Parameter = parameter;\n\tfor(int i = 0; i < count; ++i) pcfIntegerList->Values[i] = values[i];\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nvoid PCF::addFilter(MQLONG parameter, MQLONG op, const std::string& value)\n{\n\tMQLONG strucLength = ((MQCFSF_STRUC_LENGTH_FIXED + value.length()) \/ 4 + 1) * 4;\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + strucLength);\n\tMQCFSF* pcfFilter = (MQCFSF*) &buffer()[_pointers[parameter]];\n\tpcfFilter->Type = MQCFT_STRING_FILTER;\n\tpcfFilter->StrucLength = strucLength;\n\tpcfFilter->Parameter = parameter;\n\tpcfFilter->Operator = op;\n\tpcfFilter->CodedCharSetId = MQCCSI_DEFAULT;\n\tpcfFilter->FilterValueLength = value.length();\n\tmemcpy(pcfFilter->FilterValue, value.c_str(), pcfFilter->FilterValueLength);\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nvoid PCF::addFilter(MQLONG parameter, MQLONG op, MQLONG value)\n{\n\t_pointers[parameter] = buffer().size();\n\tbuffer().resize(buffer().size() + MQCFIF_STRUC_LENGTH);\n\tMQCFIF* pcfFilter = (MQCFIF*) &buffer()[_pointers[parameter]];\n\tpcfFilter->Type = MQCFT_INTEGER_FILTER;\n\tpcfFilter->StrucLength = MQCFIF_STRUC_LENGTH;\n\tpcfFilter->Parameter = parameter;\n\tpcfFilter->Operator = op;\n\tpcfFilter->FilterValue = value;\n\tMQCFH* header = (MQCFH*) (MQBYTE*) &buffer()[0];\n\theader->ParameterCount++;\n}\n\n\nstd::vector PCF::getParameters() const\n{\n\tstd::vector parameters;\n\tfor(std::map::const_iterator it = _pointers.begin(); it != _pointers.end(); it++)\n\t{\n\t\tMQLONG *pcfType = (MQLONG*) &buffer()[it->second];\n\t\tparameters.push_back(pcfType[2]);\n\t}\n\treturn parameters;\n}\n\n} \/\/ Namespace MQ\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtOpenGL module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qtriangulatingstroker_p.h\"\n#include \n\nQT_BEGIN_NAMESPACE\n\n#define CURVE_FLATNESS Q_PI \/ 8\n\n\n\n\nvoid QTriangulatingStroker::endCapOrJoinClosed(const qreal *start, const qreal *cur,\n bool implicitClose, bool endsAtStart)\n{\n if (endsAtStart) {\n join(start + 2);\n } else if (implicitClose) {\n join(start);\n lineTo(start);\n join(start+2);\n } else {\n endCap(cur);\n }\n int count = m_vertices.size();\n m_vertices.add(m_vertices.at(count-2));\n m_vertices.add(m_vertices.at(count-1));\n}\n\n\nvoid QTriangulatingStroker::process(const QVectorPath &path, const QPen &pen)\n{\n const qreal *pts = path.points();\n const QPainterPath::ElementType *types = path.elements();\n int count = path.elementCount();\n if (count < 2)\n return;\n\n float realWidth = qpen_widthf(pen);\n if (realWidth == 0)\n realWidth = 1;\n\n m_width = realWidth \/ 2;\n\n bool cosmetic = pen.isCosmetic();\n if (cosmetic) {\n m_width = m_width * m_inv_scale;\n }\n\n m_join_style = qpen_joinStyle(pen);\n m_cap_style = qpen_capStyle(pen);\n m_vertices.reset();\n m_miter_limit = pen.miterLimit() * qpen_widthf(pen);\n\n \/\/ The curvyness is based on the notion that I originally wanted\n \/\/ roughly one line segment pr 4 pixels. This may seem little, but\n \/\/ because we sample at constantly incrementing B(t) E [0(4, realWidth * CURVE_FLATNESS);\n } else {\n m_curvyness_add = m_width;\n m_curvyness_mul = CURVE_FLATNESS \/ m_inv_scale;\n m_roundness = qMax(4, realWidth * m_curvyness_mul);\n }\n\n \/\/ Over this level of segmentation, there doesn't seem to be any\n \/\/ benefit, even for huge penWidth\n if (m_roundness > 24)\n m_roundness = 24;\n\n m_sin_theta = qFastSin(Q_PI \/ m_roundness);\n m_cos_theta = qFastCos(Q_PI \/ m_roundness);\n\n const qreal *endPts = pts + (count<<1);\n const qreal *startPts;\n\n Qt::PenCapStyle cap = m_cap_style;\n\n if (!types) {\n startPts = pts;\n\n bool endsAtStart = startPts[0] == *(endPts-2) && startPts[1] == *(endPts-1);\n\n Qt::PenCapStyle cap = m_cap_style;\n if (endsAtStart || path.hasImplicitClose())\n m_cap_style = Qt::FlatCap;\n moveTo(pts);\n m_cap_style = cap;\n pts += 2;\n lineTo(pts);\n pts += 2;\n while (pts < endPts) {\n join(pts);\n lineTo(pts);\n pts += 2;\n }\n\n endCapOrJoinClosed(startPts, pts-2, path.hasImplicitClose(), endsAtStart);\n\n } else {\n bool endsAtStart;\n while (pts < endPts) {\n switch (*types) {\n case QPainterPath::MoveToElement: {\n if (pts != path.points())\n endCapOrJoinClosed(startPts, pts, path.hasImplicitClose(), endsAtStart);\n\n startPts = pts;\n int end = (endPts - pts) \/ 2;\n int i = 2; \/\/ Start looking to ahead since we never have two moveto's in a row\n while (i(64, (rad + m_curvyness_add) * m_curvyness_mul);\n if (threshold < 4)\n threshold = 4;\n qreal threshold_minus_1 = threshold - 1;\n float vx, vy;\n\n float cx = m_cx, cy = m_cy;\n float x, y;\n\n for (int i=1; iaddElement(QPainterPath::MoveToElement, x, y);\n}\n\nstatic void qdashprocessor_lineTo(qreal x, qreal y, void *data)\n{\n ((QDashedStrokeProcessor *) data)->addElement(QPainterPath::LineToElement, x, y);\n}\n\nstatic void qdashprocessor_cubicTo(qreal, qreal, qreal, qreal, qreal, qreal, void *)\n{\n Q_ASSERT(0); \/\/ The dasher should not produce curves...\n}\n\nQDashedStrokeProcessor::QDashedStrokeProcessor()\n : m_dash_stroker(0), m_inv_scale(1)\n{\n m_dash_stroker.setMoveToHook(qdashprocessor_moveTo);\n m_dash_stroker.setLineToHook(qdashprocessor_lineTo);\n m_dash_stroker.setCubicToHook(qdashprocessor_cubicTo);\n}\n\nvoid QDashedStrokeProcessor::process(const QVectorPath &path, const QPen &pen)\n{\n\n const qreal *pts = path.points();\n const QPainterPath::ElementType *types = path.elements();\n int count = path.elementCount();\n\n m_points.reset();\n m_types.reset();\n\n qreal width = pen.width();\n if (width == 0)\n width = 1;\n\n m_dash_stroker.setDashPattern(pen.dashPattern());\n m_dash_stroker.setStrokeWidth(width);\n m_dash_stroker.setMiterLimit(pen.miterLimit());\n qreal curvyness = sqrt(width) * m_inv_scale \/ 8;\n\n if (count < 2)\n return;\n\n const qreal *endPts = pts + (count<<1);\n\n m_dash_stroker.begin(this);\n\n if (!types) {\n m_dash_stroker.moveTo(pts[0], pts[1]);\n pts += 2;\n while (pts < endPts) {\n m_dash_stroker.lineTo(pts[0], pts[1]);\n pts += 2;\n }\n } else {\n while (pts < endPts) {\n switch (*types) {\n case QPainterPath::MoveToElement:\n m_dash_stroker.moveTo(pts[0], pts[1]);\n pts += 2;\n ++types;\n break;\n case QPainterPath::LineToElement:\n m_dash_stroker.lineTo(pts[0], pts[1]);\n pts += 2;\n ++types;\n break;\n case QPainterPath::CurveToElement: {\n QBezier b = QBezier::fromPoints(*(((const QPointF *) pts) - 1),\n *(((const QPointF *) pts)),\n *(((const QPointF *) pts) + 1),\n *(((const QPointF *) pts) + 2));\n QRectF bounds = b.bounds();\n int threshold = qMin(64, qMax(bounds.width(), bounds.height()) * curvyness);\n if (threshold < 4)\n threshold = 4;\n qreal threshold_minus_1 = threshold - 1;\n for (int i=0; iFixed stroking of cosmetic dashed pens with the GL2 paint engine.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtOpenGL module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qtriangulatingstroker_p.h\"\n#include \n\nQT_BEGIN_NAMESPACE\n\n#define CURVE_FLATNESS Q_PI \/ 8\n\n\n\n\nvoid QTriangulatingStroker::endCapOrJoinClosed(const qreal *start, const qreal *cur,\n bool implicitClose, bool endsAtStart)\n{\n if (endsAtStart) {\n join(start + 2);\n } else if (implicitClose) {\n join(start);\n lineTo(start);\n join(start+2);\n } else {\n endCap(cur);\n }\n int count = m_vertices.size();\n m_vertices.add(m_vertices.at(count-2));\n m_vertices.add(m_vertices.at(count-1));\n}\n\n\nvoid QTriangulatingStroker::process(const QVectorPath &path, const QPen &pen)\n{\n const qreal *pts = path.points();\n const QPainterPath::ElementType *types = path.elements();\n int count = path.elementCount();\n if (count < 2)\n return;\n\n float realWidth = qpen_widthf(pen);\n if (realWidth == 0)\n realWidth = 1;\n\n m_width = realWidth \/ 2;\n\n bool cosmetic = pen.isCosmetic();\n if (cosmetic) {\n m_width = m_width * m_inv_scale;\n }\n\n m_join_style = qpen_joinStyle(pen);\n m_cap_style = qpen_capStyle(pen);\n m_vertices.reset();\n m_miter_limit = pen.miterLimit() * qpen_widthf(pen);\n\n \/\/ The curvyness is based on the notion that I originally wanted\n \/\/ roughly one line segment pr 4 pixels. This may seem little, but\n \/\/ because we sample at constantly incrementing B(t) E [0(4, realWidth * CURVE_FLATNESS);\n } else {\n m_curvyness_add = m_width;\n m_curvyness_mul = CURVE_FLATNESS \/ m_inv_scale;\n m_roundness = qMax(4, realWidth * m_curvyness_mul);\n }\n\n \/\/ Over this level of segmentation, there doesn't seem to be any\n \/\/ benefit, even for huge penWidth\n if (m_roundness > 24)\n m_roundness = 24;\n\n m_sin_theta = qFastSin(Q_PI \/ m_roundness);\n m_cos_theta = qFastCos(Q_PI \/ m_roundness);\n\n const qreal *endPts = pts + (count<<1);\n const qreal *startPts;\n\n Qt::PenCapStyle cap = m_cap_style;\n\n if (!types) {\n startPts = pts;\n\n bool endsAtStart = startPts[0] == *(endPts-2) && startPts[1] == *(endPts-1);\n\n if (endsAtStart || path.hasImplicitClose())\n m_cap_style = Qt::FlatCap;\n moveTo(pts);\n m_cap_style = cap;\n pts += 2;\n lineTo(pts);\n pts += 2;\n while (pts < endPts) {\n join(pts);\n lineTo(pts);\n pts += 2;\n }\n\n endCapOrJoinClosed(startPts, pts-2, path.hasImplicitClose(), endsAtStart);\n\n } else {\n bool endsAtStart;\n while (pts < endPts) {\n switch (*types) {\n case QPainterPath::MoveToElement: {\n if (pts != path.points())\n endCapOrJoinClosed(startPts, pts-2, path.hasImplicitClose(), endsAtStart);\n\n startPts = pts;\n int end = (endPts - pts) \/ 2;\n int i = 2; \/\/ Start looking to ahead since we never have two moveto's in a row\n while (i(64, (rad + m_curvyness_add) * m_curvyness_mul);\n if (threshold < 4)\n threshold = 4;\n qreal threshold_minus_1 = threshold - 1;\n float vx, vy;\n\n float cx = m_cx, cy = m_cy;\n float x, y;\n\n for (int i=1; iaddElement(QPainterPath::MoveToElement, x, y);\n}\n\nstatic void qdashprocessor_lineTo(qreal x, qreal y, void *data)\n{\n ((QDashedStrokeProcessor *) data)->addElement(QPainterPath::LineToElement, x, y);\n}\n\nstatic void qdashprocessor_cubicTo(qreal, qreal, qreal, qreal, qreal, qreal, void *)\n{\n Q_ASSERT(0); \/\/ The dasher should not produce curves...\n}\n\nQDashedStrokeProcessor::QDashedStrokeProcessor()\n : m_dash_stroker(0), m_inv_scale(1)\n{\n m_dash_stroker.setMoveToHook(qdashprocessor_moveTo);\n m_dash_stroker.setLineToHook(qdashprocessor_lineTo);\n m_dash_stroker.setCubicToHook(qdashprocessor_cubicTo);\n}\n\nvoid QDashedStrokeProcessor::process(const QVectorPath &path, const QPen &pen)\n{\n\n const qreal *pts = path.points();\n const QPainterPath::ElementType *types = path.elements();\n int count = path.elementCount();\n\n m_points.reset();\n m_types.reset();\n\n qreal width = qpen_widthf(pen);\n if (width == 0)\n width = 1;\n\n m_dash_stroker.setDashPattern(pen.dashPattern());\n m_dash_stroker.setStrokeWidth(pen.isCosmetic() ? width * m_inv_scale : width);\n m_dash_stroker.setMiterLimit(pen.miterLimit());\n qreal curvyness = sqrt(width) * m_inv_scale \/ 8;\n\n if (count < 2)\n return;\n\n const qreal *endPts = pts + (count<<1);\n\n m_dash_stroker.begin(this);\n\n if (!types) {\n m_dash_stroker.moveTo(pts[0], pts[1]);\n pts += 2;\n while (pts < endPts) {\n m_dash_stroker.lineTo(pts[0], pts[1]);\n pts += 2;\n }\n } else {\n while (pts < endPts) {\n switch (*types) {\n case QPainterPath::MoveToElement:\n m_dash_stroker.moveTo(pts[0], pts[1]);\n pts += 2;\n ++types;\n break;\n case QPainterPath::LineToElement:\n m_dash_stroker.lineTo(pts[0], pts[1]);\n pts += 2;\n ++types;\n break;\n case QPainterPath::CurveToElement: {\n QBezier b = QBezier::fromPoints(*(((const QPointF *) pts) - 1),\n *(((const QPointF *) pts)),\n *(((const QPointF *) pts) + 1),\n *(((const QPointF *) pts) + 2));\n QRectF bounds = b.bounds();\n int threshold = qMin(64, qMax(bounds.width(), bounds.height()) * curvyness);\n if (threshold < 4)\n threshold = 4;\n qreal threshold_minus_1 = threshold - 1;\n for (int i=0; i"} {"text":"#pragma once\n\n#include \"WebUpdates.hpp\"\n#include \"ClientWrapper.hpp\"\n#include \"html5viewer\/html5viewer.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\/\/#include \n\nQT_BEGIN_NAMESPACE\nclass QWebEngineView;\nclass QLineEdit;\nQT_END_NAMESPACE\n\nclass MainWindow : public QMainWindow\n{\n Q_OBJECT\n QSettings _settings;\n QMenu* _fileMenu;\n QMenu* _accountMenu;\n QString _deferredUrl;\n\n \/\/Temporary storage for a web update description being considered for application.\n \/\/Do not trust this as the in-use web update.\n WebUpdateManifest::UpdateDetails _webUpdateDescription;\n \/\/Version information for the running client and GUI. These values may be trusted\n \/\/as accurate regarding the web update currently being shown to the user.\n uint8_t _majorVersion = 0;\n uint8_t _forkVersion = 0;\n uint8_t _minorVersion = 0;\n uint8_t _patchVersion = 0;\n\n QTimer* _updateChecker;\n QUuid app_id;\n QString version;\n\n public:\n MainWindow();\n QMenu* fileMenu() { return _fileMenu; }\n QMenu* accountMenu() { return _accountMenu; }\n\n bool eventFilter(QObject* object, QEvent* event);\n\n ClientWrapper *clientWrapper() const;\n void setClientWrapper(ClientWrapper* clientWrapper);\n void navigateTo(const QString& path);\n\n bool detectCrash();\n QUuid getAppId() const { return app_id; }\n\npublic Q_SLOTS:\n void goToMyAccounts();\n void goToAccount(QString accountName);\n void goToCreateAccount();\n void goToAddContact();\n void checkWebUpdates(bool showNoUpdatesAlert = true,\n std::function finishedCheckCallback = std::function());\n void loadWebUpdates();\n\n \/\/Causes this window to attempt to become the front window on the desktop\n void takeFocus();\n void hideWindow();\n\n \/\/\/Used to schedule a custom URL for processing later, once the app has finished starting\n void deferCustomUrl(QString url);\n \/\/\/Triggers the deferred URL processign. Call once app has finished starting\n void processDeferredUrl();\n \/\/\/Used to process a custom URL now (only call if app has finished starting)\n void processCustomUrl(QString url);\n void goToBlock(uint32_t blockNumber);\n void goToBlock(QString blockId);\n void goToTransaction(QString transactionId);\n void importWallet();\n\nprivate Q_SLOTS:\n void removeWebUpdates();\n\nprivate:\n ClientWrapper* _clientWrapper;\n\n Html5Viewer* getViewer();\n bool walletIsUnlocked(bool promptToUnlock = true);\n std::string getLoginUser(const fc::ecc::public_key& serverKey);\n void doLogin(QStringList components);\n void goToTransfer(QStringList components);\n void readSettings();\n virtual void closeEvent( QCloseEvent* );\n void initMenu();\n void showNoUpdateAlert(QString info = tr(\"\"));\n bool verifyUpdateSignature(QByteArray updatePackage);\n void goToRefCode(QStringList components);\n};\nrevert unexpected deleted codes#pragma once\n\n#include \"WebUpdates.hpp\"\n#include \"ClientWrapper.hpp\"\n#include \"html5viewer\/html5viewer.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\/\/#include \n\nQT_BEGIN_NAMESPACE\nclass QWebEngineView;\nclass QLineEdit;\nQT_END_NAMESPACE\n\nclass MainWindow : public QMainWindow\n{\n Q_OBJECT\n QSettings _settings;\n QMenu* _fileMenu;\n QMenu* _accountMenu;\n QString _deferredUrl;\n\n QLineEdit *_locationEdit;\n QToolBar *_navToolBar;\n\n \/\/Temporary storage for a web update description being considered for application.\n \/\/Do not trust this as the in-use web update.\n WebUpdateManifest::UpdateDetails _webUpdateDescription;\n \/\/Version information for the running client and GUI. These values may be trusted\n \/\/as accurate regarding the web update currently being shown to the user.\n uint8_t _majorVersion = 0;\n uint8_t _forkVersion = 0;\n uint8_t _minorVersion = 0;\n uint8_t _patchVersion = 0;\n\n QTimer* _updateChecker;\n QUuid app_id;\n QString version;\n\n public:\n MainWindow();\n QMenu* fileMenu() { return _fileMenu; }\n QMenu* accountMenu() { return _accountMenu; }\n\n bool eventFilter(QObject* object, QEvent* event);\n\n ClientWrapper *clientWrapper() const;\n void setClientWrapper(ClientWrapper* clientWrapper);\n void navigateTo(const QString& path);\n\n bool detectCrash();\n QUuid getAppId() const { return app_id; }\n\npublic Q_SLOTS:\n void goToMyAccounts();\n void goToAccount(QString accountName);\n void goToCreateAccount();\n void goToAddContact();\n void checkWebUpdates(bool showNoUpdatesAlert = true,\n std::function finishedCheckCallback = std::function());\n void loadWebUpdates();\n\n \/\/Causes this window to attempt to become the front window on the desktop\n void takeFocus();\n void hideWindow();\n\n void setupNavToolbar(); \n void changeLocation(); \n void updateLocationEdit(const QUrl& newUrl);\n\n \/\/\/Used to schedule a custom URL for processing later, once the app has finished starting\n void deferCustomUrl(QString url);\n \/\/\/Triggers the deferred URL processign. Call once app has finished starting\n void processDeferredUrl();\n \/\/\/Used to process a custom URL now (only call if app has finished starting)\n void processCustomUrl(QString url);\n void goToBlock(uint32_t blockNumber);\n void goToBlock(QString blockId);\n void goToTransaction(QString transactionId);\n void importWallet();\n\nprivate Q_SLOTS:\n void removeWebUpdates();\n\nprivate:\n ClientWrapper* _clientWrapper;\n\n Html5Viewer* getViewer();\n bool walletIsUnlocked(bool promptToUnlock = true);\n std::string getLoginUser(const fc::ecc::public_key& serverKey);\n void doLogin(QStringList components);\n void goToTransfer(QStringList components);\n void readSettings();\n virtual void closeEvent( QCloseEvent* );\n void initMenu();\n void showNoUpdateAlert(QString info = tr(\"\"));\n bool verifyUpdateSignature(QByteArray updatePackage);\n void goToRefCode(QStringList components);\n};\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: xformsapi.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-11-16 10:15:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"xformsapi.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing rtl::OUString;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::Sequence;\nusing com::sun::star::uno::UNO_QUERY;\nusing com::sun::star::uno::UNO_QUERY_THROW;\nusing com::sun::star::beans::XPropertySet;\nusing com::sun::star::container::XNameAccess;\nusing com::sun::star::lang::XMultiServiceFactory;\nusing com::sun::star::xforms::XFormsSupplier;\nusing com::sun::star::xforms::XDataTypeRepository;\nusing com::sun::star::container::XNameContainer;\nusing utl::getProcessServiceFactory;\nusing com::sun::star::uno::makeAny;\nusing com::sun::star::uno::Any;\nusing com::sun::star::uno::Exception;\n\nusing namespace com::sun::star;\nusing namespace xmloff::token;\n\nReference lcl_createPropertySet( const OUString& rServiceName )\n{\n Reference xFactory = getProcessServiceFactory();\n DBG_ASSERT( xFactory.is(), \"can't get service factory\" );\n\n Reference xModel( xFactory->createInstance( rServiceName ),\n UNO_QUERY_THROW );\n DBG_ASSERT( xModel.is(), \"can't create model\" );\n\n return xModel;\n}\n\nReference lcl_createXFormsModel()\n{\n return lcl_createPropertySet( OUSTRING( \"com.sun.star.xforms.Model\" ) );\n}\n\nReference lcl_createXFormsBinding()\n{\n return lcl_createPropertySet( OUSTRING( \"com.sun.star.xforms.Binding\" ) );\n}\n\nvoid lcl_addXFormsModel(\n const Reference& xDocument,\n const Reference& xModel )\n{\n bool bSuccess = false;\n try\n {\n Reference xSupplier( xDocument, UNO_QUERY );\n if( xSupplier.is() )\n {\n Reference xForms = xSupplier->getXForms();\n if( xForms.is() )\n {\n OUString sName;\n xModel->getPropertyValue( OUSTRING(\"ID\")) >>= sName;\n xForms->insertByName( sName, makeAny( xModel ) );\n bSuccess = true;\n }\n }\n }\n catch( const Exception& )\n {\n ; \/\/ no success!\n }\n\n \/\/ TODO: implement proper error handling\n DBG_ASSERT( bSuccess, \"can't import model\" );\n}\n\nReference lcl_findXFormsBindingOrSubmission(\n Reference& xDocument,\n const rtl::OUString& rBindingID,\n bool bBinding )\n{\n \/\/ find binding by iterating over all models, and look for the\n \/\/ given binding ID\n\n Reference xRet;\n try\n {\n \/\/ get supplier\n Reference xSupplier( xDocument, UNO_QUERY );\n if( xSupplier.is() )\n {\n \/\/ get XForms models\n Reference xForms = xSupplier->getXForms();\n if( xForms.is() )\n {\n \/\/ iterate over all models\n Sequence aNames = xForms->getElementNames();\n const OUString* pNames = aNames.getConstArray();\n sal_Int32 nNames = aNames.getLength();\n for( sal_Int32 n = 0; (n < nNames) && !xRet.is(); n++ )\n {\n Reference xModel(\n xForms->getByName( pNames[n] ), UNO_QUERY );\n if( xModel.is() )\n {\n \/\/ ask model for bindings\n Reference xBindings(\n bBinding\n ? xModel->getBindings()\n : xModel->getSubmissions(),\n UNO_QUERY_THROW );\n\n \/\/ finally, ask binding for name\n if( xBindings->hasByName( rBindingID ) )\n xRet.set( xBindings->getByName( rBindingID ),\n UNO_QUERY );\n }\n }\n }\n }\n }\n catch( const Exception& )\n {\n ; \/\/ no success!\n }\n\n if( ! xRet.is() )\n ; \/\/ TODO: rImport.SetError(...);\n\n return xRet;\n}\n\nReference lcl_findXFormsBinding(\n Reference& xDocument,\n const rtl::OUString& rBindingID )\n{\n return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, true );\n}\n\nReference lcl_findXFormsSubmission(\n Reference& xDocument,\n const rtl::OUString& rBindingID )\n{\n return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, false );\n}\n\nvoid lcl_setValue( Reference& xPropertySet,\n const OUString& rName,\n const Any rAny )\n{\n xPropertySet->setPropertyValue( rName, rAny );\n}\n\n\nReference lcl_getXFormsModel( const Reference& xDoc )\n{\n Reference xRet;\n try\n {\n Reference xSupplier( xDoc, UNO_QUERY );\n if( xSupplier.is() )\n {\n Reference xForms = xSupplier->getXForms();\n if( xForms.is() )\n {\n Sequence aNames = xForms->getElementNames();\n if( aNames.getLength() > 0 )\n xRet.set( xForms->getByName( aNames[0] ), UNO_QUERY );\n }\n }\n }\n catch( const Exception& )\n {\n ; \/\/ no success!\n }\n\n return xRet;\n}\n\n#define TOKEN_MAP_ENTRY(NAMESPACE,TOKEN) { XML_NAMESPACE_##NAMESPACE, xmloff::token::XML_##TOKEN, xmloff::token::XML_##TOKEN }\nstatic SvXMLTokenMapEntry aTypes[] =\n{\n TOKEN_MAP_ENTRY( XSD, STRING ),\n TOKEN_MAP_ENTRY( XSD, DECIMAL ),\n TOKEN_MAP_ENTRY( XSD, DOUBLE ),\n TOKEN_MAP_ENTRY( XSD, FLOAT ),\n TOKEN_MAP_ENTRY( XSD, BOOLEAN ),\n TOKEN_MAP_ENTRY( XSD, ANYURI ),\n TOKEN_MAP_ENTRY( XSD, DATETIME_XSD ),\n XML_TOKEN_MAP_END\n};\n\nrtl::OUString lcl_getTypeName(\n const Reference& xRepository,\n const SvXMLNamespaceMap& rNamespaceMap,\n const OUString& rXMLName )\n{\n \/\/ translate name into token for local name\n OUString sLocalName;\n sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);\n SvXMLTokenMap aMap( aTypes );\n sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );\n\n OUString sTypeName = rXMLName;\n if( mnToken != XML_TOK_UNKNOWN )\n {\n \/\/ we found an XSD name: then get the proper API name for it\n DBG_ASSERT( xRepository.is(), \"can't find type without repository\");\n sal_uInt16 nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;\n switch( mnToken )\n {\n case XML_STRING:\n nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;\n break;\n case XML_ANYURI:\n nTypeClass = com::sun::star::xsd::DataTypeClass::anyURI;\n break;\n case XML_DECIMAL:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DECIMAL;\n break;\n case XML_DOUBLE:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DOUBLE;\n break;\n case XML_FLOAT:\n nTypeClass = com::sun::star::xsd::DataTypeClass::FLOAT;\n break;\n case XML_BOOLEAN:\n nTypeClass = com::sun::star::xsd::DataTypeClass::BOOLEAN;\n break;\n case XML_DATETIME_XSD:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DATETIME;\n break;\n\n \/* data types not yet supported:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DURATION;\n nTypeClass = com::sun::star::xsd::DataTypeClass::TIME;\n nTypeClass = com::sun::star::xsd::DataTypeClass::DATE;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gYearMonth;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gYear;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gMonthDay;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gDay;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gMonth;\n nTypeClass = com::sun::star::xsd::DataTypeClass::hexBinary;\n nTypeClass = com::sun::star::xsd::DataTypeClass::base64Binary;\n nTypeClass = com::sun::star::xsd::DataTypeClass::QName;\n nTypeClass = com::sun::star::xsd::DataTypeClass::NOTATION;\n *\/\n }\n\n try\n {\n sTypeName = xRepository->getBasicDataType(nTypeClass)->getName();\n }\n catch( const Exception& )\n {\n DBG_ERROR( \"exception during type creation\" );\n }\n }\n return sTypeName;\n}\nINTEGRATION: CWS eforms4 (1.2.22); FILE MERGED 2004\/12\/23 14:10:48 dvo 1.2.22.2: #i38666# load\/save date+time related data types Issue number: Submitted by: Reviewed by: 2004\/12\/08 16:25:26 fs 1.2.22.1: #i36359# #i36303# care for DataTypeClass::DATE\/TIME\/*************************************************************************\n *\n * $RCSfile: xformsapi.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 11:26:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"xformsapi.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing rtl::OUString;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::Sequence;\nusing com::sun::star::uno::UNO_QUERY;\nusing com::sun::star::uno::UNO_QUERY_THROW;\nusing com::sun::star::beans::XPropertySet;\nusing com::sun::star::container::XNameAccess;\nusing com::sun::star::lang::XMultiServiceFactory;\nusing com::sun::star::xforms::XFormsSupplier;\nusing com::sun::star::xforms::XDataTypeRepository;\nusing com::sun::star::container::XNameContainer;\nusing utl::getProcessServiceFactory;\nusing com::sun::star::uno::makeAny;\nusing com::sun::star::uno::Any;\nusing com::sun::star::uno::Exception;\n\nusing namespace com::sun::star;\nusing namespace xmloff::token;\n\nReference lcl_createPropertySet( const OUString& rServiceName )\n{\n Reference xFactory = getProcessServiceFactory();\n DBG_ASSERT( xFactory.is(), \"can't get service factory\" );\n\n Reference xModel( xFactory->createInstance( rServiceName ),\n UNO_QUERY_THROW );\n DBG_ASSERT( xModel.is(), \"can't create model\" );\n\n return xModel;\n}\n\nReference lcl_createXFormsModel()\n{\n return lcl_createPropertySet( OUSTRING( \"com.sun.star.xforms.Model\" ) );\n}\n\nReference lcl_createXFormsBinding()\n{\n return lcl_createPropertySet( OUSTRING( \"com.sun.star.xforms.Binding\" ) );\n}\n\nvoid lcl_addXFormsModel(\n const Reference& xDocument,\n const Reference& xModel )\n{\n bool bSuccess = false;\n try\n {\n Reference xSupplier( xDocument, UNO_QUERY );\n if( xSupplier.is() )\n {\n Reference xForms = xSupplier->getXForms();\n if( xForms.is() )\n {\n OUString sName;\n xModel->getPropertyValue( OUSTRING(\"ID\")) >>= sName;\n xForms->insertByName( sName, makeAny( xModel ) );\n bSuccess = true;\n }\n }\n }\n catch( const Exception& )\n {\n ; \/\/ no success!\n }\n\n \/\/ TODO: implement proper error handling\n DBG_ASSERT( bSuccess, \"can't import model\" );\n}\n\nReference lcl_findXFormsBindingOrSubmission(\n Reference& xDocument,\n const rtl::OUString& rBindingID,\n bool bBinding )\n{\n \/\/ find binding by iterating over all models, and look for the\n \/\/ given binding ID\n\n Reference xRet;\n try\n {\n \/\/ get supplier\n Reference xSupplier( xDocument, UNO_QUERY );\n if( xSupplier.is() )\n {\n \/\/ get XForms models\n Reference xForms = xSupplier->getXForms();\n if( xForms.is() )\n {\n \/\/ iterate over all models\n Sequence aNames = xForms->getElementNames();\n const OUString* pNames = aNames.getConstArray();\n sal_Int32 nNames = aNames.getLength();\n for( sal_Int32 n = 0; (n < nNames) && !xRet.is(); n++ )\n {\n Reference xModel(\n xForms->getByName( pNames[n] ), UNO_QUERY );\n if( xModel.is() )\n {\n \/\/ ask model for bindings\n Reference xBindings(\n bBinding\n ? xModel->getBindings()\n : xModel->getSubmissions(),\n UNO_QUERY_THROW );\n\n \/\/ finally, ask binding for name\n if( xBindings->hasByName( rBindingID ) )\n xRet.set( xBindings->getByName( rBindingID ),\n UNO_QUERY );\n }\n }\n }\n }\n }\n catch( const Exception& )\n {\n ; \/\/ no success!\n }\n\n if( ! xRet.is() )\n ; \/\/ TODO: rImport.SetError(...);\n\n return xRet;\n}\n\nReference lcl_findXFormsBinding(\n Reference& xDocument,\n const rtl::OUString& rBindingID )\n{\n return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, true );\n}\n\nReference lcl_findXFormsSubmission(\n Reference& xDocument,\n const rtl::OUString& rBindingID )\n{\n return lcl_findXFormsBindingOrSubmission( xDocument, rBindingID, false );\n}\n\nvoid lcl_setValue( Reference& xPropertySet,\n const OUString& rName,\n const Any rAny )\n{\n xPropertySet->setPropertyValue( rName, rAny );\n}\n\n\nReference lcl_getXFormsModel( const Reference& xDoc )\n{\n Reference xRet;\n try\n {\n Reference xSupplier( xDoc, UNO_QUERY );\n if( xSupplier.is() )\n {\n Reference xForms = xSupplier->getXForms();\n if( xForms.is() )\n {\n Sequence aNames = xForms->getElementNames();\n if( aNames.getLength() > 0 )\n xRet.set( xForms->getByName( aNames[0] ), UNO_QUERY );\n }\n }\n }\n catch( const Exception& )\n {\n ; \/\/ no success!\n }\n\n return xRet;\n}\n\n#define TOKEN_MAP_ENTRY(NAMESPACE,TOKEN) { XML_NAMESPACE_##NAMESPACE, xmloff::token::XML_##TOKEN, xmloff::token::XML_##TOKEN }\nstatic SvXMLTokenMapEntry aTypes[] =\n{\n TOKEN_MAP_ENTRY( XSD, STRING ),\n TOKEN_MAP_ENTRY( XSD, DECIMAL ),\n TOKEN_MAP_ENTRY( XSD, DOUBLE ),\n TOKEN_MAP_ENTRY( XSD, FLOAT ),\n TOKEN_MAP_ENTRY( XSD, BOOLEAN ),\n TOKEN_MAP_ENTRY( XSD, ANYURI ),\n TOKEN_MAP_ENTRY( XSD, DATETIME_XSD ),\n TOKEN_MAP_ENTRY( XSD, DATE ),\n TOKEN_MAP_ENTRY( XSD, TIME ),\n TOKEN_MAP_ENTRY( XSD, YEAR ),\n TOKEN_MAP_ENTRY( XSD, MONTH ),\n TOKEN_MAP_ENTRY( XSD, DAY ),\n XML_TOKEN_MAP_END\n};\n\nsal_uInt16 lcl_getTypeClass(\n const Reference& xRepository,\n const SvXMLNamespaceMap& rNamespaceMap,\n const OUString& rXMLName )\n{\n \/\/ translate name into token for local name\n OUString sLocalName;\n sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);\n SvXMLTokenMap aMap( aTypes );\n sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );\n\n sal_uInt16 nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;\n if( mnToken != XML_TOK_UNKNOWN )\n {\n \/\/ we found an XSD name: then get the proper API name for it\n DBG_ASSERT( xRepository.is(), \"can't find type without repository\");\n switch( mnToken )\n {\n case XML_STRING:\n nTypeClass = com::sun::star::xsd::DataTypeClass::STRING;\n break;\n case XML_ANYURI:\n nTypeClass = com::sun::star::xsd::DataTypeClass::anyURI;\n break;\n case XML_DECIMAL:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DECIMAL;\n break;\n case XML_DOUBLE:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DOUBLE;\n break;\n case XML_FLOAT:\n nTypeClass = com::sun::star::xsd::DataTypeClass::FLOAT;\n break;\n case XML_BOOLEAN:\n nTypeClass = com::sun::star::xsd::DataTypeClass::BOOLEAN;\n break;\n case XML_DATETIME_XSD:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DATETIME;\n break;\n case XML_DATE:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DATE;\n break;\n case XML_TIME:\n nTypeClass = com::sun::star::xsd::DataTypeClass::TIME;\n break;\n case XML_YEAR:\n nTypeClass = com::sun::star::xsd::DataTypeClass::gYear;\n break;\n case XML_DAY:\n nTypeClass = com::sun::star::xsd::DataTypeClass::gDay;\n break;\n case XML_MONTH:\n nTypeClass = com::sun::star::xsd::DataTypeClass::gMonth;\n break;\n\n \/* data types not yet supported:\n nTypeClass = com::sun::star::xsd::DataTypeClass::DURATION;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gYearMonth;\n nTypeClass = com::sun::star::xsd::DataTypeClass::gMonthDay;\n nTypeClass = com::sun::star::xsd::DataTypeClass::hexBinary;\n nTypeClass = com::sun::star::xsd::DataTypeClass::base64Binary;\n nTypeClass = com::sun::star::xsd::DataTypeClass::QName;\n nTypeClass = com::sun::star::xsd::DataTypeClass::NOTATION;\n *\/\n }\n }\n\n return nTypeClass;\n}\n\n\nrtl::OUString lcl_getTypeName(\n const Reference& xRepository,\n const SvXMLNamespaceMap& rNamespaceMap,\n const OUString& rXMLName )\n{\n OUString sLocalName;\n sal_uInt16 nPrefix = rNamespaceMap.GetKeyByAttrName(rXMLName, &sLocalName);\n SvXMLTokenMap aMap( aTypes );\n sal_uInt16 mnToken = aMap.Get( nPrefix, sLocalName );\n return ( mnToken == XML_TOK_UNKNOWN )\n ? rXMLName\n : lcl_getBasicTypeName( xRepository, rNamespaceMap, rXMLName );\n}\n\nrtl::OUString lcl_getBasicTypeName(\n const Reference& xRepository,\n const SvXMLNamespaceMap& rNamespaceMap,\n const OUString& rXMLName )\n{\n OUString sTypeName = rXMLName;\n try\n {\n sTypeName =\n xRepository->getBasicDataType(\n lcl_getTypeClass( xRepository, rNamespaceMap, rXMLName ) )\n ->getName();\n }\n catch( const Exception& )\n {\n DBG_ERROR( \"exception during type creation\" );\n }\n return sTypeName;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/directory_watcher.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/hash_tables.h\"\n#include \"base\/lock.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/singleton.h\"\n#include \"base\/task.h\"\n#include \"base\/thread.h\"\n#include \"base\/waitable_event.h\"\n\nnamespace {\n\nclass DirectoryWatcherImpl;\n\n\/\/ Singleton to manage all inotify watches.\nclass InotifyReader {\n public:\n typedef int Watch; \/\/ Watch descriptor used by AddWatch and RemoveWatch.\n static const Watch kInvalidWatch = -1;\n\n \/\/ Watch |path| for changes. |watcher| will be notified on each change.\n \/\/ Returns kInvalidWatch on failure.\n Watch AddWatch(const FilePath& path, DirectoryWatcherImpl* watcher);\n\n \/\/ Remove |watch|. Returns true on success.\n bool RemoveWatch(Watch watch, DirectoryWatcherImpl* watcher);\n\n \/\/ Callback for InotifyReaderTask.\n void OnInotifyEvent(const inotify_event* event);\n\n private:\n friend struct DefaultSingletonTraits;\n\n typedef std::set WatcherSet;\n\n InotifyReader();\n ~InotifyReader();\n\n \/\/ We keep track of which delegates want to be notified on which watches.\n base::hash_map watchers_;\n\n \/\/ For each watch we also want to know the path it's watching.\n base::hash_map paths_;\n\n \/\/ Lock to protect delegates_ and paths_.\n Lock lock_;\n\n \/\/ Separate thread on which we run blocking read for inotify events.\n base::Thread thread_;\n\n \/\/ File descriptor returned by inotify_init.\n const int inotify_fd_;\n\n \/\/ Use self-pipe trick to unblock select during shutdown.\n int shutdown_pipe_[2];\n\n \/\/ Flag set to true when startup was successful.\n bool valid_;\n\n DISALLOW_COPY_AND_ASSIGN(InotifyReader);\n};\n\nclass DirectoryWatcherImpl : public DirectoryWatcher::PlatformDelegate {\n public:\n typedef std::set FilePathSet;\n\n DirectoryWatcherImpl();\n ~DirectoryWatcherImpl();\n\n void EnsureSetupFinished();\n\n \/\/ Called for each event coming from one of watches.\n void OnInotifyEvent(const inotify_event* event);\n\n \/\/ Callback for RegisterSubtreeWatchesTask.\n bool OnEnumeratedSubtree(const FilePathSet& paths);\n\n \/\/ Start watching |path| for changes and notify |delegate| on each change.\n \/\/ If |recursive| is true, watch entire subtree.\n \/\/ Returns true if watch for |path| has been added successfully. Watches\n \/\/ required for |recursive| are added on a background thread and have no\n \/\/ effect on the return value.\n virtual bool Watch(const FilePath& path, DirectoryWatcher::Delegate* delegate,\n MessageLoop* backend_loop, bool recursive);\n\n private:\n typedef std::set WatchSet;\n typedef std::set InodeSet;\n\n \/\/ Returns true if |inode| is watched by DirectoryWatcherImpl.\n bool IsInodeWatched(ino_t inode) const;\n\n \/\/ Delegate to notify upon changes.\n DirectoryWatcher::Delegate* delegate_;\n\n \/\/ Path we're watching (passed to delegate).\n FilePath root_path_;\n\n \/\/ Watch returned by InotifyReader.\n InotifyReader::Watch watch_;\n\n \/\/ Set of watched inodes.\n InodeSet inodes_watched_;\n\n \/\/ Keep track of registered watches.\n WatchSet watches_;\n\n \/\/ Lock to protect inodes_watched_ and watches_.\n Lock lock_;\n\n \/\/ Flag set to true when recursively watching subtree.\n bool recursive_;\n\n \/\/ Loop where we post directory change notifications to.\n MessageLoop* loop_;\n\n \/\/ Event signaled when the background task finished adding initial inotify\n \/\/ watches for recursive watch.\n base::WaitableEvent recursive_setup_finished_;\n\n DISALLOW_COPY_AND_ASSIGN(DirectoryWatcherImpl);\n};\n\nclass RegisterSubtreeWatchesTask : public Task {\n public:\n RegisterSubtreeWatchesTask(DirectoryWatcherImpl* watcher,\n const FilePath& path)\n : watcher_(watcher),\n path_(path) {\n }\n\n virtual void Run() {\n file_util::FileEnumerator dir_list(path_, true,\n file_util::FileEnumerator::DIRECTORIES);\n\n DirectoryWatcherImpl::FilePathSet subtree;\n for (FilePath subdirectory = dir_list.Next();\n !subdirectory.empty();\n subdirectory = dir_list.Next()) {\n subtree.insert(subdirectory);\n }\n watcher_->OnEnumeratedSubtree(subtree);\n }\n\n private:\n DirectoryWatcherImpl* watcher_;\n FilePath path_;\n\n DISALLOW_COPY_AND_ASSIGN(RegisterSubtreeWatchesTask);\n};\n\nclass DirectoryWatcherImplNotifyTask : public Task {\n public:\n DirectoryWatcherImplNotifyTask(DirectoryWatcher::Delegate* delegate,\n const FilePath& path)\n : delegate_(delegate),\n path_(path) {\n }\n\n virtual void Run() {\n delegate_->OnDirectoryChanged(path_);\n }\n\n private:\n DirectoryWatcher::Delegate* delegate_;\n FilePath path_;\n\n DISALLOW_COPY_AND_ASSIGN(DirectoryWatcherImplNotifyTask);\n};\n\nclass InotifyReaderTask : public Task {\n public:\n InotifyReaderTask(InotifyReader* reader, int inotify_fd, int shutdown_fd)\n : reader_(reader),\n inotify_fd_(inotify_fd),\n shutdown_fd_(shutdown_fd) {\n }\n\n virtual void Run() {\n while (true) {\n fd_set rfds;\n FD_ZERO(&rfds);\n FD_SET(inotify_fd_, &rfds);\n FD_SET(shutdown_fd_, &rfds);\n\n \/\/ Wait until some inotify events are available.\n int select_result =\n HANDLE_EINTR(select(std::max(inotify_fd_, shutdown_fd_) + 1,\n &rfds, NULL, NULL, NULL));\n if (select_result < 0) {\n DLOG(WARNING) << \"select failed: \" << strerror(errno);\n return;\n }\n\n if (FD_ISSET(shutdown_fd_, &rfds))\n return;\n\n \/\/ Adjust buffer size to current event queue size.\n int buffer_size;\n int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD,\n &buffer_size));\n\n if (ioctl_result != 0) {\n DLOG(WARNING) << \"ioctl failed: \" << strerror(errno);\n return;\n }\n\n std::vector buffer(buffer_size);\n\n ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd_, &buffer[0],\n buffer_size));\n\n if (bytes_read < 0) {\n DLOG(WARNING) << \"read from inotify fd failed: \" << strerror(errno);\n return;\n }\n\n ssize_t i = 0;\n while (i < bytes_read) {\n inotify_event* event = reinterpret_cast(&buffer[i]);\n size_t event_size = sizeof(inotify_event) + event->len;\n DCHECK(i + event_size <= static_cast(bytes_read));\n reader_->OnInotifyEvent(event);\n i += event_size;\n }\n }\n }\n\n private:\n InotifyReader* reader_;\n int inotify_fd_;\n int shutdown_fd_;\n\n DISALLOW_COPY_AND_ASSIGN(InotifyReaderTask);\n};\n\nInotifyReader::InotifyReader()\n : thread_(\"inotify_reader\"),\n inotify_fd_(inotify_init()),\n valid_(false) {\n shutdown_pipe_[0] = -1;\n shutdown_pipe_[1] = -1;\n if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) {\n thread_.message_loop()->PostTask(\n FROM_HERE, new InotifyReaderTask(this, inotify_fd_, shutdown_pipe_[0]));\n valid_ = true;\n }\n}\n\nInotifyReader::~InotifyReader() {\n if (valid_) {\n \/\/ Write to the self-pipe so that the select call in InotifyReaderTask\n \/\/ returns.\n HANDLE_EINTR(write(shutdown_pipe_[1], \"\", 1));\n thread_.Stop();\n }\n if (inotify_fd_ >= 0)\n close(inotify_fd_);\n if (shutdown_pipe_[0] >= 0)\n close(shutdown_pipe_[0]);\n if (shutdown_pipe_[1] >= 0)\n close(shutdown_pipe_[1]);\n}\n\nInotifyReader::Watch InotifyReader::AddWatch(\n const FilePath& path, DirectoryWatcherImpl* watcher) {\n\n if (!valid_)\n return kInvalidWatch;\n\n AutoLock auto_lock(lock_);\n\n Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),\n IN_CREATE | IN_DELETE |\n IN_CLOSE_WRITE | IN_MOVE);\n\n if (watch == kInvalidWatch)\n return kInvalidWatch;\n\n if (paths_[watch].empty())\n paths_[watch] = path; \/\/ We don't yet watch this path.\n\n watchers_[watch].insert(watcher);\n\n return watch;\n}\n\nbool InotifyReader::RemoveWatch(Watch watch,\n DirectoryWatcherImpl* watcher) {\n if (!valid_)\n return false;\n\n AutoLock auto_lock(lock_);\n\n if (paths_[watch].empty())\n return false; \/\/ We don't recognize this watch.\n\n watchers_[watch].erase(watcher);\n\n if (watchers_[watch].empty()) {\n paths_.erase(watch);\n watchers_.erase(watch);\n return (inotify_rm_watch(inotify_fd_, watch) == 0);\n }\n\n return true;\n}\n\nvoid InotifyReader::OnInotifyEvent(const inotify_event* event) {\n if (event->mask & IN_IGNORED)\n return;\n\n WatcherSet watchers_to_notify;\n FilePath changed_path;\n\n {\n AutoLock auto_lock(lock_);\n changed_path = paths_[event->wd];\n watchers_to_notify.insert(watchers_[event->wd].begin(),\n watchers_[event->wd].end());\n }\n\n for (WatcherSet::iterator watcher = watchers_to_notify.begin();\n watcher != watchers_to_notify.end();\n ++watcher) {\n (*watcher)->OnInotifyEvent(event);\n }\n}\n\nDirectoryWatcherImpl::DirectoryWatcherImpl()\n : watch_(InotifyReader::kInvalidWatch),\n recursive_setup_finished_(false, false) {\n}\n\nDirectoryWatcherImpl::~DirectoryWatcherImpl() {\n if (watch_ == InotifyReader::kInvalidWatch)\n return;\n\n if (recursive_)\n recursive_setup_finished_.Wait();\n for (WatchSet::iterator watch = watches_.begin();\n watch != watches_.end();\n ++watch) {\n Singleton::get()->RemoveWatch(*watch, this);\n }\n watches_.clear();\n inodes_watched_.clear();\n}\n\nvoid DirectoryWatcherImpl::OnInotifyEvent(const inotify_event* event) {\n loop_->PostTask(FROM_HERE,\n new DirectoryWatcherImplNotifyTask(delegate_, root_path_));\n\n if (!(event->mask & IN_ISDIR))\n return;\n\n if (event->mask & IN_CREATE || event->mask & IN_MOVED_TO) {\n \/\/ TODO(phajdan.jr): add watch for this new directory.\n NOTIMPLEMENTED();\n } else if (event->mask & IN_DELETE || event->mask & IN_MOVED_FROM) {\n \/\/ TODO(phajdan.jr): remove our watch for this directory.\n NOTIMPLEMENTED();\n }\n}\n\nbool DirectoryWatcherImpl::IsInodeWatched(ino_t inode) const {\n return inodes_watched_.find(inode) != inodes_watched_.end();\n}\n\nbool DirectoryWatcherImpl::OnEnumeratedSubtree(const FilePathSet& subtree) {\n DCHECK(recursive_);\n\n if (watch_ == InotifyReader::kInvalidWatch) {\n recursive_setup_finished_.Signal();\n return false;\n }\n\n bool success = true;\n\n {\n \/\/ Limit the scope of auto_lock so it releases lock_ before we signal\n \/\/ recursive_setup_finished_. Our dtor waits on recursive_setup_finished_\n \/\/ and could otherwise destroy the lock before we release it.\n AutoLock auto_lock(lock_);\n\n for (FilePathSet::iterator subdirectory = subtree.begin();\n subdirectory != subtree.end();\n ++subdirectory) {\n ino_t inode;\n if (!file_util::GetInode(*subdirectory, &inode)) {\n success = false;\n continue;\n }\n if (IsInodeWatched(inode))\n continue;\n InotifyReader::Watch watch =\n Singleton::get()->AddWatch(*subdirectory, this);\n if (watch != InotifyReader::kInvalidWatch) {\n watches_.insert(watch);\n inodes_watched_.insert(inode);\n }\n }\n }\n\n recursive_setup_finished_.Signal();\n return success;\n}\n\nbool DirectoryWatcherImpl::Watch(const FilePath& path,\n DirectoryWatcher::Delegate* delegate,\n MessageLoop* backend_loop, bool recursive) {\n\n \/\/ Can only watch one path.\n DCHECK(watch_ == InotifyReader::kInvalidWatch);\n\n ino_t inode;\n if (!file_util::GetInode(path, &inode))\n return false;\n\n InotifyReader::Watch watch =\n Singleton::get()->AddWatch(path, this);\n if (watch == InotifyReader::kInvalidWatch)\n return false;\n\n delegate_ = delegate;\n recursive_ = recursive;\n root_path_ = path;\n watch_ = watch;\n loop_ = MessageLoop::current();\n\n {\n AutoLock auto_lock(lock_);\n inodes_watched_.insert(inode);\n watches_.insert(watch_);\n }\n\n if (recursive_) {\n Task* subtree_task = new RegisterSubtreeWatchesTask(this, root_path_);\n if (backend_loop) {\n backend_loop->PostTask(FROM_HERE, subtree_task);\n } else {\n subtree_task->Run();\n delete subtree_task;\n }\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nDirectoryWatcher::DirectoryWatcher() {\n impl_ = new DirectoryWatcherImpl();\n}\n\nFix two races in DirectoryWatcherInotify:\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/directory_watcher.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/hash_tables.h\"\n#include \"base\/lock.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/singleton.h\"\n#include \"base\/task.h\"\n#include \"base\/thread.h\"\n#include \"base\/waitable_event.h\"\n\nnamespace {\n\nclass DirectoryWatcherImpl;\n\n\/\/ Singleton to manage all inotify watches.\nclass InotifyReader {\n public:\n typedef int Watch; \/\/ Watch descriptor used by AddWatch and RemoveWatch.\n static const Watch kInvalidWatch = -1;\n\n \/\/ Watch |path| for changes. |watcher| will be notified on each change.\n \/\/ Returns kInvalidWatch on failure.\n Watch AddWatch(const FilePath& path, DirectoryWatcherImpl* watcher);\n\n \/\/ Remove |watch|. Returns true on success.\n bool RemoveWatch(Watch watch, DirectoryWatcherImpl* watcher);\n\n \/\/ Callback for InotifyReaderTask.\n void OnInotifyEvent(const inotify_event* event);\n\n private:\n friend struct DefaultSingletonTraits;\n\n typedef std::set WatcherSet;\n\n InotifyReader();\n ~InotifyReader();\n\n \/\/ We keep track of which delegates want to be notified on which watches.\n base::hash_map watchers_;\n\n \/\/ For each watch we also want to know the path it's watching.\n base::hash_map paths_;\n\n \/\/ Lock to protect delegates_ and paths_.\n Lock lock_;\n\n \/\/ Separate thread on which we run blocking read for inotify events.\n base::Thread thread_;\n\n \/\/ File descriptor returned by inotify_init.\n const int inotify_fd_;\n\n \/\/ Use self-pipe trick to unblock select during shutdown.\n int shutdown_pipe_[2];\n\n \/\/ Flag set to true when startup was successful.\n bool valid_;\n\n DISALLOW_COPY_AND_ASSIGN(InotifyReader);\n};\n\nclass DirectoryWatcherImpl : public DirectoryWatcher::PlatformDelegate {\n public:\n typedef std::set FilePathSet;\n\n DirectoryWatcherImpl();\n ~DirectoryWatcherImpl();\n\n void EnsureSetupFinished();\n\n \/\/ Called for each event coming from one of watches.\n void OnInotifyEvent(const inotify_event* event);\n\n \/\/ Callback for RegisterSubtreeWatchesTask.\n bool OnEnumeratedSubtree(const FilePathSet& paths);\n\n \/\/ Start watching |path| for changes and notify |delegate| on each change.\n \/\/ If |recursive| is true, watch entire subtree.\n \/\/ Returns true if watch for |path| has been added successfully. Watches\n \/\/ required for |recursive| are added on a background thread and have no\n \/\/ effect on the return value.\n virtual bool Watch(const FilePath& path, DirectoryWatcher::Delegate* delegate,\n MessageLoop* backend_loop, bool recursive);\n\n private:\n typedef std::set WatchSet;\n typedef std::set InodeSet;\n\n \/\/ Returns true if |inode| is watched by DirectoryWatcherImpl.\n bool IsInodeWatched(ino_t inode) const;\n\n \/\/ Delegate to notify upon changes.\n DirectoryWatcher::Delegate* delegate_;\n\n \/\/ Path we're watching (passed to delegate).\n FilePath root_path_;\n\n \/\/ Watch returned by InotifyReader.\n InotifyReader::Watch watch_;\n\n \/\/ Set of watched inodes.\n InodeSet inodes_watched_;\n\n \/\/ Keep track of registered watches.\n WatchSet watches_;\n\n \/\/ Lock to protect inodes_watched_ and watches_.\n Lock lock_;\n\n \/\/ Flag set to true when recursively watching subtree.\n bool recursive_;\n\n \/\/ Loop where we post directory change notifications to.\n MessageLoop* loop_;\n\n \/\/ Event signaled when the background task finished adding initial inotify\n \/\/ watches for recursive watch.\n base::WaitableEvent recursive_setup_finished_;\n\n DISALLOW_COPY_AND_ASSIGN(DirectoryWatcherImpl);\n};\n\nclass RegisterSubtreeWatchesTask : public Task {\n public:\n RegisterSubtreeWatchesTask(DirectoryWatcherImpl* watcher,\n const FilePath& path)\n : watcher_(watcher),\n path_(path) {\n }\n\n virtual void Run() {\n file_util::FileEnumerator dir_list(path_, true,\n file_util::FileEnumerator::DIRECTORIES);\n\n DirectoryWatcherImpl::FilePathSet subtree;\n for (FilePath subdirectory = dir_list.Next();\n !subdirectory.empty();\n subdirectory = dir_list.Next()) {\n subtree.insert(subdirectory);\n }\n watcher_->OnEnumeratedSubtree(subtree);\n }\n\n private:\n DirectoryWatcherImpl* watcher_;\n FilePath path_;\n\n DISALLOW_COPY_AND_ASSIGN(RegisterSubtreeWatchesTask);\n};\n\nclass DirectoryWatcherImplNotifyTask : public Task {\n public:\n DirectoryWatcherImplNotifyTask(DirectoryWatcher::Delegate* delegate,\n const FilePath& path)\n : delegate_(delegate),\n path_(path) {\n }\n\n virtual void Run() {\n delegate_->OnDirectoryChanged(path_);\n }\n\n private:\n DirectoryWatcher::Delegate* delegate_;\n FilePath path_;\n\n DISALLOW_COPY_AND_ASSIGN(DirectoryWatcherImplNotifyTask);\n};\n\nclass InotifyReaderTask : public Task {\n public:\n InotifyReaderTask(InotifyReader* reader, int inotify_fd, int shutdown_fd)\n : reader_(reader),\n inotify_fd_(inotify_fd),\n shutdown_fd_(shutdown_fd) {\n }\n\n virtual void Run() {\n while (true) {\n fd_set rfds;\n FD_ZERO(&rfds);\n FD_SET(inotify_fd_, &rfds);\n FD_SET(shutdown_fd_, &rfds);\n\n \/\/ Wait until some inotify events are available.\n int select_result =\n HANDLE_EINTR(select(std::max(inotify_fd_, shutdown_fd_) + 1,\n &rfds, NULL, NULL, NULL));\n if (select_result < 0) {\n DLOG(WARNING) << \"select failed: \" << strerror(errno);\n return;\n }\n\n if (FD_ISSET(shutdown_fd_, &rfds))\n return;\n\n \/\/ Adjust buffer size to current event queue size.\n int buffer_size;\n int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD,\n &buffer_size));\n\n if (ioctl_result != 0) {\n DLOG(WARNING) << \"ioctl failed: \" << strerror(errno);\n return;\n }\n\n std::vector buffer(buffer_size);\n\n ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd_, &buffer[0],\n buffer_size));\n\n if (bytes_read < 0) {\n DLOG(WARNING) << \"read from inotify fd failed: \" << strerror(errno);\n return;\n }\n\n ssize_t i = 0;\n while (i < bytes_read) {\n inotify_event* event = reinterpret_cast(&buffer[i]);\n size_t event_size = sizeof(inotify_event) + event->len;\n DCHECK(i + event_size <= static_cast(bytes_read));\n reader_->OnInotifyEvent(event);\n i += event_size;\n }\n }\n }\n\n private:\n InotifyReader* reader_;\n int inotify_fd_;\n int shutdown_fd_;\n\n DISALLOW_COPY_AND_ASSIGN(InotifyReaderTask);\n};\n\nInotifyReader::InotifyReader()\n : thread_(\"inotify_reader\"),\n inotify_fd_(inotify_init()),\n valid_(false) {\n shutdown_pipe_[0] = -1;\n shutdown_pipe_[1] = -1;\n if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) {\n thread_.message_loop()->PostTask(\n FROM_HERE, new InotifyReaderTask(this, inotify_fd_, shutdown_pipe_[0]));\n valid_ = true;\n }\n}\n\nInotifyReader::~InotifyReader() {\n if (valid_) {\n \/\/ Write to the self-pipe so that the select call in InotifyReaderTask\n \/\/ returns.\n HANDLE_EINTR(write(shutdown_pipe_[1], \"\", 1));\n thread_.Stop();\n }\n if (inotify_fd_ >= 0)\n close(inotify_fd_);\n if (shutdown_pipe_[0] >= 0)\n close(shutdown_pipe_[0]);\n if (shutdown_pipe_[1] >= 0)\n close(shutdown_pipe_[1]);\n}\n\nInotifyReader::Watch InotifyReader::AddWatch(\n const FilePath& path, DirectoryWatcherImpl* watcher) {\n\n if (!valid_)\n return kInvalidWatch;\n\n AutoLock auto_lock(lock_);\n\n Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(),\n IN_CREATE | IN_DELETE |\n IN_CLOSE_WRITE | IN_MOVE);\n\n if (watch == kInvalidWatch)\n return kInvalidWatch;\n\n if (paths_[watch].empty())\n paths_[watch] = path; \/\/ We don't yet watch this path.\n\n watchers_[watch].insert(watcher);\n\n return watch;\n}\n\nbool InotifyReader::RemoveWatch(Watch watch,\n DirectoryWatcherImpl* watcher) {\n if (!valid_)\n return false;\n\n AutoLock auto_lock(lock_);\n\n if (paths_[watch].empty())\n return false; \/\/ We don't recognize this watch.\n\n watchers_[watch].erase(watcher);\n\n if (watchers_[watch].empty()) {\n paths_.erase(watch);\n watchers_.erase(watch);\n return (inotify_rm_watch(inotify_fd_, watch) == 0);\n }\n\n return true;\n}\n\nvoid InotifyReader::OnInotifyEvent(const inotify_event* event) {\n if (event->mask & IN_IGNORED)\n return;\n\n \/\/ In case you want to limit the scope of this lock, it's not sufficient\n \/\/ to just copy things under the lock, and then run the notifications\n \/\/ without holding the lock. DirectoryWatcherImpl's dtor removes its watches,\n \/\/ and to do that obtains the lock. After it finishes removing watches,\n \/\/ it's destroyed. So, if you copy under the lock and notify without the lock,\n \/\/ it's possible you'll copy the DirectoryWatcherImpl which is being\n \/\/ destroyed, then it will destroy itself, and then you'll try to notify it.\n AutoLock auto_lock(lock_);\n\n for (WatcherSet::iterator watcher = watchers_[event->wd].begin();\n watcher != watchers_[event->wd].end();\n ++watcher) {\n (*watcher)->OnInotifyEvent(event);\n }\n}\n\nDirectoryWatcherImpl::DirectoryWatcherImpl()\n : watch_(InotifyReader::kInvalidWatch),\n recursive_setup_finished_(false, false) {\n}\n\nDirectoryWatcherImpl::~DirectoryWatcherImpl() {\n if (watch_ == InotifyReader::kInvalidWatch)\n return;\n\n if (recursive_)\n recursive_setup_finished_.Wait();\n for (WatchSet::iterator watch = watches_.begin();\n watch != watches_.end();\n ++watch) {\n Singleton::get()->RemoveWatch(*watch, this);\n }\n watches_.clear();\n inodes_watched_.clear();\n}\n\nvoid DirectoryWatcherImpl::OnInotifyEvent(const inotify_event* event) {\n loop_->PostTask(FROM_HERE,\n new DirectoryWatcherImplNotifyTask(delegate_, root_path_));\n\n if (!(event->mask & IN_ISDIR))\n return;\n\n if (event->mask & IN_CREATE || event->mask & IN_MOVED_TO) {\n \/\/ TODO(phajdan.jr): add watch for this new directory.\n NOTIMPLEMENTED();\n } else if (event->mask & IN_DELETE || event->mask & IN_MOVED_FROM) {\n \/\/ TODO(phajdan.jr): remove our watch for this directory.\n NOTIMPLEMENTED();\n }\n}\n\nbool DirectoryWatcherImpl::IsInodeWatched(ino_t inode) const {\n return inodes_watched_.find(inode) != inodes_watched_.end();\n}\n\nbool DirectoryWatcherImpl::OnEnumeratedSubtree(const FilePathSet& subtree) {\n DCHECK(recursive_);\n\n if (watch_ == InotifyReader::kInvalidWatch) {\n recursive_setup_finished_.Signal();\n return false;\n }\n\n bool success = true;\n\n {\n \/\/ Limit the scope of auto_lock so it releases lock_ before we signal\n \/\/ recursive_setup_finished_. Our dtor waits on recursive_setup_finished_\n \/\/ and could otherwise destroy the lock before we release it.\n AutoLock auto_lock(lock_);\n\n for (FilePathSet::iterator subdirectory = subtree.begin();\n subdirectory != subtree.end();\n ++subdirectory) {\n ino_t inode;\n if (!file_util::GetInode(*subdirectory, &inode)) {\n success = false;\n continue;\n }\n if (IsInodeWatched(inode))\n continue;\n InotifyReader::Watch watch =\n Singleton::get()->AddWatch(*subdirectory, this);\n if (watch != InotifyReader::kInvalidWatch) {\n watches_.insert(watch);\n inodes_watched_.insert(inode);\n }\n }\n }\n\n recursive_setup_finished_.Signal();\n return success;\n}\n\nbool DirectoryWatcherImpl::Watch(const FilePath& path,\n DirectoryWatcher::Delegate* delegate,\n MessageLoop* backend_loop, bool recursive) {\n\n \/\/ Can only watch one path.\n DCHECK(watch_ == InotifyReader::kInvalidWatch);\n\n ino_t inode;\n if (!file_util::GetInode(path, &inode))\n return false;\n\n delegate_ = delegate;\n recursive_ = recursive;\n root_path_ = path;\n loop_ = MessageLoop::current();\n watch_ = Singleton::get()->AddWatch(path, this);\n if (watch_ == InotifyReader::kInvalidWatch)\n return false;\n\n {\n AutoLock auto_lock(lock_);\n inodes_watched_.insert(inode);\n watches_.insert(watch_);\n }\n\n if (recursive_) {\n Task* subtree_task = new RegisterSubtreeWatchesTask(this, root_path_);\n if (backend_loop) {\n backend_loop->PostTask(FROM_HERE, subtree_task);\n } else {\n subtree_task->Run();\n delete subtree_task;\n }\n }\n\n return true;\n}\n\n} \/\/ namespace\n\nDirectoryWatcher::DirectoryWatcher() {\n impl_ = new DirectoryWatcherImpl();\n}\n<|endoftext|>"} {"text":"\/\/===--- SwiftRemoteMirror.cpp - C wrapper for Reflection API -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SwiftRemoteMirror\/Platform.h\"\n\n#define SWIFT_CLASS_IS_SWIFT_MASK swift_reflection_classIsSwiftMask\nextern \"C\" {\nSWIFT_REMOTE_MIRROR_LINKAGE __attribute__((__weak_import__))\nunsigned long long swift_reflection_classIsSwiftMask = 2;\n}\n\n#include \"swift\/Reflection\/ReflectionContext.h\"\n#include \"swift\/Reflection\/TypeLowering.h\"\n#include \"swift\/Remote\/CMemoryReader.h\"\n#include \"swift\/Runtime\/Unreachable.h\"\n#include \"swift\/SwiftRemoteMirror\/SwiftRemoteMirror.h\"\n\nusing namespace swift;\nusing namespace swift::reflection;\nusing namespace swift::remote;\n\nusing NativeReflectionContext = swift::reflection::ReflectionContext<\n External>>;\n\nstruct SwiftReflectionContext {\n NativeReflectionContext *nativeContext;\n std::vector> freeFuncs;\n std::vector> dataSegments;\n \n SwiftReflectionContext(MemoryReaderImpl impl) {\n auto Reader = std::make_shared(impl);\n nativeContext = new NativeReflectionContext(Reader);\n }\n \n ~SwiftReflectionContext() {\n delete nativeContext;\n for (auto f : freeFuncs)\n f();\n }\n};\n\n\nuint16_t\nswift_reflection_getSupportedMetadataVersion() {\n return SWIFT_REFLECTION_METADATA_VERSION;\n}\n\ntemplate \nstatic int minimalDataLayoutQueryFunction(void *ReaderContext,\n DataLayoutQueryType type,\n void *inBuffer, void *outBuffer) {\n if (type == DLQ_GetPointerSize || type == DLQ_GetSizeSize) {\n auto result = static_cast(outBuffer);\n *result = WordSize;\n return 1;\n }\n return 0;\n}\n\nSwiftReflectionContextRef\nswift_reflection_createReflectionContext(void *ReaderContext,\n uint8_t PointerSize,\n FreeBytesFunction Free,\n ReadBytesFunction ReadBytes,\n GetStringLengthFunction GetStringLength,\n GetSymbolAddressFunction GetSymbolAddress) {\n assert((PointerSize == 4 || PointerSize == 8) && \"We only support 32-bit and 64-bit.\");\n assert(PointerSize == sizeof(uintptr_t) &&\n \"We currently only support the pointer size this file was compiled with.\");\n\n auto *DataLayout = PointerSize == 4 ? minimalDataLayoutQueryFunction<4>\n : minimalDataLayoutQueryFunction<8>;\n MemoryReaderImpl ReaderImpl {\n ReaderContext,\n DataLayout,\n Free,\n ReadBytes,\n GetStringLength,\n GetSymbolAddress\n };\n\n return new SwiftReflectionContext(ReaderImpl);\n}\n\nSwiftReflectionContextRef\nswift_reflection_createReflectionContextWithDataLayout(void *ReaderContext,\n QueryDataLayoutFunction DataLayout,\n FreeBytesFunction Free,\n ReadBytesFunction ReadBytes,\n GetStringLengthFunction GetStringLength,\n GetSymbolAddressFunction GetSymbolAddress) {\n MemoryReaderImpl ReaderImpl {\n ReaderContext,\n DataLayout,\n Free,\n ReadBytes,\n GetStringLength,\n GetSymbolAddress\n };\n\n return new SwiftReflectionContext(ReaderImpl);\n}\n\nvoid swift_reflection_destroyReflectionContext(SwiftReflectionContextRef ContextRef) {\n delete ContextRef;\n}\n\nvoid\nswift_reflection_addReflectionInfo(SwiftReflectionContextRef ContextRef,\n swift_reflection_info_t Info) {\n auto Context = ContextRef->nativeContext;\n \n Context->addReflectionInfo(*reinterpret_cast(&Info));\n}\n\nint\nswift_reflection_addImage(SwiftReflectionContextRef ContextRef,\n swift_addr_t imageStart) {\n auto Context = ContextRef->nativeContext;\n return Context->addImage(RemoteAddress(imageStart));\n}\n\nint\nswift_reflection_readIsaMask(SwiftReflectionContextRef ContextRef,\n uintptr_t *outIsaMask) {\n auto Context = ContextRef->nativeContext;\n auto isaMask = Context->readIsaMask();\n if (isaMask) {\n *outIsaMask = *isaMask;\n return true;\n }\n *outIsaMask = 0;\n return false;\n}\n\nswift_typeref_t\nswift_reflection_typeRefForMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata) {\n auto Context = ContextRef->nativeContext;\n auto TR = Context->readTypeFromMetadata(Metadata);\n return reinterpret_cast(TR);\n}\n\nint\nswift_reflection_ownsObject(SwiftReflectionContextRef ContextRef, uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n return Context->ownsObject(RemoteAddress(Object));\n}\n\nint\nswift_reflection_ownsAddress(SwiftReflectionContextRef ContextRef, uintptr_t Address) {\n auto Context = ContextRef->nativeContext;\n return Context->ownsAddress(RemoteAddress(Address));\n}\n\nuintptr_t\nswift_reflection_metadataForObject(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto MetadataAddress = Context->readMetadataFromInstance(Object);\n if (!MetadataAddress)\n return 0;\n return *MetadataAddress;\n}\n\nswift_typeref_t\nswift_reflection_typeRefForInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto MetadataAddress = Context->readMetadataFromInstance(Object);\n if (!MetadataAddress)\n return 0;\n auto TR = Context->readTypeFromMetadata(*MetadataAddress);\n return reinterpret_cast(TR);\n}\n\nswift_typeref_t\nswift_reflection_typeRefForMangledTypeName(SwiftReflectionContextRef ContextRef,\n const char *MangledTypeName,\n uint64_t Length) {\n auto Context = ContextRef->nativeContext;\n auto TR = Context->readTypeFromMangledName(MangledTypeName, Length);\n return reinterpret_cast(TR);\n}\n\nswift_typeref_t\nswift_reflection_genericArgumentOfTypeRef(swift_typeref_t OpaqueTypeRef,\n unsigned Index) {\n auto TR = reinterpret_cast(OpaqueTypeRef);\n\n if (auto BG = dyn_cast(TR)) {\n auto &Params = BG->getGenericParams();\n assert(Index < Params.size());\n return reinterpret_cast(Params[Index]);\n }\n return 0;\n}\n\nunsigned\nswift_reflection_genericArgumentCountOfTypeRef(swift_typeref_t OpaqueTypeRef) {\n auto TR = reinterpret_cast(OpaqueTypeRef);\n\n if (auto BG = dyn_cast(TR)) {\n auto &Params = BG->getGenericParams();\n return Params.size();\n }\n return 0;\n}\n\nswift_layout_kind_t getTypeInfoKind(const TypeInfo &TI) {\n switch (TI.getKind()) {\n case TypeInfoKind::Builtin: {\n auto &BuiltinTI = cast(TI);\n if (BuiltinTI.getMangledTypeName() == \"Bp\")\n return SWIFT_RAW_POINTER;\n return SWIFT_BUILTIN;\n }\n case TypeInfoKind::Record: {\n auto &RecordTI = cast(TI);\n switch (RecordTI.getRecordKind()) {\n case RecordKind::Invalid:\n return SWIFT_UNKNOWN;\n case RecordKind::Tuple:\n return SWIFT_TUPLE;\n case RecordKind::Struct:\n return SWIFT_STRUCT;\n case RecordKind::NoPayloadEnum:\n return SWIFT_NO_PAYLOAD_ENUM;\n case RecordKind::SinglePayloadEnum:\n return SWIFT_SINGLE_PAYLOAD_ENUM;\n case RecordKind::MultiPayloadEnum:\n return SWIFT_MULTI_PAYLOAD_ENUM;\n case RecordKind::ThickFunction:\n return SWIFT_THICK_FUNCTION;\n case RecordKind::OpaqueExistential:\n return SWIFT_OPAQUE_EXISTENTIAL;\n case RecordKind::ClassExistential:\n return SWIFT_CLASS_EXISTENTIAL;\n case RecordKind::ErrorExistential:\n return SWIFT_ERROR_EXISTENTIAL;\n case RecordKind::ExistentialMetatype:\n return SWIFT_EXISTENTIAL_METATYPE;\n case RecordKind::ClassInstance:\n return SWIFT_CLASS_INSTANCE;\n case RecordKind::ClosureContext:\n return SWIFT_CLOSURE_CONTEXT;\n }\n }\n case TypeInfoKind::Reference: {\n auto &ReferenceTI = cast(TI);\n switch (ReferenceTI.getReferenceKind()) {\n case ReferenceKind::Strong: return SWIFT_STRONG_REFERENCE;\n#define REF_STORAGE(Name, name, NAME) \\\n case ReferenceKind::Name: return SWIFT_##NAME##_REFERENCE;\n#include \"swift\/AST\/ReferenceStorage.def\"\n }\n }\n }\n\n swift_runtime_unreachable(\"Unhandled TypeInfoKind in switch\");\n}\n\nstatic swift_typeinfo_t convertTypeInfo(const TypeInfo *TI) {\n if (TI == nullptr) {\n return {\n SWIFT_UNKNOWN,\n 0,\n 0,\n 0,\n 0\n };\n }\n\n unsigned NumFields = 0;\n if (auto *RecordTI = dyn_cast(TI))\n NumFields = RecordTI->getNumFields();\n\n return {\n getTypeInfoKind(*TI),\n TI->getSize(),\n TI->getAlignment(),\n TI->getStride(),\n NumFields\n };\n}\n\nstatic swift_childinfo_t convertChild(const TypeInfo *TI, unsigned Index) {\n auto *RecordTI = cast(TI);\n auto &FieldInfo = RecordTI->getFields()[Index];\n\n return {\n FieldInfo.Name.c_str(),\n FieldInfo.Offset,\n getTypeInfoKind(FieldInfo.TI),\n reinterpret_cast(FieldInfo.TR),\n };\n}\n\nswift_typeinfo_t\nswift_reflection_infoForTypeRef(SwiftReflectionContextRef ContextRef,\n swift_typeref_t OpaqueTypeRef) {\n auto Context = ContextRef->nativeContext;\n auto TR = reinterpret_cast(OpaqueTypeRef);\n auto TI = Context->getTypeInfo(TR);\n return convertTypeInfo(TI);\n}\n\nswift_childinfo_t\nswift_reflection_childOfTypeRef(SwiftReflectionContextRef ContextRef,\n swift_typeref_t OpaqueTypeRef,\n unsigned Index) {\n auto Context = ContextRef->nativeContext;\n auto TR = reinterpret_cast(OpaqueTypeRef);\n auto *TI = Context->getTypeInfo(TR);\n return convertChild(TI, Index);\n}\n\nswift_typeinfo_t\nswift_reflection_infoForMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getMetadataTypeInfo(Metadata);\n return convertTypeInfo(TI);\n}\n\nswift_childinfo_t\nswift_reflection_childOfMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata,\n unsigned Index) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getMetadataTypeInfo(Metadata);\n return convertChild(TI, Index);\n}\n\nswift_typeinfo_t\nswift_reflection_infoForInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getInstanceTypeInfo(Object);\n return convertTypeInfo(TI);\n}\n\nswift_childinfo_t\nswift_reflection_childOfInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object,\n unsigned Index) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getInstanceTypeInfo(Object);\n return convertChild(TI, Index);\n}\n\nint swift_reflection_projectExistential(SwiftReflectionContextRef ContextRef,\n swift_addr_t ExistentialAddress,\n swift_typeref_t ExistentialTypeRef,\n swift_typeref_t *InstanceTypeRef,\n swift_addr_t *StartOfInstanceData) {\n auto Context = ContextRef->nativeContext;\n auto ExistentialTR = reinterpret_cast(ExistentialTypeRef);\n auto RemoteExistentialAddress = RemoteAddress(ExistentialAddress);\n const TypeRef *InstanceTR = nullptr;\n RemoteAddress RemoteStartOfInstanceData(nullptr);\n auto Success = Context->projectExistential(RemoteExistentialAddress,\n ExistentialTR,\n &InstanceTR,\n &RemoteStartOfInstanceData);\n\n if (Success) {\n *InstanceTypeRef = reinterpret_cast(InstanceTR);\n *StartOfInstanceData = RemoteStartOfInstanceData.getAddressData();\n }\n\n return Success;\n}\n\nvoid swift_reflection_dumpTypeRef(swift_typeref_t OpaqueTypeRef) {\n auto TR = reinterpret_cast(OpaqueTypeRef);\n if (TR == nullptr) {\n std::cout << \"\\n\";\n } else {\n TR->dump(std::cout);\n }\n}\n\nvoid swift_reflection_dumpInfoForTypeRef(SwiftReflectionContextRef ContextRef,\n swift_typeref_t OpaqueTypeRef) {\n auto Context = ContextRef->nativeContext;\n auto TR = reinterpret_cast(OpaqueTypeRef);\n auto TI = Context->getTypeInfo(TR);\n if (TI == nullptr) {\n std::cout << \"\\n\";\n } else {\n TI->dump(std::cout);\n }\n}\n\nvoid swift_reflection_dumpInfoForMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata) {\n auto Context = ContextRef->nativeContext;\n auto TI = Context->getMetadataTypeInfo(Metadata);\n if (TI == nullptr) {\n std::cout << \"\\n\";\n } else {\n TI->dump(std::cout);\n }\n}\n\nvoid swift_reflection_dumpInfoForInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto TI = Context->getInstanceTypeInfo(Object);\n if (TI == nullptr) {\n std::cout << \"\\n\";\n } else {\n TI->dump(std::cout);\n }\n}\n\nsize_t swift_reflection_demangle(const char *MangledName, size_t Length,\n char *OutDemangledName, size_t MaxLength) {\n if (MangledName == nullptr || Length == 0)\n return 0;\n\n std::string Mangled(MangledName, Length);\n auto Demangled = Demangle::demangleTypeAsString(Mangled);\n strncpy(OutDemangledName, Demangled.c_str(), MaxLength);\n return Demangled.size();\n}\n[RemoteMirror] Rearrange #includes to fix warnings generated from the addition of __weak_import__ to classIsSwiftMask.\/\/===--- SwiftRemoteMirror.cpp - C wrapper for Reflection API -------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SwiftRemoteMirror\/Platform.h\"\n#include \"swift\/SwiftRemoteMirror\/SwiftRemoteMirror.h\"\n\n#define SWIFT_CLASS_IS_SWIFT_MASK swift_reflection_classIsSwiftMask\nextern \"C\" {\nSWIFT_REMOTE_MIRROR_LINKAGE\nunsigned long long swift_reflection_classIsSwiftMask = 2;\n}\n\n#include \"swift\/Reflection\/ReflectionContext.h\"\n#include \"swift\/Reflection\/TypeLowering.h\"\n#include \"swift\/Remote\/CMemoryReader.h\"\n#include \"swift\/Runtime\/Unreachable.h\"\n\nusing namespace swift;\nusing namespace swift::reflection;\nusing namespace swift::remote;\n\nusing NativeReflectionContext = swift::reflection::ReflectionContext<\n External>>;\n\nstruct SwiftReflectionContext {\n NativeReflectionContext *nativeContext;\n std::vector> freeFuncs;\n std::vector> dataSegments;\n \n SwiftReflectionContext(MemoryReaderImpl impl) {\n auto Reader = std::make_shared(impl);\n nativeContext = new NativeReflectionContext(Reader);\n }\n \n ~SwiftReflectionContext() {\n delete nativeContext;\n for (auto f : freeFuncs)\n f();\n }\n};\n\n\nuint16_t\nswift_reflection_getSupportedMetadataVersion() {\n return SWIFT_REFLECTION_METADATA_VERSION;\n}\n\ntemplate \nstatic int minimalDataLayoutQueryFunction(void *ReaderContext,\n DataLayoutQueryType type,\n void *inBuffer, void *outBuffer) {\n if (type == DLQ_GetPointerSize || type == DLQ_GetSizeSize) {\n auto result = static_cast(outBuffer);\n *result = WordSize;\n return 1;\n }\n return 0;\n}\n\nSwiftReflectionContextRef\nswift_reflection_createReflectionContext(void *ReaderContext,\n uint8_t PointerSize,\n FreeBytesFunction Free,\n ReadBytesFunction ReadBytes,\n GetStringLengthFunction GetStringLength,\n GetSymbolAddressFunction GetSymbolAddress) {\n assert((PointerSize == 4 || PointerSize == 8) && \"We only support 32-bit and 64-bit.\");\n assert(PointerSize == sizeof(uintptr_t) &&\n \"We currently only support the pointer size this file was compiled with.\");\n\n auto *DataLayout = PointerSize == 4 ? minimalDataLayoutQueryFunction<4>\n : minimalDataLayoutQueryFunction<8>;\n MemoryReaderImpl ReaderImpl {\n ReaderContext,\n DataLayout,\n Free,\n ReadBytes,\n GetStringLength,\n GetSymbolAddress\n };\n\n return new SwiftReflectionContext(ReaderImpl);\n}\n\nSwiftReflectionContextRef\nswift_reflection_createReflectionContextWithDataLayout(void *ReaderContext,\n QueryDataLayoutFunction DataLayout,\n FreeBytesFunction Free,\n ReadBytesFunction ReadBytes,\n GetStringLengthFunction GetStringLength,\n GetSymbolAddressFunction GetSymbolAddress) {\n MemoryReaderImpl ReaderImpl {\n ReaderContext,\n DataLayout,\n Free,\n ReadBytes,\n GetStringLength,\n GetSymbolAddress\n };\n\n return new SwiftReflectionContext(ReaderImpl);\n}\n\nvoid swift_reflection_destroyReflectionContext(SwiftReflectionContextRef ContextRef) {\n delete ContextRef;\n}\n\nvoid\nswift_reflection_addReflectionInfo(SwiftReflectionContextRef ContextRef,\n swift_reflection_info_t Info) {\n auto Context = ContextRef->nativeContext;\n \n Context->addReflectionInfo(*reinterpret_cast(&Info));\n}\n\nint\nswift_reflection_addImage(SwiftReflectionContextRef ContextRef,\n swift_addr_t imageStart) {\n auto Context = ContextRef->nativeContext;\n return Context->addImage(RemoteAddress(imageStart));\n}\n\nint\nswift_reflection_readIsaMask(SwiftReflectionContextRef ContextRef,\n uintptr_t *outIsaMask) {\n auto Context = ContextRef->nativeContext;\n auto isaMask = Context->readIsaMask();\n if (isaMask) {\n *outIsaMask = *isaMask;\n return true;\n }\n *outIsaMask = 0;\n return false;\n}\n\nswift_typeref_t\nswift_reflection_typeRefForMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata) {\n auto Context = ContextRef->nativeContext;\n auto TR = Context->readTypeFromMetadata(Metadata);\n return reinterpret_cast(TR);\n}\n\nint\nswift_reflection_ownsObject(SwiftReflectionContextRef ContextRef, uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n return Context->ownsObject(RemoteAddress(Object));\n}\n\nint\nswift_reflection_ownsAddress(SwiftReflectionContextRef ContextRef, uintptr_t Address) {\n auto Context = ContextRef->nativeContext;\n return Context->ownsAddress(RemoteAddress(Address));\n}\n\nuintptr_t\nswift_reflection_metadataForObject(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto MetadataAddress = Context->readMetadataFromInstance(Object);\n if (!MetadataAddress)\n return 0;\n return *MetadataAddress;\n}\n\nswift_typeref_t\nswift_reflection_typeRefForInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto MetadataAddress = Context->readMetadataFromInstance(Object);\n if (!MetadataAddress)\n return 0;\n auto TR = Context->readTypeFromMetadata(*MetadataAddress);\n return reinterpret_cast(TR);\n}\n\nswift_typeref_t\nswift_reflection_typeRefForMangledTypeName(SwiftReflectionContextRef ContextRef,\n const char *MangledTypeName,\n uint64_t Length) {\n auto Context = ContextRef->nativeContext;\n auto TR = Context->readTypeFromMangledName(MangledTypeName, Length);\n return reinterpret_cast(TR);\n}\n\nswift_typeref_t\nswift_reflection_genericArgumentOfTypeRef(swift_typeref_t OpaqueTypeRef,\n unsigned Index) {\n auto TR = reinterpret_cast(OpaqueTypeRef);\n\n if (auto BG = dyn_cast(TR)) {\n auto &Params = BG->getGenericParams();\n assert(Index < Params.size());\n return reinterpret_cast(Params[Index]);\n }\n return 0;\n}\n\nunsigned\nswift_reflection_genericArgumentCountOfTypeRef(swift_typeref_t OpaqueTypeRef) {\n auto TR = reinterpret_cast(OpaqueTypeRef);\n\n if (auto BG = dyn_cast(TR)) {\n auto &Params = BG->getGenericParams();\n return Params.size();\n }\n return 0;\n}\n\nswift_layout_kind_t getTypeInfoKind(const TypeInfo &TI) {\n switch (TI.getKind()) {\n case TypeInfoKind::Builtin: {\n auto &BuiltinTI = cast(TI);\n if (BuiltinTI.getMangledTypeName() == \"Bp\")\n return SWIFT_RAW_POINTER;\n return SWIFT_BUILTIN;\n }\n case TypeInfoKind::Record: {\n auto &RecordTI = cast(TI);\n switch (RecordTI.getRecordKind()) {\n case RecordKind::Invalid:\n return SWIFT_UNKNOWN;\n case RecordKind::Tuple:\n return SWIFT_TUPLE;\n case RecordKind::Struct:\n return SWIFT_STRUCT;\n case RecordKind::NoPayloadEnum:\n return SWIFT_NO_PAYLOAD_ENUM;\n case RecordKind::SinglePayloadEnum:\n return SWIFT_SINGLE_PAYLOAD_ENUM;\n case RecordKind::MultiPayloadEnum:\n return SWIFT_MULTI_PAYLOAD_ENUM;\n case RecordKind::ThickFunction:\n return SWIFT_THICK_FUNCTION;\n case RecordKind::OpaqueExistential:\n return SWIFT_OPAQUE_EXISTENTIAL;\n case RecordKind::ClassExistential:\n return SWIFT_CLASS_EXISTENTIAL;\n case RecordKind::ErrorExistential:\n return SWIFT_ERROR_EXISTENTIAL;\n case RecordKind::ExistentialMetatype:\n return SWIFT_EXISTENTIAL_METATYPE;\n case RecordKind::ClassInstance:\n return SWIFT_CLASS_INSTANCE;\n case RecordKind::ClosureContext:\n return SWIFT_CLOSURE_CONTEXT;\n }\n }\n case TypeInfoKind::Reference: {\n auto &ReferenceTI = cast(TI);\n switch (ReferenceTI.getReferenceKind()) {\n case ReferenceKind::Strong: return SWIFT_STRONG_REFERENCE;\n#define REF_STORAGE(Name, name, NAME) \\\n case ReferenceKind::Name: return SWIFT_##NAME##_REFERENCE;\n#include \"swift\/AST\/ReferenceStorage.def\"\n }\n }\n }\n\n swift_runtime_unreachable(\"Unhandled TypeInfoKind in switch\");\n}\n\nstatic swift_typeinfo_t convertTypeInfo(const TypeInfo *TI) {\n if (TI == nullptr) {\n return {\n SWIFT_UNKNOWN,\n 0,\n 0,\n 0,\n 0\n };\n }\n\n unsigned NumFields = 0;\n if (auto *RecordTI = dyn_cast(TI))\n NumFields = RecordTI->getNumFields();\n\n return {\n getTypeInfoKind(*TI),\n TI->getSize(),\n TI->getAlignment(),\n TI->getStride(),\n NumFields\n };\n}\n\nstatic swift_childinfo_t convertChild(const TypeInfo *TI, unsigned Index) {\n auto *RecordTI = cast(TI);\n auto &FieldInfo = RecordTI->getFields()[Index];\n\n return {\n FieldInfo.Name.c_str(),\n FieldInfo.Offset,\n getTypeInfoKind(FieldInfo.TI),\n reinterpret_cast(FieldInfo.TR),\n };\n}\n\nswift_typeinfo_t\nswift_reflection_infoForTypeRef(SwiftReflectionContextRef ContextRef,\n swift_typeref_t OpaqueTypeRef) {\n auto Context = ContextRef->nativeContext;\n auto TR = reinterpret_cast(OpaqueTypeRef);\n auto TI = Context->getTypeInfo(TR);\n return convertTypeInfo(TI);\n}\n\nswift_childinfo_t\nswift_reflection_childOfTypeRef(SwiftReflectionContextRef ContextRef,\n swift_typeref_t OpaqueTypeRef,\n unsigned Index) {\n auto Context = ContextRef->nativeContext;\n auto TR = reinterpret_cast(OpaqueTypeRef);\n auto *TI = Context->getTypeInfo(TR);\n return convertChild(TI, Index);\n}\n\nswift_typeinfo_t\nswift_reflection_infoForMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getMetadataTypeInfo(Metadata);\n return convertTypeInfo(TI);\n}\n\nswift_childinfo_t\nswift_reflection_childOfMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata,\n unsigned Index) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getMetadataTypeInfo(Metadata);\n return convertChild(TI, Index);\n}\n\nswift_typeinfo_t\nswift_reflection_infoForInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getInstanceTypeInfo(Object);\n return convertTypeInfo(TI);\n}\n\nswift_childinfo_t\nswift_reflection_childOfInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object,\n unsigned Index) {\n auto Context = ContextRef->nativeContext;\n auto *TI = Context->getInstanceTypeInfo(Object);\n return convertChild(TI, Index);\n}\n\nint swift_reflection_projectExistential(SwiftReflectionContextRef ContextRef,\n swift_addr_t ExistentialAddress,\n swift_typeref_t ExistentialTypeRef,\n swift_typeref_t *InstanceTypeRef,\n swift_addr_t *StartOfInstanceData) {\n auto Context = ContextRef->nativeContext;\n auto ExistentialTR = reinterpret_cast(ExistentialTypeRef);\n auto RemoteExistentialAddress = RemoteAddress(ExistentialAddress);\n const TypeRef *InstanceTR = nullptr;\n RemoteAddress RemoteStartOfInstanceData(nullptr);\n auto Success = Context->projectExistential(RemoteExistentialAddress,\n ExistentialTR,\n &InstanceTR,\n &RemoteStartOfInstanceData);\n\n if (Success) {\n *InstanceTypeRef = reinterpret_cast(InstanceTR);\n *StartOfInstanceData = RemoteStartOfInstanceData.getAddressData();\n }\n\n return Success;\n}\n\nvoid swift_reflection_dumpTypeRef(swift_typeref_t OpaqueTypeRef) {\n auto TR = reinterpret_cast(OpaqueTypeRef);\n if (TR == nullptr) {\n std::cout << \"\\n\";\n } else {\n TR->dump(std::cout);\n }\n}\n\nvoid swift_reflection_dumpInfoForTypeRef(SwiftReflectionContextRef ContextRef,\n swift_typeref_t OpaqueTypeRef) {\n auto Context = ContextRef->nativeContext;\n auto TR = reinterpret_cast(OpaqueTypeRef);\n auto TI = Context->getTypeInfo(TR);\n if (TI == nullptr) {\n std::cout << \"\\n\";\n } else {\n TI->dump(std::cout);\n }\n}\n\nvoid swift_reflection_dumpInfoForMetadata(SwiftReflectionContextRef ContextRef,\n uintptr_t Metadata) {\n auto Context = ContextRef->nativeContext;\n auto TI = Context->getMetadataTypeInfo(Metadata);\n if (TI == nullptr) {\n std::cout << \"\\n\";\n } else {\n TI->dump(std::cout);\n }\n}\n\nvoid swift_reflection_dumpInfoForInstance(SwiftReflectionContextRef ContextRef,\n uintptr_t Object) {\n auto Context = ContextRef->nativeContext;\n auto TI = Context->getInstanceTypeInfo(Object);\n if (TI == nullptr) {\n std::cout << \"\\n\";\n } else {\n TI->dump(std::cout);\n }\n}\n\nsize_t swift_reflection_demangle(const char *MangledName, size_t Length,\n char *OutDemangledName, size_t MaxLength) {\n if (MangledName == nullptr || Length == 0)\n return 0;\n\n std::string Mangled(MangledName, Length);\n auto Demangled = Demangle::demangleTypeAsString(Mangled);\n strncpy(OutDemangledName, Demangled.c_str(), MaxLength);\n return Demangled.size();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: networkdomain.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-01-16 13:17:55 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_HELPER_NETWORKDOMAIN_HXX_\n#include \n#endif\n\nnamespace framework\n{\n\n#ifdef WNT\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\n#define UNICODE\n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win NT, Win 2000, Win XP\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_NT( LPWSTR lpBuffer, DWORD nSize )\n{\n return GetEnvironmentVariable( TEXT(\"USERDOMAIN\"), lpBuffer, nSize );\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win 9x,Win ME\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_WINDOWS( LPWSTR lpBuffer, DWORD nSize )\n{\n HKEY hkeyLogon;\n HKEY hkeyWorkgroup;\n DWORD dwResult = 0;\n\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"Network\\\\Logon\"),\n 0, KEY_READ, &hkeyLogon ) )\n {\n DWORD dwLogon = 0;\n DWORD dwLogonSize = sizeof(dwLogon);\n LONG lResult = RegQueryValueEx( hkeyLogon, TEXT(\"LMLogon\"), 0, NULL, (LPBYTE)&dwLogon, &dwLogonSize );\n RegCloseKey( hkeyLogon );\n\n if ( dwLogon )\n {\n HKEY hkeyNetworkProvider;\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\MSNP32\\\\NetworkProvider\"),\n 0, KEY_READ, &hkeyNetworkProvider ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyNetworkProvider, TEXT(\"AuthenticatingAgent\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyNetworkProvider );\n }\n }\n }\n else if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\VxD\\\\VNETSUP\"),\n 0, KEY_READ, &hkeyWorkgroup ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyWorkgroup, TEXT(\"Workgroup\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyWorkgroup );\n }\n\n\n return dwResult;\n}\n\nstatic rtl::OUString GetUserDomain()\n{\n sal_Unicode aBuffer[256];\n\n long nVersion = GetVersion();\n DWORD nResult;\n\n if ( nVersion < 0 )\n nResult = GetUserDomainW_WINDOWS( aBuffer, sizeof( aBuffer ) );\n else\n nResult = GetUserDomainW_NT( aBuffer, sizeof( aBuffer ) );\n\n if ( nResult > 0 )\n return rtl::OUString( aBuffer );\n else\n return rtl::OUString();\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return ::rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return GetUserDomain();\n}\n\n#elif defined( UNIX )\n\n#include \n#include \n#include \n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\n#if defined( SOLARIS )\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Solaris\n\/\/_________________________________________________________________________________________________________________\n\n#include \n#include \n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char szBuffer[256];\n\n long nCopied = sizeof(szBuffer);\n char *pBuffer = szBuffer;\n long nBufSize;\n\n do\n {\n nBufSize = nCopied;\n nCopied = sysinfo( SI_SRPC_DOMAIN, pBuffer, nBufSize );\n\n \/* If nCopied is greater than buffersize we need to allocate\n a buffer with suitable size *\/\n\n if ( nCopied > nBufSize )\n pBuffer = (char *)alloca( nCopied );\n\n } while ( nCopied > nBufSize );\n\n if ( -1 != nCopied )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n nCopied - 1,\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#elif defined( LINUX ) \/* endif SOLARIS *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Linux\n\/\/_________________________________________________________________________________________________________________\n\n#include \n#include \n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char *pBuffer;\n int result;\n size_t nBufSize = 0;\n\n do\n {\n nBufSize += 256; \/* Increase buffer size by steps of 256 bytes *\/\n pBuffer = (char *)alloca( nBufSize );\n result = getdomainname( pBuffer, nBufSize );\n \/* If buffersize in not large enough -1 is returned and errno\n is set to EINVAL. This only applies to libc. With glibc the name\n is truncated. *\/\n } while ( -1 == result && EINVAL == errno );\n\n if ( 0 == result )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n strlen( pBuffer ),\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#else \/* LINUX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other Unix\n\/\/_________________________________________________________________________________________________________________\n\nstatic rtl_uString *getDomainName()\n{\n return NULL;\n}\n\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n rtl_uString* pResult = getDomainName();\n if ( pResult )\n return rtl::OUString( pResult );\n else\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return ::rtl::OUString();\n}\n\n#else \/* UNIX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other operating systems (non-Windows and non-Unix)\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return rtl::OUString();\n}\n\n#endif\n\n} \/\/ namespace framework\nINTEGRATION: CWS pchfix02 (1.5.148); FILE MERGED 2006\/09\/01 17:29:09 kaib 1.5.148.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: networkdomain.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 13:57:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n#ifndef __FRAMEWORK_HELPER_NETWORKDOMAIN_HXX_\n#include \n#endif\n\nnamespace framework\n{\n\n#ifdef WNT\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\n#define UNICODE\n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win NT, Win 2000, Win XP\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_NT( LPWSTR lpBuffer, DWORD nSize )\n{\n return GetEnvironmentVariable( TEXT(\"USERDOMAIN\"), lpBuffer, nSize );\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win 9x,Win ME\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_WINDOWS( LPWSTR lpBuffer, DWORD nSize )\n{\n HKEY hkeyLogon;\n HKEY hkeyWorkgroup;\n DWORD dwResult = 0;\n\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"Network\\\\Logon\"),\n 0, KEY_READ, &hkeyLogon ) )\n {\n DWORD dwLogon = 0;\n DWORD dwLogonSize = sizeof(dwLogon);\n LONG lResult = RegQueryValueEx( hkeyLogon, TEXT(\"LMLogon\"), 0, NULL, (LPBYTE)&dwLogon, &dwLogonSize );\n RegCloseKey( hkeyLogon );\n\n if ( dwLogon )\n {\n HKEY hkeyNetworkProvider;\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\MSNP32\\\\NetworkProvider\"),\n 0, KEY_READ, &hkeyNetworkProvider ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyNetworkProvider, TEXT(\"AuthenticatingAgent\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyNetworkProvider );\n }\n }\n }\n else if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\VxD\\\\VNETSUP\"),\n 0, KEY_READ, &hkeyWorkgroup ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyWorkgroup, TEXT(\"Workgroup\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyWorkgroup );\n }\n\n\n return dwResult;\n}\n\nstatic rtl::OUString GetUserDomain()\n{\n sal_Unicode aBuffer[256];\n\n long nVersion = GetVersion();\n DWORD nResult;\n\n if ( nVersion < 0 )\n nResult = GetUserDomainW_WINDOWS( aBuffer, sizeof( aBuffer ) );\n else\n nResult = GetUserDomainW_NT( aBuffer, sizeof( aBuffer ) );\n\n if ( nResult > 0 )\n return rtl::OUString( aBuffer );\n else\n return rtl::OUString();\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return ::rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return GetUserDomain();\n}\n\n#elif defined( UNIX )\n\n#include \n#include \n#include \n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\n#if defined( SOLARIS )\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Solaris\n\/\/_________________________________________________________________________________________________________________\n\n#include \n#include \n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char szBuffer[256];\n\n long nCopied = sizeof(szBuffer);\n char *pBuffer = szBuffer;\n long nBufSize;\n\n do\n {\n nBufSize = nCopied;\n nCopied = sysinfo( SI_SRPC_DOMAIN, pBuffer, nBufSize );\n\n \/* If nCopied is greater than buffersize we need to allocate\n a buffer with suitable size *\/\n\n if ( nCopied > nBufSize )\n pBuffer = (char *)alloca( nCopied );\n\n } while ( nCopied > nBufSize );\n\n if ( -1 != nCopied )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n nCopied - 1,\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#elif defined( LINUX ) \/* endif SOLARIS *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Linux\n\/\/_________________________________________________________________________________________________________________\n\n#include \n#include \n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char *pBuffer;\n int result;\n size_t nBufSize = 0;\n\n do\n {\n nBufSize += 256; \/* Increase buffer size by steps of 256 bytes *\/\n pBuffer = (char *)alloca( nBufSize );\n result = getdomainname( pBuffer, nBufSize );\n \/* If buffersize in not large enough -1 is returned and errno\n is set to EINVAL. This only applies to libc. With glibc the name\n is truncated. *\/\n } while ( -1 == result && EINVAL == errno );\n\n if ( 0 == result )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n strlen( pBuffer ),\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#else \/* LINUX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other Unix\n\/\/_________________________________________________________________________________________________________________\n\nstatic rtl_uString *getDomainName()\n{\n return NULL;\n}\n\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n rtl_uString* pResult = getDomainName();\n if ( pResult )\n return rtl::OUString( pResult );\n else\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return ::rtl::OUString();\n}\n\n#else \/* UNIX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other operating systems (non-Windows and non-Unix)\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return rtl::OUString();\n}\n\n#endif\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014-2015 Daniel Collin. All rights reserved.\n * License: http:\/\/www.opensource.org\/licenses\/BSD-2-Clause\n *\/\n\n#include \n#include \n#include \n#include \n#include \"imgui.h\"\n#include \"ocornut_imgui.h\"\n#include \n\n#if defined(SCI_NAMESPACE)\n#\tinclude \"..\/entry\/input.h\"\n#endif \/\/ defined(SCI_NAMESPACE)\n\n#include \"vs_ocornut_imgui.bin.h\"\n#include \"fs_ocornut_imgui.bin.h\"\n\nstruct OcornutImguiContext\n{\n\tstatic void* memAlloc(size_t _size);\n\tstatic void memFree(void* _ptr);\n\tstatic void renderDrawLists(ImDrawData* draw_data);\n\n\tvoid render(ImDrawData* draw_data)\n\t{\n\t\tconst float width = ImGui::GetIO().DisplaySize.x;\n\t\tconst float height = ImGui::GetIO().DisplaySize.y;\n\n\t\tfloat ortho[16];\n\t\tbx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, -1.0f, 1.0f);\n\n\t\tbgfx::setViewTransform(m_viewId, NULL, ortho);\n\n\t\t\/\/ Render command lists\n\t\tfor (int32_t ii = 0; ii < draw_data->CmdListsCount; ++ii)\n\t\t{\n\t\t\tbgfx::TransientVertexBuffer tvb;\n\t\t\tbgfx::TransientIndexBuffer tib;\n\n\t\t\tconst ImDrawList* cmd_list = draw_data->CmdLists[ii];\n\t\t\tuint32_t vtx_size = (uint32_t)cmd_list->VtxBuffer.size();\n\t\t\tuint32_t idx_size = (uint32_t)cmd_list->IdxBuffer.size();\n\n\t\t\tif (!bgfx::checkAvailTransientVertexBuffer(vtx_size, m_decl) || !bgfx::checkAvailTransientIndexBuffer(idx_size) )\n\t\t\t{\n\t\t\t\t\/\/ not enough space in transient buffer just quit drawing the rest...\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbgfx::allocTransientVertexBuffer(&tvb, vtx_size, m_decl);\n\t\t\tbgfx::allocTransientIndexBuffer(&tib, idx_size);\n\n\t\t\tImDrawVert* verts = (ImDrawVert*)tvb.data;\n\t\t\tmemcpy(verts, cmd_list->VtxBuffer.begin(), vtx_size * sizeof(ImDrawVert) );\n\n\t\t\tImDrawIdx* indices = (ImDrawIdx*)tib.data;\n\t\t\tmemcpy(indices, cmd_list->IdxBuffer.begin(), idx_size * sizeof(ImDrawIdx) );\n\n\t\t\tuint32_t elem_offset = 0;\n\t\t\tconst ImDrawCmd* pcmd_begin = cmd_list->CmdBuffer.begin();\n\t\t\tconst ImDrawCmd* pcmd_end = cmd_list->CmdBuffer.end();\n\t\t\tfor (const ImDrawCmd* pcmd = pcmd_begin; pcmd != pcmd_end; pcmd++)\n\t\t\t{\n\t\t\t\tif (pcmd->UserCallback)\n\t\t\t\t{\n\t\t\t\t\tpcmd->UserCallback(cmd_list, pcmd);\n\t\t\t\t\telem_offset += pcmd->ElemCount;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (0 == pcmd->ElemCount)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbgfx::setState(0\n\t\t\t\t\t| BGFX_STATE_RGB_WRITE\n\t\t\t\t\t| BGFX_STATE_ALPHA_WRITE\n\t\t\t\t\t| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)\n\t\t\t\t\t| BGFX_STATE_MSAA\n\t\t\t\t\t);\n\t\t\t\tbgfx::setScissor(uint16_t(bx::fmax(pcmd->ClipRect.x, 0.0f) )\n\t\t\t\t\t, uint16_t(bx::fmax(pcmd->ClipRect.y, 0.0f) )\n\t\t\t\t\t, uint16_t(bx::fmin(pcmd->ClipRect.z, 65535.0f)-bx::fmax(pcmd->ClipRect.x, 0.0f) )\n\t\t\t\t\t, uint16_t(bx::fmin(pcmd->ClipRect.w, 65535.0f)-bx::fmax(pcmd->ClipRect.y, 0.0f) )\n\t\t\t\t\t);\n\t\t\t\tunion { void* ptr; bgfx::TextureHandle handle; } texture = { pcmd->TextureId };\n\n\t\t\t\tbgfx::setTexture(0, s_tex, 0 != texture.handle.idx\n\t\t\t\t\t? texture.handle\n\t\t\t\t\t: m_texture\n\t\t\t\t\t);\n\n\t\t\t\tbgfx::setVertexBuffer(&tvb, 0, vtx_size);\n\t\t\t\tbgfx::setIndexBuffer(&tib, elem_offset, pcmd->ElemCount);\n\t\t\t\tbgfx::setProgram(m_program);\n\t\t\t\tbgfx::submit(m_viewId);\n\n\t\t\t\telem_offset += pcmd->ElemCount;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid create(const void* _data, uint32_t _size, float _fontSize, bx::AllocatorI* _allocator)\n\t{\n\t\tm_viewId = 255;\n\t\tm_allocator = _allocator;\n\t\tm_lastScroll = 0;\n\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tio.RenderDrawListsFn = renderDrawLists;\n\t\tif (NULL != m_allocator)\n\t\t{\n\t\t\tio.MemAllocFn = memAlloc;\n\t\t\tio.MemFreeFn = memFree;\n\t\t}\n\t\tio.DisplaySize = ImVec2(1280.0f, 720.0f);\n\t\tio.DeltaTime = 1.0f \/ 60.0f;\n\t\tio.IniFilename = NULL;\n\n#if defined(SCI_NAMESPACE)\n\t\tio.KeyMap[ImGuiKey_Tab] = (int)entry::Key::Tab;\n\t\tio.KeyMap[ImGuiKey_LeftArrow] = (int)entry::Key::Left;\n\t\tio.KeyMap[ImGuiKey_RightArrow] = (int)entry::Key::Right;\n\t\tio.KeyMap[ImGuiKey_UpArrow] = (int)entry::Key::Up;\n\t\tio.KeyMap[ImGuiKey_DownArrow] = (int)entry::Key::Down;\n\t\tio.KeyMap[ImGuiKey_Home] = (int)entry::Key::Home;\n\t\tio.KeyMap[ImGuiKey_End] = (int)entry::Key::End;\n\t\tio.KeyMap[ImGuiKey_Delete] = (int)entry::Key::Delete;\n\t\tio.KeyMap[ImGuiKey_Backspace] = (int)entry::Key::Backspace;\n\t\tio.KeyMap[ImGuiKey_Enter] = (int)entry::Key::Return;\n\t\tio.KeyMap[ImGuiKey_Escape] = (int)entry::Key::Esc;\n\t\tio.KeyMap[ImGuiKey_A] = (int)entry::Key::KeyA;\n\t\tio.KeyMap[ImGuiKey_C] = (int)entry::Key::KeyC;\n\t\tio.KeyMap[ImGuiKey_V] = (int)entry::Key::KeyV;\n\t\tio.KeyMap[ImGuiKey_X] = (int)entry::Key::KeyX;\n\t\tio.KeyMap[ImGuiKey_Y] = (int)entry::Key::KeyY;\n\t\tio.KeyMap[ImGuiKey_Z] = (int)entry::Key::KeyZ;\n#endif \/\/ defined(SCI_NAMESPACE)\n\n\t\tconst bgfx::Memory* vsmem;\n\t\tconst bgfx::Memory* fsmem;\n\n\t\tswitch (bgfx::getRendererType() )\n\t\t{\n\t\tcase bgfx::RendererType::Direct3D9:\n\t\t\tvsmem = bgfx::makeRef(vs_ocornut_imgui_dx9, sizeof(vs_ocornut_imgui_dx9) );\n\t\t\tfsmem = bgfx::makeRef(fs_ocornut_imgui_dx9, sizeof(fs_ocornut_imgui_dx9) );\n\t\t\tbreak;\n\n\t\tcase bgfx::RendererType::Direct3D11:\n\t\tcase bgfx::RendererType::Direct3D12:\n\t\t\tvsmem = bgfx::makeRef(vs_ocornut_imgui_dx11, sizeof(vs_ocornut_imgui_dx11) );\n\t\t\tfsmem = bgfx::makeRef(fs_ocornut_imgui_dx11, sizeof(fs_ocornut_imgui_dx11) );\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tvsmem = bgfx::makeRef(vs_ocornut_imgui_glsl, sizeof(vs_ocornut_imgui_glsl) );\n\t\t\tfsmem = bgfx::makeRef(fs_ocornut_imgui_glsl, sizeof(fs_ocornut_imgui_glsl) );\n\t\t\tbreak;\n\t\t}\n\n\t\tbgfx::ShaderHandle vsh = bgfx::createShader(vsmem);\n\t\tbgfx::ShaderHandle fsh = bgfx::createShader(fsmem);\n\t\tm_program = bgfx::createProgram(vsh, fsh, true);\n\n\t\tm_decl\n\t\t\t.begin()\n\t\t\t.add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)\n\t\t\t.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)\n\t\t\t.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)\n\t\t\t.end();\n\n\t\ts_tex = bgfx::createUniform(\"s_tex\", bgfx::UniformType::Int1);\n\n\t\tuint8_t* data;\n\t\tint32_t width;\n\t\tint32_t height;\n\t\tvoid* font = ImGui::MemAlloc(_size);\n\t\tmemcpy(font, _data, _size);\n\t\tio.Fonts->AddFontFromMemoryTTF(font, _size, _fontSize);\n\n\t\tio.Fonts->GetTexDataAsRGBA32(&data, &width, &height);\n\n\t\tm_texture = bgfx::createTexture2D( (uint16_t)width\n\t\t\t, (uint16_t)height\n\t\t\t, 1\n\t\t\t, bgfx::TextureFormat::BGRA8\n\t\t\t, 0\n\t\t\t, bgfx::copy(data, width*height*4)\n\t\t\t);\n\n\t\tImGuiStyle& style = ImGui::GetStyle();\n\t\tstyle.FrameRounding = 4.0f;\n\t}\n\n\tvoid destroy()\n\t{\n\t\tImGui::Shutdown();\n\n\t\tbgfx::destroyUniform(s_tex);\n\t\tbgfx::destroyTexture(m_texture);\n\t\tbgfx::destroyProgram(m_program);\n\n\t\tm_allocator = NULL;\n\t}\n\n\tvoid beginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, int _width, int _height, char _inputChar, uint8_t _viewId)\n\t{\n\t\tm_viewId = _viewId;\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tif (_inputChar < 0x7f)\n\t\t{\n\t\t\tio.AddInputCharacter(_inputChar); \/\/ ASCII or GTFO! :(\n\t\t}\n\n\t\tio.DisplaySize = ImVec2( (float)_width, (float)_height);\n\t\tio.DeltaTime = 1.0f \/ 60.0f;\n\t\tio.MousePos = ImVec2( (float)_mx, (float)_my);\n\t\tio.MouseDown[0] = 0 != (_button & IMGUI_MBUT_LEFT);\n\t\tio.MouseDown[1] = 0 != (_button & IMGUI_MBUT_RIGHT);\n\t\tio.MouseWheel = (float)(_scroll - m_lastScroll);\n\t\tm_lastScroll = _scroll;\n\n#if defined(SCI_NAMESPACE)\n\t\tuint8_t modifiers = inputGetModifiersState();\n\t\tio.KeyShift = 0 != (modifiers & (entry::Modifier::LeftShift | entry::Modifier::RightShift) );\n\t\tio.KeyCtrl = 0 != (modifiers & (entry::Modifier::LeftCtrl | entry::Modifier::RightCtrl ) );\n\t\tio.KeyAlt = 0 != (modifiers & (entry::Modifier::LeftAlt | entry::Modifier::RightAlt ) );\n\t\tfor (int32_t ii = 0; ii < (int32_t)entry::Key::Count; ++ii)\n\t\t{\n\t\t\tio.KeysDown[ii] = inputGetKeyState(entry::Key::Enum(ii) );\n\t\t}\n#endif \/\/ defined(SCI_NAMESPACE)\n\n\t\tImGui::NewFrame();\n\n\t\t\/\/ImGui::ShowTestWindow(); \/\/Debug only.\n\t}\n\n\tvoid endFrame()\n\t{\n\t\tImGui::Render();\n\t}\n\n\tbx::AllocatorI* m_allocator;\n\tbgfx::VertexDecl m_decl;\n\tbgfx::ProgramHandle m_program;\n\tbgfx::TextureHandle m_texture;\n\tbgfx::UniformHandle s_tex;\n\tuint8_t m_viewId;\n\tint32_t m_lastScroll;\n};\n\nstatic OcornutImguiContext s_ctx;\n\nvoid* OcornutImguiContext::memAlloc(size_t _size)\n{\n\treturn BX_ALLOC(s_ctx.m_allocator, _size);\n}\n\nvoid OcornutImguiContext::memFree(void* _ptr)\n{\n\tBX_FREE(s_ctx.m_allocator, _ptr);\n}\n\nvoid OcornutImguiContext::renderDrawLists(ImDrawData* draw_data)\n{\n\ts_ctx.render(draw_data);\n}\n\nvoid IMGUI_create(const void* _data, uint32_t _size, float _fontSize, bx::AllocatorI* _allocator)\n{\n\ts_ctx.create(_data, _size, _fontSize, _allocator);\n}\n\nvoid IMGUI_destroy()\n{\n\ts_ctx.destroy();\n}\n\nvoid IMGUI_beginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, int _width, int _height, char _inputChar, uint8_t _viewId)\n{\n\ts_ctx.beginFrame(_mx, _my, _button, _scroll, _width, _height, _inputChar, _viewId);\n}\n\nvoid IMGUI_endFrame()\n{\n\ts_ctx.endFrame();\n}\nFixed imgui delta time.\/*\n * Copyright 2014-2015 Daniel Collin. All rights reserved.\n * License: http:\/\/www.opensource.org\/licenses\/BSD-2-Clause\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"imgui.h\"\n#include \"ocornut_imgui.h\"\n#include \n\n#if defined(SCI_NAMESPACE)\n#\tinclude \"..\/entry\/input.h\"\n#endif \/\/ defined(SCI_NAMESPACE)\n\n#include \"vs_ocornut_imgui.bin.h\"\n#include \"fs_ocornut_imgui.bin.h\"\n\nstruct OcornutImguiContext\n{\n\tstatic void* memAlloc(size_t _size);\n\tstatic void memFree(void* _ptr);\n\tstatic void renderDrawLists(ImDrawData* draw_data);\n\n\tvoid render(ImDrawData* draw_data)\n\t{\n\t\tconst float width = ImGui::GetIO().DisplaySize.x;\n\t\tconst float height = ImGui::GetIO().DisplaySize.y;\n\n\t\tfloat ortho[16];\n\t\tbx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, -1.0f, 1.0f);\n\n\t\tbgfx::setViewTransform(m_viewId, NULL, ortho);\n\n\t\t\/\/ Render command lists\n\t\tfor (int32_t ii = 0; ii < draw_data->CmdListsCount; ++ii)\n\t\t{\n\t\t\tbgfx::TransientVertexBuffer tvb;\n\t\t\tbgfx::TransientIndexBuffer tib;\n\n\t\t\tconst ImDrawList* cmd_list = draw_data->CmdLists[ii];\n\t\t\tuint32_t vtx_size = (uint32_t)cmd_list->VtxBuffer.size();\n\t\t\tuint32_t idx_size = (uint32_t)cmd_list->IdxBuffer.size();\n\n\t\t\tif (!bgfx::checkAvailTransientVertexBuffer(vtx_size, m_decl) || !bgfx::checkAvailTransientIndexBuffer(idx_size) )\n\t\t\t{\n\t\t\t\t\/\/ not enough space in transient buffer just quit drawing the rest...\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tbgfx::allocTransientVertexBuffer(&tvb, vtx_size, m_decl);\n\t\t\tbgfx::allocTransientIndexBuffer(&tib, idx_size);\n\n\t\t\tImDrawVert* verts = (ImDrawVert*)tvb.data;\n\t\t\tmemcpy(verts, cmd_list->VtxBuffer.begin(), vtx_size * sizeof(ImDrawVert) );\n\n\t\t\tImDrawIdx* indices = (ImDrawIdx*)tib.data;\n\t\t\tmemcpy(indices, cmd_list->IdxBuffer.begin(), idx_size * sizeof(ImDrawIdx) );\n\n\t\t\tuint32_t elem_offset = 0;\n\t\t\tconst ImDrawCmd* pcmd_begin = cmd_list->CmdBuffer.begin();\n\t\t\tconst ImDrawCmd* pcmd_end = cmd_list->CmdBuffer.end();\n\t\t\tfor (const ImDrawCmd* pcmd = pcmd_begin; pcmd != pcmd_end; pcmd++)\n\t\t\t{\n\t\t\t\tif (pcmd->UserCallback)\n\t\t\t\t{\n\t\t\t\t\tpcmd->UserCallback(cmd_list, pcmd);\n\t\t\t\t\telem_offset += pcmd->ElemCount;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (0 == pcmd->ElemCount)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbgfx::setState(0\n\t\t\t\t\t| BGFX_STATE_RGB_WRITE\n\t\t\t\t\t| BGFX_STATE_ALPHA_WRITE\n\t\t\t\t\t| BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)\n\t\t\t\t\t| BGFX_STATE_MSAA\n\t\t\t\t\t);\n\t\t\t\tbgfx::setScissor(uint16_t(bx::fmax(pcmd->ClipRect.x, 0.0f) )\n\t\t\t\t\t, uint16_t(bx::fmax(pcmd->ClipRect.y, 0.0f) )\n\t\t\t\t\t, uint16_t(bx::fmin(pcmd->ClipRect.z, 65535.0f)-bx::fmax(pcmd->ClipRect.x, 0.0f) )\n\t\t\t\t\t, uint16_t(bx::fmin(pcmd->ClipRect.w, 65535.0f)-bx::fmax(pcmd->ClipRect.y, 0.0f) )\n\t\t\t\t\t);\n\t\t\t\tunion { void* ptr; bgfx::TextureHandle handle; } texture = { pcmd->TextureId };\n\n\t\t\t\tbgfx::setTexture(0, s_tex, 0 != texture.handle.idx\n\t\t\t\t\t? texture.handle\n\t\t\t\t\t: m_texture\n\t\t\t\t\t);\n\n\t\t\t\tbgfx::setVertexBuffer(&tvb, 0, vtx_size);\n\t\t\t\tbgfx::setIndexBuffer(&tib, elem_offset, pcmd->ElemCount);\n\t\t\t\tbgfx::setProgram(m_program);\n\t\t\t\tbgfx::submit(m_viewId);\n\n\t\t\t\telem_offset += pcmd->ElemCount;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid create(const void* _data, uint32_t _size, float _fontSize, bx::AllocatorI* _allocator)\n\t{\n\t\tm_viewId = 255;\n\t\tm_allocator = _allocator;\n\t\tm_lastScroll = 0;\n\t\tm_last = bx::getHPCounter();\n\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tio.RenderDrawListsFn = renderDrawLists;\n\t\tif (NULL != m_allocator)\n\t\t{\n\t\t\tio.MemAllocFn = memAlloc;\n\t\t\tio.MemFreeFn = memFree;\n\t\t}\n\n\t\tio.DisplaySize = ImVec2(1280.0f, 720.0f);\n\t\tio.DeltaTime = 1.0f \/ 60.0f;\n\t\tio.IniFilename = NULL;\n\n#if defined(SCI_NAMESPACE)\n\t\tio.KeyMap[ImGuiKey_Tab] = (int)entry::Key::Tab;\n\t\tio.KeyMap[ImGuiKey_LeftArrow] = (int)entry::Key::Left;\n\t\tio.KeyMap[ImGuiKey_RightArrow] = (int)entry::Key::Right;\n\t\tio.KeyMap[ImGuiKey_UpArrow] = (int)entry::Key::Up;\n\t\tio.KeyMap[ImGuiKey_DownArrow] = (int)entry::Key::Down;\n\t\tio.KeyMap[ImGuiKey_Home] = (int)entry::Key::Home;\n\t\tio.KeyMap[ImGuiKey_End] = (int)entry::Key::End;\n\t\tio.KeyMap[ImGuiKey_Delete] = (int)entry::Key::Delete;\n\t\tio.KeyMap[ImGuiKey_Backspace] = (int)entry::Key::Backspace;\n\t\tio.KeyMap[ImGuiKey_Enter] = (int)entry::Key::Return;\n\t\tio.KeyMap[ImGuiKey_Escape] = (int)entry::Key::Esc;\n\t\tio.KeyMap[ImGuiKey_A] = (int)entry::Key::KeyA;\n\t\tio.KeyMap[ImGuiKey_C] = (int)entry::Key::KeyC;\n\t\tio.KeyMap[ImGuiKey_V] = (int)entry::Key::KeyV;\n\t\tio.KeyMap[ImGuiKey_X] = (int)entry::Key::KeyX;\n\t\tio.KeyMap[ImGuiKey_Y] = (int)entry::Key::KeyY;\n\t\tio.KeyMap[ImGuiKey_Z] = (int)entry::Key::KeyZ;\n#endif \/\/ defined(SCI_NAMESPACE)\n\n\t\tconst bgfx::Memory* vsmem;\n\t\tconst bgfx::Memory* fsmem;\n\n\t\tswitch (bgfx::getRendererType() )\n\t\t{\n\t\tcase bgfx::RendererType::Direct3D9:\n\t\t\tvsmem = bgfx::makeRef(vs_ocornut_imgui_dx9, sizeof(vs_ocornut_imgui_dx9) );\n\t\t\tfsmem = bgfx::makeRef(fs_ocornut_imgui_dx9, sizeof(fs_ocornut_imgui_dx9) );\n\t\t\tbreak;\n\n\t\tcase bgfx::RendererType::Direct3D11:\n\t\tcase bgfx::RendererType::Direct3D12:\n\t\t\tvsmem = bgfx::makeRef(vs_ocornut_imgui_dx11, sizeof(vs_ocornut_imgui_dx11) );\n\t\t\tfsmem = bgfx::makeRef(fs_ocornut_imgui_dx11, sizeof(fs_ocornut_imgui_dx11) );\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tvsmem = bgfx::makeRef(vs_ocornut_imgui_glsl, sizeof(vs_ocornut_imgui_glsl) );\n\t\t\tfsmem = bgfx::makeRef(fs_ocornut_imgui_glsl, sizeof(fs_ocornut_imgui_glsl) );\n\t\t\tbreak;\n\t\t}\n\n\t\tbgfx::ShaderHandle vsh = bgfx::createShader(vsmem);\n\t\tbgfx::ShaderHandle fsh = bgfx::createShader(fsmem);\n\t\tm_program = bgfx::createProgram(vsh, fsh, true);\n\n\t\tm_decl\n\t\t\t.begin()\n\t\t\t.add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)\n\t\t\t.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)\n\t\t\t.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)\n\t\t\t.end();\n\n\t\ts_tex = bgfx::createUniform(\"s_tex\", bgfx::UniformType::Int1);\n\n\t\tuint8_t* data;\n\t\tint32_t width;\n\t\tint32_t height;\n\t\tvoid* font = ImGui::MemAlloc(_size);\n\t\tmemcpy(font, _data, _size);\n\t\tio.Fonts->AddFontFromMemoryTTF(font, _size, _fontSize);\n\n\t\tio.Fonts->GetTexDataAsRGBA32(&data, &width, &height);\n\n\t\tm_texture = bgfx::createTexture2D( (uint16_t)width\n\t\t\t, (uint16_t)height\n\t\t\t, 1\n\t\t\t, bgfx::TextureFormat::BGRA8\n\t\t\t, 0\n\t\t\t, bgfx::copy(data, width*height*4)\n\t\t\t);\n\n\t\tImGuiStyle& style = ImGui::GetStyle();\n\t\tstyle.FrameRounding = 4.0f;\n\t}\n\n\tvoid destroy()\n\t{\n\t\tImGui::Shutdown();\n\n\t\tbgfx::destroyUniform(s_tex);\n\t\tbgfx::destroyTexture(m_texture);\n\t\tbgfx::destroyProgram(m_program);\n\n\t\tm_allocator = NULL;\n\t}\n\n\tvoid beginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, int _width, int _height, char _inputChar, uint8_t _viewId)\n\t{\n\t\tm_viewId = _viewId;\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tif (_inputChar < 0x7f)\n\t\t{\n\t\t\tio.AddInputCharacter(_inputChar); \/\/ ASCII or GTFO! :(\n\t\t}\n\n\t\tio.DisplaySize = ImVec2( (float)_width, (float)_height);\n\n\t\tconst int64_t now = bx::getHPCounter();\n\t\tconst int64_t frameTime = now - m_last;\n\t\tm_last = now;\n\t\tconst double freq = double(bx::getHPFrequency() );\n\t\tio.DeltaTime = float(frameTime\/freq);\n\n\t\tio.MousePos = ImVec2( (float)_mx, (float)_my);\n\t\tio.MouseDown[0] = 0 != (_button & IMGUI_MBUT_LEFT);\n\t\tio.MouseDown[1] = 0 != (_button & IMGUI_MBUT_RIGHT);\n\t\tio.MouseWheel = (float)(_scroll - m_lastScroll);\n\t\tm_lastScroll = _scroll;\n\n#if defined(SCI_NAMESPACE)\n\t\tuint8_t modifiers = inputGetModifiersState();\n\t\tio.KeyShift = 0 != (modifiers & (entry::Modifier::LeftShift | entry::Modifier::RightShift) );\n\t\tio.KeyCtrl = 0 != (modifiers & (entry::Modifier::LeftCtrl | entry::Modifier::RightCtrl ) );\n\t\tio.KeyAlt = 0 != (modifiers & (entry::Modifier::LeftAlt | entry::Modifier::RightAlt ) );\n\t\tfor (int32_t ii = 0; ii < (int32_t)entry::Key::Count; ++ii)\n\t\t{\n\t\t\tio.KeysDown[ii] = inputGetKeyState(entry::Key::Enum(ii) );\n\t\t}\n#endif \/\/ defined(SCI_NAMESPACE)\n\n\t\tImGui::NewFrame();\n\n\t\tImGui::ShowTestWindow(); \/\/Debug only.\n\t}\n\n\tvoid endFrame()\n\t{\n\t\tImGui::Render();\n\t}\n\n\tbx::AllocatorI* m_allocator;\n\tbgfx::VertexDecl m_decl;\n\tbgfx::ProgramHandle m_program;\n\tbgfx::TextureHandle m_texture;\n\tbgfx::UniformHandle s_tex;\n\tint64_t m_last;\n\tint32_t m_lastScroll;\n\tuint8_t m_viewId;\n};\n\nstatic OcornutImguiContext s_ctx;\n\nvoid* OcornutImguiContext::memAlloc(size_t _size)\n{\n\treturn BX_ALLOC(s_ctx.m_allocator, _size);\n}\n\nvoid OcornutImguiContext::memFree(void* _ptr)\n{\n\tBX_FREE(s_ctx.m_allocator, _ptr);\n}\n\nvoid OcornutImguiContext::renderDrawLists(ImDrawData* draw_data)\n{\n\ts_ctx.render(draw_data);\n}\n\nvoid IMGUI_create(const void* _data, uint32_t _size, float _fontSize, bx::AllocatorI* _allocator)\n{\n\ts_ctx.create(_data, _size, _fontSize, _allocator);\n}\n\nvoid IMGUI_destroy()\n{\n\ts_ctx.destroy();\n}\n\nvoid IMGUI_beginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, int _width, int _height, char _inputChar, uint8_t _viewId)\n{\n\ts_ctx.beginFrame(_mx, _my, _button, _scroll, _width, _height, _inputChar, _viewId);\n}\n\nvoid IMGUI_endFrame()\n{\n\ts_ctx.endFrame();\n}\n<|endoftext|>"} {"text":"\/\/\/ @example store_primes_in_vector.cpp\n\/\/\/ Store primes in a std::vector using primesieve.\n\n#include \n#include \n\nint main()\n{\n std::vector primes;\n\n \/\/ Store the primes <= 1000\n primesieve::generate_primes(1000, &primes);\n\n primes.clear();\n\n \/\/ Store the first 1000 primes\n primesieve::generate_n_primes(1000, &primes);\n\n return 0;\n}\nAdd more examples\/\/\/ @example store_primes_in_vector.cpp\n\/\/\/ Store primes in a std::vector using primesieve.\n\n#include \n#include \n\nint main()\n{\n std::vector primes;\n\n \/\/ Store primes <= 1000\n primesieve::generate_primes(1000, &primes);\n\n primes.clear();\n\n \/\/ Store primes inside [1000, 2000]\n primesieve::generate_primes(1000, 2000, &primes);\n\n primes.clear();\n\n \/\/ Store first 1000 primes\n primesieve::generate_n_primes(1000, &primes);\n\n primes.clear();\n\n \/\/ Store first 10 primes >= 1000\n primesieve::generate_n_primes(10, 1000, &primes);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"src\/triangle.h\"\n\n\/\/ simplest case: will plot either a flat bottom or flat top triangles\nenum TriangleType\n{\n FLAT_BOTTOM,\n FLAT_TOP\n};\n\n\/\/ internal triangle renderer based on triangle type\nvoid drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type);\n\n\/\/ draw the triangle!\nvoid drawTriangle(const Triangle *t, unsigned char *buffer)\n{\n const Vertex *v0, *v1, *v2;\n\n v0 = &t->vertices[0];\n v1 = &t->vertices[1];\n v2 = &t->vertices[2];\n\n \/\/ sort vertices here so that v0 is topmost, then v1, then v2\n if(v0->position.y > v1->position.y)\n {\n v0 = &t->vertices[1];\n v1 = &t->vertices[0];\n }\n\n if(v0->position.y > v2->position.y)\n {\n v2 = v0;\n v0 = &t->vertices[2];\n }\n\n if(v1->position.y == v2->position.y)\n drawTriangleType(t, v0, v1, v2, buffer, FLAT_BOTTOM);\n else if(v0->position.y == v1->position.y)\n drawTriangleType(t, v2, v1, v0, buffer, FLAT_TOP);\n else\n {\n Vertex v3;\n\n if(v2->position.y > v1->position.y)\n {\n const Vertex *tmp = v2;\n v2 = v1;\n v1 = tmp;\n }\n\n v3.position.x = v0->position.x + ((float)(v2->position.y - v0->position.y) \/ (float)(v1->position.y - v0->position.y)) * (v1->position.x - v0->position.x);\n v3.position.y = v2->position.y;\n v3.position.z = v2->position.z;\n v3.uv.u = v1->uv.u * 0.5;\n v3.uv.v = v1->uv.v * 0.5;\n drawTriangleType(t, v0, &v3, v2, buffer, FLAT_BOTTOM);\n drawTriangleType(t, v1, &v3, v2, buffer, FLAT_TOP);\n }\n}\n\n\n\/*\n* Render counter clockwise (v0->v1->v2) for wanted effect.\n* v0 v0----v1\n* |\\ | \/\n* | \\ | \/\n* | \\ | \/\n* | \\ | \/\n* | \\ | \/\n* | \\ |\/\n* v2-----v1 v2\n*\/\nvoid drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type)\n{\n float invDy, dxLeft, dxRight, xLeft, xRight;\n int x, y, yDir = 1;\n \n if(type == FLAT_BOTTOM)\n {\n invDy = 1.f \/ (v2->position.y - v0->position.y);\n }\n else\n {\n invDy = 1.f \/ (v0->position.y - v2->position.y);\n yDir = -1;\n }\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n xLeft = v0->position.x;\n xRight = xLeft;\n\n if(!t->texture)\n {\n for(y = v0->position.y; ; y += yDir)\n {\n drawLine(xLeft, y, xRight, y, t->color, buffer);\n xLeft += dxLeft;\n xRight += dxRight;\n \n if(type == FLAT_BOTTOM && y >= v2->position.y)\n break;\n else if(type == FLAT_TOP && y <= v2->position.y)\n break;\n }\n }\n else\n {\n float texW = t->texture->width - 1;\n float texH = t->texture->height - 1;\n float duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;\n float dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;\n float duRight = texW * (v1->uv.u - v0->uv.u) * invDy;\n float dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;\n\n float uLeft = texW * v0->uv.u;\n float uRight = uLeft;\n float vLeft = texH * v0->uv.v;\n float vRight = vLeft;\n int startY = v0->position.y;\n int endY = v2->position.y;\n\n setPalette(t->texture->palette);\n \n if(type == FLAT_BOTTOM)\n y = startY;\n else\n {\n startY = v2->position.y;\n endY = v0->position.y;\n y = endY;\n }\n\n for(; ; y += yDir)\n {\n int startX = xLeft;\n int endX = xRight;\n float u = uLeft;\n float v = vLeft;\n float du, dv;\n float dx = endX - startX;\n\n if(dx > 0)\n {\n du = (uRight - uLeft) \/ dx;\n dv = (vRight - vLeft) \/ dx;\n }\n else\n {\n du = uRight - uLeft;\n dv = vRight - vLeft;\n }\n\n for(x = startX; x <= endX; ++x)\n {\n byte pixel = t->texture->data[(int)u + ((int)v << 6)];\n drawPixel(x, y, pixel, buffer);\n u += du;\n v += dv;\n }\n\n xLeft += dxLeft;\n xRight += dxRight;\n uLeft += duLeft;\n uRight += duRight;\n vLeft += dvLeft;\n vRight += dvRight;\n \n if(type == FLAT_BOTTOM && y >= endY)\n break;\n else if ( type == FLAT_TOP && y <= startY)\n break;\n }\n }\n}\nmore precision tweaks#include \"src\/triangle.h\"\n\n\/\/ simplest case: will plot either a flat bottom or flat top triangles\nenum TriangleType\n{\n FLAT_BOTTOM,\n FLAT_TOP\n};\n\n\/\/ internal triangle renderer based on triangle type\nvoid drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type);\n\n\/\/ draw the triangle!\nvoid drawTriangle(const Triangle *t, unsigned char *buffer)\n{\n const Vertex *v0, *v1, *v2;\n\n v0 = &t->vertices[0];\n v1 = &t->vertices[1];\n v2 = &t->vertices[2];\n\n \/\/ sort vertices here so that v0 is topmost, then v1, then v2\n if(v0->position.y > v1->position.y)\n {\n v0 = &t->vertices[1];\n v1 = &t->vertices[0];\n }\n\n if(v0->position.y > v2->position.y)\n {\n v2 = v0;\n v0 = &t->vertices[2];\n }\n\n if(v1->position.y == v2->position.y)\n drawTriangleType(t, v0, v1, v2, buffer, FLAT_BOTTOM);\n else if(v0->position.y == v1->position.y)\n drawTriangleType(t, v2, v1, v0, buffer, FLAT_TOP);\n else\n {\n Vertex v3;\n\n if(v2->position.y > v1->position.y)\n {\n const Vertex *tmp = v2;\n v2 = v1;\n v1 = tmp;\n }\n\n v3.position.x = v0->position.x + ((float)(v2->position.y - v0->position.y) \/ (float)(v1->position.y - v0->position.y)) * (v1->position.x - v0->position.x);\n v3.position.y = v2->position.y;\n v3.position.z = v2->position.z;\n v3.uv.u = v1->uv.u * 0.5;\n v3.uv.v = v1->uv.v * 0.5;\n drawTriangleType(t, v0, &v3, v2, buffer, FLAT_BOTTOM);\n drawTriangleType(t, v1, &v3, v2, buffer, FLAT_TOP);\n }\n}\n\n\n\/*\n* Render counter clockwise (v0->v1->v2) for wanted effect.\n* v0 v0----v1\n* |\\ | \/\n* | \\ | \/\n* | \\ | \/\n* | \\ | \/\n* | \\ | \/\n* | \\ |\/\n* v2-----v1 v2\n*\/\nvoid drawTriangleType(const Triangle *t, const Vertex *v0, const Vertex *v1, const Vertex *v2, unsigned char *buffer, enum TriangleType type)\n{\n double invDy, dxLeft, dxRight, xLeft, xRight;\n double x, y, yDir = 1;\n \n if(type == FLAT_BOTTOM)\n {\n invDy = 1.f \/ (v2->position.y - v0->position.y);\n }\n else\n {\n invDy = 1.f \/ (v0->position.y - v2->position.y);\n yDir = -1;\n }\n dxLeft = (v2->position.x - v0->position.x) * invDy;\n dxRight = (v1->position.x - v0->position.x) * invDy;\n xLeft = v0->position.x;\n xRight = xLeft;\n\n if(!t->texture)\n {\n for(y = v0->position.y; ; y += yDir)\n {\n drawLine(xLeft, y, xRight, y, t->color, buffer);\n xLeft += dxLeft;\n xRight += dxRight;\n \n if(type == FLAT_BOTTOM && y >= v2->position.y)\n break;\n else if(type == FLAT_TOP && y <= v2->position.y)\n break;\n }\n }\n else\n {\n float texW = t->texture->width - 1;\n float texH = t->texture->height - 1;\n float duLeft = texW * (v2->uv.u - v0->uv.u) * invDy;\n float dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy;\n float duRight = texW * (v1->uv.u - v0->uv.u) * invDy;\n float dvRight = texH * (v1->uv.v - v0->uv.v) * invDy;\n\n float uLeft = texW * v0->uv.u;\n float uRight = uLeft;\n float vLeft = texH * v0->uv.v;\n float vRight = vLeft;\n int startY = v0->position.y;\n int endY = v2->position.y;\n\n setPalette(t->texture->palette);\n \n if(type == FLAT_BOTTOM)\n y = startY;\n else\n {\n startY = v2->position.y;\n endY = v0->position.y;\n y = endY;\n }\n\n for(; ; y += yDir)\n {\n int startX = xLeft;\n int endX = xRight;\n float u = uLeft;\n float v = vLeft;\n float du, dv;\n float dx = endX - startX;\n\n if(dx > 0)\n {\n du = (uRight - uLeft) \/ dx;\n dv = (vRight - vLeft) \/ dx;\n }\n else\n {\n du = uRight - uLeft;\n dv = vRight - vLeft;\n }\n\n for(x = startX; x <= endX; ++x)\n {\n byte pixel = t->texture->data[(int)u + ((int)v << 6)];\n drawPixel(x, y, pixel, buffer);\n u += du;\n v += dv;\n }\n\n xLeft += dxLeft;\n xRight += dxRight;\n uLeft += duLeft;\n uRight += duRight;\n vLeft += dvLeft;\n vRight += dvRight;\n \n if(type == FLAT_BOTTOM && y >= endY)\n break;\n else if ( type == FLAT_TOP && y <= startY)\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \nusing namespace spii;\n\n#include \"hastighet.h\"\n\n\/\/ One term in the negative log-likelihood function for\n\/\/ a one-dimensional Gaussian distribution.\nstruct NegLogLikelihood\n{\n\tdouble sample;\n\tNegLogLikelihood(double sample)\n\t{\n\t\tthis->sample = sample;\n\t}\n\n\ttemplate\n\tR operator()(const R* const mu, const R* const sigma) const\n\t{\n\t\tR diff = (*mu - sample) \/ *sigma;\n\t\treturn 0.5 * diff*diff + log(*sigma);\n\t}\n};\n\nclass LikelihoodBenchmark :\n\tpublic hastighet::Test\n{\npublic:\n\tFunction f;\n\tdouble mu;\n\tdouble sigma;\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\tdouble out;\n\tSolver solver;\n\tSolverResults results;\n\n\tLikelihoodBenchmark() : \n\t\tx(2),\n\t\tg(2)\n\t{\n\t\tstd::mt19937 prng(unsigned(1));\n\t\tstd::normal_distribution normal;\n\t\tauto randn = std::bind(normal, prng);\n\n\t\tmu = 5.0;\n\t\tsigma = 3.0;\n\n\t\tf.add_variable(&mu, 1);\n\t\tf.add_variable(&sigma, 1);\n\n\t\tfor (int i = 0; i < 10000; ++i) {\n\t\t\tdouble sample = sigma*randn() + mu;\n\t\t\tauto* llh = new NegLogLikelihood(sample);\n\t\t\tf.add_term(new AutoDiffTerm(llh), &mu, &sigma);\n\t\t}\n\n\t\tf.copy_user_to_global(&x);\n\t\tf.set_number_of_threads(1);\n\n\t\tsolver.log_function = [](const std::string&) { };\n\t\tsolver.maximum_iterations = 1;\n\t}\n};\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate)\n{\n\tf.evaluate();\n}\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate_x)\n{\n\tf.evaluate(x);\n}\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate_x_g)\n{\n\tf.evaluate(x, &g);\n}\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate_x_g_H)\n{\n\tf.evaluate(x, &g, &H);\n}\n\nstruct LennardJonesTerm\n{\n\ttemplate\n\tR operator()(const R* const p1, const R* const p2) const\n\t{\n\t\tR dx = p1[0] - p2[0];\n\t\tR dy = p1[1] - p2[1];\n\t\tR dz = p1[2] - p2[2];\n\t\tR r2 = dx*dx + dy*dy + dz*dz;\n\t\tR r6 = r2*r2*r2;\n\t\tR r12 = r6*r6;\n\t\treturn 1.0 \/ r12 - 2.0 \/ r6;\n\t}\n};\n\nclass LennardJonesBenchmark :\n\tpublic hastighet::Test\n{\npublic:\n\tFunction potential;\n\tstd::vector points;\n\tstd::vector org_points;\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\tSolver solver;\n\tSolverResults results;\n\n\tLennardJonesBenchmark() : \n\t\tpoints(100)\n\t{\n\t\tstd::mt19937 prng(1);\n\t\tstd::normal_distribution normal;\n\t\tauto randn = std::bind(normal, prng);\n\n\t\tint N = points.size();\n\t\tint n = int(std::ceil(std::pow(double(N), 1.0\/3.0)));\n\n\t\t\/\/ Initial position is a cubic grid with random pertubations.\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tint x = i % n;\n\t\t\tint y = (i \/ n) % n;\n\t\t\tint z = (i \/ n) \/ n;\n\n\t\t\tpotential.add_variable(&points[i][0], 3);\n\t\t\tpoints[i][0] = x + 0.05 * randn();\n\t\t\tpoints[i][1] = y + 0.05 * randn();\n\t\t\tpoints[i][2] = z + 0.05 * randn();\n\t\t}\n\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (int j = i + 1; j < N; ++j) {\n\t\t\t\tpotential.add_term(\n\t\t\t\t\tnew AutoDiffTerm(\n\t\t\t\t\t\tnew LennardJonesTerm),\n\t\t\t\t\t\t&points[i][0],\n\t\t\t\t\t\t&points[j][0]);\n\t\t\t}\n\t\t}\n\n\t\tx.resize(potential.get_number_of_scalars());\n\t\tpotential.copy_user_to_global(&x);\n\t\tg.resize(potential.get_number_of_scalars());\n\t\torg_points = points;\n\n\t\tpotential.set_number_of_threads(1);\n\n\t\tsolver.log_function = [](const std::string&) { };\n\t\tsolver.maximum_iterations = 1;\n\t}\n};\n\nBENCHMARK_F(LennardJonesBenchmark, solver_1_newton_iter)\n{\n\tpoints = org_points;\n\tsolver.solve_newton(potential, &results);\n}\n\nBENCHMARK_F(LennardJonesBenchmark, solver_1_lbfgs_iter)\n{\n\tpoints = org_points;\n\tsolver.solve_lbfgs(potential, &results);\n}\n\nint main(int argc, char** argv)\n{\n\thastighet::Benchmarker::RunAllTests(argc, argv);\n}\nNo solver in function benchmark.#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \nusing namespace spii;\n\n#include \"hastighet.h\"\n\n\/\/ One term in the negative log-likelihood function for\n\/\/ a one-dimensional Gaussian distribution.\nstruct NegLogLikelihood\n{\n\tdouble sample;\n\tNegLogLikelihood(double sample)\n\t{\n\t\tthis->sample = sample;\n\t}\n\n\ttemplate\n\tR operator()(const R* const mu, const R* const sigma) const\n\t{\n\t\tR diff = (*mu - sample) \/ *sigma;\n\t\treturn 0.5 * diff*diff + log(*sigma);\n\t}\n};\n\nclass LikelihoodBenchmark :\n\tpublic hastighet::Test\n{\npublic:\n\tFunction f;\n\tdouble mu;\n\tdouble sigma;\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\tdouble out;\n\n\tLikelihoodBenchmark() : \n\t\tx(2),\n\t\tg(2)\n\t{\n\t\tstd::mt19937 prng(unsigned(1));\n\t\tstd::normal_distribution normal;\n\t\tauto randn = std::bind(normal, prng);\n\n\t\tmu = 5.0;\n\t\tsigma = 3.0;\n\n\t\tf.add_variable(&mu, 1);\n\t\tf.add_variable(&sigma, 1);\n\n\t\tfor (int i = 0; i < 10000; ++i) {\n\t\t\tdouble sample = sigma*randn() + mu;\n\t\t\tauto* llh = new NegLogLikelihood(sample);\n\t\t\tf.add_term(new AutoDiffTerm(llh), &mu, &sigma);\n\t\t}\n\n\t\tf.copy_user_to_global(&x);\n\t\tf.set_number_of_threads(1);\n\t}\n};\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate)\n{\n\tf.evaluate();\n}\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate_x)\n{\n\tf.evaluate(x);\n}\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate_x_g)\n{\n\tf.evaluate(x, &g);\n}\n\nBENCHMARK_F(LikelihoodBenchmark, evaluate_x_g_H)\n{\n\tf.evaluate(x, &g, &H);\n}\n\nstruct LennardJonesTerm\n{\n\ttemplate\n\tR operator()(const R* const p1, const R* const p2) const\n\t{\n\t\tR dx = p1[0] - p2[0];\n\t\tR dy = p1[1] - p2[1];\n\t\tR dz = p1[2] - p2[2];\n\t\tR r2 = dx*dx + dy*dy + dz*dz;\n\t\tR r6 = r2*r2*r2;\n\t\tR r12 = r6*r6;\n\t\treturn 1.0 \/ r12 - 2.0 \/ r6;\n\t}\n};\n\nclass LennardJonesBenchmark :\n\tpublic hastighet::Test\n{\npublic:\n\tFunction potential;\n\tstd::vector points;\n\tstd::vector org_points;\n\tEigen::VectorXd x, g;\n\tEigen::MatrixXd H;\n\n\tLennardJonesBenchmark() : \n\t\tpoints(100)\n\t{\n\t\tstd::mt19937 prng(1);\n\t\tstd::normal_distribution normal;\n\t\tauto randn = std::bind(normal, prng);\n\n\t\tint N = points.size();\n\t\tint n = int(std::ceil(std::pow(double(N), 1.0\/3.0)));\n\n\t\t\/\/ Initial position is a cubic grid with random pertubations.\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tint x = i % n;\n\t\t\tint y = (i \/ n) % n;\n\t\t\tint z = (i \/ n) \/ n;\n\n\t\t\tpotential.add_variable(&points[i][0], 3);\n\t\t\tpoints[i][0] = x + 0.05 * randn();\n\t\t\tpoints[i][1] = y + 0.05 * randn();\n\t\t\tpoints[i][2] = z + 0.05 * randn();\n\t\t}\n\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (int j = i + 1; j < N; ++j) {\n\t\t\t\tpotential.add_term(\n\t\t\t\t\tnew AutoDiffTerm(\n\t\t\t\t\t\tnew LennardJonesTerm),\n\t\t\t\t\t\t&points[i][0],\n\t\t\t\t\t\t&points[j][0]);\n\t\t\t}\n\t\t}\n\n\t\tx.resize(potential.get_number_of_scalars());\n\t\tpotential.copy_user_to_global(&x);\n\t\tg.resize(potential.get_number_of_scalars());\n\t\torg_points = points;\n\n\t\tpotential.set_number_of_threads(1);\n\t}\n};\n\nBENCHMARK_F(LennardJonesBenchmark, evaluate)\n{\n\tpotential.evaluate();\n}\n\nBENCHMARK_F(LennardJonesBenchmark, evaluate_x)\n{\n\tpotential.evaluate(x);\n}\n\nBENCHMARK_F(LennardJonesBenchmark, evaluate_x_g)\n{\n\tpotential.evaluate(x, &g);\n}\n\nBENCHMARK_F(LennardJonesBenchmark, evaluate_x_g_H)\n{\n\tpotential.evaluate(x, &g, &H);\n}\n\nint main(int argc, char** argv)\n{\n\thastighet::Benchmarker::RunAllTests(argc, argv);\n}\n<|endoftext|>"} {"text":"#include \"include\/rados\/librados.h\"\n#include \"include\/rados\/librados.hpp\"\n#include \"test\/rados-api\/test.h\"\n\n#include \n#include \"gtest\/gtest.h\"\n\nusing namespace librados;\n\nTEST(LibRadosIo, SimpleWrite) {\n char buf[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, SimpleWritePP) {\n char buf[128];\n std::string pool_name = get_temp_pool_name();\n Rados cluster;\n ASSERT_EQ(\"\", create_one_pool_pp(pool_name, cluster));\n IoCtx ioctx;\n cluster.ioctx_create(pool_name.c_str(), ioctx);\n memset(buf, 0xcc, sizeof(buf));\n bufferlist bl;\n bl.append(buf, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), ioctx.write(\"foo\", bl, sizeof(buf), 0));\n ioctx.close();\n ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));\n}\n\nTEST(LibRadosIo, RoundTrip) {\n char buf[128];\n char buf2[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n memset(buf2, 0, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, OverlappingWriteRoundTrip) {\n char buf[128];\n char buf2[64];\n char buf3[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n memset(buf2, 0xdd, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), rados_write(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n memset(buf3, 0xdd, sizeof(buf3));\n ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, \"foo\", buf3, sizeof(buf3), 0));\n ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2)));\n ASSERT_EQ(0, memcmp(buf3 + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, WriteFullRoundTrip) {\n char buf[128];\n char buf2[64];\n char buf3[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n memset(buf2, 0xdd, sizeof(buf2));\n ASSERT_EQ(0, rados_write_full(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n memset(buf3, 0xdd, sizeof(buf3));\n ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, \"foo\", buf3, sizeof(buf3), 0));\n ASSERT_EQ(0, memcmp(buf2, buf2, sizeof(buf2)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, AppendRoundTrip) {\n char buf[64];\n char buf2[64];\n char buf3[sizeof(buf) + sizeof(buf2)];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xde, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n memset(buf2, 0xad, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), rados_append(ioctx, \"foo\", buf2, sizeof(buf2)));\n memset(buf3, 0, sizeof(buf3));\n ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, \"foo\", buf3, sizeof(buf3), 0));\n ASSERT_EQ(0, memcmp(buf3, buf, sizeof(buf)));\n ASSERT_EQ(0, memcmp(buf3 + sizeof(buf), buf2, sizeof(buf2)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, TruncTest) {\n char buf[128];\n char buf2[sizeof(buf)];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ(0, rados_trunc(ioctx, \"foo\", sizeof(buf) \/ 2));\n memset(buf2, 0, sizeof(buf2));\n ASSERT_EQ((int)(sizeof(buf)\/2), rados_read(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)\/2));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, RemoveTest) {\n char buf[128];\n char buf2[sizeof(buf)];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ(0, rados_remove(ioctx, \"foo\"));\n memset(buf2, 0, sizeof(buf2));\n ASSERT_EQ(-ENOENT, rados_read(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, XattrsRoundTrip) {\n char buf[128];\n char attr1[] = \"attr1\";\n char attr1_buf[] = \"foo bar baz\";\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, \"foo\", attr1, buf, sizeof(buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n rados_setxattr(ioctx, \"foo\", attr1, attr1_buf, sizeof(attr1_buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n\t rados_getxattr(ioctx, \"foo\", attr1, buf, sizeof(buf)));\n ASSERT_EQ(0, memcmp(attr1_buf, buf, sizeof(attr1_buf)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, RmXattr) {\n char buf[128];\n char attr1[] = \"attr1\";\n char attr1_buf[] = \"foo bar baz\";\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n rados_setxattr(ioctx, \"foo\", attr1, attr1_buf, sizeof(attr1_buf)));\n ASSERT_EQ(0, rados_rmxattr(ioctx, \"foo\", attr1));\n ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, \"foo\", attr1, buf, sizeof(buf)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, XattrIter) {\n char buf[128];\n char attr1[] = \"attr1\";\n char attr1_buf[] = \"foo bar baz\";\n char attr2[] = \"attr2\";\n char attr2_buf[256];\n for (size_t j = 0; j < sizeof(attr2_buf); ++j) {\n attr2_buf[j] = j % 0xff;\n }\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n rados_setxattr(ioctx, \"foo\", attr1, attr1_buf, sizeof(attr1_buf)));\n ASSERT_EQ((int)sizeof(attr2_buf),\n rados_setxattr(ioctx, \"foo\", attr2, attr2_buf, sizeof(attr2_buf)));\n rados_xattrs_iter_t iter;\n ASSERT_EQ(0, rados_getxattrs(ioctx, \"foo\", &iter));\n int num_seen = 0;\n while (true) {\n const char *name;\n const char *val;\n size_t len;\n ASSERT_EQ(0, rados_getxattrs_next(iter, &name, &val, &len));\n if (name == NULL) {\n break;\n }\n ASSERT_LT(num_seen, 2);\n if ((strcmp(name, attr1) == 0) && (memcmp(val, attr1_buf, len) == 0)) {\n num_seen++;\n continue;\n }\n else if ((strcmp(name, attr2) == 0) && (memcmp(val, attr2_buf, len) == 0)) {\n num_seen++;\n continue;\n }\n else {\n ASSERT_EQ(0, 1);\n }\n }\n rados_getxattrs_end(iter);\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\ntest\/rados-api\/io.cc: test RoundTripPP, etc.#include \"include\/rados\/librados.h\"\n#include \"include\/rados\/librados.hpp\"\n#include \"test\/rados-api\/test.h\"\n\n#include \n#include \"gtest\/gtest.h\"\n\nusing namespace librados;\n\nTEST(LibRadosIo, SimpleWrite) {\n char buf[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, SimpleWritePP) {\n char buf[128];\n std::string pool_name = get_temp_pool_name();\n Rados cluster;\n ASSERT_EQ(\"\", create_one_pool_pp(pool_name, cluster));\n IoCtx ioctx;\n cluster.ioctx_create(pool_name.c_str(), ioctx);\n memset(buf, 0xcc, sizeof(buf));\n bufferlist bl;\n bl.append(buf, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), ioctx.write(\"foo\", bl, sizeof(buf), 0));\n ioctx.close();\n ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));\n}\n\nTEST(LibRadosIo, RoundTrip) {\n char buf[128];\n char buf2[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n memset(buf2, 0, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, RoundTripPP) {\n char buf[128];\n char buf2[128];\n Rados cluster;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool_pp(pool_name, cluster));\n IoCtx ioctx;\n cluster.ioctx_create(pool_name.c_str(), ioctx);\n memset(buf, 0xcc, sizeof(buf));\n bufferlist bl;\n bl.append(buf, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), ioctx.write(\"foo\", bl, sizeof(buf), 0));\n bufferlist cl;\n ASSERT_EQ((int)sizeof(buf2), ioctx.read(\"foo\", cl, sizeof(buf), 0));\n ASSERT_EQ(0, memcmp(buf, cl.c_str(), sizeof(buf)));\n ioctx.close();\n ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));\n}\n\nTEST(LibRadosIo, OverlappingWriteRoundTrip) {\n char buf[128];\n char buf2[64];\n char buf3[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n memset(buf2, 0xdd, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), rados_write(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n memset(buf3, 0xdd, sizeof(buf3));\n ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, \"foo\", buf3, sizeof(buf3), 0));\n ASSERT_EQ(0, memcmp(buf3, buf2, sizeof(buf2)));\n ASSERT_EQ(0, memcmp(buf3 + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, OverlappingWriteRoundTripPP) {\n char buf[128];\n char buf2[64];\n Rados cluster;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool_pp(pool_name, cluster));\n IoCtx ioctx;\n cluster.ioctx_create(pool_name.c_str(), ioctx);\n memset(buf, 0xcc, sizeof(buf));\n bufferlist bl1;\n bl1.append(buf, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), ioctx.write(\"foo\", bl1, sizeof(buf), 0));\n memset(buf2, 0xdd, sizeof(buf2));\n bufferlist bl2;\n bl2.append(buf2, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), ioctx.write(\"foo\", bl2, sizeof(buf2), 0));\n bufferlist bl3;\n ASSERT_EQ((int)sizeof(buf), ioctx.read(\"foo\", bl3, sizeof(buf), 0));\n ASSERT_EQ(0, memcmp(bl3.c_str(), buf2, sizeof(buf2)));\n ASSERT_EQ(0, memcmp(bl3.c_str() + sizeof(buf2), buf, sizeof(buf) - sizeof(buf2)));\n ioctx.close();\n ASSERT_EQ(0, destroy_one_pool_pp(pool_name, cluster));\n}\n\nTEST(LibRadosIo, WriteFullRoundTrip) {\n char buf[128];\n char buf2[64];\n char buf3[128];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xcc, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_write(ioctx, \"foo\", buf, sizeof(buf), 0));\n memset(buf2, 0xdd, sizeof(buf2));\n ASSERT_EQ(0, rados_write_full(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n memset(buf3, 0xdd, sizeof(buf3));\n ASSERT_EQ((int)sizeof(buf2), rados_read(ioctx, \"foo\", buf3, sizeof(buf3), 0));\n ASSERT_EQ(0, memcmp(buf2, buf2, sizeof(buf2)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, AppendRoundTrip) {\n char buf[64];\n char buf2[64];\n char buf3[sizeof(buf) + sizeof(buf2)];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xde, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n memset(buf2, 0xad, sizeof(buf2));\n ASSERT_EQ((int)sizeof(buf2), rados_append(ioctx, \"foo\", buf2, sizeof(buf2)));\n memset(buf3, 0, sizeof(buf3));\n ASSERT_EQ((int)sizeof(buf3), rados_read(ioctx, \"foo\", buf3, sizeof(buf3), 0));\n ASSERT_EQ(0, memcmp(buf3, buf, sizeof(buf)));\n ASSERT_EQ(0, memcmp(buf3 + sizeof(buf), buf2, sizeof(buf2)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, TruncTest) {\n char buf[128];\n char buf2[sizeof(buf)];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ(0, rados_trunc(ioctx, \"foo\", sizeof(buf) \/ 2));\n memset(buf2, 0, sizeof(buf2));\n ASSERT_EQ((int)(sizeof(buf)\/2), rados_read(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)\/2));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, RemoveTest) {\n char buf[128];\n char buf2[sizeof(buf)];\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ(0, rados_remove(ioctx, \"foo\"));\n memset(buf2, 0, sizeof(buf2));\n ASSERT_EQ(-ENOENT, rados_read(ioctx, \"foo\", buf2, sizeof(buf2), 0));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, XattrsRoundTrip) {\n char buf[128];\n char attr1[] = \"attr1\";\n char attr1_buf[] = \"foo bar baz\";\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, \"foo\", attr1, buf, sizeof(buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n rados_setxattr(ioctx, \"foo\", attr1, attr1_buf, sizeof(attr1_buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n\t rados_getxattr(ioctx, \"foo\", attr1, buf, sizeof(buf)));\n ASSERT_EQ(0, memcmp(attr1_buf, buf, sizeof(attr1_buf)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, RmXattr) {\n char buf[128];\n char attr1[] = \"attr1\";\n char attr1_buf[] = \"foo bar baz\";\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n rados_setxattr(ioctx, \"foo\", attr1, attr1_buf, sizeof(attr1_buf)));\n ASSERT_EQ(0, rados_rmxattr(ioctx, \"foo\", attr1));\n ASSERT_EQ(-ENODATA, rados_getxattr(ioctx, \"foo\", attr1, buf, sizeof(buf)));\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n\nTEST(LibRadosIo, XattrIter) {\n char buf[128];\n char attr1[] = \"attr1\";\n char attr1_buf[] = \"foo bar baz\";\n char attr2[] = \"attr2\";\n char attr2_buf[256];\n for (size_t j = 0; j < sizeof(attr2_buf); ++j) {\n attr2_buf[j] = j % 0xff;\n }\n rados_t cluster;\n rados_ioctx_t ioctx;\n std::string pool_name = get_temp_pool_name();\n ASSERT_EQ(\"\", create_one_pool(pool_name, &cluster));\n rados_ioctx_create(cluster, pool_name.c_str(), &ioctx);\n memset(buf, 0xaa, sizeof(buf));\n ASSERT_EQ((int)sizeof(buf), rados_append(ioctx, \"foo\", buf, sizeof(buf)));\n ASSERT_EQ((int)sizeof(attr1_buf),\n rados_setxattr(ioctx, \"foo\", attr1, attr1_buf, sizeof(attr1_buf)));\n ASSERT_EQ((int)sizeof(attr2_buf),\n rados_setxattr(ioctx, \"foo\", attr2, attr2_buf, sizeof(attr2_buf)));\n rados_xattrs_iter_t iter;\n ASSERT_EQ(0, rados_getxattrs(ioctx, \"foo\", &iter));\n int num_seen = 0;\n while (true) {\n const char *name;\n const char *val;\n size_t len;\n ASSERT_EQ(0, rados_getxattrs_next(iter, &name, &val, &len));\n if (name == NULL) {\n break;\n }\n ASSERT_LT(num_seen, 2);\n if ((strcmp(name, attr1) == 0) && (memcmp(val, attr1_buf, len) == 0)) {\n num_seen++;\n continue;\n }\n else if ((strcmp(name, attr2) == 0) && (memcmp(val, attr2_buf, len) == 0)) {\n num_seen++;\n continue;\n }\n else {\n ASSERT_EQ(0, 1);\n }\n }\n rados_getxattrs_end(iter);\n rados_ioctx_destroy(ioctx);\n ASSERT_EQ(0, destroy_one_pool(pool_name, &cluster));\n}\n<|endoftext|>"} {"text":"\/*The MIT License (MIT)\n\nCopyright (c) 2017 k-brac\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\/**\n* Switch betwenn member and static operator<< for serializing.\n* Usefull if both are defined\n*\/\n\/\/#define CUTI_USE_MEMBER_SERIALIZE\n\n\/**\n* Prepend test_ to all function declared using CUTI_TEST in XCode.\n* Indeed XCode needs the prefix \"test\" to automatically detect test methods\n*\/\n#define CUTI_PREPEND_TEST\n#include \"Cuti.h\"\n#undef CUTI_PREPEND_TEST\n#include \"ComputeInt.h\"\n\n\nCUTI_DEFAULT_TO_STRING(ComputeInt);\n\nCUTI_TEST_CLASS(TestLibInt){\npublic:\n\tvoid simpleAssertTest() {\n\t\tComputeInt c(5);\n\t\tCUTI_ASSERT(c.add(-2) != 0);\n\t\tCUTI_ASSERT(c.add(-2) != 0, \"c.add should have returned a value != 0\");\n\t}\n\n\tvoid assertThrowTest() {\n\t\tComputeInt c(1);\n\t\tCUTI_ASSERT_THROW(c.divide(0), std::runtime_error);\n\t\tCUTI_ASSERT_THROW(c.divide(0), std::runtime_error, \"Tried to divide by 0\");\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_THROW(c.divide(0), std::logic_error));\n\t}\n\t\n\tvoid assertNoThrowTest() {\n\t\tComputeInt c(1);\n\t\tCUTI_ASSERT_NO_THROW(c.divide(1));\n\t\tCUTI_ASSERT_NO_THROW(c.divide(1), \"Should not have thrown\");\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_NO_THROW(c.divide(0)));\n\t}\n\n\tvoid assertFailTest() {\n\t\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_FAIL(\"This test has failed\"));\n uint16_t a = 0, b = 0;\n CUTI_ASSERT_EQUAL(a, b);\n\t}\n\n \n\tvoid assertLessTest() {\n\t\tComputeInt c(5);\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESS(10, c.add(5)));\n\t\tCUTI_ASSERT_LESS(10, c.add(1));\n\t\tCUTI_ASSERT_LESSEQUAL(10, c.add(5));\n\t\tCUTI_ASSERT_LESSEQUAL(10, c.add(1));\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESSEQUAL(10, c.add(6)));\n\t}\n\n\tvoid assertGreaterTest() {\n\t\tComputeInt c(5);\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATER(11, c.add(5)));\n\t\tCUTI_ASSERT_GREATER(1, c.add(1));\n\t\tCUTI_ASSERT_GREATEREQUAL(1, c.add(5));\n\t\tCUTI_ASSERT_GREATEREQUAL(10, c.add(6));\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATEREQUAL(10, c.add(1)));\n\t}\n\n\tvoid assertEqual() {\n\t\tComputeInt c(5);\n ComputeInt c2(5);\n\t\tCUTI_ASSERT_EQUAL(5, c.add(0), \"Should be equal\");\n\t\tCUTI_ASSERT_EQUAL(5, c.add(0));\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_EQUAL(10, c.add(1)));\n CUTI_ASSERT_EQUAL(c, c2);\n\t}\n\n CUTI_BEGIN_TESTS_REGISTRATION(TestLibInt);\n CUTI_TEST(simpleAssertTest);\n CUTI_TEST(assertThrowTest);\n CUTI_TEST(assertNoThrowTest);\n CUTI_TEST(assertFailTest);\n CUTI_TEST(assertLessTest);\n CUTI_TEST(assertGreaterTest);\n CUTI_TEST(assertEqual);\n CUTI_END_TESTS_REGISTRATION();\/\/must be the last statement in the class\n};\nshould fix visual studio 2017 compilation\/*The MIT License (MIT)\n\nCopyright (c) 2017 k-brac\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n\/**\n* Switch between member and static operator<< for serializing.\n* Usefull if both are defined\n*\/\n#define CUTI_USE_MEMBER_SERIALIZE\n\n\/**\n* Prepend test_ to all function declared using CUTI_TEST in XCode.\n* Indeed XCode needs the prefix \"test\" to automatically detect test methods\n*\/\n#define CUTI_PREPEND_TEST\n#include \"Cuti.h\"\n#undef CUTI_PREPEND_TEST\n#include \"ComputeInt.h\"\n\n\nCUTI_DEFAULT_TO_STRING(ComputeInt);\n\nCUTI_TEST_CLASS(TestLibInt){\npublic:\n\tvoid simpleAssertTest() {\n\t\tComputeInt c(5);\n\t\tCUTI_ASSERT(c.add(-2) != 0);\n\t\tCUTI_ASSERT(c.add(-2) != 0, \"c.add should have returned a value != 0\");\n\t}\n\n\tvoid assertThrowTest() {\n\t\tComputeInt c(1);\n\t\tCUTI_ASSERT_THROW(c.divide(0), std::runtime_error);\n\t\tCUTI_ASSERT_THROW(c.divide(0), std::runtime_error, \"Tried to divide by 0\");\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_THROW(c.divide(0), std::logic_error));\n\t}\n\t\n\tvoid assertNoThrowTest() {\n\t\tComputeInt c(1);\n\t\tCUTI_ASSERT_NO_THROW(c.divide(1));\n\t\tCUTI_ASSERT_NO_THROW(c.divide(1), \"Should not have thrown\");\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_NO_THROW(c.divide(0)));\n\t}\n\n\tvoid assertFailTest() {\n\t\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_FAIL(\"This test has failed\"));\n uint16_t a = 0, b = 0;\n CUTI_ASSERT_EQUAL(a, b);\n\t}\n\n \n\tvoid assertLessTest() {\n\t\tComputeInt c(5);\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESS(10, c.add(5)));\n\t\tCUTI_ASSERT_LESS(10, c.add(1));\n\t\tCUTI_ASSERT_LESSEQUAL(10, c.add(5));\n\t\tCUTI_ASSERT_LESSEQUAL(10, c.add(1));\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_LESSEQUAL(10, c.add(6)));\n\t}\n\n\tvoid assertGreaterTest() {\n\t\tComputeInt c(5);\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATER(11, c.add(5)));\n\t\tCUTI_ASSERT_GREATER(1, c.add(1));\n\t\tCUTI_ASSERT_GREATEREQUAL(1, c.add(5));\n\t\tCUTI_ASSERT_GREATEREQUAL(10, c.add(6));\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_GREATEREQUAL(10, c.add(1)));\n\t}\n\n\tvoid assertEqual() {\n\t\tComputeInt c(5);\n ComputeInt c2(5);\n\t\tCUTI_ASSERT_EQUAL(5, c.add(0), \"Should be equal\");\n\t\tCUTI_ASSERT_EQUAL(5, c.add(0));\n\t\t\/\/CUTI_ASSERT_ASSERTION_FAIL(CUTI_ASSERT_EQUAL(10, c.add(1)));\n CUTI_ASSERT_EQUAL(c, c2);\n\t}\n\n CUTI_BEGIN_TESTS_REGISTRATION(TestLibInt);\n CUTI_TEST(simpleAssertTest);\n CUTI_TEST(assertThrowTest);\n CUTI_TEST(assertNoThrowTest);\n CUTI_TEST(assertFailTest);\n CUTI_TEST(assertLessTest);\n CUTI_TEST(assertGreaterTest);\n CUTI_TEST(assertEqual);\n CUTI_END_TESTS_REGISTRATION();\/\/must be the last statement in the class\n};\n<|endoftext|>"} {"text":"#include \"util.h\"\n\n#include \"clientversion.h\"\n#include \"primitives\/transaction.h\"\n#include \"random.h\"\n#include \"sync.h\"\n#include \"utilstrencodings.h\"\n#include \"utilmoneystr.h\"\n#include \"test\/test_bitcoin.h\"\n\n#include \n#include \n\n#include \"chainparams.h\"\n#include \"consensus\/consensus.h\"\n#include \"consensus\/validation.h\"\n#include \"key.h\"\n#include \"validation.h\"\n#include \"miner.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n#include \"txdb.h\"\n#include \"txmempool.h\"\n#include \"ui_interface.h\"\n#include \"rpc\/server.h\"\n#include \"rpc\/register.h\"\n#include \"zerocoin.h\"\n#include \"znodeman.h\"\n#include \"znode-sync.h\"\n#include \"znode-payments.h\"\n\n#include \"test\/testutil.h\"\n#include \"consensus\/merkle.h\"\n\n#include \"wallet\/db.h\"\n#include \"wallet\/wallet.h\"\n\n#include \n#include \n#include \n\nextern CCriticalSection cs_main;\nusing namespace std;\n\nCScript scriptPubKeyZnode;\n\n\nstruct ZnodeTestingSetup : public TestingSetup {\n ZnodeTestingSetup() : TestingSetup(CBaseChainParams::REGTEST)\n {\n CPubKey newKey;\n BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));\n\n string strAddress = CBitcoinAddress(newKey.GetID()).ToString();\n pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), \"\",\n ( \"receive\"));\n\n scriptPubKeyZnode = CScript() << ToByteVector(newKey\/*coinbaseKey.GetPubKey()*\/) << OP_CHECKSIG;\n bool mtp = false;\n CBlock b;\n for (int i = 0; i < 150; i++)\n {\n std::vector noTxns;\n b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, mtp);\n coinbaseTxns.push_back(*b.vtx[0]);\n LOCK(cs_main);\n {\n LOCK(pwalletMain->cs_wallet);\n pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);\n } \n }\n }\n\n CBlock CreateBlock(const std::vector& txns,\n const CScript& scriptPubKeyZnode, bool mtp = false) {\n const CChainParams& chainparams = Params();\n std::unique_ptr pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKeyZnode);\n CBlock block = pblocktemplate->block;\n\n \/\/ Replace mempool-selected txns with just coinbase plus passed-in txns:\n if(txns.size() > 0) {\n block.vtx.resize(1);\n BOOST_FOREACH(const CMutableTransaction& tx, txns)\n block.vtx.push_back(MakeTransactionRef(tx));\n }\n \/\/ IncrementExtraNonce creates a valid coinbase and merkleRoot\n unsigned int extraNonce = 0;\n IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);\n\n while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){\n ++block.nNonce;\n }\n if(mtp) {\n while (!CheckMerkleTreeProof(block, chainparams.GetConsensus())){\n block.mtpHashValue = mtp::hash(block, Params().GetConsensus().powLimit);\n }\n }\n else {\n while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){\n ++block.nNonce;\n }\n }\n\n \/\/delete pblocktemplate;\n return block;\n }\n\n bool ProcessBlock(const CBlock &block) {\n const CChainParams& chainparams = Params();\n return ProcessNewBlock(chainparams, std::make_shared(block), true, NULL);\n }\n\n \/\/ Create a new block with just given transactions, coinbase paying to\n \/\/ scriptPubKeyZnode, and try to add it to the current chain.\n CBlock CreateAndProcessBlock(const std::vector& txns,\n const CScript& scriptPubKeyZnode, bool mtp = false){\n\n CBlock block = CreateBlock(txns, scriptPubKeyZnode, mtp);\n BOOST_CHECK_MESSAGE(ProcessBlock(block), \"Processing block failed\");\n return block;\n }\n\n std::vector coinbaseTxns; \/\/ For convenience, coinbase transactions\n CKey coinbaseKey; \/\/ private\/public key needed to spend coinbase transactions\n};\n\nBOOST_FIXTURE_TEST_SUITE(znode_tests, ZnodeTestingSetup)\n\nBOOST_AUTO_TEST_CASE(Test_EnforceZnodePayment)\n{\n\n std::vector noTxns;\n CBlock b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, false);\n const CChainParams& chainparams = Params();\n\n CMutableTransaction tx = *b.vtx[0];\n bool mutated;\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n\n BOOST_CHECK(CTransaction(tx).IsCoinBase());\n\n CValidationState state;\n BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));\n \/\/BOOST_CHECK(true == CheckTransaction(tx, state, tx.GetHash(), false, INT_MAX));\n\n auto const before_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK\n , after_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK + 1;\n \/\/ Emulates synced state of znodes.\n for(size_t i =0; i < 4; ++i)\n znodeSync.SwitchToNextAsset();\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Paying to the best payee\n CZnodePayee payee1(tx.vout[1].scriptPubKey, uint256());\n \/\/ Emulates 6 votes for the payee\n for(size_t i =0; i < 5; ++i)\n payee1.AddVoteHash(uint256());\n\n CZnodeBlockPayees payees;\n payees.vecPayees.push_back(payee1);\n\n znpayments.mapZnodeBlocks[after_block] = payees;\n\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(tx, state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Paying to a completely wrong payee\n CMutableTransaction txCopy = tx;\n txCopy.vout[1].scriptPubKey = txCopy.vout[0].scriptPubKey;\n b.vtx[0] = MakeTransactionRef(txCopy);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Making znodes not synchronized and checking the functionality is disabled\n znodeSync.Reset();\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Paying to an acceptable payee\n for(size_t i =0; i < 4; ++i)\n znodeSync.SwitchToNextAsset();\n\n CZnodePayee payee2(tx.vout[0].scriptPubKey, uint256());\n \/\/ Emulates 9 votes for the payee\n for(size_t i =0; i < 8; ++i)\n payee2.AddVoteHash(uint256());\n\n znpayments.mapZnodeBlocks[after_block].vecPayees.insert(znpayments.mapZnodeBlocks[after_block].vecPayees.begin(), payee2);\n\n txCopy.vout[1].scriptPubKey = payee1.GetPayee();\n b.vtx[0] = MakeTransactionRef(txCopy);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Checking the functionality is disabled for previous blocks\n txCopy.vout[1].scriptPubKey = txCopy.vout[2].scriptPubKey;\n b.vtx[0] = MakeTransactionRef(txCopy);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n znpayments.mapZnodeBlocks[before_block] = payees;\n\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, before_block));\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\nZnode test fix#include \"util.h\"\n\n#include \"clientversion.h\"\n#include \"primitives\/transaction.h\"\n#include \"random.h\"\n#include \"sync.h\"\n#include \"utilstrencodings.h\"\n#include \"utilmoneystr.h\"\n#include \"test\/test_bitcoin.h\"\n\n#include \n#include \n\n#include \"chainparams.h\"\n#include \"consensus\/consensus.h\"\n#include \"consensus\/validation.h\"\n#include \"key.h\"\n#include \"validation.h\"\n#include \"miner.h\"\n#include \"pubkey.h\"\n#include \"random.h\"\n#include \"txdb.h\"\n#include \"txmempool.h\"\n#include \"ui_interface.h\"\n#include \"rpc\/server.h\"\n#include \"rpc\/register.h\"\n#include \"zerocoin.h\"\n#include \"znodeman.h\"\n#include \"znode-sync.h\"\n#include \"znode-payments.h\"\n\n#include \"test\/testutil.h\"\n#include \"consensus\/merkle.h\"\n\n#include \"wallet\/db.h\"\n#include \"wallet\/wallet.h\"\n\n#include \n#include \n#include \n\nextern CCriticalSection cs_main;\nusing namespace std;\n\nCScript scriptPubKeyZnode;\n\n\nstruct ZnodeTestingSetup : public TestingSetup {\n ZnodeTestingSetup() : TestingSetup(CBaseChainParams::REGTEST)\n {\n CPubKey newKey;\n BOOST_CHECK(pwalletMain->GetKeyFromPool(newKey));\n\n string strAddress = CBitcoinAddress(newKey.GetID()).ToString();\n pwalletMain->SetAddressBook(CBitcoinAddress(strAddress).Get(), \"\",\n ( \"receive\"));\n\n scriptPubKeyZnode = CScript() << ToByteVector(newKey\/*coinbaseKey.GetPubKey()*\/) << OP_CHECKSIG;\n bool mtp = false;\n CBlock b;\n for (int i = 0; i < 150; i++)\n {\n std::vector noTxns;\n b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, mtp);\n coinbaseTxns.push_back(*b.vtx[0]);\n LOCK(cs_main);\n {\n LOCK(pwalletMain->cs_wallet);\n pwalletMain->AddToWalletIfInvolvingMe(*b.vtx[0], chainActive.Tip(), 0, true);\n } \n }\n }\n\n CBlock CreateBlock(const std::vector& txns,\n const CScript& scriptPubKeyZnode, bool mtp = false) {\n const CChainParams& chainparams = Params();\n std::unique_ptr pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKeyZnode);\n CBlock block = pblocktemplate->block;\n\n \/\/ Replace mempool-selected txns with just coinbase plus passed-in txns:\n if(txns.size() > 0) {\n block.vtx.resize(1);\n BOOST_FOREACH(const CMutableTransaction& tx, txns)\n block.vtx.push_back(MakeTransactionRef(tx));\n }\n \/\/ IncrementExtraNonce creates a valid coinbase and merkleRoot\n unsigned int extraNonce = 0;\n IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);\n\n while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){\n ++block.nNonce;\n }\n if(mtp) {\n while (!CheckMerkleTreeProof(block, chainparams.GetConsensus())){\n block.mtpHashValue = mtp::hash(block, Params().GetConsensus().powLimit);\n }\n }\n else {\n while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())){\n ++block.nNonce;\n }\n }\n\n \/\/delete pblocktemplate;\n return block;\n }\n\n bool ProcessBlock(const CBlock &block) {\n const CChainParams& chainparams = Params();\n return ProcessNewBlock(chainparams, std::make_shared(block), true, NULL);\n }\n\n \/\/ Create a new block with just given transactions, coinbase paying to\n \/\/ scriptPubKeyZnode, and try to add it to the current chain.\n CBlock CreateAndProcessBlock(const std::vector& txns,\n const CScript& scriptPubKeyZnode, bool mtp = false){\n\n CBlock block = CreateBlock(txns, scriptPubKeyZnode, mtp);\n BOOST_CHECK_MESSAGE(ProcessBlock(block), \"Processing block failed\");\n return block;\n }\n\n std::vector coinbaseTxns; \/\/ For convenience, coinbase transactions\n CKey coinbaseKey; \/\/ private\/public key needed to spend coinbase transactions\n};\n\nBOOST_FIXTURE_TEST_SUITE(znode_tests, ZnodeTestingSetup)\n\nnamespace {\n size_t FindZnodeOutput(CTransaction const & tx) {\n static std::vector const founders {\n GetScriptForDestination(CBitcoinAddress(\"TDk19wPKYq91i18qmY6U9FeTdTxwPeSveo\").Get()),\n GetScriptForDestination(CBitcoinAddress(\"TWZZcDGkNixTAMtRBqzZkkMHbq1G6vUTk5\").Get()),\n GetScriptForDestination(CBitcoinAddress(\"TRZTFdNCKCKbLMQV8cZDkQN9Vwuuq4gDzT\").Get()),\n GetScriptForDestination(CBitcoinAddress(\"TG2ruj59E5b1u9G3F7HQVs6pCcVDBxrQve\").Get()),\n GetScriptForDestination(CBitcoinAddress(\"TCsTzQZKVn4fao8jDmB9zQBk9YQNEZ3XfS\").Get()),\n };\n\n BOOST_CHECK(tx.IsCoinBase());\n for(size_t i = 0; i < tx.vout.size(); ++i) {\n CTxOut const & out = tx.vout[i];\n if(std::find(founders.begin(), founders.end(), out.scriptPubKey) == founders.end()) {\n if(out.nValue == GetZnodePayment(Params().GetConsensus(), false))\n return i;\n }\n }\n throw std::runtime_error(\"Cannot find the Znode output\");\n }\n}\nBOOST_AUTO_TEST_CASE(Test_EnforceZnodePayment)\n{\n\n std::vector noTxns;\n CBlock b = CreateAndProcessBlock(noTxns, scriptPubKeyZnode, false);\n const CChainParams& chainparams = Params();\n\n CMutableTransaction tx = *b.vtx[0];\n bool mutated;\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n\n BOOST_CHECK(CTransaction(tx).IsCoinBase());\n\n CValidationState state;\n BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));\n \/\/BOOST_CHECK(true == CheckTransaction(tx, state, tx.GetHash(), false, INT_MAX));\n\n auto const before_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK\n , after_block = ZC_ZNODE_PAYMENT_BUG_FIXED_AT_BLOCK + 1;\n \/\/ Emulates synced state of znodes.\n for(size_t i =0; i < 4; ++i)\n znodeSync.SwitchToNextAsset();\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Paying to the best payee\n CZnodePayee payee1(tx.vout[1].scriptPubKey, uint256());\n \/\/ Emulates 6 votes for the payee\n for(size_t i =0; i < 5; ++i)\n payee1.AddVoteHash(uint256());\n\n CZnodeBlockPayees payees;\n payees.vecPayees.push_back(payee1);\n\n znpayments.mapZnodeBlocks[after_block] = payees;\n\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(tx, state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Paying to a completely wrong payee\n size_t const znodeOutput = FindZnodeOutput(tx);\n CMutableTransaction txCopy = tx;\n txCopy.vout[znodeOutput].scriptPubKey = txCopy.vout[0].scriptPubKey;\n b.vtx[0] = MakeTransactionRef(txCopy);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus(), true, true, after_block));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Making znodes not synchronized and checking the functionality is disabled\n CTxOut storedCopy = tx.vout[znodeOutput];\n tx.vout.erase(tx.vout.begin() + znodeOutput);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n\n BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus(), true, true, after_block));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n tx.vout.insert(tx.vout.begin() + znodeOutput, storedCopy);\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Making znodes not synchronized and checking the functionality is disabled\n znodeSync.Reset();\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Paying to an acceptable payee\n for(size_t i =0; i < 4; ++i)\n znodeSync.SwitchToNextAsset();\n\n CZnodePayee payee2(tx.vout[0].scriptPubKey, uint256());\n \/\/ Emulates 9 votes for the payee\n for(size_t i =0; i < 8; ++i)\n payee2.AddVoteHash(uint256());\n\n znpayments.mapZnodeBlocks[after_block].vecPayees.insert(znpayments.mapZnodeBlocks[after_block].vecPayees.begin(), payee2);\n\n txCopy.vout[1].scriptPubKey = payee1.GetPayee();\n b.vtx[0] = MakeTransactionRef(txCopy);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Checking the functionality is disabled for previous blocks\n txCopy.vout[1].scriptPubKey = txCopy.vout[2].scriptPubKey;\n b.vtx[0] = MakeTransactionRef(txCopy);\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(false == CheckBlock(b, state, chainparams.GetConsensus()));\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, after_block));\n\n znpayments.mapZnodeBlocks[before_block] = payees;\n\n b.fChecked = false;\n b.hashMerkleRoot = BlockMerkleRoot(b, &mutated);\n while (!CheckProofOfWork(b.GetHash(), b.nBits, chainparams.GetConsensus())){\n ++b.nNonce;\n }\n BOOST_CHECK(true == CheckTransaction(*b.vtx[0], state, true, tx.GetHash(), false, before_block));\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"hotKeyManager.h\"\n\nusing namespace qReal;\n\nHotKeyManager::HotKeyManager()\n\t: mCurrentModifer(\"\")\n{\n}\n\nHotKeyManager& HotKeyManager::instance()\n{\n\tstatic HotKeyManager instance;\n\treturn instance;\n}\n\nvoid HotKeyManager::setCommand(const QString &id, const QString &label, QAction *command)\n{\n\tcommand->setWhatsThis(label);\n\n\tinstance().registerCommand(id, command);\n}\n\nvoid HotKeyManager::deleteCommand(QString const &id)\n{\n\tresetShortcuts(id);\n\tinstance().deleteCommandPrivate(id);\n}\n\nbool HotKeyManager::setShortcut(QString const &id, QKeySequence const &keyseq)\n{\n\treturn instance().registerShortcut(id, keyseq);\n}\n\nbool HotKeyManager::setShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)\n{\n\treturn instance().registerShortcut(id, modifier, mousebutton);\n}\n\nvoid HotKeyManager::resetShortcuts(QString const &id)\n{\n\tinstance().resetShortcutsPrivate(id);\n}\n\nvoid HotKeyManager::resetAllShortcuts()\n{\n\tinstance().resetAllShortcutsPrivate();\n}\n\nvoid HotKeyManager::deleteShortcut(const QString &id, const QString &shortcut)\n{\n\tinstance().deleteShortcutPrivate(id, shortcut);\n}\n\nvoid HotKeyManager::doShortcut(QEvent *event)\n{\n\tMouseButtons mb = None;\n\tswitch(event->type()) {\n\t\tcase QEvent::Wheel: {\n\t\t\tmb = static_cast(event)->delta() > 0 ? MouseWU : MouseWD;\n\t\t\tbreak;\n\t\t}\n\t\tcase QEvent::MouseButtonPress: {\n\t\t\tswitch(static_cast(event)->button()) {\n\t\t\t\tcase Qt::RightButton:\n\t\t\t\t\tmb = MouseRB;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Qt::LeftButton:\n\t\t\t\t\tmb = MouseLB;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Qt::MiddleButton:\n\t\t\t\t\tmb = MouseMB;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tinstance().findShortcut(sequence(instance().currentModifier(), mb));\n}\n\nvoid HotKeyManager::setCurrentModifier(const QString &modifier)\n{\n\tinstance().setCurrentModifierPrivate(modifier);\n}\n\nQHash HotKeyManager::commands()\n{\n\treturn instance().commandsPrivate();\n}\n\nQHash HotKeyManager::shortcuts()\n{\n\treturn instance().shortcutsPrivate();\n}\n\nvoid HotKeyManager::registerCommand(const QString &id, QAction *command)\n{\n\tQList shortcuts = command->shortcuts();\n\n\tforeach (QKeySequence const &shortcut, shortcuts) {\n\t\tinstance().registerShortcut(id, shortcut.toString());\n\t}\n\n\tmCommands[id] = command;\n}\n\nbool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &keyseq)\n{\n\tif (mCommands.contains(id)) {\n\t\tQString const shortcut = keyseq.toString();\n\n\t\tif (!hasPrefixOf(shortcut)) {\n\t\t\taddPrefixes(shortcut);\n\t\t\tmShortcuts[shortcut] = id;\n\t\t\tmCommands[id]->setShortcuts(mCommands[id]->shortcuts() << keyseq);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)\n{\n\tif (mCommands.contains(id)) {\n\t\tQString const shortcut = sequence(modifier.toString(), mousebutton);\n\n\t\tif (!mShortcuts.contains(shortcut)) {\n\t\t\taddPrefixes(shortcut);\n\t\t\tmShortcuts[shortcut] = id;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid HotKeyManager::registerShortcut(QString const &id, QString const &shortcut)\n{\n\tif (!hasPrefixOf(shortcut)) {\n\t\taddPrefixes(shortcut);\n\t\tmShortcuts[shortcut] = id;\n\t}\n}\n\nvoid HotKeyManager::findShortcut(QString const &shortcut)\n{\n\tif (mShortcuts.contains(shortcut) && mCommands[mShortcuts.value(shortcut)]->parentWidget()->isActiveWindow()) {\n\t\tmCommands[mShortcuts.value(shortcut)]->trigger();\n\t}\n}\n\nQString HotKeyManager::sequence(const QString &modifier, MouseButtons mousebutton)\n{\n\tQString seq = modifier;\n\n\tswitch(mousebutton) {\n\tcase MouseLB:\n\t\tseq += \"MouseLB\";\n\t\tbreak;\n\tcase MouseRB:\n\t\tseq += \"MouseRB\";\n\t\tbreak;\n\tcase MouseMB:\n\t\tseq += \"MouseMB\";\n\t\tbreak;\n\tcase MouseWU:\n\t\tseq += \"MouseWU\";\n\t\tbreak;\n\tcase MouseWD:\n\t\tseq += \"MouseWD\";\n\t}\n\n\treturn seq;\n}\n\nvoid HotKeyManager::setCurrentModifierPrivate(QString const &modifier)\n{\n\tmCurrentModifer = modifier;\n}\n\nQString HotKeyManager::currentModifier()\n{\n\treturn mCurrentModifer;\n}\n\nvoid HotKeyManager::resetShortcutsPrivate(QString const &id)\n{\n\tif (mCommands.contains(id)) {\n\t\tQList shortcuts = mShortcuts.keys(id);\n\n\t\tforeach (QString const &shortcut, shortcuts) {\n\t\t\tdeletePrefixes(shortcut);\n\t\t\tmShortcuts.remove(shortcut);\n\t\t}\n\n\t\tmCommands[id]->setShortcuts(QList());\n\t}\n}\n\nvoid HotKeyManager::resetAllShortcutsPrivate()\n{\n\tQList cmds = mCommands.values();\n\n\tforeach (QAction *cmd, cmds) {\n\t\tcmd->setShortcuts(QList());\n\t}\n\n\tmShortcuts.clear();\n\tmPrefixes.clear();\n}\n\nvoid HotKeyManager::deleteShortcutPrivate(const QString &id, const QString &shortcut)\n{\n\tmShortcuts.remove(shortcut);\n\tdeletePrefixes(shortcut);\n\t\/\/if == \"\" then shortcut with mouse\n\tif (QKeySequence(shortcut).toString() != \"\" ) {\n\t\tQList shortcuts = mCommands[id]->shortcuts();\n\n\t\tshortcuts.removeOne(shortcut);\n\t\tmCommands[id]->setShortcuts(shortcuts);\n\t}\n}\n\nvoid HotKeyManager::deleteCommandPrivate(QString const &id)\n{\n\tif (mCommands.contains(id)) {\n\t\tmCommands.remove(id);\n\t}\n}\n\nQHash HotKeyManager::commandsPrivate()\n{\n\treturn mCommands;\n}\n\nQHash HotKeyManager::shortcutsPrivate()\n{\n\treturn mShortcuts;\n}\n\nbool HotKeyManager::hasPrefixOf(QString const &keyseq)\n{\n\tif (!mPrefixes.contains(keyseq)) {\n\t\tQStringList seqlist = keyseq.split(\", \");\n\t\tQString prefix;\n\n\t\tforeach (QString const &seq, seqlist) {\n\t\t\tprefix += seq;\n\t\t\tif (mShortcuts.contains(prefix) || mShortcuts.contains(seq)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tprefix += \", \";\n\t\t}\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid HotKeyManager::addPrefixes(QString const &keyseq)\n{\n\tQStringList seqlist = keyseq.split(\", \");\n\tQString prefix;\n\n\tforeach (QString const &seq, seqlist) {\n\t\tprefix += seq;\n\t\tif (mPrefixes.contains(prefix)) {\n\t\t\t++mPrefixes[prefix];\n\t\t} else {\n\t\t\tmPrefixes[prefix] = 1;\n\t\t}\n\t\tprefix += \", \";\n\t}\n}\n\nvoid HotKeyManager::deletePrefixes(QString const &keyseq)\n{\n\tQStringList seqlist = keyseq.split(\", \");\n\tQString prefix;\n\n\tforeach (QString const &seq, seqlist) {\n\t\tprefix += seq;\n\t\t--mPrefixes[prefix];\n\t\tif (mPrefixes.value(prefix) == 0) {\n\t\t\tmPrefixes.remove(prefix);\n\t\t}\n\t\tprefix += \", \";\n\t}\n}\nfixed method hasPrefixOf#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"hotKeyManager.h\"\n\nusing namespace qReal;\n\nHotKeyManager::HotKeyManager()\n\t: mCurrentModifer(\"\")\n{\n}\n\nHotKeyManager& HotKeyManager::instance()\n{\n\tstatic HotKeyManager instance;\n\treturn instance;\n}\n\nvoid HotKeyManager::setCommand(const QString &id, const QString &label, QAction *command)\n{\n\tcommand->setWhatsThis(label);\n\n\tinstance().registerCommand(id, command);\n}\n\nvoid HotKeyManager::deleteCommand(QString const &id)\n{\n\tresetShortcuts(id);\n\tinstance().deleteCommandPrivate(id);\n}\n\nbool HotKeyManager::setShortcut(QString const &id, QKeySequence const &keyseq)\n{\n\treturn instance().registerShortcut(id, keyseq);\n}\n\nbool HotKeyManager::setShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)\n{\n\treturn instance().registerShortcut(id, modifier, mousebutton);\n}\n\nvoid HotKeyManager::resetShortcuts(QString const &id)\n{\n\tinstance().resetShortcutsPrivate(id);\n}\n\nvoid HotKeyManager::resetAllShortcuts()\n{\n\tinstance().resetAllShortcutsPrivate();\n}\n\nvoid HotKeyManager::deleteShortcut(const QString &id, const QString &shortcut)\n{\n\tinstance().deleteShortcutPrivate(id, shortcut);\n}\n\nvoid HotKeyManager::doShortcut(QEvent *event)\n{\n\tMouseButtons mb = None;\n\tswitch(event->type()) {\n\t\tcase QEvent::Wheel: {\n\t\t\tmb = static_cast(event)->delta() > 0 ? MouseWU : MouseWD;\n\t\t\tbreak;\n\t\t}\n\t\tcase QEvent::MouseButtonPress: {\n\t\t\tswitch(static_cast(event)->button()) {\n\t\t\t\tcase Qt::RightButton:\n\t\t\t\t\tmb = MouseRB;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Qt::LeftButton:\n\t\t\t\t\tmb = MouseLB;\n\t\t\t\t\tbreak;\n\t\t\t\tcase Qt::MiddleButton:\n\t\t\t\t\tmb = MouseMB;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tinstance().findShortcut(sequence(instance().currentModifier(), mb));\n}\n\nvoid HotKeyManager::setCurrentModifier(const QString &modifier)\n{\n\tinstance().setCurrentModifierPrivate(modifier);\n}\n\nQHash HotKeyManager::commands()\n{\n\treturn instance().commandsPrivate();\n}\n\nQHash HotKeyManager::shortcuts()\n{\n\treturn instance().shortcutsPrivate();\n}\n\nvoid HotKeyManager::registerCommand(const QString &id, QAction *command)\n{\n\tQList shortcuts = command->shortcuts();\n\n\tforeach (QKeySequence const &shortcut, shortcuts) {\n\t\tinstance().registerShortcut(id, shortcut.toString());\n\t}\n\n\tmCommands[id] = command;\n}\n\nbool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &keyseq)\n{\n\tif (mCommands.contains(id)) {\n\t\tQString const shortcut = keyseq.toString();\n\n\t\tif (!hasPrefixOf(shortcut)) {\n\t\t\taddPrefixes(shortcut);\n\t\t\tmShortcuts[shortcut] = id;\n\t\t\tmCommands[id]->setShortcuts(mCommands[id]->shortcuts() << keyseq);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool HotKeyManager::registerShortcut(QString const &id, QKeySequence const &modifier, MouseButtons mousebutton)\n{\n\tif (mCommands.contains(id)) {\n\t\tQString const shortcut = sequence(modifier.toString(), mousebutton);\n\n\t\tif (!mShortcuts.contains(shortcut)) {\n\t\t\taddPrefixes(shortcut);\n\t\t\tmShortcuts[shortcut] = id;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid HotKeyManager::registerShortcut(QString const &id, QString const &shortcut)\n{\n\tif (!hasPrefixOf(shortcut)) {\n\t\taddPrefixes(shortcut);\n\t\tmShortcuts[shortcut] = id;\n\t}\n}\n\nvoid HotKeyManager::findShortcut(QString const &shortcut)\n{\n\tif (mShortcuts.contains(shortcut) && mCommands[mShortcuts.value(shortcut)]->parentWidget()->isActiveWindow()) {\n\t\tmCommands[mShortcuts.value(shortcut)]->trigger();\n\t}\n}\n\nQString HotKeyManager::sequence(const QString &modifier, MouseButtons mousebutton)\n{\n\tQString seq = modifier;\n\n\tswitch(mousebutton) {\n\tcase MouseLB:\n\t\tseq += \"MouseLB\";\n\t\tbreak;\n\tcase MouseRB:\n\t\tseq += \"MouseRB\";\n\t\tbreak;\n\tcase MouseMB:\n\t\tseq += \"MouseMB\";\n\t\tbreak;\n\tcase MouseWU:\n\t\tseq += \"MouseWU\";\n\t\tbreak;\n\tcase MouseWD:\n\t\tseq += \"MouseWD\";\n\t}\n\n\treturn seq;\n}\n\nvoid HotKeyManager::setCurrentModifierPrivate(QString const &modifier)\n{\n\tmCurrentModifer = modifier;\n}\n\nQString HotKeyManager::currentModifier()\n{\n\treturn mCurrentModifer;\n}\n\nvoid HotKeyManager::resetShortcutsPrivate(QString const &id)\n{\n\tif (mCommands.contains(id)) {\n\t\tQList shortcuts = mShortcuts.keys(id);\n\n\t\tforeach (QString const &shortcut, shortcuts) {\n\t\t\tdeletePrefixes(shortcut);\n\t\t\tmShortcuts.remove(shortcut);\n\t\t}\n\n\t\tmCommands[id]->setShortcuts(QList());\n\t}\n}\n\nvoid HotKeyManager::resetAllShortcutsPrivate()\n{\n\tQList cmds = mCommands.values();\n\n\tforeach (QAction *cmd, cmds) {\n\t\tcmd->setShortcuts(QList());\n\t}\n\n\tmShortcuts.clear();\n\tmPrefixes.clear();\n}\n\nvoid HotKeyManager::deleteShortcutPrivate(const QString &id, const QString &shortcut)\n{\n\tmShortcuts.remove(shortcut);\n\tdeletePrefixes(shortcut);\n\t\/\/if == \"\" then shortcut with mouse\n\tif (QKeySequence(shortcut).toString() != \"\" ) {\n\t\tQList shortcuts = mCommands[id]->shortcuts();\n\n\t\tshortcuts.removeOne(shortcut);\n\t\tmCommands[id]->setShortcuts(shortcuts);\n\t}\n}\n\nvoid HotKeyManager::deleteCommandPrivate(QString const &id)\n{\n\tif (mCommands.contains(id)) {\n\t\tmCommands.remove(id);\n\t}\n}\n\nQHash HotKeyManager::commandsPrivate()\n{\n\treturn mCommands;\n}\n\nQHash HotKeyManager::shortcutsPrivate()\n{\n\treturn mShortcuts;\n}\n\nbool HotKeyManager::hasPrefixOf(QString const &keyseq)\n{\n\tif (!mPrefixes.contains(keyseq)) {\n\t\tQStringList seqlist = keyseq.split(\", \");\n\t\tQString prefix;\n\n\t\tforeach (QString const &seq, seqlist) {\n\t\t\tprefix += seq;\n\t\t\tif (mShortcuts.contains(prefix)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tprefix += \", \";\n\t\t}\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid HotKeyManager::addPrefixes(QString const &keyseq)\n{\n\tQStringList seqlist = keyseq.split(\", \");\n\tQString prefix;\n\n\tforeach (QString const &seq, seqlist) {\n\t\tprefix += seq;\n\t\tif (mPrefixes.contains(prefix)) {\n\t\t\t++mPrefixes[prefix];\n\t\t} else {\n\t\t\tmPrefixes[prefix] = 1;\n\t\t}\n\t\tprefix += \", \";\n\t}\n}\n\nvoid HotKeyManager::deletePrefixes(QString const &keyseq)\n{\n\tQStringList seqlist = keyseq.split(\", \");\n\tQString prefix;\n\n\tforeach (QString const &seq, seqlist) {\n\t\tprefix += seq;\n\t\t--mPrefixes[prefix];\n\t\tif (mPrefixes.value(prefix) == 0) {\n\t\t\tmPrefixes.remove(prefix);\n\t\t}\n\t\tprefix += \", \";\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) Microsoft Corporation\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"pch.h\"\n#include \"lhc_mock.h\"\n#include \"..\/HTTP\/httpcall.h\"\n\nusing namespace xbox::httpclient;\n\nbool DoesMockCallMatch(_In_ const HC_CALL* mockCall, _In_ const HC_CALL* originalCall)\n{\n if (mockCall->url.empty())\n {\n return true;\n }\n else\n {\n if (originalCall->url.substr(0, mockCall->url.size()) == mockCall->url)\n {\n if (mockCall->requestBodyBytes.empty())\n {\n return true;\n }\n else\n {\n if (originalCall->requestBodyBytes == mockCall->requestBodyBytes)\n {\n return true;\n }\n }\n }\n }\n\n return false;\n}\n\nbool Mock_Internal_HCHttpCallPerformAsync(\n _In_ HCCallHandle originalCall\n )\n{\n auto httpSingleton = get_http_singleton(false);\n if (nullptr == httpSingleton)\n {\n return false;\n }\n\n std::lock_guard guard(httpSingleton->m_mocksLock);\n\n if (httpSingleton->m_mocks.size() == 0)\n {\n return false;\n }\n\n auto& mocks{ httpSingleton->m_mocks };\n HC_MOCK_CALL* mock{ nullptr };\n\n \/\/ Use the most recently added mock that matches (similar to a stack).\n for (auto iter = mocks.rbegin(); iter != mocks.rend(); ++iter)\n {\n if (DoesMockCallMatch(*iter, originalCall))\n {\n mock = *iter;\n break;\n }\n }\n\n if (mock->matchedCallback)\n {\n mock->matchedCallback(\n mock,\n originalCall->method.data(),\n originalCall->url.data(),\n originalCall->requestBodyBytes.data(),\n static_cast(originalCall->requestBodyBytes.size()),\n mock->matchCallbackContext\n );\n }\n\n size_t byteBuf;\n HCHttpCallResponseGetResponseBodyBytesSize(mock, &byteBuf);\n http_memory_buffer buffer(byteBuf);\n HCHttpCallResponseGetResponseBodyBytes(mock, byteBuf, static_cast(buffer.get()), nullptr);\n HCHttpCallResponseSetResponseBodyBytes(originalCall, static_cast(buffer.get()), byteBuf);\n\n uint32_t code;\n HCHttpCallResponseGetStatusCode(mock, &code);\n HCHttpCallResponseSetStatusCode(originalCall, code);\n\n HRESULT genCode;\n HCHttpCallResponseGetNetworkErrorCode(mock, &genCode, &code);\n HCHttpCallResponseSetNetworkErrorCode(originalCall, genCode, code);\n\n uint32_t numheaders;\n HCHttpCallResponseGetNumHeaders(mock, &numheaders);\n\n const char* str1;\n const char* str2;\n for (uint32_t i = 0; i < numheaders; i++)\n {\n HCHttpCallResponseGetHeaderAtIndex(mock, i, &str1, &str2);\n HCHttpCallResponseSetHeader(originalCall, str1, str2);\n }\n\n return true;\n}\nAdd missed null check in mock stack (#474)\/\/ Copyright (c) Microsoft Corporation\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"pch.h\"\n#include \"lhc_mock.h\"\n#include \"..\/HTTP\/httpcall.h\"\n\nusing namespace xbox::httpclient;\n\nbool DoesMockCallMatch(_In_ const HC_CALL* mockCall, _In_ const HC_CALL* originalCall)\n{\n if (mockCall->url.empty())\n {\n return true;\n }\n else\n {\n if (originalCall->url.substr(0, mockCall->url.size()) == mockCall->url)\n {\n if (mockCall->requestBodyBytes.empty())\n {\n return true;\n }\n else\n {\n if (originalCall->requestBodyBytes == mockCall->requestBodyBytes)\n {\n return true;\n }\n }\n }\n }\n\n return false;\n}\n\nbool Mock_Internal_HCHttpCallPerformAsync(\n _In_ HCCallHandle originalCall\n )\n{\n auto httpSingleton = get_http_singleton(false);\n if (nullptr == httpSingleton)\n {\n return false;\n }\n\n std::lock_guard guard(httpSingleton->m_mocksLock);\n\n if (httpSingleton->m_mocks.size() == 0)\n {\n return false;\n }\n\n auto& mocks{ httpSingleton->m_mocks };\n HC_MOCK_CALL* mock{ nullptr };\n\n \/\/ Use the most recently added mock that matches (similar to a stack).\n for (auto iter = mocks.rbegin(); iter != mocks.rend(); ++iter)\n {\n if (DoesMockCallMatch(*iter, originalCall))\n {\n mock = *iter;\n break;\n }\n }\n\n if (!mock)\n {\n return false;\n }\n\n if (mock->matchedCallback)\n {\n mock->matchedCallback(\n mock,\n originalCall->method.data(),\n originalCall->url.data(),\n originalCall->requestBodyBytes.data(),\n static_cast(originalCall->requestBodyBytes.size()),\n mock->matchCallbackContext\n );\n }\n\n size_t byteBuf;\n HCHttpCallResponseGetResponseBodyBytesSize(mock, &byteBuf);\n http_memory_buffer buffer(byteBuf);\n HCHttpCallResponseGetResponseBodyBytes(mock, byteBuf, static_cast(buffer.get()), nullptr);\n HCHttpCallResponseSetResponseBodyBytes(originalCall, static_cast(buffer.get()), byteBuf);\n\n uint32_t code;\n HCHttpCallResponseGetStatusCode(mock, &code);\n HCHttpCallResponseSetStatusCode(originalCall, code);\n\n HRESULT genCode;\n HCHttpCallResponseGetNetworkErrorCode(mock, &genCode, &code);\n HCHttpCallResponseSetNetworkErrorCode(originalCall, genCode, code);\n\n uint32_t numheaders;\n HCHttpCallResponseGetNumHeaders(mock, &numheaders);\n\n const char* str1;\n const char* str2;\n for (uint32_t i = 0; i < numheaders; i++)\n {\n HCHttpCallResponseGetHeaderAtIndex(mock, i, &str1, &str2);\n HCHttpCallResponseSetHeader(originalCall, str1, str2);\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2009-2018 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE qmpair_test\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace votca::tools;\n\nusing namespace votca::xtp;\n\nBOOST_AUTO_TEST_SUITE(qmpair_test)\n\nBOOST_AUTO_TEST_CASE(constructors_test) { QMPair qm_p; }\n\nBOOST_AUTO_TEST_CASE( getters_test ) { \n\n double tolerancePerc = 0.01;\n \/\/ Box takes a vector\n double x1 = 12.0;\n double y1 = 0.0;\n double z1 = 0.0;\n\n double x2 = 0.0;\n double y2 = 12.0;\n double z2 = 0.0;\n\n double x3 = 0.0;\n double y3 = 0.0;\n double z3 = 12.0;\n\n vec v1(x1,y1,z1);\n vec v2(x2,y2,z2);\n vec v3(x3,y3,z3);\n\n matrix box(v1,v2,v3);\n\n Topology top;\n top.setBox(box);\n vec p1;\n p1.setX(0.0);\n p1.setY(0.0);\n p1.setZ(0.0);\n \n vec p2;\n p2.setX(10.0);\n p2.setY(0.0);\n p2.setZ(0.0);\n top.PbShortestConnect(p1,p2);\n\n bool hasQM = true; \n vec qmpos;\n qmpos.setX(2.0);\n qmpos.setY(2.0);\n qmpos.setZ(2.0);\n\n vec pos;\n pos.setX(3.0);\n pos.setY(3.0);\n pos.setZ(3.0);\n\n Atom * atm = new Atom(nullptr, \"res1\",1,\"CSP\",2,hasQM,3,qmpos,\"C\",1.0);\n atm->setPos(pos);\n Segment * seg1 = new Segment(1, \"seg1\");\n seg1->AddAtom(atm);\n seg1->setTopology(&top);\n\n vec qmpos_2;\n qmpos_2.setX(4.0);\n qmpos_2.setY(4.0);\n qmpos_2.setZ(4.0);\n\n vec pos_2;\n pos_2.setX(1.0);\n pos_2.setY(1.0);\n pos_2.setZ(1.0);\n\n Atom * atm_2 = new Atom(nullptr, \"res1\",1,\"CSP\",2,hasQM,3,qmpos_2,\"H\",1.0);\n atm->setPos(pos_2);\n Segment * seg2 = new Segment(2, \"seg2\");\n seg2->AddAtom(atm_2);\n seg2->setTopology(&top);\n\n int pair_num = 1;\n QMPair qm_p(pair_num,seg1,seg2); \n BOOST_CHECK_EQUAL(qm_p.getId(),1);\n auto r = qm_p.R();\n BOOST_CHECK_EQUAL(r.x(),0.0);\n BOOST_CHECK_EQUAL(r.y(),0.0);\n BOOST_CHECK_EQUAL(r.z(),0.0);\n BOOST_CHECK_EQUAL(qm_p.HasGhost(),false);\n\n int state = -1;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n \n state = 1;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n\n state = 2;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n \n state = 3;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nFinally figured out complicated segment configuration and testing\/*\n * Copyright 2009-2018 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE qmpair_test\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace votca::tools;\n\nusing namespace votca::xtp;\n\nBOOST_AUTO_TEST_SUITE(qmpair_test)\n\nBOOST_AUTO_TEST_CASE(constructors_test) { QMPair qm_p; }\n\nBOOST_AUTO_TEST_CASE( getters_test ) { \n\n double tolerancePerc = 0.01;\n \/\/ Box takes a vector\n double x1 = 12.0;\n double y1 = 0.0;\n double z1 = 0.0;\n\n double x2 = 0.0;\n double y2 = 12.0;\n double z2 = 0.0;\n\n double x3 = 0.0;\n double y3 = 0.0;\n double z3 = 12.0;\n\n vec v1(x1,y1,z1);\n vec v2(x2,y2,z2);\n vec v3(x3,y3,z3);\n\n matrix box(v1,v2,v3);\n\n Topology top;\n top.setBox(box);\n vec p1;\n p1.setX(0.0);\n p1.setY(0.0);\n p1.setZ(0.0);\n \n vec p2;\n p2.setX(10.0);\n p2.setY(0.0);\n p2.setZ(0.0);\n top.PbShortestConnect(p1,p2);\n\n bool hasQM = true; \n vec qmpos;\n qmpos.setX(2.0);\n qmpos.setY(2.0);\n qmpos.setZ(2.0);\n\n vec pos;\n pos.setX(3.0);\n pos.setY(3.0);\n pos.setZ(3.0);\n\n Atom * atm = new Atom(nullptr, \"res1\",1,\"CSP\",2,hasQM,3,qmpos,\"C\",1.0);\n atm->setPos(pos);\n Segment * seg1 = new Segment(1, \"seg1\");\n seg1->AddAtom(atm);\n seg1->setTopology(&top);\n\n int state = -1;\n seg1->setU_cC_nN(0.0,state);\n seg1->setU_nC_nN(0.0,state);\n seg1->setU_cN_cC(0.0,state);\n state = 1;\n seg1->setU_cC_nN(0.0,state);\n seg1->setU_nC_nN(0.0,state);\n seg1->setU_cN_cC(0.0,state);\n state = 2;\n seg1->setU_xX_nN(0.0,state);\n seg1->setU_nX_nN(0.0,state);\n seg1->setU_xN_xX(0.0,state);\n state = 3;\n seg1->setU_xX_nN(0.0,state);\n seg1->setU_nX_nN(0.0,state);\n seg1->setU_xN_xX(0.0,state);\n\n vec qmpos_2;\n qmpos_2.setX(4.0);\n qmpos_2.setY(4.0);\n qmpos_2.setZ(4.0);\n\n vec pos_2;\n pos_2.setX(1.0);\n pos_2.setY(1.0);\n pos_2.setZ(1.0);\n\n Atom * atm_2 = new Atom(nullptr, \"res1\",1,\"CSP\",2,hasQM,3,qmpos_2,\"H\",1.0);\n atm->setPos(pos_2);\n Segment * seg2 = new Segment(2, \"seg2\");\n seg2->AddAtom(atm_2);\n seg2->setTopology(&top);\n state = -1;\n seg2->setU_cC_nN(0.0,state);\n seg2->setU_nC_nN(0.0,state);\n seg2->setU_cN_cC(0.0,state);\n state = 1;\n seg2->setU_cC_nN(0.0,state);\n seg2->setU_nC_nN(0.0,state);\n seg2->setU_cN_cC(0.0,state);\n state = 2;\n seg2->setU_xX_nN(0.0,state);\n seg2->setU_nX_nN(0.0,state);\n seg2->setU_xN_xX(0.0,state);\n state = 3;\n seg2->setU_xX_nN(0.0,state);\n seg2->setU_nX_nN(0.0,state);\n seg2->setU_xN_xX(0.0,state);\n\n\n int pair_num = 1;\n QMPair qm_p(pair_num,seg1,seg2); \n BOOST_CHECK_EQUAL(qm_p.getId(),1);\n auto r = qm_p.R();\n BOOST_CHECK_CLOSE(r.x(),0.0,tolerancePerc);\n BOOST_CHECK_CLOSE(r.y(),0.0,tolerancePerc);\n BOOST_CHECK_CLOSE(r.z(),0.0,tolerancePerc);\n BOOST_CHECK(qm_p.HasGhost()==false);\n\n state = -1;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n \n state = 1;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n\n state = 2;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n \n state = 3;\n BOOST_CHECK_CLOSE(qm_p.getLambdaO(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg12_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getReorg21_x(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate12(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getRate21(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getJeff2(state),0.0,(tolerancePerc));\n BOOST_CHECK_CLOSE(qm_p.getdE12(state),0.0,(tolerancePerc));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ texturetest.cc a test app for Textures\n\/\/ Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)\n\n#include \"ImageControl.hh\"\n#include \"Color.hh\"\n#include \"GContext.hh\"\n#include \"FbPixmap.hh\"\n#include \"Texture.hh\"\n#include \"FbWindow.hh\"\n#include \"EventHandler.hh\"\n#include \"EventManager.hh\"\n#include \"Theme.hh\"\n#include \"Font.hh\"\n#include \"App.hh\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace FbTk;\n\nclass TestTheme: public Theme {\npublic:\n TestTheme(int screen):Theme(screen) { }\n bool fallback(ThemeItem_base &item) { return false; }\n void reconfigTheme() { } \n};\n\nclass Application: public FbTk::FbWindow, public FbTk::EventHandler {\npublic:\n Application(int box_size, int num):\n FbWindow(0, 0, 0, 640, box_size*num\/8 - 3*5, ExposureMask | KeyPressMask),\n m_box_size(box_size),\n m_num(num),\n m_font(\"fixed\"),\n m_imgctrl(screenNumber(), true, 8,\n 100, 100),\n m_background(*this, 640, 480, depth()),\n m_gc(m_background) {\n setName(\"Texture Test\");\n setBackgroundPixmap(m_background.drawable());\n\n FbTk::EventManager::instance()->add(*this, *this);\n\n renderPixmaps();\n\n show(); \n }\n void keyPressEvent(XKeyEvent &ev) {\n App::instance()->end();\n }\n void exposeEvent(XExposeEvent &ev) {\n clear();\n }\n\nprivate:\n\n void renderPixmap(const Texture &text, int x, int y) {\n Pixmap pm = m_imgctrl.renderImage(m_box_size, m_box_size,\n text);\n\n m_background.copyArea(pm, m_gc.gc(),\n 0, 0,\n x, y,\n m_box_size, m_box_size);\n m_imgctrl.removeImage(pm);\n }\n\n void renderPixmaps() {\n\n m_gc.setForeground(Color(\"gray\", screenNumber()));\n\n m_background.fillRectangle(m_gc.gc(),\n 0, 0,\n width(), height());\n \/\/ for text color\n m_gc.setForeground(Color(\"black\", screenNumber()));\n\n const int step_size = m_box_size + 5;\n int next_x = 5;\n int next_y = 5;\n\n TestTheme tm(screenNumber());\n std::auto_ptr > text;\n char value[18];\n for (int i=0; i\n (tm, \n string(\"texture\") + value, \n string(\"Texture\") + value));\n \/\/ load new style\n ThemeManager::instance().load(\"test.theme\");\n\n renderPixmap(**text.get(), next_x, next_y);\n\n next_x += step_size;\n if (next_x + m_box_size > width()) {\n m_font.drawText(m_background,\n screenNumber(),\n m_gc.gc(),\n value, strlen(value),\n next_x, next_y + m_box_size\/2);\n next_x = 5;\n next_y += step_size;\n }\n\n }\n\n\n }\n\n\n const int m_box_size;\n const int m_num;\n FbTk::Font m_font;\n ImageControl m_imgctrl;\n FbPixmap m_background;\n FbTk::GContext m_gc;\n};\n\nint main(int argc, char **argv) {\n int boxsize= 60;\n int num = 63;\n for (int i=1; iupdated 'texturetest.cc' to work with current API\/\/ texturetest.cc a test app for Textures\n\/\/ Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)\n\n#include \"ImageControl.hh\"\n#include \"Color.hh\"\n#include \"GContext.hh\"\n#include \"FbPixmap.hh\"\n#include \"Texture.hh\"\n#include \"FbWindow.hh\"\n#include \"EventHandler.hh\"\n#include \"EventManager.hh\"\n#include \"Theme.hh\"\n#include \"Font.hh\"\n#include \"App.hh\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace FbTk;\n\nclass TestTheme: public Theme {\npublic:\n TestTheme(int screen):Theme(screen) { }\n bool fallback(ThemeItem_base &item) { return false; }\n void reconfigTheme() { } \n};\n\nclass Application: public FbTk::FbWindow, public FbTk::EventHandler {\npublic:\n Application(int box_size, int num):\n FbWindow(0, 0, 0, 640, box_size*num\/8 - 3*5, ExposureMask | KeyPressMask),\n m_box_size(box_size),\n m_num(num),\n m_font(\"fixed\"),\n m_imgctrl(screenNumber()),\n m_background(*this, 640, 480, depth()),\n m_gc(m_background) {\n setName(\"Texture Test\");\n setBackgroundPixmap(m_background.drawable());\n\n FbTk::EventManager::instance()->add(*this, *this);\n\n renderPixmaps();\n\n show(); \n }\n void keyPressEvent(XKeyEvent &ev) {\n \/\/App::instance()->end();\n }\n void exposeEvent(XExposeEvent &ev) {\n clear();\n }\n\nprivate:\n\n void renderPixmap(const Texture &text, int x, int y) {\n Pixmap pm = m_imgctrl.renderImage(m_box_size, m_box_size,\n text);\n\n m_background.copyArea(pm, m_gc.gc(),\n 0, 0,\n x, y,\n m_box_size, m_box_size);\n m_imgctrl.removeImage(pm);\n }\n\n void renderPixmaps() {\n\n m_gc.setForeground(Color(\"gray\", screenNumber()));\n\n m_background.fillRectangle(m_gc.gc(),\n 0, 0,\n width(), height());\n \/\/ for text color\n m_gc.setForeground(Color(\"black\", screenNumber()));\n\n const int step_size = m_box_size + 5;\n int next_x = 5;\n int next_y = 5;\n\n TestTheme tm(screenNumber());\n std::auto_ptr > text;\n char value[18];\n for (int i=0; i\n (tm, \n string(\"texture\") + value, \n string(\"Texture\") + value));\n \/\/ load new style\n ThemeManager::instance().load(\"test.theme\", \"\");\n\n renderPixmap(**text.get(), next_x, next_y);\n\n next_x += step_size;\n if (next_x + m_box_size > width()) {\n m_font.drawText(m_background,\n screenNumber(),\n m_gc.gc(),\n value, strlen(value),\n next_x, next_y + m_box_size\/2);\n next_x = 5;\n next_y += step_size;\n }\n\n }\n\n\n }\n\n\n const int m_box_size;\n const int m_num;\n FbTk::Font m_font;\n ImageControl m_imgctrl;\n FbPixmap m_background;\n FbTk::GContext m_gc;\n};\n\nint main(int argc, char **argv) {\n int boxsize= 60;\n int num = 63;\n for (int i=1; i"} {"text":"\/\/ texturetest.cc a test app for Textures\n\/\/ Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)\n\n#include \"ImageControl.hh\"\n#include \"Color.hh\"\n#include \"GContext.hh\"\n#include \"FbPixmap.hh\"\n#include \"Texture.hh\"\n#include \"FbWindow.hh\"\n#include \"EventHandler.hh\"\n#include \"EventManager.hh\"\n#include \"Theme.hh\"\n#include \"Font.hh\"\n#include \"App.hh\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace FbTk;\n\nclass TestTheme: public Theme {\npublic:\n TestTheme(int screen):Theme(screen) { }\n bool fallback(ThemeItem_base &item) { return false; }\n void reconfigTheme() { } \n};\n\nclass Application: public FbTk::FbWindow, public FbTk::EventHandler {\npublic:\n Application(int box_size, int num):\n FbWindow(0, 0, 0, 640, box_size*num\/8 - 3*5, ExposureMask | KeyPressMask),\n m_box_size(box_size),\n m_num(num),\n m_font(\"fixed\"),\n m_imgctrl(screenNumber()),\n m_background(*this, 640, 480, depth()),\n m_gc(m_background) {\n setName(\"Texture Test\");\n setBackgroundPixmap(m_background.drawable());\n\n FbTk::EventManager::instance()->add(*this, *this);\n\n renderPixmaps();\n\n show(); \n }\n void keyPressEvent(XKeyEvent &ev) {\n \/\/App::instance()->end();\n }\n void exposeEvent(XExposeEvent &ev) {\n clear();\n }\n\nprivate:\n\n void renderPixmap(const Texture &text, int x, int y) {\n Pixmap pm = m_imgctrl.renderImage(m_box_size, m_box_size,\n text);\n\n m_background.copyArea(pm, m_gc.gc(),\n 0, 0,\n x, y,\n m_box_size, m_box_size);\n m_imgctrl.removeImage(pm);\n }\n\n void renderPixmaps() {\n\n m_gc.setForeground(Color(\"gray\", screenNumber()));\n\n m_background.fillRectangle(m_gc.gc(),\n 0, 0,\n width(), height());\n \/\/ for text color\n m_gc.setForeground(Color(\"black\", screenNumber()));\n\n const int step_size = m_box_size + 5;\n int next_x = 5;\n int next_y = 5;\n\n TestTheme tm(screenNumber());\n std::auto_ptr > text;\n char value[18];\n for (int i=0; i\n (tm, \n string(\"texture\") + value, \n string(\"Texture\") + value));\n \/\/ load new style\n ThemeManager::instance().load(\"test.theme\", \"\");\n\n renderPixmap(**text.get(), next_x, next_y);\n\n next_x += step_size;\n if (next_x + m_box_size > width()) {\n m_font.drawText(m_background,\n screenNumber(),\n m_gc.gc(),\n value, strlen(value),\n next_x, next_y + m_box_size\/2);\n next_x = 5;\n next_y += step_size;\n }\n\n }\n\n\n }\n\n\n const int m_box_size;\n const int m_num;\n FbTk::Font m_font;\n ImageControl m_imgctrl;\n FbPixmap m_background;\n FbTk::GContext m_gc;\n};\n\nint main(int argc, char **argv) {\n int boxsize= 60;\n int num = 63;\n for (int i=1; iRender rectangles instead of squares to test TextureRender.cc\/\/ texturetest.cc a test app for Textures\n\/\/ Copyright (c) 2004 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)\n\n#include \"ImageControl.hh\"\n#include \"Color.hh\"\n#include \"GContext.hh\"\n#include \"FbPixmap.hh\"\n#include \"Texture.hh\"\n#include \"FbWindow.hh\"\n#include \"EventHandler.hh\"\n#include \"EventManager.hh\"\n#include \"Theme.hh\"\n#include \"Font.hh\"\n#include \"App.hh\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace FbTk;\n\nclass TestTheme: public Theme {\npublic:\n TestTheme(int screen):Theme(screen) { }\n bool fallback(ThemeItem_base &item) { return false; }\n void reconfigTheme() { } \n};\n\nclass Application: public FbTk::FbWindow, public FbTk::EventHandler {\npublic:\n Application(int box_size, int num):\n FbWindow(0, 0, 0, 640, ((5+box_size)*num)\/9 + 5, ExposureMask | KeyPressMask),\n m_box_size(box_size),\n m_num(num),\n m_font(\"fixed\"),\n m_imgctrl(screenNumber()),\n m_background(*this, width(), height(), depth()),\n m_gc(m_background) {\n setName(\"Texture Test\");\n setBackgroundPixmap(m_background.drawable());\n\n FbTk::EventManager::instance()->add(*this, *this);\n\n renderPixmaps();\n\n show(); \n }\n void keyPressEvent(XKeyEvent &ev) {\n \/\/App::instance()->end();\n }\n void exposeEvent(XExposeEvent &ev) {\n clear();\n }\n\nprivate:\n\n void renderPixmap(const Texture &text, int x, int y) {\n Pixmap pm = m_imgctrl.renderImage(2*m_box_size, m_box_size,\n text);\n\n m_background.copyArea(pm, m_gc.gc(),\n 0, 0,\n x, y,\n 2*m_box_size, m_box_size);\n m_imgctrl.removeImage(pm);\n }\n\n void renderPixmaps() {\n\n m_gc.setForeground(Color(\"gray\", screenNumber()));\n\n m_background.fillRectangle(m_gc.gc(),\n 0, 0,\n width(), height());\n \/\/ for text color\n m_gc.setForeground(Color(\"black\", screenNumber()));\n\n const int step_size = m_box_size + 5;\n int next_x = 5;\n int next_y = 5;\n\n TestTheme tm(screenNumber());\n std::auto_ptr > text;\n char value[18];\n for (int i=0; i (tm, string(\"texture\") + value, string(\"Texture\") + value));\n\n ThemeManager::instance().load(\"test.theme\", \"\");\n renderPixmap(**text.get(), next_x, next_y);\n\n next_x += (step_size + m_box_size);\n if (next_x + 2*m_box_size > width()) {\n m_font.drawText(m_background,\n screenNumber(),\n m_gc.gc(),\n value, strlen(value),\n next_x, next_y + m_box_size\/2);\n next_x = 5;\n next_y += step_size;\n }\n\n }\n\n\n }\n\n\n const int m_box_size;\n const int m_num;\n FbTk::Font m_font;\n ImageControl m_imgctrl;\n FbPixmap m_background;\n FbTk::GContext m_gc;\n};\n\nint main(int argc, char **argv) {\n int boxsize= 30;\n int num = 63;\n for (int i=1; i"} {"text":"#pragma once\n#include \n#include \n#include \n#include \"RegistryUtil.h\"\n#include \"LogOperation.h\"\n\nstatic CRITICAL_SECTION LogFileCS;\nstatic HANDLE hLogFile;\nstatic LONG LogFileCsInitialized;\n\nBOOL LogOperation::OpenLogFile( std::string &log_filename )\n{\n\tEnterCriticalSection( &LogFileCS );\n\t\/\/ Create the new file to write the upper-case version to.\n\tif( hLogFile == INVALID_HANDLE_VALUE )\n\t{\n\t\thLogFile = CreateFile((LPTSTR) log_filename.c_str(),\/\/ file name \n\t\t\t\tGENERIC_READ | GENERIC_WRITE,\/\/ open r-w \n\t\t\t\tFILE_SHARE_READ,\n\t\t\t\tNULL,\t\t\t\t\/\/ default security \n\t\t\t\tOPEN_ALWAYS,\t\t\/\/ overwrite existing\n\t\t\t\tFILE_ATTRIBUTE_NORMAL,\/\/ normal file \n\t\t\t\tNULL);\t\t\t\t\/\/ no template \n\t\tif( hLogFile == INVALID_HANDLE_VALUE )\n\t\t{ \n\t\t\tprintf(\"CreateFile failed for [%s] with error %u.\\r\\n\", log_filename.c_str(), GetLastError());\n\t\t\tLeaveCriticalSection( &LogFileCS );\n\t\t\treturn FALSE;\n\t\t}\n\t\tSetFilePointer(hLogFile,0,0,FILE_END);\n\t}\n\tLeaveCriticalSection( &LogFileCS );\n\treturn TRUE;\n}\n\nvoid LogOperation::CloseLogFile( )\n{\n\tEnterCriticalSection( &LogFileCS );\n\tif( hLogFile != INVALID_HANDLE_VALUE )\n\t{\n\t\tCloseHandle( hLogFile );\n\t\thLogFile = INVALID_HANDLE_VALUE;\n\t}\n\tLeaveCriticalSection( &LogFileCS );\n}\n\nvoid LogOperation::_Log(const CHAR *log_message)\n{\n\tstd::string full_log_message;\n\tif( OutputType & LogToFile )\n\t{\n\t\tif( hLogFile != INVALID_HANDLE_VALUE ) \n\t\t{\n\t\t\tEnterCriticalSection( &LogFileCS );\n\t\t\tDWORD bytes_written;\n\n\t\t\tSYSTEMTIME lt;\n\t\t\tGetLocalTime(<);\n\t\t\tchar time_buffer[50];\n\t\t\t_snprintf(time_buffer, sizeof(time_buffer), \"[%02d\/%02d\/%04d %02d:%02d:%02d] \",\n\t\t\t\tlt.wMonth,\n\t\t\t\tlt.wDay,\n\t\t\t\tlt.wYear,\n\t\t\t\tlt.wHour,\n\t\t\t\tlt.wMinute,\n\t\t\t\tlt.wSecond);\n\n\t\t\tfull_log_message = time_buffer;\n\t\t\tfull_log_message += \" [\";\n\t\t\tfull_log_message += CategoryName.c_str();\n\t\t\tfull_log_message += \"] \";\n\t\t\tfull_log_message += log_message;\n\n\t\t\tDWORD ret = WriteFile( hLogFile,\n\t\t\t\tfull_log_message.c_str(),\n\t\t\t\tfull_log_message.length(),\n\t\t\t\t&bytes_written,\n\t\t\t\tNULL); \n\t\t\tif( !ret ) \n\t\t\t{\n\t\t\t\tprintf(\"WriteFile failed with error %u.\\r\\n\",GetLastError());\n\t\t\t}\n\t\t\tLeaveCriticalSection( &LogFileCS );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"%s\", log_message);\n\t\t}\n\t}\n\n\tif( (OutputType & LogToDbgview) || (OutputType & LogToIDAMessageBox) || (OutputType & LogToStdout) )\n\t{\n\t\tfull_log_message = \"[\";\n\t\tfull_log_message += CategoryName.c_str();\n\t\tfull_log_message += \"] \";\n\t\tfull_log_message += log_message;\n\t}\n\n\tif( OutputType & LogToDbgview )\n\t\tOutputDebugStringA( full_log_message.c_str() );\n\n\tif( OutputType & LogToIDAMessageBox )\n\t{\n#ifdef IDA_PLUGIN\n\t\tmsg(\"%s\", full_log_message.c_str() );\n#endif\n\t}\n\n\tif( OutputType & LogToStdout )\n\t\tprintf(\"%s\", full_log_message.c_str() );\n}\n\nvoid LogOperation::_Log(const WCHAR *log_message)\n{\n\tCHAR log_message_a[1024];\n\t_snprintf(log_message_a, sizeof(log_message_a)-1, \"%ws\", log_message );\n\t_Log( log_message_a );\n}\n\nLogOperation::LogOperation( int output_type ): OutputType(output_type), DebugLevel(5)\n{\n\tif( !GetConsoleWindow() )\n\t\tOutputType = LogToDbgview;\n}\n\nLogOperation::LogOperation( const char *category_name ): OutputType(LogToFile)\n{\n\tSetCategory( category_name );\n}\n\nvoid LogOperation::InitLog()\n{\n\tInitializeCriticalSection( &LogFileCS );\n\thLogFile = INVALID_HANDLE_VALUE;\n\t\/\/InterlockedExchange( &LogFileCsInitialized, 1 );\n}\n\nvoid LogOperation::FiniLog()\n{\n\t\/\/if( InterlockedExchange( &LogFileCsInitialized, 0 ) == 1 )\n\t{\n\t\t\/\/CloseLogFile();\n\t\tDeleteCriticalSection( &LogFileCS );\n\t}\n}\n\nvoid LogOperation::RetrieveLogInfoFromRegistry()\n{\n\tstd::string key_name = \"HKEY_LOCAL_MACHINE\\\\Software\\\\\";\n\tkey_name += CompanyName;\n\tkey_name += \"\\\\\";\n\tkey_name += ProductName;\n\tkey_name += \"\\\\Logging\\\\\";\n\n\tstd::string category_key_name = key_name;\n\tcategory_key_name += CategoryName;\n\n\tchar *type = GetRegValueString( category_key_name.c_str(), \"Type\" );\n\tif( type )\n\t{\n\t\tif( !_stricmp( type, \"stdout\" ) )\n\t\t{\n\t\t\tOutputType = LogToStdout;\n\t\t}\n\t\telse if( !_stricmp( type, \"dbgview\" ) )\n\t\t{\n\t\t\tOutputType = LogToDbgview;\n\t\t}\n\t\telse if( !_stricmp( type, \"file\" ) )\n\t\t{\n\t\t\tOutputType = LogToFile;\n\t\t}\n#ifdef IDA_PLUGIN\n\t\telse if( !_stricmp( type, \"ida\" ) )\n\t\t{\n\t\t\tOutputType = LogToIDAMessageBox;\n\t\t}\n#endif\n\t\tfree( type );\n\t}\n\n\tif( OutputType == LogToFile && hLogFile == INVALID_HANDLE_VALUE )\n\t{\n\t\tchar *log_filename_str = GetRegValueString( key_name.c_str(), \"LogFileName\" );\n\t\tif( log_filename_str )\n\t\t{\n\t\t\tstd::string log_filename = log_filename_str;\n\t\t\tfree( log_filename_str );\n\n\t\t\tchar *image_filename;\n\t\t\tchar image_full_filename[MAX_PATH+1];\n\t\t\tGetModuleFileNameA( NULL, image_full_filename, MAX_PATH );\n\t\t\timage_filename = image_full_filename;\n\t\t\tfor( int i = strlen( image_full_filename ) - 1; i >=0 ; i-- )\n\t\t\t{\n\t\t\t\tif( image_full_filename[i] == '\\\\' )\n\t\t\t\t{\n\t\t\t\t\timage_filename = image_full_filename + i + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog_filename += \"-\";\n\t\t\tlog_filename += image_filename;\n\n\t\t\tDWORD pid = GetCurrentProcessId();\n\t\t\tchar pid_buffer[11];\n\n\t\t\t_snprintf( pid_buffer, sizeof(pid_buffer) -1, \"%d\", pid );\n\t\t\tlog_filename += \"-\";\n\t\t\tlog_filename += pid_buffer;\n\n\t\t\tlog_filename += \".log\";\n\t\t\tOpenLogFile( log_filename );\n\t\t}\n\t}\n\n\tGetRegValueInteger( key_name.c_str(), \"Level\", DebugLevel );\n}\n\nvoid LogOperation::SetCompanyName( const char *company_name )\n{\n\tCompanyName = company_name;\n}\n\nvoid LogOperation::SetProductName( const char *product_name )\n{\n\tProductName = product_name;\n}\n\nvoid LogOperation::SetCategory( const char *category_name )\n{\n\tCategoryName = category_name;\n\tDebugLevel = 0;\n\tOutputType = LogToDbgview;\n\tif( CategoryName == \"IEAutomator\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentMain\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"Agent\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogByLogServer\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentC\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessWorker\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessWorkerInBHO\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogMessage\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ApplicationServer\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessWorkerProcessor\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"HookOperation\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessOperation\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProtocolTransport\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LocalCommunicator\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"SocketConnection\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"SocketOperation\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"WorkQueueManager\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"SandBoxRuleManager\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"Controller\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentManager::WorkOnItem\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentManager\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentController\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogServer::LogServerThreadCallback\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogServer\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\n\tRetrieveLogInfoFromRegistry();\n}\n\nLogOperation::~LogOperation()\n{\n}\n\nvoid LogOperation::SetOutputType( int output_type )\n{\n\tOutputType = output_type;\n}\n\nvoid LogOperation::SetDebugLevel( DWORD newDebugLevel )\n{\n\tDebugLevel = newDebugLevel;\n}\n\nvoid LogOperation::SetLogFilename( const char *filename )\n{\n\tLogFilename = filename;\n\n\tCloseLogFile();\n\tOpenLogFile( LogFilename );\n}\n\nvoid LogOperation::Log( DWORD MessageDebugLevel, const CHAR *format, ... )\n{\n\tif( MessageDebugLevel < DebugLevel )\n\t{\n\t\tva_list args;\n\t\tva_start(args,format);\n\t\tCHAR log_message[1024]={0,};\n\t\t_vsnprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\t\tva_end(args);\n\n\t\t_Log(log_message);\n\t}\n}\n\nvoid LogOperation::Log( const CHAR *format, ... )\n{\n\tva_list args;\n\tva_start(args,format);\n\tCHAR log_message[1024]={0,};\n\t_vsnprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\tva_end(args);\n\t_Log(log_message);\n}\n\nvoid LogOperation::Log( DWORD MessageDebugLevel, const WCHAR *format, ... )\n{\n\tif( MessageDebugLevel < DebugLevel )\n\t{\n\t\tva_list args;\n\t\tva_start(args,format);\n\t\tWCHAR log_message[1024]={0,};\n\t\t_vsnwprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\t\tva_end(args);\n\n\t\t_Log(log_message);\n\t}\n}\n\nvoid LogOperation::Log( const WCHAR *format, ... )\n{\n\tva_list args;\n\tva_start(args,format);\n\tWCHAR log_message[1024]={0,};\n\t_vsnwprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\tva_end(args);\n\t_Log(log_message);\n}\n\nvoid LogOperation::DumpHex( TCHAR *Prefix, unsigned char *Buffer, int BufferLen )\n{\n\tTCHAR LineBuffer[256];\n\tmemset(LineBuffer,' ',50);\n\tLineBuffer[50]=0;\n\tint cursor=0;\n\tTCHAR ascii[17];\n\tint start_i=0;\n\tint i;\n\tascii[16]=0;\n\n\tfor(i=0;iDon't try to open a log file when the log file name size is 0#pragma once\n#include \n#include \n#include \n#include \"RegistryUtil.h\"\n#include \"LogOperation.h\"\n\nstatic CRITICAL_SECTION LogFileCS;\nstatic HANDLE hLogFile;\nstatic LONG LogFileCsInitialized;\n\nBOOL LogOperation::OpenLogFile( std::string &log_filename )\n{\n\tEnterCriticalSection( &LogFileCS );\n\t\/\/ Create the new file to write the upper-case version to.\n\tif (hLogFile == INVALID_HANDLE_VALUE && log_filename.size()>0)\n\t{\n\t\thLogFile = CreateFile((LPTSTR) log_filename.c_str(),\/\/ file name \n\t\t\t\tGENERIC_READ | GENERIC_WRITE,\/\/ open r-w \n\t\t\t\tFILE_SHARE_READ,\n\t\t\t\tNULL,\t\t\t\t\/\/ default security \n\t\t\t\tOPEN_ALWAYS,\t\t\/\/ overwrite existing\n\t\t\t\tFILE_ATTRIBUTE_NORMAL,\/\/ normal file \n\t\t\t\tNULL);\t\t\t\t\/\/ no template \n\t\tif( hLogFile == INVALID_HANDLE_VALUE )\n\t\t{ \n\t\t\tprintf(\"CreateFile failed for [%s] with error %u.\\r\\n\", log_filename.c_str(), GetLastError());\n\t\t\tLeaveCriticalSection( &LogFileCS );\n\t\t\treturn FALSE;\n\t\t}\n\t\tSetFilePointer(hLogFile,0,0,FILE_END);\n\t}\n\tLeaveCriticalSection( &LogFileCS );\n\treturn TRUE;\n}\n\nvoid LogOperation::CloseLogFile( )\n{\n\tEnterCriticalSection( &LogFileCS );\n\tif( hLogFile != INVALID_HANDLE_VALUE )\n\t{\n\t\tCloseHandle( hLogFile );\n\t\thLogFile = INVALID_HANDLE_VALUE;\n\t}\n\tLeaveCriticalSection( &LogFileCS );\n}\n\nvoid LogOperation::_Log(const CHAR *log_message)\n{\n\tstd::string full_log_message;\n\tif( OutputType & LogToFile )\n\t{\n\t\tif( hLogFile != INVALID_HANDLE_VALUE ) \n\t\t{\n\t\t\tEnterCriticalSection( &LogFileCS );\n\t\t\tDWORD bytes_written;\n\n\t\t\tSYSTEMTIME lt;\n\t\t\tGetLocalTime(<);\n\t\t\tchar time_buffer[50];\n\t\t\t_snprintf(time_buffer, sizeof(time_buffer), \"[%02d\/%02d\/%04d %02d:%02d:%02d] \",\n\t\t\t\tlt.wMonth,\n\t\t\t\tlt.wDay,\n\t\t\t\tlt.wYear,\n\t\t\t\tlt.wHour,\n\t\t\t\tlt.wMinute,\n\t\t\t\tlt.wSecond);\n\n\t\t\tfull_log_message = time_buffer;\n\t\t\tfull_log_message += \" [\";\n\t\t\tfull_log_message += CategoryName.c_str();\n\t\t\tfull_log_message += \"] \";\n\t\t\tfull_log_message += log_message;\n\n\t\t\tDWORD ret = WriteFile( hLogFile,\n\t\t\t\tfull_log_message.c_str(),\n\t\t\t\tfull_log_message.length(),\n\t\t\t\t&bytes_written,\n\t\t\t\tNULL); \n\t\t\tif( !ret ) \n\t\t\t{\n\t\t\t\tprintf(\"WriteFile failed with error %u.\\r\\n\",GetLastError());\n\t\t\t}\n\t\t\tLeaveCriticalSection( &LogFileCS );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"%s\", log_message);\n\t\t}\n\t}\n\n\tif( (OutputType & LogToDbgview) || (OutputType & LogToIDAMessageBox) || (OutputType & LogToStdout) )\n\t{\n\t\tfull_log_message = \"[\";\n\t\tfull_log_message += CategoryName.c_str();\n\t\tfull_log_message += \"] \";\n\t\tfull_log_message += log_message;\n\t}\n\n\tif( OutputType & LogToDbgview )\n\t\tOutputDebugStringA( full_log_message.c_str() );\n\n\tif( OutputType & LogToIDAMessageBox )\n\t{\n#ifdef IDA_PLUGIN\n\t\tmsg(\"%s\", full_log_message.c_str() );\n#endif\n\t}\n\n\tif( OutputType & LogToStdout )\n\t\tprintf(\"%s\", full_log_message.c_str() );\n}\n\nvoid LogOperation::_Log(const WCHAR *log_message)\n{\n\tCHAR log_message_a[1024];\n\t_snprintf(log_message_a, sizeof(log_message_a)-1, \"%ws\", log_message );\n\t_Log( log_message_a );\n}\n\nLogOperation::LogOperation( int output_type ): OutputType(output_type), DebugLevel(5)\n{\n\tif( !GetConsoleWindow() )\n\t\tOutputType = LogToDbgview;\n}\n\nLogOperation::LogOperation( const char *category_name ): OutputType(LogToFile)\n{\n\tSetCategory( category_name );\n}\n\nvoid LogOperation::InitLog()\n{\n\tInitializeCriticalSection( &LogFileCS );\n\thLogFile = INVALID_HANDLE_VALUE;\n\t\/\/InterlockedExchange( &LogFileCsInitialized, 1 );\n}\n\nvoid LogOperation::FiniLog()\n{\n\t\/\/if( InterlockedExchange( &LogFileCsInitialized, 0 ) == 1 )\n\t{\n\t\t\/\/CloseLogFile();\n\t\tDeleteCriticalSection( &LogFileCS );\n\t}\n}\n\nvoid LogOperation::RetrieveLogInfoFromRegistry()\n{\n\tstd::string key_name = \"HKEY_LOCAL_MACHINE\\\\Software\\\\\";\n\tkey_name += CompanyName;\n\tkey_name += \"\\\\\";\n\tkey_name += ProductName;\n\tkey_name += \"\\\\Logging\\\\\";\n\n\tstd::string category_key_name = key_name;\n\tcategory_key_name += CategoryName;\n\n\tchar *type = GetRegValueString( category_key_name.c_str(), \"Type\" );\n\tif( type )\n\t{\n\t\tif( !_stricmp( type, \"stdout\" ) )\n\t\t{\n\t\t\tOutputType = LogToStdout;\n\t\t}\n\t\telse if( !_stricmp( type, \"dbgview\" ) )\n\t\t{\n\t\t\tOutputType = LogToDbgview;\n\t\t}\n\t\telse if( !_stricmp( type, \"file\" ) )\n\t\t{\n\t\t\tOutputType = LogToFile;\n\t\t}\n#ifdef IDA_PLUGIN\n\t\telse if( !_stricmp( type, \"ida\" ) )\n\t\t{\n\t\t\tOutputType = LogToIDAMessageBox;\n\t\t}\n#endif\n\t\tfree( type );\n\t}\n\n\tif( OutputType == LogToFile && hLogFile == INVALID_HANDLE_VALUE )\n\t{\n\t\tchar *log_filename_str = GetRegValueString( key_name.c_str(), \"LogFileName\" );\n\t\tif( log_filename_str )\n\t\t{\n\t\t\tstd::string log_filename = log_filename_str;\n\t\t\tfree( log_filename_str );\n\n\t\t\tchar *image_filename;\n\t\t\tchar image_full_filename[MAX_PATH+1];\n\t\t\tGetModuleFileNameA( NULL, image_full_filename, MAX_PATH );\n\t\t\timage_filename = image_full_filename;\n\t\t\tfor( int i = strlen( image_full_filename ) - 1; i >=0 ; i-- )\n\t\t\t{\n\t\t\t\tif( image_full_filename[i] == '\\\\' )\n\t\t\t\t{\n\t\t\t\t\timage_filename = image_full_filename + i + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog_filename += \"-\";\n\t\t\tlog_filename += image_filename;\n\n\t\t\tDWORD pid = GetCurrentProcessId();\n\t\t\tchar pid_buffer[11];\n\n\t\t\t_snprintf( pid_buffer, sizeof(pid_buffer) -1, \"%d\", pid );\n\t\t\tlog_filename += \"-\";\n\t\t\tlog_filename += pid_buffer;\n\n\t\t\tlog_filename += \".log\";\n\t\t\tOpenLogFile( log_filename );\n\t\t}\n\t}\n\n\tGetRegValueInteger( key_name.c_str(), \"Level\", DebugLevel );\n}\n\nvoid LogOperation::SetCompanyName( const char *company_name )\n{\n\tCompanyName = company_name;\n}\n\nvoid LogOperation::SetProductName( const char *product_name )\n{\n\tProductName = product_name;\n}\n\nvoid LogOperation::SetCategory( const char *category_name )\n{\n\tCategoryName = category_name;\n\tDebugLevel = 0;\n\tOutputType = LogToDbgview;\n\tif( CategoryName == \"IEAutomator\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentMain\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"Agent\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogByLogServer\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentC\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessWorker\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessWorkerInBHO\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogMessage\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ApplicationServer\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessWorkerProcessor\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"HookOperation\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProcessOperation\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"ProtocolTransport\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LocalCommunicator\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"SocketConnection\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"SocketOperation\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"WorkQueueManager\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"SandBoxRuleManager\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"Controller\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentManager::WorkOnItem\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentManager\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"AgentController\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogServer::LogServerThreadCallback\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\telse if( CategoryName == \"LogServer\" )\n\t{\n\t\tDebugLevel = 0;\n\t\tOutputType = LogToDbgview;\n\t}\n\n\tRetrieveLogInfoFromRegistry();\n}\n\nLogOperation::~LogOperation()\n{\n}\n\nvoid LogOperation::SetOutputType( int output_type )\n{\n\tOutputType = output_type;\n}\n\nvoid LogOperation::SetDebugLevel( DWORD newDebugLevel )\n{\n\tDebugLevel = newDebugLevel;\n}\n\nvoid LogOperation::SetLogFilename( const char *filename )\n{\n\tLogFilename = filename;\n\n\tCloseLogFile();\n\tOpenLogFile( LogFilename );\n}\n\nvoid LogOperation::Log( DWORD MessageDebugLevel, const CHAR *format, ... )\n{\n\tif( MessageDebugLevel < DebugLevel )\n\t{\n\t\tva_list args;\n\t\tva_start(args,format);\n\t\tCHAR log_message[1024]={0,};\n\t\t_vsnprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\t\tva_end(args);\n\n\t\t_Log(log_message);\n\t}\n}\n\nvoid LogOperation::Log( const CHAR *format, ... )\n{\n\tva_list args;\n\tva_start(args,format);\n\tCHAR log_message[1024]={0,};\n\t_vsnprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\tva_end(args);\n\t_Log(log_message);\n}\n\nvoid LogOperation::Log( DWORD MessageDebugLevel, const WCHAR *format, ... )\n{\n\tif( MessageDebugLevel < DebugLevel )\n\t{\n\t\tva_list args;\n\t\tva_start(args,format);\n\t\tWCHAR log_message[1024]={0,};\n\t\t_vsnwprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\t\tva_end(args);\n\n\t\t_Log(log_message);\n\t}\n}\n\nvoid LogOperation::Log( const WCHAR *format, ... )\n{\n\tva_list args;\n\tva_start(args,format);\n\tWCHAR log_message[1024]={0,};\n\t_vsnwprintf(log_message,sizeof(log_message)\/sizeof(char),format,args);\n\tva_end(args);\n\t_Log(log_message);\n}\n\nvoid LogOperation::DumpHex( TCHAR *Prefix, unsigned char *Buffer, int BufferLen )\n{\n\tTCHAR LineBuffer[256];\n\tmemset(LineBuffer,' ',50);\n\tLineBuffer[50]=0;\n\tint cursor=0;\n\tTCHAR ascii[17];\n\tint start_i=0;\n\tint i;\n\tascii[16]=0;\n\n\tfor(i=0;i"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2012 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n\n#include \"memory_tracker.h\"\n\n\/**\n * THIS FILE SHOULD NEVER ACTUALLY BE RUN. IT IS JUST USED TO GET SOME OF OUR\n * TESTS TO COMPILE.\n *\/\n\nextern \"C\" {\n static bool mock_add_new_hook(void (*)(const void* ptr, size_t size)) {\n return false;\n }\n\n static bool mock_remove_new_hook(void (*)(const void* ptr, size_t size)) {\n return false;\n }\n\n static bool mock_add_delete_hook(void (*)(const void* ptr)) {\n return false;\n }\n\n static bool mock_remove_delete_hook(void (*)(const void* ptr)) {\n return false;\n }\n\n static int mock_get_extra_stats_size() {\n return 0;\n }\n\n static void mock_get_allocator_stats(allocator_stats*) {\n \/\/ Empty\n }\n\n static size_t mock_get_allocation_size(void*) {\n return 0;\n }\n}\n\nALLOCATOR_HOOKS_API* getHooksApi(void) {\n static ALLOCATOR_HOOKS_API hooksApi;\n hooksApi.add_new_hook = mock_add_new_hook;\n hooksApi.remove_new_hook = mock_remove_new_hook;\n hooksApi.add_delete_hook = mock_add_delete_hook;\n hooksApi.remove_delete_hook = mock_remove_delete_hook;\n hooksApi.get_extra_stats_size = mock_get_extra_stats_size;\n hooksApi.get_allocator_stats = mock_get_allocator_stats;\n hooksApi.get_allocation_size = mock_get_allocation_size;\n return &hooksApi;\n}\n\nbool MemoryTracker::tracking = false;\nMemoryTracker *MemoryTracker::instance = 0;\n\nMemoryTracker *MemoryTracker::getInstance() {\n if (!instance) {\n instance = new MemoryTracker();\n }\n return instance;\n}\n\nMemoryTracker::MemoryTracker() {\n \/\/ Do nothing\n}\n\nMemoryTracker::~MemoryTracker() {\n \/\/ Do nothing\n}\n\nvoid MemoryTracker::getAllocatorStats(std::map &allocator_stats) {\n (void) allocator_stats;\n \/\/ Do nothing\n}\n\nbool MemoryTracker::trackingMemoryAllocations() {\n \/\/ This should ALWAYS return false\n return tracking;\n}\n\nsize_t MemoryTracker::getFragmentation() {\n return 0;\n}\n\nsize_t MemoryTracker::getTotalBytesAllocated() {\n return 0;\n}\n\nsize_t MemoryTracker::getTotalHeapBytes() {\n return 0;\n}\n\nGet allocation size should be const\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2012 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n\n#include \"memory_tracker.h\"\n\n\/**\n * THIS FILE SHOULD NEVER ACTUALLY BE RUN. IT IS JUST USED TO GET SOME OF OUR\n * TESTS TO COMPILE.\n *\/\n\nextern \"C\" {\n static bool mock_add_new_hook(void (*)(const void* ptr, size_t size)) {\n return false;\n }\n\n static bool mock_remove_new_hook(void (*)(const void* ptr, size_t size)) {\n return false;\n }\n\n static bool mock_add_delete_hook(void (*)(const void* ptr)) {\n return false;\n }\n\n static bool mock_remove_delete_hook(void (*)(const void* ptr)) {\n return false;\n }\n\n static int mock_get_extra_stats_size() {\n return 0;\n }\n\n static void mock_get_allocator_stats(allocator_stats*) {\n \/\/ Empty\n }\n\n static size_t mock_get_allocation_size(const void*) {\n return 0;\n }\n}\n\nALLOCATOR_HOOKS_API* getHooksApi(void) {\n static ALLOCATOR_HOOKS_API hooksApi;\n hooksApi.add_new_hook = mock_add_new_hook;\n hooksApi.remove_new_hook = mock_remove_new_hook;\n hooksApi.add_delete_hook = mock_add_delete_hook;\n hooksApi.remove_delete_hook = mock_remove_delete_hook;\n hooksApi.get_extra_stats_size = mock_get_extra_stats_size;\n hooksApi.get_allocator_stats = mock_get_allocator_stats;\n hooksApi.get_allocation_size = mock_get_allocation_size;\n return &hooksApi;\n}\n\nbool MemoryTracker::tracking = false;\nMemoryTracker *MemoryTracker::instance = 0;\n\nMemoryTracker *MemoryTracker::getInstance() {\n if (!instance) {\n instance = new MemoryTracker();\n }\n return instance;\n}\n\nMemoryTracker::MemoryTracker() {\n \/\/ Do nothing\n}\n\nMemoryTracker::~MemoryTracker() {\n \/\/ Do nothing\n}\n\nvoid MemoryTracker::getAllocatorStats(std::map &allocator_stats) {\n (void) allocator_stats;\n \/\/ Do nothing\n}\n\nbool MemoryTracker::trackingMemoryAllocations() {\n \/\/ This should ALWAYS return false\n return tracking;\n}\n\nsize_t MemoryTracker::getFragmentation() {\n return 0;\n}\n\nsize_t MemoryTracker::getTotalBytesAllocated() {\n return 0;\n}\n\nsize_t MemoryTracker::getTotalHeapBytes() {\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2009 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"v8.h\"\n\n#include \"log-utils.h\"\n#include \"string-stream.h\"\n\nnamespace v8 {\nnamespace internal {\n\n\nconst char* Log::kLogToTemporaryFile = \"&\";\n\n\nLog::Log(Logger* logger)\n : is_stopped_(false),\n output_handle_(NULL),\n ll_output_handle_(NULL),\n mutex_(NULL),\n message_buffer_(NULL),\n logger_(logger) {\n}\n\n\nstatic void AddIsolateIdIfNeeded(StringStream* stream) {\n Isolate* isolate = Isolate::Current();\n if (isolate->IsDefaultIsolate()) return;\n stream->Add(\"isolate-%p-\", isolate);\n}\n\n\nvoid Log::Initialize() {\n mutex_ = OS::CreateMutex();\n message_buffer_ = NewArray(kMessageBufferSize);\n\n \/\/ --log-all enables all the log flags.\n if (FLAG_log_all) {\n FLAG_log_runtime = true;\n FLAG_log_api = true;\n FLAG_log_code = true;\n FLAG_log_gc = true;\n FLAG_log_suspect = true;\n FLAG_log_handles = true;\n FLAG_log_regexp = true;\n }\n\n \/\/ --prof implies --log-code.\n if (FLAG_prof) FLAG_log_code = true;\n\n \/\/ --prof_lazy controls --log-code, implies --noprof_auto.\n if (FLAG_prof_lazy) {\n FLAG_log_code = false;\n FLAG_prof_auto = false;\n }\n\n bool open_log_file = FLAG_log || FLAG_log_runtime || FLAG_log_api\n || FLAG_log_code || FLAG_log_gc || FLAG_log_handles || FLAG_log_suspect\n || FLAG_log_regexp || FLAG_log_state_changes || FLAG_ll_prof;\n\n \/\/ If we're logging anything, we need to open the log file.\n if (open_log_file) {\n if (strcmp(FLAG_logfile, \"-\") == 0) {\n OpenStdout();\n } else if (strcmp(FLAG_logfile, \"*\") == 0) {\n \/\/ Does nothing for now. Will be removed.\n } else if (strcmp(FLAG_logfile, kLogToTemporaryFile) == 0) {\n OpenTemporaryFile();\n } else {\n if (strchr(FLAG_logfile, '%') != NULL ||\n !Isolate::Current()->IsDefaultIsolate()) {\n \/\/ If there's a '%' in the log file name we have to expand\n \/\/ placeholders.\n HeapStringAllocator allocator;\n StringStream stream(&allocator);\n AddIsolateIdIfNeeded(&stream);\n for (const char* p = FLAG_logfile; *p; p++) {\n if (*p == '%') {\n p++;\n switch (*p) {\n case '\\0':\n \/\/ If there's a % at the end of the string we back up\n \/\/ one character so we can escape the loop properly.\n p--;\n break;\n case 't': {\n \/\/ %t expands to the current time in milliseconds.\n double time = OS::TimeCurrentMillis();\n stream.Add(\"%.0f\", FmtElm(time));\n break;\n }\n case '%':\n \/\/ %% expands (contracts really) to %.\n stream.Put('%');\n break;\n default:\n \/\/ All other %'s expand to themselves.\n stream.Put('%');\n stream.Put(*p);\n break;\n }\n } else {\n stream.Put(*p);\n }\n }\n SmartPointer expanded = stream.ToCString();\n OpenFile(*expanded);\n } else {\n OpenFile(FLAG_logfile);\n }\n }\n }\n}\n\n\nvoid Log::OpenStdout() {\n ASSERT(!IsEnabled());\n output_handle_ = stdout;\n}\n\n\nvoid Log::OpenTemporaryFile() {\n ASSERT(!IsEnabled());\n output_handle_ = i::OS::OpenTemporaryFile();\n}\n\n\n\/\/ Extension added to V8 log file name to get the low-level log name.\nstatic const char kLowLevelLogExt[] = \".ll\";\n\n\/\/ File buffer size of the low-level log. We don't use the default to\n\/\/ minimize the associated overhead.\nstatic const int kLowLevelLogBufferSize = 2 * MB;\n\n\nvoid Log::OpenFile(const char* name) {\n ASSERT(!IsEnabled());\n output_handle_ = OS::FOpen(name, OS::LogFileOpenMode);\n if (FLAG_ll_prof) {\n \/\/ Open the low-level log file.\n size_t len = strlen(name);\n ScopedVector ll_name(static_cast(len + sizeof(kLowLevelLogExt)));\n memcpy(ll_name.start(), name, len);\n memcpy(ll_name.start() + len, kLowLevelLogExt, sizeof(kLowLevelLogExt));\n ll_output_handle_ = OS::FOpen(ll_name.start(), OS::LogFileOpenMode);\n setvbuf(ll_output_handle_, NULL, _IOFBF, kLowLevelLogBufferSize);\n }\n}\n\n\nFILE* Log::Close() {\n FILE* result = NULL;\n if (output_handle_ != NULL) {\n if (strcmp(FLAG_logfile, kLogToTemporaryFile) != 0) {\n fclose(output_handle_);\n } else {\n result = output_handle_;\n }\n }\n output_handle_ = NULL;\n if (ll_output_handle_ != NULL) fclose(ll_output_handle_);\n ll_output_handle_ = NULL;\n\n DeleteArray(message_buffer_);\n message_buffer_ = NULL;\n\n delete mutex_;\n mutex_ = NULL;\n\n is_stopped_ = false;\n return result;\n}\n\n\nLogMessageBuilder::LogMessageBuilder(Logger* logger)\n : log_(logger->log_),\n sl(log_->mutex_),\n pos_(0) {\n ASSERT(log_->message_buffer_ != NULL);\n}\n\n\nvoid LogMessageBuilder::Append(const char* format, ...) {\n Vector buf(log_->message_buffer_ + pos_,\n Log::kMessageBufferSize - pos_);\n va_list args;\n va_start(args, format);\n AppendVA(format, args);\n va_end(args);\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::AppendVA(const char* format, va_list args) {\n Vector buf(log_->message_buffer_ + pos_,\n Log::kMessageBufferSize - pos_);\n int result = v8::internal::OS::VSNPrintF(buf, format, args);\n\n \/\/ Result is -1 if output was truncated.\n if (result >= 0) {\n pos_ += result;\n } else {\n pos_ = Log::kMessageBufferSize;\n }\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::Append(const char c) {\n if (pos_ < Log::kMessageBufferSize) {\n log_->message_buffer_[pos_++] = c;\n }\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::Append(String* str) {\n AssertNoAllocation no_heap_allocation; \/\/ Ensure string stay valid.\n int length = str->length();\n for (int i = 0; i < length; i++) {\n Append(static_cast(str->Get(i)));\n }\n}\n\n\nvoid LogMessageBuilder::AppendAddress(Address addr) {\n Append(\"0x%\" V8PRIxPTR, addr);\n}\n\n\nvoid LogMessageBuilder::AppendDetailed(String* str, bool show_impl_info) {\n if (str == NULL) return;\n AssertNoAllocation no_heap_allocation; \/\/ Ensure string stay valid.\n int len = str->length();\n if (len > 0x1000)\n len = 0x1000;\n if (show_impl_info) {\n Append(str->IsAsciiRepresentation() ? 'a' : '2');\n if (StringShape(str).IsExternal())\n Append('e');\n if (StringShape(str).IsSymbol())\n Append('#');\n Append(\":%i:\", str->length());\n }\n for (int i = 0; i < len; i++) {\n uc32 c = str->Get(i);\n if (c > 0xff) {\n Append(\"\\\\u%04x\", c);\n } else if (c < 32 || c > 126) {\n Append(\"\\\\x%02x\", c);\n } else if (c == ',') {\n Append(\"\\\\,\");\n } else if (c == '\\\\') {\n Append(\"\\\\\\\\\");\n } else if (c == '\\\"') {\n Append(\"\\\"\\\"\");\n } else {\n Append(\"%lc\", c);\n }\n }\n}\n\n\nvoid LogMessageBuilder::AppendStringPart(const char* str, int len) {\n if (pos_ + len > Log::kMessageBufferSize) {\n len = Log::kMessageBufferSize - pos_;\n ASSERT(len >= 0);\n if (len == 0) return;\n }\n Vector buf(log_->message_buffer_ + pos_,\n Log::kMessageBufferSize - pos_);\n OS::StrNCpy(buf, str, len);\n pos_ += len;\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::WriteToLogFile() {\n ASSERT(pos_ <= Log::kMessageBufferSize);\n const int written = log_->WriteToFile(log_->message_buffer_, pos_);\n if (written != pos_) {\n log_->stop();\n log_->logger_->LogFailure();\n }\n}\n\n\n} } \/\/ namespace v8::internal\nFinally, remove logging to memory support.\/\/ Copyright 2009 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"v8.h\"\n\n#include \"log-utils.h\"\n#include \"string-stream.h\"\n\nnamespace v8 {\nnamespace internal {\n\n\nconst char* Log::kLogToTemporaryFile = \"&\";\n\n\nLog::Log(Logger* logger)\n : is_stopped_(false),\n output_handle_(NULL),\n ll_output_handle_(NULL),\n mutex_(NULL),\n message_buffer_(NULL),\n logger_(logger) {\n}\n\n\nstatic void AddIsolateIdIfNeeded(StringStream* stream) {\n Isolate* isolate = Isolate::Current();\n if (isolate->IsDefaultIsolate()) return;\n stream->Add(\"isolate-%p-\", isolate);\n}\n\n\nvoid Log::Initialize() {\n mutex_ = OS::CreateMutex();\n message_buffer_ = NewArray(kMessageBufferSize);\n\n \/\/ --log-all enables all the log flags.\n if (FLAG_log_all) {\n FLAG_log_runtime = true;\n FLAG_log_api = true;\n FLAG_log_code = true;\n FLAG_log_gc = true;\n FLAG_log_suspect = true;\n FLAG_log_handles = true;\n FLAG_log_regexp = true;\n }\n\n \/\/ --prof implies --log-code.\n if (FLAG_prof) FLAG_log_code = true;\n\n \/\/ --prof_lazy controls --log-code, implies --noprof_auto.\n if (FLAG_prof_lazy) {\n FLAG_log_code = false;\n FLAG_prof_auto = false;\n }\n\n bool open_log_file = FLAG_log || FLAG_log_runtime || FLAG_log_api\n || FLAG_log_code || FLAG_log_gc || FLAG_log_handles || FLAG_log_suspect\n || FLAG_log_regexp || FLAG_log_state_changes || FLAG_ll_prof;\n\n \/\/ If we're logging anything, we need to open the log file.\n if (open_log_file) {\n if (strcmp(FLAG_logfile, \"-\") == 0) {\n OpenStdout();\n } else if (strcmp(FLAG_logfile, kLogToTemporaryFile) == 0) {\n OpenTemporaryFile();\n } else {\n if (strchr(FLAG_logfile, '%') != NULL ||\n !Isolate::Current()->IsDefaultIsolate()) {\n \/\/ If there's a '%' in the log file name we have to expand\n \/\/ placeholders.\n HeapStringAllocator allocator;\n StringStream stream(&allocator);\n AddIsolateIdIfNeeded(&stream);\n for (const char* p = FLAG_logfile; *p; p++) {\n if (*p == '%') {\n p++;\n switch (*p) {\n case '\\0':\n \/\/ If there's a % at the end of the string we back up\n \/\/ one character so we can escape the loop properly.\n p--;\n break;\n case 't': {\n \/\/ %t expands to the current time in milliseconds.\n double time = OS::TimeCurrentMillis();\n stream.Add(\"%.0f\", FmtElm(time));\n break;\n }\n case '%':\n \/\/ %% expands (contracts really) to %.\n stream.Put('%');\n break;\n default:\n \/\/ All other %'s expand to themselves.\n stream.Put('%');\n stream.Put(*p);\n break;\n }\n } else {\n stream.Put(*p);\n }\n }\n SmartPointer expanded = stream.ToCString();\n OpenFile(*expanded);\n } else {\n OpenFile(FLAG_logfile);\n }\n }\n }\n}\n\n\nvoid Log::OpenStdout() {\n ASSERT(!IsEnabled());\n output_handle_ = stdout;\n}\n\n\nvoid Log::OpenTemporaryFile() {\n ASSERT(!IsEnabled());\n output_handle_ = i::OS::OpenTemporaryFile();\n}\n\n\n\/\/ Extension added to V8 log file name to get the low-level log name.\nstatic const char kLowLevelLogExt[] = \".ll\";\n\n\/\/ File buffer size of the low-level log. We don't use the default to\n\/\/ minimize the associated overhead.\nstatic const int kLowLevelLogBufferSize = 2 * MB;\n\n\nvoid Log::OpenFile(const char* name) {\n ASSERT(!IsEnabled());\n output_handle_ = OS::FOpen(name, OS::LogFileOpenMode);\n if (FLAG_ll_prof) {\n \/\/ Open the low-level log file.\n size_t len = strlen(name);\n ScopedVector ll_name(static_cast(len + sizeof(kLowLevelLogExt)));\n memcpy(ll_name.start(), name, len);\n memcpy(ll_name.start() + len, kLowLevelLogExt, sizeof(kLowLevelLogExt));\n ll_output_handle_ = OS::FOpen(ll_name.start(), OS::LogFileOpenMode);\n setvbuf(ll_output_handle_, NULL, _IOFBF, kLowLevelLogBufferSize);\n }\n}\n\n\nFILE* Log::Close() {\n FILE* result = NULL;\n if (output_handle_ != NULL) {\n if (strcmp(FLAG_logfile, kLogToTemporaryFile) != 0) {\n fclose(output_handle_);\n } else {\n result = output_handle_;\n }\n }\n output_handle_ = NULL;\n if (ll_output_handle_ != NULL) fclose(ll_output_handle_);\n ll_output_handle_ = NULL;\n\n DeleteArray(message_buffer_);\n message_buffer_ = NULL;\n\n delete mutex_;\n mutex_ = NULL;\n\n is_stopped_ = false;\n return result;\n}\n\n\nLogMessageBuilder::LogMessageBuilder(Logger* logger)\n : log_(logger->log_),\n sl(log_->mutex_),\n pos_(0) {\n ASSERT(log_->message_buffer_ != NULL);\n}\n\n\nvoid LogMessageBuilder::Append(const char* format, ...) {\n Vector buf(log_->message_buffer_ + pos_,\n Log::kMessageBufferSize - pos_);\n va_list args;\n va_start(args, format);\n AppendVA(format, args);\n va_end(args);\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::AppendVA(const char* format, va_list args) {\n Vector buf(log_->message_buffer_ + pos_,\n Log::kMessageBufferSize - pos_);\n int result = v8::internal::OS::VSNPrintF(buf, format, args);\n\n \/\/ Result is -1 if output was truncated.\n if (result >= 0) {\n pos_ += result;\n } else {\n pos_ = Log::kMessageBufferSize;\n }\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::Append(const char c) {\n if (pos_ < Log::kMessageBufferSize) {\n log_->message_buffer_[pos_++] = c;\n }\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::Append(String* str) {\n AssertNoAllocation no_heap_allocation; \/\/ Ensure string stay valid.\n int length = str->length();\n for (int i = 0; i < length; i++) {\n Append(static_cast(str->Get(i)));\n }\n}\n\n\nvoid LogMessageBuilder::AppendAddress(Address addr) {\n Append(\"0x%\" V8PRIxPTR, addr);\n}\n\n\nvoid LogMessageBuilder::AppendDetailed(String* str, bool show_impl_info) {\n if (str == NULL) return;\n AssertNoAllocation no_heap_allocation; \/\/ Ensure string stay valid.\n int len = str->length();\n if (len > 0x1000)\n len = 0x1000;\n if (show_impl_info) {\n Append(str->IsAsciiRepresentation() ? 'a' : '2');\n if (StringShape(str).IsExternal())\n Append('e');\n if (StringShape(str).IsSymbol())\n Append('#');\n Append(\":%i:\", str->length());\n }\n for (int i = 0; i < len; i++) {\n uc32 c = str->Get(i);\n if (c > 0xff) {\n Append(\"\\\\u%04x\", c);\n } else if (c < 32 || c > 126) {\n Append(\"\\\\x%02x\", c);\n } else if (c == ',') {\n Append(\"\\\\,\");\n } else if (c == '\\\\') {\n Append(\"\\\\\\\\\");\n } else if (c == '\\\"') {\n Append(\"\\\"\\\"\");\n } else {\n Append(\"%lc\", c);\n }\n }\n}\n\n\nvoid LogMessageBuilder::AppendStringPart(const char* str, int len) {\n if (pos_ + len > Log::kMessageBufferSize) {\n len = Log::kMessageBufferSize - pos_;\n ASSERT(len >= 0);\n if (len == 0) return;\n }\n Vector buf(log_->message_buffer_ + pos_,\n Log::kMessageBufferSize - pos_);\n OS::StrNCpy(buf, str, len);\n pos_ += len;\n ASSERT(pos_ <= Log::kMessageBufferSize);\n}\n\n\nvoid LogMessageBuilder::WriteToLogFile() {\n ASSERT(pos_ <= Log::kMessageBufferSize);\n const int written = log_->WriteToFile(log_->message_buffer_, pos_);\n if (written != pos_) {\n log_->stop();\n log_->logger_->LogFailure();\n }\n}\n\n\n} } \/\/ namespace v8::internal\n<|endoftext|>"} {"text":"#include \n#include \n\n\/\/ #include \n#include \n\nnamespace tests_containers {\n\ntemplate\nstruct Ref : smartref::using_\n{\n T ref;\n\n static auto &counter()\n {\n static auto count = 0;\n return count;\n }\n\n operator T &()\n {\n ++counter();\n return ref;\n }\n\n Ref(T arg) : ref{arg} {}\n\n using smartref::using_::operator=;\n\n Ref() = default;\n\n Ref(const Ref &) = default;\n Ref &operator=(const Ref &) = default;\n Ref(Ref &&) = default;\n Ref &operator=(Ref &&) = default;\n};\n\ntemplate\nauto test = []{\n \/\/! Uninitialized construction\n T a;\n\n \/\/! Default construction\n T b{};\n T c = {};\n\n \/\/! Copy construction\n T d{a};\n T e = a;\n T f = {a};\n auto g{a};\n auto h = a;\n auto i = {a};\n\n \/\/! Move construction\n T j{std::move(a)};\n T k = std::move(a);\n T l = {std::move(a)};\n auto m{T{}};\n auto n = T{};\n auto o = {T{}};\n\n \/\/! Delegate type copy construction\n auto delegate = Delegate{};\n T p{delegate};\n T q = delegate;\n T r = {delegate};\n auto s{T{delegate}};\n auto t = T{delegate};\n auto u = {T{delegate}};\n\n \/\/! Delegate type move construction\n T v{std::move(delegate)};\n T w = std::move(delegate);\n T x = {std::move(delegate)};\n auto y{T{std::move(delegate)}};\n auto z = T{std::move(delegate)};\n auto A = {T{std::move(delegate)}};\n\n \/\/ TODO: Check whether semantics are right (e.g. (a = b)++ changes a, instead of a copy).\n \/\/! Copy assignment\n a = b;\n a = b = c;\n a = (b = c);\n (a = b) = c;\n (a = b) = delegate; \/\/ TODO: also add similar checks for other tests.\n\n \/\/! Move assignment\n a = std::move(b);\n a = b = std::move(c);\n a = (b = std::move(c));\n (a = b) = std::move(c);\n\n \/\/! Delegate type copy assignment\n a = delegate;\n a = b = delegate;\n a = (b = delegate);\n (a = b) = delegate;\n\n \/\/! Delegate type move assignment\n a = std::move(delegate);\n a = b = std::move(delegate);\n a = (b = std::move(delegate));\n (a = b) = std::move(delegate);\n\n return 0;\n};\n\nauto test_int = test();\n\nauto test_ref = []{\n Ref::counter() = 0;\n test, int>();\n printf(\"counter: %d\\n\", Ref::counter());\n assert(Ref::counter() == 34);\n\n Ref::counter() = 0;\n test, float>();\n assert(Ref::counter() == 34);\n\n Ref::counter() = 0;\n test, bool>();\n assert(Ref::counter() == 34);\n\n return 0;\n}();\n\n\/\/ using T = int;\n\/\/ using T = std::vector;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/ \/\/ auto expected = reflect(), std::declval< T >()))>;\n\/\/ auto actual = reflect>(), std::declval< T >()))>;\n\n\/\/ return true;\n\/\/ \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref x;)\n\n\/\/ static_assert(reflect::value_type> == reflect);\n\/\/ static_assert(reflect::allocator_type> == reflect);\n\/\/ static_assert(reflect::size_type> == reflect);\n\/\/ static_assert(reflect::difference_type> == reflect);\n\/\/ static_assert(reflect::reference> == reflect);\n\/\/ static_assert(reflect::const_reference> == reflect);\n\/\/ static_assert(reflect::pointer> == reflect);\n\/\/ static_assert(reflect::const_pointer> == reflect);\n\/\/ static_assert(reflect::iterator> == reflect);\n\/\/ static_assert(reflect::const_iterator> == reflect);\n\/\/ static_assert(reflect::reverse_iterator> == reflect);\n\/\/ static_assert(reflect::const_reverse_iterator> == reflect);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\nAdded assignment operator unit test for std::string.#include \n#include \n\n\/\/ #include \n#include \n#include \n\nnamespace tests_containers {\n\ntemplate\nstruct Ref : smartref::using_\n{\n T ref;\n\n static auto &counter()\n {\n static auto count = 0;\n return count;\n }\n\n operator T &()\n {\n ++counter();\n return ref;\n }\n\n Ref(T arg) : ref{arg} {}\n\n using smartref::using_::operator=;\n\n Ref() = default;\n\n Ref(const Ref &) = default;\n Ref &operator=(const Ref &) = default;\n Ref(Ref &&) = default;\n Ref &operator=(Ref &&) = default;\n};\n\ntemplate\nauto test = []{\n \/\/! Uninitialized construction\n T a;\n\n \/\/! Default construction\n T b{};\n T c = {};\n\n \/\/! Copy construction\n T d{a};\n T e = a;\n T f = {a};\n auto g{a};\n auto h = a;\n auto i = {a};\n\n \/\/! Move construction\n T j{std::move(a)};\n T k = std::move(a);\n T l = {std::move(a)};\n auto m{T{}};\n auto n = T{};\n auto o = {T{}};\n\n \/\/! Delegate type copy construction\n auto delegate = Delegate{};\n T p{delegate};\n T q = delegate;\n T r = {delegate};\n auto s{T{delegate}};\n auto t = T{delegate};\n auto u = {T{delegate}};\n\n \/\/! Delegate type move construction\n T v{std::move(delegate)};\n T w = std::move(delegate);\n T x = {std::move(delegate)};\n auto y{T{std::move(delegate)}};\n auto z = T{std::move(delegate)};\n auto A = {T{std::move(delegate)}};\n\n \/\/ TODO: Check whether semantics are right (e.g. (a = b)++ changes a, instead of a copy).\n \/\/! Copy assignment\n a = b;\n a = b = c;\n a = (b = c);\n (a = b) = c;\n (a = b) = delegate; \/\/ TODO: also add similar checks for other tests.\n\n \/\/! Move assignment\n a = std::move(b);\n a = b = std::move(c);\n a = (b = std::move(c));\n (a = b) = std::move(c);\n\n \/\/! Delegate type copy assignment\n a = delegate;\n a = b = delegate;\n a = (b = delegate);\n (a = b) = delegate;\n\n \/\/! Delegate type move assignment\n a = std::move(delegate);\n a = b = std::move(delegate);\n a = (b = std::move(delegate));\n (a = b) = std::move(delegate);\n\n return 0;\n};\n\nauto test_int = test();\n\nauto test_ref = []{\n Ref::counter() = 0;\n test, int>();\n printf(\"counter: %d\\n\", Ref::counter());\n assert(Ref::counter() == 34);\n\n Ref::counter() = 0;\n test, float>();\n assert(Ref::counter() == 34);\n\n Ref::counter() = 0;\n test, bool>();\n assert(Ref::counter() == 34);\n\n Ref::counter() = 0;\n test, std::string>();\n assert(Ref::counter() == 34);\n\n return 0;\n}();\n\n\/\/ using T = int;\n\/\/ using T = std::vector;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/ \/\/ auto expected = reflect(), std::declval< T >()))>;\n\/\/ auto actual = reflect>(), std::declval< T >()))>;\n\n\/\/ return true;\n\/\/ \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref x;)\n\n\/\/ static_assert(reflect::value_type> == reflect);\n\/\/ static_assert(reflect::allocator_type> == reflect);\n\/\/ static_assert(reflect::size_type> == reflect);\n\/\/ static_assert(reflect::difference_type> == reflect);\n\/\/ static_assert(reflect::reference> == reflect);\n\/\/ static_assert(reflect::const_reference> == reflect);\n\/\/ static_assert(reflect::pointer> == reflect);\n\/\/ static_assert(reflect::const_pointer> == reflect);\n\/\/ static_assert(reflect::iterator> == reflect);\n\/\/ static_assert(reflect::const_iterator> == reflect);\n\/\/ static_assert(reflect::reverse_iterator> == reflect);\n\/\/ static_assert(reflect::const_reverse_iterator> == reflect);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\nnamespace tests_containers {\n\ntemplate\nstruct Ref : smartref::using_\n{\n T ref;\n\n operator T &()\n {\n return ref;\n }\n};\n\nusing T = std::vector;\n\nusing reflection::reflect;\n\n\/\/! Member-types\nconstexpr auto is_valid = [](auto expression)\n{\n auto expected = reflect()))>;\n auto actual = reflect>()))>;\n\n return actual == expected;\n};\n\n#define IS_VALID(expression) is_valid([](auto &&_) {expression;})\n\nstatic_assert(reflect::value_type> == reflect);\nstatic_assert(reflect::allocator_type> == reflect);\nstatic_assert(reflect::size_type> == reflect);\nstatic_assert(reflect::difference_type> == reflect);\nstatic_assert(reflect::reference> == reflect);\nstatic_assert(reflect::const_reference> == reflect);\nstatic_assert(reflect::pointer> == reflect);\nstatic_assert(reflect::const_pointer> == reflect);\nstatic_assert(reflect::iterator> == reflect);\nstatic_assert(reflect::const_iterator> == reflect);\nstatic_assert(reflect::reverse_iterator> == reflect);\nstatic_assert(reflect::const_reverse_iterator> == reflect);\n\n\/\/! Member functions\n\/\/ TODO: Test all overloads\n\/\/ TODO: (constructor)\n\/\/ TODO: operator=\n\/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ static_assert(IS_VALID(_ = _));\nstatic_assert(IS_VALID(_.assign(0, 0)));\nstatic_assert(IS_VALID(_.assign(begin(_), end(_))));\nstatic_assert(IS_VALID(_.get_allocator()));\n\n\/\/! Element access\nstatic_assert(IS_VALID(_.at(T::size_type{})));\nstatic_assert(IS_VALID(_.operator[](0)));\nstatic_assert(IS_VALID(_[0]));\nstatic_assert(IS_VALID(_.front()));\nstatic_assert(IS_VALID(_.back()));\nstatic_assert(IS_VALID(_.data()));\n\n\/\/! Iterators\nstatic_assert(IS_VALID(_.begin()));\nstatic_assert(IS_VALID(_.cbegin()));\nstatic_assert(IS_VALID(_.end()));\nstatic_assert(IS_VALID(_.cend()));\nstatic_assert(IS_VALID(_.rbegin()));\nstatic_assert(IS_VALID(_.crbegin()));\nstatic_assert(IS_VALID(_.rend()));\nstatic_assert(IS_VALID(_.crend()));\n\n\/\/! Capacity\nstatic_assert(IS_VALID(_.empty()));\nstatic_assert(IS_VALID(_.size()));\nstatic_assert(IS_VALID(_.max_size()));\nstatic_assert(IS_VALID(_.reserve(T::size_type{})));\nstatic_assert(IS_VALID(_.capacity()));\nstatic_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/! Modifiers\nstatic_assert(IS_VALID(_.clear()));\nstatic_assert(IS_VALID(_.insert(begin(_), 0)));\nstatic_assert(IS_VALID(_.emplace(begin(_), 0)));\nstatic_assert(IS_VALID(_.template emplace(begin(_), 0)));\nstatic_assert(IS_VALID(_.erase(begin(_))));\nstatic_assert(IS_VALID(_.push_back(0)));\nstatic_assert(IS_VALID(_.emplace_back(0)));\nstatic_assert(IS_VALID(_.template emplace_back(0)));\nstatic_assert(IS_VALID(_.pop_back()));\nstatic_assert(IS_VALID(_.resize(T::size_type{})));\nstatic_assert(IS_VALID(_.swap(_)));\n\n\/\/! Non-member functions\n\/\/ TODO: operator==\n\/\/ TODO: operator!=\n\/\/ TODO: operator<\n\/\/ TODO: operator<=\n\/\/ TODO: operator>\n\/\/ TODO: operator>=\n\/\/ TODO: std::swap\n\n\/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\nApparently, operator= works out of the box.#include \n#include \n\n#include \n\nnamespace tests_containers {\n\ntemplate\nstruct Ref : smartref::using_\n{\n T ref;\n\n operator T &()\n {\n return ref;\n }\n};\n\nusing T = std::vector;\n\nusing reflection::reflect;\n\n\/\/! Member-types\nconstexpr auto is_valid = [](auto expression)\n{\n auto expected = reflect()))>;\n auto actual = reflect>()))>;\n\n return actual == expected;\n};\n\n#define IS_VALID(expression) is_valid([](auto &&_) {expression;})\n\nstatic_assert(reflect::value_type> == reflect);\nstatic_assert(reflect::allocator_type> == reflect);\nstatic_assert(reflect::size_type> == reflect);\nstatic_assert(reflect::difference_type> == reflect);\nstatic_assert(reflect::reference> == reflect);\nstatic_assert(reflect::const_reference> == reflect);\nstatic_assert(reflect::pointer> == reflect);\nstatic_assert(reflect::const_pointer> == reflect);\nstatic_assert(reflect::iterator> == reflect);\nstatic_assert(reflect::const_iterator> == reflect);\nstatic_assert(reflect::reverse_iterator> == reflect);\nstatic_assert(reflect::const_reverse_iterator> == reflect);\n\n\/\/! Member functions\n\/\/ TODO: Test all overloads\n\/\/ TODO: (constructor)\n\/\/ TODO: Why does operator= work? What does it do?\nstatic_assert(IS_VALID(_.operator=(_)));\nstatic_assert(IS_VALID(_ = _));\nstatic_assert(IS_VALID(_.assign(0, 0)));\nstatic_assert(IS_VALID(_.assign(begin(_), end(_))));\nstatic_assert(IS_VALID(_.get_allocator()));\n\n\/\/! Element access\nstatic_assert(IS_VALID(_.at(T::size_type{})));\nstatic_assert(IS_VALID(_.operator[](0)));\nstatic_assert(IS_VALID(_[0]));\nstatic_assert(IS_VALID(_.front()));\nstatic_assert(IS_VALID(_.back()));\nstatic_assert(IS_VALID(_.data()));\n\n\/\/! Iterators\nstatic_assert(IS_VALID(_.begin()));\nstatic_assert(IS_VALID(_.cbegin()));\nstatic_assert(IS_VALID(_.end()));\nstatic_assert(IS_VALID(_.cend()));\nstatic_assert(IS_VALID(_.rbegin()));\nstatic_assert(IS_VALID(_.crbegin()));\nstatic_assert(IS_VALID(_.rend()));\nstatic_assert(IS_VALID(_.crend()));\n\n\/\/! Capacity\nstatic_assert(IS_VALID(_.empty()));\nstatic_assert(IS_VALID(_.size()));\nstatic_assert(IS_VALID(_.max_size()));\nstatic_assert(IS_VALID(_.reserve(T::size_type{})));\nstatic_assert(IS_VALID(_.capacity()));\nstatic_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/! Modifiers\nstatic_assert(IS_VALID(_.clear()));\nstatic_assert(IS_VALID(_.insert(begin(_), 0)));\nstatic_assert(IS_VALID(_.emplace(begin(_), 0)));\nstatic_assert(IS_VALID(_.template emplace(begin(_), 0)));\nstatic_assert(IS_VALID(_.erase(begin(_))));\nstatic_assert(IS_VALID(_.push_back(0)));\nstatic_assert(IS_VALID(_.emplace_back(0)));\nstatic_assert(IS_VALID(_.template emplace_back(0)));\nstatic_assert(IS_VALID(_.pop_back()));\nstatic_assert(IS_VALID(_.resize(T::size_type{})));\nstatic_assert(IS_VALID(_.swap(_)));\n\n\/\/! Non-member functions\n\/\/ TODO: operator==\n\/\/ TODO: operator!=\n\/\/ TODO: operator<\n\/\/ TODO: operator<=\n\/\/ TODO: operator>\n\/\/ TODO: operator>=\n\/\/ TODO: std::swap\n\n\/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<|endoftext|>"} {"text":"#include \n#include \n\n\/\/ #include \n\nnamespace tests_containers {\n\n\/\/ template \n\/\/ class reflect_member_function : public reflection::reflect_base {\n\/\/ private:\n\/\/ template \n\/\/ decltype(auto) indirect(Args&&... args)\n\/\/ {\n\/\/ auto f = [](auto& obj, auto&&... args) { if constexpr (sizeof...(ExplicitArgs) == 0) return obj.operator=(std::forward(args)...); else if constexpr (utils::always_true) return obj.template operator=( std::forward(args)...); };\n\/\/ return F{}(*this, f, std::forward(args)...);\n\/\/ }\n\/\/ public:\n\/\/ template \n\/\/ auto operator=(Args&&... args) -> decltype(indirect(std::forward(args)...)) { return indirect(std::forward(args)...); }\n\/\/ };\n\/\/ template\nstruct Ref : smartref::reflect_member_function\n\/\/ struct Ref : smartref::using_\n{\n int ref;\n\n operator int &()\n {\n return ref;\n }\n\n \/\/ Ref() = default;\n \/\/ Ref(const Ref &) = default;\n Ref(int arg) : ref{arg} {}\n\n \/\/ using Base = smartref::reflect_member_function;\n \/\/ using Base::operator=;\n\n \/\/ int &operator=(int arg)\n \/\/ {\n \/\/ return ref = arg;\n \/\/ }\n\n \/\/ using smartref::using_::using_;\n \/\/ using smartref::using_::operator=;\n\n Ref() = default;\n\n \/\/ Ref(const Ref &) = default;\n \/\/ Ref &operator=(const Ref &) = default;\n \/\/ Ref(Ref &&) = default;\n \/\/ Ref &operator=(Ref &&) = default;\n\n Ref(const Ref &) = delete;\n Ref(Ref &&) = delete;\n Ref &operator=(const Ref &) = delete;\n Ref &operator=(Ref &&) = delete;\n};\n\n\/\/ struct uiop {\n\/\/ auto operator=(int) {}\n\/\/ };\n\/\/ struct qwerty : uiop {\n\/\/ using uiop::operator=;\n\/\/ };\ntemplate\nauto test = []{\n T a;\n T b{};\n T c = {};\n T d = 0;\n \/\/ T e = {0};\n \/\/ T f = a;\n \/\/ T g = {a};\n \/\/ auto h = T{};\n \/\/ auto i = a;\n \/\/ auto j = {a};\n \/\/ auto k{T{}};\n \/\/ auto l{a};\n\n \/\/ a = 0;\n \/\/ a = b;\n \/\/ a = b = 0;\n \/\/ a = b = c;\n \/\/ a = (b = 0);\n \/\/ a = (b = c);\n \/\/ (a = b) = 0;\n \/\/ (a = b) = c;\n};\n\nauto test_int = test;\nauto test_ref = test;\n\n\/\/ using T = int;\n\/\/ using T = std::vector;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/ \/\/ auto expected = reflect(), std::declval< T >()))>;\n\/\/ auto actual = reflect>(), std::declval< T >()))>;\n\n\/\/ return true;\n\/\/ \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref x;)\n\n\/\/ static_assert(reflect::value_type> == reflect);\n\/\/ static_assert(reflect::allocator_type> == reflect);\n\/\/ static_assert(reflect::size_type> == reflect);\n\/\/ static_assert(reflect::difference_type> == reflect);\n\/\/ static_assert(reflect::reference> == reflect);\n\/\/ static_assert(reflect::const_reference> == reflect);\n\/\/ static_assert(reflect::pointer> == reflect);\n\/\/ static_assert(reflect::const_pointer> == reflect);\n\/\/ static_assert(reflect::iterator> == reflect);\n\/\/ static_assert(reflect::const_iterator> == reflect);\n\/\/ static_assert(reflect::reverse_iterator> == reflect);\n\/\/ static_assert(reflect::const_reverse_iterator> == reflect);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\nRe-enabled some more tests.#include \n#include \n\n\/\/ #include \n\nnamespace tests_containers {\n\n\/\/ template \n\/\/ class reflect_member_function : public reflection::reflect_base {\n\/\/ private:\n\/\/ template \n\/\/ decltype(auto) indirect(Args&&... args)\n\/\/ {\n\/\/ auto f = [](auto& obj, auto&&... args) { if constexpr (sizeof...(ExplicitArgs) == 0) return obj.operator=(std::forward(args)...); else if constexpr (utils::always_true) return obj.template operator=( std::forward(args)...); };\n\/\/ return F{}(*this, f, std::forward(args)...);\n\/\/ }\n\/\/ public:\n\/\/ template \n\/\/ auto operator=(Args&&... args) -> decltype(indirect(std::forward(args)...)) { return indirect(std::forward(args)...); }\n\/\/ };\n\/\/ template\nstruct Ref : smartref::reflect_member_function\n\/\/ struct Ref : smartref::using_\n{\n int ref;\n\n operator int &()\n {\n return ref;\n }\n\n \/\/ Ref() = default;\n \/\/ Ref(const Ref &) = default;\n Ref(int arg) : ref{arg} {}\n\n \/\/ using Base = smartref::reflect_member_function;\n \/\/ using Base::operator=;\n\n \/\/ int &operator=(int arg)\n \/\/ {\n \/\/ return ref = arg;\n \/\/ }\n\n \/\/ using smartref::using_::using_;\n \/\/ using smartref::using_::operator=;\n\n Ref() = default;\n\n \/\/ Ref(const Ref &) = default;\n \/\/ Ref &operator=(const Ref &) = default;\n \/\/ Ref(Ref &&) = default;\n \/\/ Ref &operator=(Ref &&) = default;\n\n Ref(const Ref &) = delete;\n Ref(Ref &&) = delete;\n Ref &operator=(const Ref &) = delete;\n Ref &operator=(Ref &&) = delete;\n};\n\n\/\/ struct uiop {\n\/\/ auto operator=(int) {}\n\/\/ };\n\/\/ struct qwerty : uiop {\n\/\/ using uiop::operator=;\n\/\/ };\ntemplate\nauto test = []{\n T a;\n T b{};\n T c = {};\n T d = 0;\n T e = {0};\n \/\/ T f = a;\n \/\/ T g = {a};\n \/\/ auto h = T{};\n \/\/ auto i = a;\n \/\/ auto j = {a};\n \/\/ auto k{T{}};\n \/\/ auto l{a};\n\n \/\/ a = 0;\n \/\/ a = b;\n \/\/ a = b = 0;\n \/\/ a = b = c;\n \/\/ a = (b = 0);\n \/\/ a = (b = c);\n \/\/ (a = b) = 0;\n \/\/ (a = b) = c;\n};\n\nauto test_int = test;\nauto test_ref = test;\n\n\/\/ using T = int;\n\/\/ using T = std::vector;\n\n\/\/ using reflection::reflect;\n\n\/\/ \/\/! Member-types\n\/\/ constexpr auto is_valid = [](auto expression)\n\/\/ {\n\/\/ \/\/ auto expected = reflect(), std::declval< T >()))>;\n\/\/ auto actual = reflect>(), std::declval< T >()))>;\n\n\/\/ return true;\n\/\/ \/\/ return actual == expected;\n\/\/ };\n\n\/\/ #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})\n\n\/\/ TODO:\n\/\/ - constructing a smartref (e.g. Ref x;)\n\n\/\/ static_assert(reflect::value_type> == reflect);\n\/\/ static_assert(reflect::allocator_type> == reflect);\n\/\/ static_assert(reflect::size_type> == reflect);\n\/\/ static_assert(reflect::difference_type> == reflect);\n\/\/ static_assert(reflect::reference> == reflect);\n\/\/ static_assert(reflect::const_reference> == reflect);\n\/\/ static_assert(reflect::pointer> == reflect);\n\/\/ static_assert(reflect::const_pointer> == reflect);\n\/\/ static_assert(reflect::iterator> == reflect);\n\/\/ static_assert(reflect::const_iterator> == reflect);\n\/\/ static_assert(reflect::reverse_iterator> == reflect);\n\/\/ static_assert(reflect::const_reverse_iterator> == reflect);\n\n\/\/ \/\/! Member functions\n\/\/ \/\/ TODO: Test all overloads\n\/\/ \/\/ TODO: (constructor)\n\/\/ \/\/ TODO: Why does operator= work? What does it do?\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(_)));\n\/\/ \/\/ static_assert(IS_VALID(_.operator=(__)));\n\/\/ static_assert(IS_VALID(_ = __));\n\/\/ static_assert(IS_VALID(_.assign(0, 0)));\n\/\/ static_assert(IS_VALID(_.assign(begin(_), end(_))));\n\/\/ static_assert(IS_VALID(_.get_allocator()));\n\/\/ \/\/! Element access\n\/\/ static_assert(IS_VALID(_.at(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.operator[](0)));\n\/\/ static_assert(IS_VALID(_[0]));\n\/\/ static_assert(IS_VALID(_.front()));\n\/\/ static_assert(IS_VALID(_.back()));\n\/\/ static_assert(IS_VALID(_.data()));\n\n\/\/ \/\/! Iterators\n\/\/ static_assert(IS_VALID(_.begin()));\n\/\/ static_assert(IS_VALID(_.cbegin()));\n\/\/ static_assert(IS_VALID(_.end()));\n\/\/ static_assert(IS_VALID(_.cend()));\n\/\/ static_assert(IS_VALID(_.rbegin()));\n\/\/ static_assert(IS_VALID(_.crbegin()));\n\/\/ static_assert(IS_VALID(_.rend()));\n\/\/ static_assert(IS_VALID(_.crend()));\n\n\/\/ \/\/! Capacity\n\/\/ static_assert(IS_VALID(_.empty()));\n\/\/ static_assert(IS_VALID(_.size()));\n\/\/ static_assert(IS_VALID(_.max_size()));\n\/\/ static_assert(IS_VALID(_.reserve(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.capacity()));\n\/\/ static_assert(IS_VALID(_.shrink_to_fit()));\n\n\/\/ \/\/! Modifiers\n\/\/ static_assert(IS_VALID(_.clear()));\n\/\/ static_assert(IS_VALID(_.insert(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.template emplace(begin(_), 0)));\n\/\/ static_assert(IS_VALID(_.erase(begin(_))));\n\/\/ static_assert(IS_VALID(_.push_back(0)));\n\/\/ static_assert(IS_VALID(_.emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.template emplace_back(0)));\n\/\/ static_assert(IS_VALID(_.pop_back()));\n\/\/ static_assert(IS_VALID(_.resize(T::size_type{})));\n\/\/ static_assert(IS_VALID(_.swap(_)));\n\n\/\/ \/\/! Non-member functions\n\/\/ \/\/ static_assert(IS_VALID(_ == _);\n\/\/ \/\/ TODO: operator!=\n\/\/ \/\/ TODO: operator<\n\/\/ \/\/ TODO: operator<=\n\/\/ \/\/ TODO: operator>\n\/\/ \/\/ TODO: operator>=\n\/\/ \/\/ TODO: std::swap\n\n\/\/ \/\/ TODO: Deduction guides\n\n} \/\/ namespace tests_containers\n<|endoftext|>"} {"text":"#include \"..\/ParserTestsBase.h\"\n\nclass ParserTests_FunctionCalls : public ParserTestsBase {\n};\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallOperator) {\n ASTNode* node = this->parseSingleFunction(\"def test()\\n\"\n \" test()\\n\"\n \"end\\n\");\n\n FunctionCallOperatorNode* fnCall = dynamic_cast(node->childAtIndex(0));\n\n ASSERT_EQ(\"Function Call Operator\", fnCall->nodeName());\n ASSERT_EQ(\"Function Variable\", fnCall->receiver()->nodeName());\n ASSERT_EQ(0, fnCall->childCount());\n\n ASSERT_EQ(NewDataType::Void, fnCall->dataType().kind());\n}\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallOperatorWithArgument) {\n ASTNode* node = this->parseSingleFunction(\"def test(Int a)\\n\"\n \" test(a)\\n\"\n \"end\\n\");\n\n FunctionCallOperatorNode* fnCall = dynamic_cast(node->childAtIndex(0));\n\n ASSERT_EQ(\"Function Call Operator\", fnCall->nodeName());\n ASSERT_EQ(1, fnCall->childCount());\n ASSERT_EQ(\"Local Variable\", fnCall->childAtIndex(0)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallOperatorWithTwoArguments) {\n ASTNode* node = this->parseSingleFunction(\"def test(Int a)\\n\"\n \" test(a, a)\\n\"\n \"end\\n\");\n\n FunctionCallOperatorNode* fnCall = dynamic_cast(node->childAtIndex(0));\n\n ASSERT_EQ(\"Function Call Operator\", fnCall->nodeName());\n ASSERT_EQ(2, fnCall->childCount());\n ASSERT_EQ(\"Local Variable\", fnCall->childAtIndex(0)->nodeName());\n ASSERT_EQ(\"Local Variable\", fnCall->childAtIndex(1)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeClosureParameter) {\n Three::ASTNode* node = this->parseSingleFunction(\"def test({Int} closure)\\n\"\n \" closure(1)\\n\"\n \"end\\n\");\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Function Call Operator\", node->nodeName());\n\n Three::FunctionCallOperatorNode* fnCall = dynamic_cast(node);\n\n ASSERT_EQ(1, fnCall->childCount());\n ASSERT_EQ(\"Local Variable\", fnCall->receiver()->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeClosurePointerParameter) {\n Three::ASTNode* node = this->parseSingleFunction(\"def test(*{Int} closure)\\n\"\n \" (*closure)(1)\\n\"\n \"end\\n\");\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Function Call Operator\", node->nodeName());\n\n Three::FunctionCallOperatorNode* fnCall = dynamic_cast(node);\n\n ASSERT_EQ(1, fnCall->childCount());\n\n node = fnCall->receiver();\n ASSERT_EQ(\"Dereference Operator\", node->nodeName());\n ASSERT_EQ(\"Local Variable\", node->childAtIndex(0)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, MethodInvocation) {\n Three::ASTNode* node = this->parseNodeWithBodies(\"def Int.test(Int b)\\n\"\n \"end\\n\"\n \"def invoke(*Int a)\\n\"\n \" a.test(5)\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n ASSERT_EQ(\"Function Definition\", node->childAtIndex(0)->nodeName());\n ASSERT_EQ(NewDataType::Kind::Integer, dynamic_cast(node->childAtIndex(0))->methodOnType().kind());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Function Definition\", node->nodeName());\n ASSERT_EQ(1, node->childCount());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Method Call Operator\", node->nodeName());\n\n Three::MethodCallOperatorNode* method = dynamic_cast(node);\n\n ASSERT_EQ(\"test\", method->name());\n ASSERT_EQ(\"Local Variable\", method->receiver()->nodeName());\n ASSERT_EQ(\"a\", dynamic_cast(method->receiver())->name());\n ASSERT_EQ(1, method->childCount());\n EXPECT_EQ(\"Integer Literal\", method->childAtIndex(0)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeVariableAsFunction) {\n Three::ASTNode* node = this->parseSingleFunction(\"def test()\\n\"\n \" (Int) func\\n\"\n \" func(1)\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n EXPECT_EQ(\"Variable Declaration\", node->childAtIndex(0)->nodeName());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Function Call Operator\", node->nodeName());\n\n Three::FunctionCallOperatorNode* fnCall = dynamic_cast(node);\n\n ASSERT_EQ(\"Local Variable\", fnCall->receiver()->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallDereference) {\n Three::ASTNode* node = this->parseNodeWithBodies(\"def foo(;*Int)\\n\"\n \" return null\\n\"\n \"end\\n\"\n \"def test()\\n\"\n \" *foo() = 1\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n ASSERT_EQ(\"Function Definition\", node->childAtIndex(0)->nodeName());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Function Definition\", node->nodeName());\n ASSERT_EQ(1, node->childCount());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Assign Operator\", node->nodeName());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Dereference Operator\", node->nodeName());\n ASSERT_EQ(\"Function Call Operator\", node->childAtIndex(0)->nodeName());\n}\nAdd test for multiple namespaces with methods#include \"..\/ParserTestsBase.h\"\n\nclass ParserTests_FunctionCalls : public ParserTestsBase {\n};\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallOperator) {\n ASTNode* node = this->parseSingleFunction(\"def test()\\n\"\n \" test()\\n\"\n \"end\\n\");\n\n FunctionCallOperatorNode* fnCall = dynamic_cast(node->childAtIndex(0));\n\n ASSERT_EQ(\"Function Call Operator\", fnCall->nodeName());\n ASSERT_EQ(\"Function Variable\", fnCall->receiver()->nodeName());\n ASSERT_EQ(0, fnCall->childCount());\n\n ASSERT_EQ(NewDataType::Void, fnCall->dataType().kind());\n}\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallOperatorWithArgument) {\n ASTNode* node = this->parseSingleFunction(\"def test(Int a)\\n\"\n \" test(a)\\n\"\n \"end\\n\");\n\n FunctionCallOperatorNode* fnCall = dynamic_cast(node->childAtIndex(0));\n\n ASSERT_EQ(\"Function Call Operator\", fnCall->nodeName());\n ASSERT_EQ(1, fnCall->childCount());\n ASSERT_EQ(\"Local Variable\", fnCall->childAtIndex(0)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallOperatorWithTwoArguments) {\n ASTNode* node = this->parseSingleFunction(\"def test(Int a)\\n\"\n \" test(a, a)\\n\"\n \"end\\n\");\n\n FunctionCallOperatorNode* fnCall = dynamic_cast(node->childAtIndex(0));\n\n ASSERT_EQ(\"Function Call Operator\", fnCall->nodeName());\n ASSERT_EQ(2, fnCall->childCount());\n ASSERT_EQ(\"Local Variable\", fnCall->childAtIndex(0)->nodeName());\n ASSERT_EQ(\"Local Variable\", fnCall->childAtIndex(1)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeClosureParameter) {\n Three::ASTNode* node = this->parseSingleFunction(\"def test({Int} closure)\\n\"\n \" closure(1)\\n\"\n \"end\\n\");\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Function Call Operator\", node->nodeName());\n\n Three::FunctionCallOperatorNode* fnCall = dynamic_cast(node);\n\n ASSERT_EQ(1, fnCall->childCount());\n ASSERT_EQ(\"Local Variable\", fnCall->receiver()->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeClosurePointerParameter) {\n Three::ASTNode* node = this->parseSingleFunction(\"def test(*{Int} closure)\\n\"\n \" (*closure)(1)\\n\"\n \"end\\n\");\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Function Call Operator\", node->nodeName());\n\n Three::FunctionCallOperatorNode* fnCall = dynamic_cast(node);\n\n ASSERT_EQ(1, fnCall->childCount());\n\n node = fnCall->receiver();\n ASSERT_EQ(\"Dereference Operator\", node->nodeName());\n ASSERT_EQ(\"Local Variable\", node->childAtIndex(0)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, MethodInvocation) {\n Three::ASTNode* node = this->parseNodeWithBodies(\"def Int.test(Int b)\\n\"\n \"end\\n\"\n \"def invoke(*Int a)\\n\"\n \" a.test(5)\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n ASSERT_EQ(\"Function Definition\", node->childAtIndex(0)->nodeName());\n ASSERT_EQ(NewDataType::Kind::Integer, dynamic_cast(node->childAtIndex(0))->methodOnType().kind());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Function Definition\", node->nodeName());\n ASSERT_EQ(1, node->childCount());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Method Call Operator\", node->nodeName());\n\n Three::MethodCallOperatorNode* method = dynamic_cast(node);\n\n ASSERT_EQ(\"test\", method->name());\n ASSERT_EQ(\"Local Variable\", method->receiver()->nodeName());\n ASSERT_EQ(\"a\", dynamic_cast(method->receiver())->name());\n ASSERT_EQ(1, method->childCount());\n EXPECT_EQ(\"Integer Literal\", method->childAtIndex(0)->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeMethodDefinedInPreviousNamespace) {\n Three::ASTNode* node = this->parseNodeWithBodies(\"namespace Foo\\n\"\n \" def Int.something()\\n\"\n \" end\\n\"\n \"end\\n\"\n \"namespace Foo\\n\"\n \" def test(*Int a)\\n\"\n \" a.something()\\n\"\n \" end\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Namespace\", node->nodeName());\n ASSERT_EQ(1, node->childCount());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Function Definition\", node->nodeName());\n ASSERT_EQ(1, node->childCount());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Method Call Operator\", node->nodeName());\n auto method = dynamic_cast(node);\n\n ASSERT_EQ(\"something\", method->name());\n}\n\nTEST_F(ParserTests_FunctionCalls, InvokeVariableAsFunction) {\n Three::ASTNode* node = this->parseSingleFunction(\"def test()\\n\"\n \" (Int) func\\n\"\n \" func(1)\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n EXPECT_EQ(\"Variable Declaration\", node->childAtIndex(0)->nodeName());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Function Call Operator\", node->nodeName());\n\n Three::FunctionCallOperatorNode* fnCall = dynamic_cast(node);\n\n ASSERT_EQ(\"Local Variable\", fnCall->receiver()->nodeName());\n}\n\nTEST_F(ParserTests_FunctionCalls, FunctionCallDereference) {\n Three::ASTNode* node = this->parseNodeWithBodies(\"def foo(;*Int)\\n\"\n \" return null\\n\"\n \"end\\n\"\n \"def test()\\n\"\n \" *foo() = 1\\n\"\n \"end\\n\");\n\n ASSERT_EQ(2, node->childCount());\n ASSERT_EQ(\"Function Definition\", node->childAtIndex(0)->nodeName());\n\n node = node->childAtIndex(1);\n ASSERT_EQ(\"Function Definition\", node->nodeName());\n ASSERT_EQ(1, node->childCount());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Assign Operator\", node->nodeName());\n\n node = node->childAtIndex(0);\n ASSERT_EQ(\"Dereference Operator\", node->nodeName());\n ASSERT_EQ(\"Function Call Operator\", node->childAtIndex(0)->nodeName());\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"token.h\"\n#include \"token_exception.h\"\n#include \"tokenreader.h\"\n\nusing namespace std;\n\nTokenReader::TokenReader( const char * file ){\n\tifile.open( file );\n\tmyfile = string( file );\n\tifile >> noskipws;\n\t\/\/ cout<<\"Opened \"<> noskipws;\n}\n\nTokenReader::~TokenReader(){\n\tifile.close();\n\n\t\/* tokenreader giveth, and tokenreader taketh *\/\n\tfor ( vector< Token * >::iterator it = my_tokens.begin(); it != my_tokens.end(); it++ ){\n\t\tdelete *it;\n\t}\n}\n\nToken * TokenReader::readToken() throw( TokenException ){\n\n\tif ( !ifile ){\n throw TokenException( string(\"Could not open \") + myfile );\n }\n\t\/\/ Token * t;\n\n\t\/\/ string token_string;\n\n\tchar open_paren = 'x';\n\tint parens = 1;\n\twhile ( ifile.good() && open_paren != '(' ){\n\t\tifile >> open_paren;\n\t}\n\t\/\/ token_string += '(';\n\n\tToken * cur_token = new Token();\n\tcur_token->setFile( myfile );\n\tmy_tokens.push_back( cur_token );\n\tToken * first = cur_token;\n\tvector< Token * > token_stack;\n\ttoken_stack.push_back( cur_token );\n\n\tchar n;\n\tstring cur_string = \"\";\n\t\/\/ while ( parens != 0 ){\n\t\n\t\/* in_quote is true if a \" is read and before another \" is read *\/\n\tbool in_quote = false;\n\n\t\/* escaped unconditionally adds the next character to the string *\/\n\tbool escaped = false;\n\twhile ( !token_stack.empty() ){\n\t\tif ( !ifile ){\n\t\t\tcout<<__FILE__<<\": \"<print( \" \" );\n\t\t\tthrow TokenException(\"Wrong number of parentheses\");\n\t\t}\n\t\t\/\/ char n;\n\t\t\/\/ slow as we go\n\t\tifile >> n;\n\t\t\n\t\tconst char * alpha = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/-_!\";\n\t\tconst char * nonalpha = \" ;()#\\\"\";\n\t\t\/\/ cout<<\"Alpha char: \"<setParent( cur_token );\n\t\t\t\tcur_token->addToken( sub );\n\t\t\t\tcur_string = \"\";\n\n\t\t\t} else\n\t\t\t\tcur_string += n;\n\n\t\t} else {\n\t\t\tif ( n == '\"' )\n\t\t\t\tin_quote = true;\n\t\t\t\t\n\t\t\tif ( strchr( alpha, n ) != NULL ){\n\t\t\t\tcur_string += n;\n\t\t\t} else if ( cur_string != \"\" && strchr( nonalpha, n ) != NULL ){\n\t\t\t\t\/\/ cout<<\"Made new token \"<setParent( cur_token );\n\t\t\t\tcur_token->addToken( sub );\n\t\t\t\tcur_string = \"\";\n\t\t\t}\n\t\t}\n\n\t\tif ( n == '#' || n == ';' ){\n\t\t\twhile ( n != '\\n' && !ifile.eof() ){\n\t\t\t\tifile >> n;\n\t\t\t}\n\t\t\tcontinue;\n\t\t} else if ( n == '(' ){\n\t\t\tToken * another = new Token();\n\t\t\tanother->setParent( cur_token );\n\t\t\tcur_token->addToken( another );\n\t\t\tcur_token = another;\n\t\t\ttoken_stack.push_back( cur_token );\n\t\t\t\/*\n\t\t\tparens++;\n\t\t\tcout<<\"Inc Parens is \"<print(\"\");\n\tfirst->finalize();\n\treturn first;\n\n}\n\nadd a comment#include \n#include \n#include \n#include \n#include \n\n#include \"token.h\"\n#include \"token_exception.h\"\n#include \"tokenreader.h\"\n\nusing namespace std;\n\n\/* tokenreader reads a file formatted with s-expressions. examples:\n * (hello)\n * (hello world)\n * (hello \"world\")\n * (hello (world))\n * (hello (world hi))\n *\/\nTokenReader::TokenReader( const char * file ){\n\tifile.open( file );\n\tmyfile = string( file );\n\tifile >> noskipws;\n\t\/\/ cout<<\"Opened \"<> noskipws;\n}\n\nTokenReader::~TokenReader(){\n\tifile.close();\n\n\t\/* tokenreader giveth, and tokenreader taketh *\/\n\tfor ( vector< Token * >::iterator it = my_tokens.begin(); it != my_tokens.end(); it++ ){\n\t\tdelete *it;\n\t}\n}\n\nToken * TokenReader::readToken() throw( TokenException ){\n\n\tif ( !ifile ){\n throw TokenException( string(\"Could not open \") + myfile );\n }\n\t\/\/ Token * t;\n\n\t\/\/ string token_string;\n\n\tchar open_paren = 'x';\n\tint parens = 1;\n\twhile ( ifile.good() && open_paren != '(' ){\n\t\tifile >> open_paren;\n\t}\n\t\/\/ token_string += '(';\n\n\tToken * cur_token = new Token();\n\tcur_token->setFile( myfile );\n\tmy_tokens.push_back( cur_token );\n\tToken * first = cur_token;\n\tvector< Token * > token_stack;\n\ttoken_stack.push_back( cur_token );\n\n\tchar n;\n\tstring cur_string = \"\";\n\t\/\/ while ( parens != 0 ){\n\t\n\t\/* in_quote is true if a \" is read and before another \" is read *\/\n\tbool in_quote = false;\n\n\t\/* escaped unconditionally adds the next character to the string *\/\n\tbool escaped = false;\n\twhile ( !token_stack.empty() ){\n\t\tif ( !ifile ){\n\t\t\tcout<<__FILE__<<\": \"<print( \" \" );\n\t\t\tthrow TokenException(\"Wrong number of parentheses\");\n\t\t}\n\t\t\/\/ char n;\n\t\t\/\/ slow as we go\n\t\tifile >> n;\n\t\t\n\t\tconst char * alpha = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.\/-_!\";\n\t\tconst char * nonalpha = \" ;()#\\\"\";\n\t\t\/\/ cout<<\"Alpha char: \"<setParent( cur_token );\n\t\t\t\tcur_token->addToken( sub );\n\t\t\t\tcur_string = \"\";\n\n\t\t\t} else\n\t\t\t\tcur_string += n;\n\n\t\t} else {\n\t\t\tif ( n == '\"' )\n\t\t\t\tin_quote = true;\n\t\t\t\t\n\t\t\tif ( strchr( alpha, n ) != NULL ){\n\t\t\t\tcur_string += n;\n\t\t\t} else if ( cur_string != \"\" && strchr( nonalpha, n ) != NULL ){\n\t\t\t\t\/\/ cout<<\"Made new token \"<setParent( cur_token );\n\t\t\t\tcur_token->addToken( sub );\n\t\t\t\tcur_string = \"\";\n\t\t\t}\n\t\t}\n\n\t\tif ( n == '#' || n == ';' ){\n\t\t\twhile ( n != '\\n' && !ifile.eof() ){\n\t\t\t\tifile >> n;\n\t\t\t}\n\t\t\tcontinue;\n\t\t} else if ( n == '(' ){\n\t\t\tToken * another = new Token();\n\t\t\tanother->setParent( cur_token );\n\t\t\tcur_token->addToken( another );\n\t\t\tcur_token = another;\n\t\t\ttoken_stack.push_back( cur_token );\n\t\t\t\/*\n\t\t\tparens++;\n\t\t\tcout<<\"Inc Parens is \"<print(\"\");\n\tfirst->finalize();\n\treturn first;\n\n}\n\n<|endoftext|>"} {"text":"\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ includes\n#include \/\/ for std::fill\n#include \/\/ *must* precede for proper std:abs() on PGI, Sun Studio CC\n#include \/\/ for std::sqrt std::pow std::abs\n\n\n\/\/ Local Includes\n#include \"libmesh\/libmesh_common.h\"\n#include \"libmesh\/patch.h\"\n#include \"libmesh\/elem.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/-----------------------------------------------------------------\n\/\/ Patch implementations\nvoid Patch::find_face_neighbors(std::set &new_neighbors)\n{\n \/\/ Loop over all the elements in the patch\n std::set::const_iterator it = this->begin();\n const std::set::const_iterator end = this->end();\n\n for (; it != end; ++it)\n {\n const Elem* elem = *it;\n for (unsigned int s=0; sn_sides(); s++)\n if (elem->neighbor(s) != NULL) \/\/ we have a neighbor on this side\n {\n\t const Elem* neighbor = elem->neighbor(s);\n\n#ifdef LIBMESH_ENABLE_AMR\n\t if (!neighbor->active()) \/\/ the neighbor is *not* active,\n\t { \/\/ so add *all* neighboring\n \/\/ active children to the patch\n\t std::vector active_neighbor_children;\n\n\t neighbor->active_family_tree_by_neighbor\n (active_neighbor_children, elem);\n\n std::vector::const_iterator\n child_it = active_neighbor_children.begin();\n const std::vector::const_iterator\n child_end = active_neighbor_children.end();\n for (; child_it != child_end; ++child_it)\n\t\t new_neighbors.insert(*child_it);\n\t }\n else\n#endif \/\/ #ifdef LIBMESH_ENABLE_AMR\n\t new_neighbors.insert (neighbor); \/\/ add active neighbors\n }\n }\n}\n\n\n\nvoid Patch::add_face_neighbors()\n{\n std::set new_neighbors;\n\n this->find_face_neighbors(new_neighbors);\n\n this->insert(new_neighbors.begin(), new_neighbors.end());\n}\n\n\n\nvoid Patch::add_local_face_neighbors()\n{\n std::set new_neighbors;\n\n this->find_face_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end = new_neighbors.end();\n\n for (; it != end; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->processor_id() ==\n\t libMesh::processor_id()) \/\/ ... if the neighbor belongs to this processor\n\tthis->insert (neighbor); \/\/ ... then add it to the patch\n }\n}\n\n\n\nvoid Patch::add_semilocal_face_neighbors()\n{\n std::set new_neighbors;\n\n this->find_face_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end = new_neighbors.end();\n\n for (; it != end; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->is_semilocal())\n\tthis->insert (neighbor);\n }\n}\n\n\n\nvoid Patch::find_point_neighbors(std::set &new_neighbors)\n{\n \/\/ Loop over all the elements in the patch\n std::set::const_iterator it = this->begin();\n const std::set::const_iterator end = this->end();\n\n for (; it != end; ++it)\n {\n std::set elem_point_neighbors;\n\n const Elem* elem = *it;\n elem->find_point_neighbors(elem_point_neighbors);\n\n new_neighbors.insert(elem_point_neighbors.begin(),\n elem_point_neighbors.end());\n }\n}\n\n\n\nvoid Patch::add_point_neighbors()\n{\n std::set new_neighbors;\n\n this->find_point_neighbors(new_neighbors);\n\n this->insert(new_neighbors.begin(), new_neighbors.end());\n}\n\n\n\nvoid Patch::add_local_point_neighbors()\n{\n std::set new_neighbors;\n\n this->find_point_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end = new_neighbors.end();\n\n for (; it != end; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->processor_id() ==\n\t libMesh::processor_id()) \/\/ ... if the neighbor belongs to this processor\n\tthis->insert (neighbor); \/\/ ... then add it to the patch\n }\n}\n\n\n\nvoid Patch::add_semilocal_point_neighbors()\n{\n std::set new_neighbors;\n\n this->find_point_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end = new_neighbors.end();\n\n for (; it != end; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->is_semilocal())\n\tthis->insert (neighbor);\n }\n}\n\n\n\nvoid Patch::build_around_element (const Elem* e0,\n const unsigned int target_patch_size,\n PMF patchtype)\n{\n\n \/\/ Make sure we are building a patch for an active element.\n libmesh_assert(e0);\n libmesh_assert (e0->active());\n \/\/ Make sure we are either starting with a local element or\n \/\/ requesting a nonlocal patch\n libmesh_assert ((patchtype != &Patch::add_local_face_neighbors &&\n patchtype != &Patch::add_local_point_neighbors) ||\n e0->processor_id() == libMesh::processor_id());\n\n \/\/ First clear the current set, then add the element of interest.\n this->clear();\n this->insert (e0);\n\n \/\/ Repeatedly add the neighbors of the elements in the patch until\n \/\/ the target patch size is met\n while (this->size() < target_patch_size)\n {\n \/\/ It is possible that the target patch size is larger than the number\n \/\/ of elements that can be added to the patch. Since we don't\n \/\/ have access to the Mesh object here, the only way we can\n \/\/ detect this case is by detecting a \"stagnant patch,\" i.e. a\n \/\/ patch whose size does not increase after adding face neighbors\n const std::size_t old_patch_size = this->size();\n\n \/\/ We profile the patch-extending functions separately\n (this->*patchtype)();\n\n \/\/ Check for a \"stagnant\" patch\n if (this->size() == old_patch_size)\n\t{\n\t libmesh_do_once(libMesh::err <<\n \"WARNING: stagnant patch of \" << this->size() << \" elements.\"\n << std::endl <<\n \"Does the target patch size exceed the number of local elements?\"\n\t << std::endl;\n\t libmesh_here(););\n\t break;\n\t}\n } \/\/ end while loop\n\n\n \/\/ make sure all the elements in the patch are active and local\n \/\/ if we are in debug mode\n#ifdef DEBUG\n {\n std::set::const_iterator it = this->begin();\n const std::set::const_iterator end = this->end();\n\n for (; it != end; ++it)\n {\n\t\/\/ Convenience. Keep the syntax simple.\n\tconst Elem* elem = *it;\n\n\tlibmesh_assert (elem->active());\n if ((patchtype == &Patch::add_local_face_neighbors ||\n patchtype == &Patch::add_local_point_neighbors))\n\t libmesh_assert_equal_to (elem->processor_id(), libMesh::processor_id());\n }\n }\n#endif\n\n}\n\n} \/\/ namespace libMesh\nChanges in patch.C for -Wshadow.\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ includes\n#include \/\/ for std::fill\n#include \/\/ *must* precede for proper std:abs() on PGI, Sun Studio CC\n#include \/\/ for std::sqrt std::pow std::abs\n\n\n\/\/ Local Includes\n#include \"libmesh\/libmesh_common.h\"\n#include \"libmesh\/patch.h\"\n#include \"libmesh\/elem.h\"\n\nnamespace libMesh\n{\n\n\n\n\/\/-----------------------------------------------------------------\n\/\/ Patch implementations\nvoid Patch::find_face_neighbors(std::set &new_neighbors)\n{\n \/\/ Loop over all the elements in the patch\n std::set::const_iterator it = this->begin();\n const std::set::const_iterator end_it = this->end();\n\n for (; it != end_it; ++it)\n {\n const Elem* elem = *it;\n for (unsigned int s=0; sn_sides(); s++)\n if (elem->neighbor(s) != NULL) \/\/ we have a neighbor on this side\n {\n\t const Elem* neighbor = elem->neighbor(s);\n\n#ifdef LIBMESH_ENABLE_AMR\n\t if (!neighbor->active()) \/\/ the neighbor is *not* active,\n\t { \/\/ so add *all* neighboring\n \/\/ active children to the patch\n\t std::vector active_neighbor_children;\n\n\t neighbor->active_family_tree_by_neighbor\n (active_neighbor_children, elem);\n\n std::vector::const_iterator\n child_it = active_neighbor_children.begin();\n const std::vector::const_iterator\n child_end = active_neighbor_children.end();\n for (; child_it != child_end; ++child_it)\n\t\t new_neighbors.insert(*child_it);\n\t }\n else\n#endif \/\/ #ifdef LIBMESH_ENABLE_AMR\n\t new_neighbors.insert (neighbor); \/\/ add active neighbors\n }\n }\n}\n\n\n\nvoid Patch::add_face_neighbors()\n{\n std::set new_neighbors;\n\n this->find_face_neighbors(new_neighbors);\n\n this->insert(new_neighbors.begin(), new_neighbors.end());\n}\n\n\n\nvoid Patch::add_local_face_neighbors()\n{\n std::set new_neighbors;\n\n this->find_face_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end_it = new_neighbors.end();\n\n for (; it != end_it; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->processor_id() ==\n\t libMesh::processor_id()) \/\/ ... if the neighbor belongs to this processor\n\tthis->insert (neighbor); \/\/ ... then add it to the patch\n }\n}\n\n\n\nvoid Patch::add_semilocal_face_neighbors()\n{\n std::set new_neighbors;\n\n this->find_face_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end_it = new_neighbors.end();\n\n for (; it != end_it; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->is_semilocal())\n\tthis->insert (neighbor);\n }\n}\n\n\n\nvoid Patch::find_point_neighbors(std::set &new_neighbors)\n{\n \/\/ Loop over all the elements in the patch\n std::set::const_iterator it = this->begin();\n const std::set::const_iterator end_it = this->end();\n\n for (; it != end_it; ++it)\n {\n std::set elem_point_neighbors;\n\n const Elem* elem = *it;\n elem->find_point_neighbors(elem_point_neighbors);\n\n new_neighbors.insert(elem_point_neighbors.begin(),\n elem_point_neighbors.end());\n }\n}\n\n\n\nvoid Patch::add_point_neighbors()\n{\n std::set new_neighbors;\n\n this->find_point_neighbors(new_neighbors);\n\n this->insert(new_neighbors.begin(), new_neighbors.end());\n}\n\n\n\nvoid Patch::add_local_point_neighbors()\n{\n std::set new_neighbors;\n\n this->find_point_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end_it = new_neighbors.end();\n\n for (; it != end_it; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->processor_id() ==\n\t libMesh::processor_id()) \/\/ ... if the neighbor belongs to this processor\n\tthis->insert (neighbor); \/\/ ... then add it to the patch\n }\n}\n\n\n\nvoid Patch::add_semilocal_point_neighbors()\n{\n std::set new_neighbors;\n\n this->find_point_neighbors(new_neighbors);\n\n std::set::const_iterator it = new_neighbors.begin();\n const std::set::const_iterator end_it = new_neighbors.end();\n\n for (; it != end_it; ++it)\n {\n const Elem* neighbor = *it;\n if (neighbor->is_semilocal())\n\tthis->insert (neighbor);\n }\n}\n\n\n\nvoid Patch::build_around_element (const Elem* e0,\n const unsigned int target_patch_size,\n PMF patchtype)\n{\n\n \/\/ Make sure we are building a patch for an active element.\n libmesh_assert(e0);\n libmesh_assert (e0->active());\n \/\/ Make sure we are either starting with a local element or\n \/\/ requesting a nonlocal patch\n libmesh_assert ((patchtype != &Patch::add_local_face_neighbors &&\n patchtype != &Patch::add_local_point_neighbors) ||\n e0->processor_id() == libMesh::processor_id());\n\n \/\/ First clear the current set, then add the element of interest.\n this->clear();\n this->insert (e0);\n\n \/\/ Repeatedly add the neighbors of the elements in the patch until\n \/\/ the target patch size is met\n while (this->size() < target_patch_size)\n {\n \/\/ It is possible that the target patch size is larger than the number\n \/\/ of elements that can be added to the patch. Since we don't\n \/\/ have access to the Mesh object here, the only way we can\n \/\/ detect this case is by detecting a \"stagnant patch,\" i.e. a\n \/\/ patch whose size does not increase after adding face neighbors\n const std::size_t old_patch_size = this->size();\n\n \/\/ We profile the patch-extending functions separately\n (this->*patchtype)();\n\n \/\/ Check for a \"stagnant\" patch\n if (this->size() == old_patch_size)\n\t{\n\t libmesh_do_once(libMesh::err <<\n \"WARNING: stagnant patch of \" << this->size() << \" elements.\"\n << std::endl <<\n \"Does the target patch size exceed the number of local elements?\"\n\t << std::endl;\n\t libmesh_here(););\n\t break;\n\t}\n } \/\/ end while loop\n\n\n \/\/ make sure all the elements in the patch are active and local\n \/\/ if we are in debug mode\n#ifdef DEBUG\n {\n std::set::const_iterator it = this->begin();\n const std::set::const_iterator end_it = this->end();\n\n for (; it != end_it; ++it)\n {\n\t\/\/ Convenience. Keep the syntax simple.\n\tconst Elem* elem = *it;\n\n\tlibmesh_assert (elem->active());\n if ((patchtype == &Patch::add_local_face_neighbors ||\n patchtype == &Patch::add_local_point_neighbors))\n\t libmesh_assert_equal_to (elem->processor_id(), libMesh::processor_id());\n }\n }\n#endif\n\n}\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"#include \"ms_layer.hpp\"\n#include \"ms_hashtable.hpp\"\n#include \"ms_projection.hpp\"\n\nNan::Persistent MSLayer::constructor;\n\nvoid MSLayer::Initialize(v8::Local target) {\n v8::Local tpl = Nan::New (MSLayer::New);\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n tpl->SetClassName(Nan::New(\"Layer\").ToLocalChecked());\n\n Nan::SetPrototypeMethod(tpl, \"getGridIntersectionCoordinates\", GetGridIntersectionCoordinates);\n Nan::SetPrototypeMethod(tpl, \"updateFromString\", UpdateFromString);\n#if MS_VERSION_NUM >= 60400\n Nan::SetPrototypeMethod(tpl, \"toString\", ToString);\n#endif\n\n RW_ATTR(tpl, \"name\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"status\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"type\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"connection\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"minscaledenom\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"maxscaledenom\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"projection\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"units\", PropertyGetter, PropertySetter);\n RO_ATTR(tpl, \"connectiontype\", PropertyGetter);\n RO_ATTR(tpl, \"metadata\", PropertyGetter);\n\n target->Set(Nan::New(\"Layer\").ToLocalChecked(), tpl->GetFunction());\n constructor.Reset(tpl);\n}\n\nMSLayer::MSLayer(layerObj *layer) : ObjectWrap(), this_(layer) {}\n\nMSLayer::MSLayer() : ObjectWrap(), this_(0) {}\n\nMSLayer::~MSLayer() { }\n\nNAN_METHOD(MSLayer::New)\n{\n MSLayer* obj;\n if (!info.IsConstructCall()) {\n Nan::ThrowError(\"Cannot call constructor as function, you need to use 'new' keyword\");\n return;\n }\n\n if (info[0]->IsExternal()) {\n v8::Local ext = info[0].As();\n void *ptr = ext->Value();\n MSLayer *f = static_cast(ptr);\n f->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n return;\n }\n\n if (info.Length() != 1 || !info[0]->IsString()) {\n Nan::ThrowTypeError(\"requires one argument: a string\");\n return;\n }\n\n layerObj* layer = (layerObj*)calloc(1,sizeof(layerObj));\n initLayer(layer, (mapObj*)NULL);\n\n layer->name = strdup(TOSTR(info[0]));\n\n obj = new MSLayer(layer);\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n}\n\nv8::Local MSLayer::NewInstance(layerObj *ptr) {\n Nan::EscapableHandleScope scope;\n MSLayer* obj = new MSLayer();\n obj->this_ = ptr;\n v8::Local ext = Nan::New(obj);\n return scope.Escape(Nan::New(constructor)->GetFunction()->NewInstance(1, &ext));\n}\n\nNAN_GETTER(MSLayer::PropertyGetter) {\n\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.Holder());\n\n if (STRCMP(property, \"name\")) {\n info.GetReturnValue().Set(Nan::New(obj->this_->name).ToLocalChecked());\n } else if (STRCMP(property, \"status\")) {\n info.GetReturnValue().Set(obj->this_->status);\n } else if (STRCMP(property, \"metadata\")) {\n info.GetReturnValue().Set(MSHashTable::NewInstance(&(obj->this_->metadata)));\n } else if (STRCMP(property, \"type\")) {\n info.GetReturnValue().Set(obj->this_->type);\n } else if (STRCMP(property, \"minscaledenom\")) {\n info.GetReturnValue().Set(obj->this_->minscaledenom);\n } else if (STRCMP(property, \"maxscaledenom\")) {\n info.GetReturnValue().Set(obj->this_->maxscaledenom);\n } else if (STRCMP(property, \"units\")) {\n info.GetReturnValue().Set(obj->this_->units);\n } else if (STRCMP(property, \"projection\")) {\n info.GetReturnValue().Set(MSProjection::NewInstance(&obj->this_->projection));\n } else if (STRCMP(property, \"connection\")) {\n if (obj->this_->connection == NULL) {\n info.GetReturnValue().Set(Nan::Undefined());\n } else {\n info.GetReturnValue().Set(Nan::New(obj->this_->connection).ToLocalChecked());\n }\n } else if (STRCMP(property, \"connectiontype\")) {\n info.GetReturnValue().Set(obj->this_->connectiontype);\n }\n}\n\nNAN_SETTER(MSLayer::PropertySetter) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.Holder());\n\n if (STRCMP(property, \"name\")) {\n REPLACE_STRING(obj->this_->name, value)\n } else if (STRCMP(property, \"status\")) {\n obj->this_->status = value->NumberValue();\n } else if (STRCMP(property, \"minscaledenom\")) {\n obj->this_->minscaledenom = value->NumberValue();\n } else if (STRCMP(property, \"maxscaledenom\")) {\n obj->this_->maxscaledenom = value->NumberValue();\n } else if (STRCMP(property, \"units\")) {\n int32_t units = value->Int32Value();\n if (units >= MS_INCHES && units <= MS_NAUTICALMILES) {\n obj->this_->units = (MS_UNITS) units;\n }\n } else if (STRCMP(property, \"projection\")) {\n msLoadProjectionString(&(obj->this_->projection), TOSTR(value));\n } else if (STRCMP(property, \"type\")) {\n int32_t type = value->Int32Value();\n if (type >= MS_LAYER_ANNOTATION && type <= MS_LAYER_TILEINDEX) {\n obj->this_->type = (MS_LAYER_TYPE) type;\n }\n } else if (STRCMP(property, \"connection\")) {\n REPLACE_STRING(obj->this_->connection, value)\n }\n}\n\nNAN_METHOD(MSLayer::GetGridIntersectionCoordinates) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n int i = 0;\n\n graticuleIntersectionObj *values = msGraticuleLayerGetIntersectionPoints(obj->this_->map, obj->this_);\n\n v8::Local left = Nan::New(values->nLeft);\n v8::Local top = Nan::New(values->nTop);\n v8::Local right = Nan::New(values->nRight);\n v8::Local bottom = Nan::New(values->nBottom);\n v8::Local val = Nan::New();\n\n for (i=0; inLeft; i++) {\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasLeft[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasLeft[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszLeftLabels[i]).ToLocalChecked());\n left->Set(i, val);\n }\n for (i=0; inTop; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasTop[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasTop[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszTopLabels[i]).ToLocalChecked());\n top->Set(i, val);\n }\n for (i=0; inRight; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasRight[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasRight[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszRightLabels[i]).ToLocalChecked());\n right->Set(i, val);\n }\n for (i=0; inBottom; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasBottom[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasBottom[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszBottomLabels[i]).ToLocalChecked());\n bottom->Set(i, val);\n }\n\n \/\/ return object like this:\n \/\/ {\n \/\/ left: [{position: 0, label: '123.00'}],\n \/\/ top: [{position: 0, label: '123.00'}],\n \/\/ right: [{position: 0, label: '123.00'}],\n \/\/ bottom: [{position: 0, label: '123.00'}],\n \/\/ }\n v8::Local result = Nan::New();\n result->Set(Nan::New(\"left\").ToLocalChecked(), left);\n result->Set(Nan::New(\"top\").ToLocalChecked(), top);\n result->Set(Nan::New(\"right\").ToLocalChecked(), right);\n result->Set(Nan::New(\"bottom\").ToLocalChecked(), bottom);\n info.GetReturnValue().Set(result);\n}\n\nNAN_METHOD(MSLayer::UpdateFromString) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.This());\n int result;\n if (info.Length() < 1) {\n Nan::ThrowError(\"UpdateFromString requires one string argument\");\n return;\n }\n if (!info[0]->IsString()) {\n Nan::ThrowError(\"UpdateFromString requires one string argument\");\n return;\n }\n result = msUpdateLayerFromString(obj->this_, TOSTR(info[0]), MS_FALSE);\n info.GetReturnValue().Set(result);\n}\n\n#if MS_VERSION_NUM >= 60400\nNAN_METHOD(MSLayer::ToString) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.This());\n char *text = msWriteLayerToString(obj->this_);\n info.GetReturnValue().Set(Nan::New(text).ToLocalChecked());\n}\n#endif\nFix missing object initializer in left grid coordinate computation.#include \"ms_layer.hpp\"\n#include \"ms_hashtable.hpp\"\n#include \"ms_projection.hpp\"\n\nNan::Persistent MSLayer::constructor;\n\nvoid MSLayer::Initialize(v8::Local target) {\n v8::Local tpl = Nan::New (MSLayer::New);\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n tpl->SetClassName(Nan::New(\"Layer\").ToLocalChecked());\n\n Nan::SetPrototypeMethod(tpl, \"getGridIntersectionCoordinates\", GetGridIntersectionCoordinates);\n Nan::SetPrototypeMethod(tpl, \"updateFromString\", UpdateFromString);\n#if MS_VERSION_NUM >= 60400\n Nan::SetPrototypeMethod(tpl, \"toString\", ToString);\n#endif\n\n RW_ATTR(tpl, \"name\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"status\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"type\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"connection\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"minscaledenom\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"maxscaledenom\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"projection\", PropertyGetter, PropertySetter);\n RW_ATTR(tpl, \"units\", PropertyGetter, PropertySetter);\n RO_ATTR(tpl, \"connectiontype\", PropertyGetter);\n RO_ATTR(tpl, \"metadata\", PropertyGetter);\n\n target->Set(Nan::New(\"Layer\").ToLocalChecked(), tpl->GetFunction());\n constructor.Reset(tpl);\n}\n\nMSLayer::MSLayer(layerObj *layer) : ObjectWrap(), this_(layer) {}\n\nMSLayer::MSLayer() : ObjectWrap(), this_(0) {}\n\nMSLayer::~MSLayer() { }\n\nNAN_METHOD(MSLayer::New)\n{\n MSLayer* obj;\n if (!info.IsConstructCall()) {\n Nan::ThrowError(\"Cannot call constructor as function, you need to use 'new' keyword\");\n return;\n }\n\n if (info[0]->IsExternal()) {\n v8::Local ext = info[0].As();\n void *ptr = ext->Value();\n MSLayer *f = static_cast(ptr);\n f->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n return;\n }\n\n if (info.Length() != 1 || !info[0]->IsString()) {\n Nan::ThrowTypeError(\"requires one argument: a string\");\n return;\n }\n\n layerObj* layer = (layerObj*)calloc(1,sizeof(layerObj));\n initLayer(layer, (mapObj*)NULL);\n\n layer->name = strdup(TOSTR(info[0]));\n\n obj = new MSLayer(layer);\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n}\n\nv8::Local MSLayer::NewInstance(layerObj *ptr) {\n Nan::EscapableHandleScope scope;\n MSLayer* obj = new MSLayer();\n obj->this_ = ptr;\n v8::Local ext = Nan::New(obj);\n return scope.Escape(Nan::New(constructor)->GetFunction()->NewInstance(1, &ext));\n}\n\nNAN_GETTER(MSLayer::PropertyGetter) {\n\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.Holder());\n\n if (STRCMP(property, \"name\")) {\n info.GetReturnValue().Set(Nan::New(obj->this_->name).ToLocalChecked());\n } else if (STRCMP(property, \"status\")) {\n info.GetReturnValue().Set(obj->this_->status);\n } else if (STRCMP(property, \"metadata\")) {\n info.GetReturnValue().Set(MSHashTable::NewInstance(&(obj->this_->metadata)));\n } else if (STRCMP(property, \"type\")) {\n info.GetReturnValue().Set(obj->this_->type);\n } else if (STRCMP(property, \"minscaledenom\")) {\n info.GetReturnValue().Set(obj->this_->minscaledenom);\n } else if (STRCMP(property, \"maxscaledenom\")) {\n info.GetReturnValue().Set(obj->this_->maxscaledenom);\n } else if (STRCMP(property, \"units\")) {\n info.GetReturnValue().Set(obj->this_->units);\n } else if (STRCMP(property, \"projection\")) {\n info.GetReturnValue().Set(MSProjection::NewInstance(&obj->this_->projection));\n } else if (STRCMP(property, \"connection\")) {\n if (obj->this_->connection == NULL) {\n info.GetReturnValue().Set(Nan::Undefined());\n } else {\n info.GetReturnValue().Set(Nan::New(obj->this_->connection).ToLocalChecked());\n }\n } else if (STRCMP(property, \"connectiontype\")) {\n info.GetReturnValue().Set(obj->this_->connectiontype);\n }\n}\n\nNAN_SETTER(MSLayer::PropertySetter) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.Holder());\n\n if (STRCMP(property, \"name\")) {\n REPLACE_STRING(obj->this_->name, value)\n } else if (STRCMP(property, \"status\")) {\n obj->this_->status = value->NumberValue();\n } else if (STRCMP(property, \"minscaledenom\")) {\n obj->this_->minscaledenom = value->NumberValue();\n } else if (STRCMP(property, \"maxscaledenom\")) {\n obj->this_->maxscaledenom = value->NumberValue();\n } else if (STRCMP(property, \"units\")) {\n int32_t units = value->Int32Value();\n if (units >= MS_INCHES && units <= MS_NAUTICALMILES) {\n obj->this_->units = (MS_UNITS) units;\n }\n } else if (STRCMP(property, \"projection\")) {\n msLoadProjectionString(&(obj->this_->projection), TOSTR(value));\n } else if (STRCMP(property, \"type\")) {\n int32_t type = value->Int32Value();\n if (type >= MS_LAYER_ANNOTATION && type <= MS_LAYER_TILEINDEX) {\n obj->this_->type = (MS_LAYER_TYPE) type;\n }\n } else if (STRCMP(property, \"connection\")) {\n REPLACE_STRING(obj->this_->connection, value)\n }\n}\n\nNAN_METHOD(MSLayer::GetGridIntersectionCoordinates) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.This());\n\n int i = 0;\n\n graticuleIntersectionObj *values = msGraticuleLayerGetIntersectionPoints(obj->this_->map, obj->this_);\n\n v8::Local left = Nan::New(values->nLeft);\n v8::Local top = Nan::New(values->nTop);\n v8::Local right = Nan::New(values->nRight);\n v8::Local bottom = Nan::New(values->nBottom);\n v8::Local val;\n\n for (i=0; inLeft; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasLeft[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasLeft[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszLeftLabels[i]).ToLocalChecked());\n left->Set(i, val);\n }\n for (i=0; inTop; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasTop[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasTop[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszTopLabels[i]).ToLocalChecked());\n top->Set(i, val);\n }\n for (i=0; inRight; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasRight[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasRight[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszRightLabels[i]).ToLocalChecked());\n right->Set(i, val);\n }\n for (i=0; inBottom; i++) {\n val = Nan::New();\n val->Set(Nan::New(\"x\").ToLocalChecked(), Nan::New(values->pasBottom[i].x));\n val->Set(Nan::New(\"y\").ToLocalChecked(), Nan::New(values->pasBottom[i].y));\n val->Set(Nan::New(\"label\").ToLocalChecked(), Nan::New(values->papszBottomLabels[i]).ToLocalChecked());\n bottom->Set(i, val);\n }\n\n \/\/ return object like this:\n \/\/ {\n \/\/ left: [{position: 0, label: '123.00'}],\n \/\/ top: [{position: 0, label: '123.00'}],\n \/\/ right: [{position: 0, label: '123.00'}],\n \/\/ bottom: [{position: 0, label: '123.00'}],\n \/\/ }\n v8::Local result = Nan::New();\n result->Set(Nan::New(\"left\").ToLocalChecked(), left);\n result->Set(Nan::New(\"top\").ToLocalChecked(), top);\n result->Set(Nan::New(\"right\").ToLocalChecked(), right);\n result->Set(Nan::New(\"bottom\").ToLocalChecked(), bottom);\n info.GetReturnValue().Set(result);\n}\n\nNAN_METHOD(MSLayer::UpdateFromString) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.This());\n int result;\n if (info.Length() < 1) {\n Nan::ThrowError(\"UpdateFromString requires one string argument\");\n return;\n }\n if (!info[0]->IsString()) {\n Nan::ThrowError(\"UpdateFromString requires one string argument\");\n return;\n }\n result = msUpdateLayerFromString(obj->this_, TOSTR(info[0]), MS_FALSE);\n info.GetReturnValue().Set(result);\n}\n\n#if MS_VERSION_NUM >= 60400\nNAN_METHOD(MSLayer::ToString) {\n MSLayer *obj = Nan::ObjectWrap::Unwrap(info.This());\n char *text = msWriteLayerToString(obj->this_);\n info.GetReturnValue().Set(Nan::New(text).ToLocalChecked());\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.COM]\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n#include \"BlockMakerEth.h\"\n#include \"EthConsensus.h\"\n\n#include \"utilities_js.hpp\"\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/BlockMakerEth\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nBlockMakerEth::BlockMakerEth(const BlockMakerDefinition& def, const char *kafkaBrokers, const MysqlConnectInfo &poolDB) \n : BlockMaker(def, kafkaBrokers, poolDB)\n{\n useSubmitBlockDetail_ = checkRpcSubmitBlockDetail();\n if (useSubmitBlockDetail_) {\n LOG(INFO) << \"use RPC eth_submitBlockDetail\";\n }\n else if (checkRpcSubmitBlock()) {\n LOG(INFO) << \"use RPC eth_submitBlock, it has limited functionality and the block hash will not be recorded.\";\n }\n else {\n LOG(FATAL) << \"Ethereum nodes doesn't support both eth_submitBlockDetail and eth_submitBlock, cannot submit block!\";\n }\n}\n\nvoid BlockMakerEth::processSolvedShare(rd_kafka_message_t *rkmessage)\n{\n const char *message = (const char *)rkmessage->payload;\n JsonNode r;\n if (!JsonNode::parse(message, message + rkmessage->len, r))\n {\n LOG(ERROR) << \"decode common event failure\";\n return;\n }\n\n if (r.type() != Utilities::JS::type::Obj ||\n r[\"nonce\"].type() != Utilities::JS::type::Str ||\n r[\"header\"].type() != Utilities::JS::type::Str ||\n r[\"mix\"].type() != Utilities::JS::type::Str ||\n r[\"height\"].type() != Utilities::JS::type::Int ||\n r[\"networkDiff\"].type() != Utilities::JS::type::Int ||\n r[\"userId\"].type() != Utilities::JS::type::Int ||\n r[\"workerId\"].type() != Utilities::JS::type::Int ||\n r[\"workerFullName\"].type() != Utilities::JS::type::Str ||\n r[\"chain\"].type() != Utilities::JS::type::Str)\n {\n LOG(ERROR) << \"eth solved share format wrong\";\n return;\n }\n\n StratumWorker worker;\n worker.userId_ = r[\"userId\"].int32();\n worker.workerHashId_ = r[\"workerId\"].int64();\n worker.fullName_ = r[\"workerFullName\"].str();\n\n submitBlockNonBlocking(r[\"nonce\"].str(), r[\"header\"].str(), r[\"mix\"].str(), def_.nodes,\n r[\"height\"].uint32(), r[\"chain\"].str(), r[\"networkDiff\"].uint64(),\n worker);\n}\n\nbool BlockMakerEth::submitBlock(const string &nonce, const string &header, const string &mix,\n const string &rpcUrl, const string &rpcUserPass) {\n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWork\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n HexAddPrefix(nonce).c_str(),\n HexAddPrefix(header).c_str(),\n HexAddPrefix(mix).c_str());\n\n string response;\n bool ok = blockchainNodeRpcCall(rpcUrl.c_str(), rpcUserPass.c_str(), request.c_str(), response);\n DLOG(INFO) << \"eth_submitWork request: \" << request;\n DLOG(INFO) << \"eth_submitWork response: \" << response;\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWork failed, node url: \" << rpcUrl;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj || r[\"result\"].type() != Utilities::JS::type::Bool) {\n LOG(WARNING) << \"node doesn't support eth_submitWork, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n return r[\"result\"].boolean();\n}\n\n\/**\n * RPC eth_submitWorkDetail:\n * A new RPC to submit POW work to Ethereum node. It has the same functionality as `eth_submitWork`\n * but returns more details about the submitted block.\n * It defined by the BTCPool project and implemented in the Parity Ethereum node as a patch.\n * \n * Params (same as `eth_submitWork`):\n * [\n * (string) nonce,\n * (string) pow_hash,\n * (string) mix_hash\n * ]\n * \n * Result:\n * [\n * (bool) success,\n * (string or null) error_msg,\n * (string or null) block_hash,\n * ... \/\/ more fields may added in the future\n * ]\n *\/\nbool BlockMakerEth::submitBlockDetail(const string &nonce, const string &header, const string &mix,\n const string &rpcUrl, const string &rpcUserPass,\n string &errMsg, string &blockHash) {\n \n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWorkDetail\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n HexAddPrefix(nonce).c_str(),\n HexAddPrefix(header).c_str(),\n HexAddPrefix(mix).c_str());\n\n string response;\n bool ok = blockchainNodeRpcCall(rpcUrl.c_str(), rpcUserPass.c_str(), request.c_str(), response);\n DLOG(INFO) << \"eth_submitWorkDetail request: \" << request;\n DLOG(INFO) << \"eth_submitWorkDetail response: \" << response;\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWorkDetail failed, node url: \" << rpcUrl;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj || r[\"result\"].type() != Utilities::JS::type::Array) {\n LOG(WARNING) << \"node doesn't support eth_submitWorkDetail, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n auto result = r[\"result\"].children();\n\n bool success = false;\n if (result->size() >= 1 && result->at(0).type() == Utilities::JS::type::Bool) {\n success = result->at(0).boolean();\n }\n\n if (result->size() >= 2 && result->at(1).type() == Utilities::JS::type::Str) {\n errMsg = result->at(1).str();\n }\n\n if (result->size() >= 3 && result->at(2).type() == Utilities::JS::type::Str) {\n blockHash = result->at(2).str();\n }\n\n return success;\n}\n\nbool BlockMakerEth::checkRpcSubmitBlock() {\n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWork\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n \"0x0000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\");\n\n for (const auto &itr : nodeRpcUri_) {\n string response;\n bool ok = blockchainNodeRpcCall(itr.first.c_str(), itr.second.c_str(), request.c_str(), response);\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWork failed, node url: \" << itr.first;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj || r[\"result\"].type() != Utilities::JS::type::Bool) {\n LOG(WARNING) << \"node doesn't support eth_submitWork, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n }\n\n return true;\n}\n\nbool BlockMakerEth::checkRpcSubmitBlockDetail() {\n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWorkDetail\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n \"0x0000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\");\n\n for (const auto &itr : nodeRpcUri_) {\n string response;\n bool ok = blockchainNodeRpcCall(itr.first.c_str(), itr.second.c_str(), request.c_str(), response);\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWorkDetail failed, node url: \" << itr.first;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj ||\n r[\"result\"].type() != Utilities::JS::type::Array ||\n r[\"result\"].children()->size() < 3 ||\n r[\"result\"].children()->at(0).type() != Utilities::JS::type::Bool)\n {\n LOG(WARNING) << \"node doesn't support eth_submitWorkDetail, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n }\n\n return true;\n}\n\nvoid BlockMakerEth::submitBlockNonBlocking(const string &nonce, const string &header, const string &mix, const vector &nodes,\n const uint32_t height, const string &chain, const uint64_t networkDiff, const StratumWorker &worker) {\n boost::thread t(boost::bind(&BlockMakerEth::_submitBlockThread, this,\n nonce, header, mix, nodes,\n height, chain, networkDiff, worker));\n}\n\nvoid BlockMakerEth::_submitBlockThread(const string &nonce, const string &header, const string &mix, const vector &nodes,\n const uint32_t height, const string &chain, const uint64_t networkDiff, const StratumWorker &worker) {\n string blockHash;\n\n auto submitBlockOnce = [&]() {\n \/\/ try eth_submitWorkDetail\n if (useSubmitBlockDetail_) {\n for (size_t i=0; i 0) {\n if (submitBlockOnce()) {\n break;\n }\n sleep(6 - retryTime); \/\/ first sleep 1s, second sleep 2s, ...\n retryTime--;\n }\n\n \/\/ Still writing to the database even if submitting failed\n saveBlockToDB(header, blockHash, height, chain, networkDiff, worker);\n}\n\nvoid BlockMakerEth::saveBlockToDB(const string &header, const string &blockHash, const uint32_t height,\n const string &chain, const uint64_t networkDiff, const StratumWorker &worker) {\n const string nowStr = date(\"%F %T\");\n string sql;\n sql = Strings::Format(\"INSERT INTO `found_blocks` \"\n \" (`puid`, `worker_id`\"\n \", `worker_full_name`, `chain`\"\n \", `height`, `hash`, `hash_no_nonce`\"\n \", `rewards`\"\n \", `network_diff`, `created_at`)\"\n \" VALUES (%ld, %\" PRId64\n \", '%s', '%s'\"\n \", %lu, '%s', '%s'\"\n \", %\" PRId64\n \", %\" PRIu64 \", '%s'); \",\n worker.userId_, worker.workerHashId_,\n \/\/ filter again, just in case\n filterWorkerName(worker.fullName_).c_str(), chain.c_str(),\n height, blockHash.c_str(), header.c_str(),\n EthConsensus::getStaticBlockReward(height, chain),\n networkDiff, nowStr.c_str());\n\n \/\/ try connect to DB\n MySQLConnection db(poolDB_);\n for (size_t i = 0; i < 3; i++) {\n if (db.ping())\n break;\n else\n sleep(3);\n }\n\n if (db.execute(sql) == false) {\n LOG(ERROR) << \"insert found block failure: \" << sql;\n }\n else\n {\n LOG(INFO) << \"insert found block success for height \" << height;\n }\n}\nblkmaker ETH: don't allow empty node list.\/*\n The MIT License (MIT)\n\n Copyright (c) [2016] [BTC.COM]\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n#include \"BlockMakerEth.h\"\n#include \"EthConsensus.h\"\n\n#include \"utilities_js.hpp\"\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/BlockMakerEth\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nBlockMakerEth::BlockMakerEth(const BlockMakerDefinition& def, const char *kafkaBrokers, const MysqlConnectInfo &poolDB) \n : BlockMaker(def, kafkaBrokers, poolDB)\n{\n useSubmitBlockDetail_ = checkRpcSubmitBlockDetail();\n if (useSubmitBlockDetail_) {\n LOG(INFO) << \"use RPC eth_submitBlockDetail\";\n }\n else if (checkRpcSubmitBlock()) {\n LOG(INFO) << \"use RPC eth_submitBlock, it has limited functionality and the block hash will not be recorded.\";\n }\n else {\n LOG(FATAL) << \"Ethereum nodes doesn't support both eth_submitBlockDetail and eth_submitBlock, cannot submit block!\";\n }\n}\n\nvoid BlockMakerEth::processSolvedShare(rd_kafka_message_t *rkmessage)\n{\n const char *message = (const char *)rkmessage->payload;\n JsonNode r;\n if (!JsonNode::parse(message, message + rkmessage->len, r))\n {\n LOG(ERROR) << \"decode common event failure\";\n return;\n }\n\n if (r.type() != Utilities::JS::type::Obj ||\n r[\"nonce\"].type() != Utilities::JS::type::Str ||\n r[\"header\"].type() != Utilities::JS::type::Str ||\n r[\"mix\"].type() != Utilities::JS::type::Str ||\n r[\"height\"].type() != Utilities::JS::type::Int ||\n r[\"networkDiff\"].type() != Utilities::JS::type::Int ||\n r[\"userId\"].type() != Utilities::JS::type::Int ||\n r[\"workerId\"].type() != Utilities::JS::type::Int ||\n r[\"workerFullName\"].type() != Utilities::JS::type::Str ||\n r[\"chain\"].type() != Utilities::JS::type::Str)\n {\n LOG(ERROR) << \"eth solved share format wrong\";\n return;\n }\n\n StratumWorker worker;\n worker.userId_ = r[\"userId\"].int32();\n worker.workerHashId_ = r[\"workerId\"].int64();\n worker.fullName_ = r[\"workerFullName\"].str();\n\n submitBlockNonBlocking(r[\"nonce\"].str(), r[\"header\"].str(), r[\"mix\"].str(), def_.nodes,\n r[\"height\"].uint32(), r[\"chain\"].str(), r[\"networkDiff\"].uint64(),\n worker);\n}\n\nbool BlockMakerEth::submitBlock(const string &nonce, const string &header, const string &mix,\n const string &rpcUrl, const string &rpcUserPass) {\n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWork\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n HexAddPrefix(nonce).c_str(),\n HexAddPrefix(header).c_str(),\n HexAddPrefix(mix).c_str());\n\n string response;\n bool ok = blockchainNodeRpcCall(rpcUrl.c_str(), rpcUserPass.c_str(), request.c_str(), response);\n DLOG(INFO) << \"eth_submitWork request: \" << request;\n DLOG(INFO) << \"eth_submitWork response: \" << response;\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWork failed, node url: \" << rpcUrl;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj || r[\"result\"].type() != Utilities::JS::type::Bool) {\n LOG(WARNING) << \"node doesn't support eth_submitWork, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n return r[\"result\"].boolean();\n}\n\n\/**\n * RPC eth_submitWorkDetail:\n * A new RPC to submit POW work to Ethereum node. It has the same functionality as `eth_submitWork`\n * but returns more details about the submitted block.\n * It defined by the BTCPool project and implemented in the Parity Ethereum node as a patch.\n * \n * Params (same as `eth_submitWork`):\n * [\n * (string) nonce,\n * (string) pow_hash,\n * (string) mix_hash\n * ]\n * \n * Result:\n * [\n * (bool) success,\n * (string or null) error_msg,\n * (string or null) block_hash,\n * ... \/\/ more fields may added in the future\n * ]\n *\/\nbool BlockMakerEth::submitBlockDetail(const string &nonce, const string &header, const string &mix,\n const string &rpcUrl, const string &rpcUserPass,\n string &errMsg, string &blockHash) {\n \n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWorkDetail\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n HexAddPrefix(nonce).c_str(),\n HexAddPrefix(header).c_str(),\n HexAddPrefix(mix).c_str());\n\n string response;\n bool ok = blockchainNodeRpcCall(rpcUrl.c_str(), rpcUserPass.c_str(), request.c_str(), response);\n DLOG(INFO) << \"eth_submitWorkDetail request: \" << request;\n DLOG(INFO) << \"eth_submitWorkDetail response: \" << response;\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWorkDetail failed, node url: \" << rpcUrl;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj || r[\"result\"].type() != Utilities::JS::type::Array) {\n LOG(WARNING) << \"node doesn't support eth_submitWorkDetail, node url: \" << rpcUrl << \", response: \" << response;\n return false;\n }\n\n auto result = r[\"result\"].children();\n\n bool success = false;\n if (result->size() >= 1 && result->at(0).type() == Utilities::JS::type::Bool) {\n success = result->at(0).boolean();\n }\n\n if (result->size() >= 2 && result->at(1).type() == Utilities::JS::type::Str) {\n errMsg = result->at(1).str();\n }\n\n if (result->size() >= 3 && result->at(2).type() == Utilities::JS::type::Str) {\n blockHash = result->at(2).str();\n }\n\n return success;\n}\n\nbool BlockMakerEth::checkRpcSubmitBlock() {\n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWork\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n \"0x0000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\");\n\n for (const auto &itr : nodeRpcUri_) {\n string response;\n bool ok = blockchainNodeRpcCall(itr.first.c_str(), itr.second.c_str(), request.c_str(), response);\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWork failed, node url: \" << itr.first;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj || r[\"result\"].type() != Utilities::JS::type::Bool) {\n LOG(WARNING) << \"node doesn't support eth_submitWork, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n }\n\n return true;\n}\n\nbool BlockMakerEth::checkRpcSubmitBlockDetail() {\n string request = Strings::Format(\"{\\\"jsonrpc\\\": \\\"2.0\\\", \\\"method\\\": \\\"eth_submitWorkDetail\\\", \\\"params\\\": [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], \\\"id\\\": 5}\\n\",\n \"0x0000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"0x0000000000000000000000000000000000000000000000000000000000000000\");\n\n if (nodeRpcUri_.empty()) {\n LOG(FATAL) << \"Node list is empty, cannot submit block!\";\n return false;\n }\n\n for (const auto &itr : nodeRpcUri_) {\n string response;\n bool ok = blockchainNodeRpcCall(itr.first.c_str(), itr.second.c_str(), request.c_str(), response);\n if (!ok) {\n LOG(WARNING) << \"Call RPC eth_submitWorkDetail failed, node url: \" << itr.first;\n return false;\n }\n\n JsonNode r;\n if (!JsonNode::parse(response.c_str(), response.c_str() + response.size(), r)) {\n LOG(WARNING) << \"decode response failure, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n\n if (r.type() != Utilities::JS::type::Obj ||\n r[\"result\"].type() != Utilities::JS::type::Array ||\n r[\"result\"].children()->size() < 3 ||\n r[\"result\"].children()->at(0).type() != Utilities::JS::type::Bool)\n {\n LOG(WARNING) << \"node doesn't support eth_submitWorkDetail, node url: \" << itr.first << \", response: \" << response;\n return false;\n }\n }\n\n return true;\n}\n\nvoid BlockMakerEth::submitBlockNonBlocking(const string &nonce, const string &header, const string &mix, const vector &nodes,\n const uint32_t height, const string &chain, const uint64_t networkDiff, const StratumWorker &worker) {\n boost::thread t(boost::bind(&BlockMakerEth::_submitBlockThread, this,\n nonce, header, mix, nodes,\n height, chain, networkDiff, worker));\n}\n\nvoid BlockMakerEth::_submitBlockThread(const string &nonce, const string &header, const string &mix, const vector &nodes,\n const uint32_t height, const string &chain, const uint64_t networkDiff, const StratumWorker &worker) {\n string blockHash;\n\n auto submitBlockOnce = [&]() {\n \/\/ try eth_submitWorkDetail\n if (useSubmitBlockDetail_) {\n for (size_t i=0; i 0) {\n if (submitBlockOnce()) {\n break;\n }\n sleep(6 - retryTime); \/\/ first sleep 1s, second sleep 2s, ...\n retryTime--;\n }\n\n \/\/ Still writing to the database even if submitting failed\n saveBlockToDB(header, blockHash, height, chain, networkDiff, worker);\n}\n\nvoid BlockMakerEth::saveBlockToDB(const string &header, const string &blockHash, const uint32_t height,\n const string &chain, const uint64_t networkDiff, const StratumWorker &worker) {\n const string nowStr = date(\"%F %T\");\n string sql;\n sql = Strings::Format(\"INSERT INTO `found_blocks` \"\n \" (`puid`, `worker_id`\"\n \", `worker_full_name`, `chain`\"\n \", `height`, `hash`, `hash_no_nonce`\"\n \", `rewards`\"\n \", `network_diff`, `created_at`)\"\n \" VALUES (%ld, %\" PRId64\n \", '%s', '%s'\"\n \", %lu, '%s', '%s'\"\n \", %\" PRId64\n \", %\" PRIu64 \", '%s'); \",\n worker.userId_, worker.workerHashId_,\n \/\/ filter again, just in case\n filterWorkerName(worker.fullName_).c_str(), chain.c_str(),\n height, blockHash.c_str(), header.c_str(),\n EthConsensus::getStaticBlockReward(height, chain),\n networkDiff, nowStr.c_str());\n\n \/\/ try connect to DB\n MySQLConnection db(poolDB_);\n for (size_t i = 0; i < 3; i++) {\n if (db.ping())\n break;\n else\n sleep(3);\n }\n\n if (db.execute(sql) == false) {\n LOG(ERROR) << \"insert found block failure: \" << sql;\n }\n else\n {\n LOG(INFO) << \"insert found block success for height \" << height;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Minimal teleportation OpenQASM example\n\/\/ Source: .\/examples\/qasm\/qasm_teleport_minimal.cpp\n#include \n\n#include \"qpp.h\"\n\nint main() {\n using namespace qpp;\n\n \/\/ create a qpp::QCircuit from a QASM file\n QCircuit qc = qasm::read_from_file(QPP_ROOT_DIR\n \"\/examples\/qasm\/teleport_minimal.qasm\");\n\n \/\/ we could have also used a C++ standard stream from , like below\n \/\/ std::ifstream ifs{PATH \"\/examples\/qasm\/teleport_minimal.qasm\"};\n \/\/ QCircuit qc = qasm::read(ifs);\n\n \/\/ note that QASM measurements are non-destructive, so the final state after\n \/\/ this step when executed on an engine will be a state of 3 qubits; that is\n \/\/ why we discard the first two qubits in the next line\n qc.discard({0, 1});\n\n std::cout << \">> BEGIN CIRCUIT\\n\";\n \/\/ display the circuit; use qc.to_JSON() for JSON output\n std::cout << qc << '\\n';\n std::cout << \">> END CIRCUIT\\n\\n\";\n\n QEngine q_engine{qc}; \/\/ create an engine out of a quantum circuit\n q_engine.execute(); \/\/ execute the circuit\n std::cout << \">> BEGIN ENGINE STATISTICS\\n\";\n \/\/ display the measurement statistics; use q_engine.to_JSON() for JSON\n \/\/ output\n std::cout << q_engine << '\\n';\n std::cout << \">> END ENGINE STATISTICS\\n\\n\";\n\n \/\/ displays the final output state\n std::cout << \">> Final state:\\n\";\n std::cout << disp(q_engine.get_psi()) << '\\n';\n}\nUpdate qasm_teleport_minimal.cpp\/\/ Minimal teleportation OpenQASM example\n\/\/ Source: .\/examples\/qasm\/qasm_teleport_minimal.cpp\n#include \n\n#include \"qpp.h\"\n\nint main() {\n using namespace qpp;\n\n \/\/ create a qpp::QCircuit from a QASM file\n QCircuit qc = qasm::read_from_file(QPP_ROOT_DIR\n \"\/examples\/qasm\/teleport_minimal.qasm\");\n\n \/\/ we could have also used a C++ standard stream from , like below\n \/\/ std::ifstream ifs{PATH \"\/examples\/qasm\/teleport_minimal.qasm\"};\n \/\/ QCircuit qc = qasm::read(ifs);\n\n \/\/ note that QASM measurements are non-destructive, so the final state after\n \/\/ this step when executed on an engine will be a state of 3 qubits; that is\n \/\/ why we discard the first two qubits in the next line\n qc.discard({0, 1});\n\n \/\/ display the quantum circuit and its corresponding resources\n \/\/ use qc.to_JSON() for JSON output\n std::cout << qc << \"\\n\\n\" << qc.get_resources() << \"\\n\\n\";\n\n QEngine q_engine{qc}; \/\/ create an engine out of a quantum circuit\n\n \/\/ execute the quantum circuit\n q_engine.execute();\n\n \/\/ display the measurement statistics\n \/\/ use q_engine.to_JSON() for JSON output\n std::cout << q_engine << '\\n';\n\n \/\/ displays the final output state\n std::cout << \">> Final state:\\n\";\n std::cout << disp(q_engine.get_psi()) << '\\n';\n}\n<|endoftext|>"} {"text":"paintitems.cc: fixed arrow color by using foreground().<|endoftext|>"} {"text":"\/\/ RUN: %clang_cc1 -fsyntax-only -verify %s\ntemplate\nstruct X0 {\n typedef T* type;\n \n void f0(T);\n void f1(type);\n};\n\ntemplate<> void X0::f0(char);\ntemplate<> void X0::f1(type);\n\nnamespace PR6161 {\n template\n class numpunct : public locale::facet \/\/ expected-error{{use of undeclared identifier 'locale'}} \\\n \/\/ expected-error{{expected class name}}\n {\n static locale::id id; \/\/ expected-error{{use of undeclared identifier}}\n };\n numpunct::~numpunct(); \/\/ expected-error{{expected the class name after '~' to name a destructor}}\n}\nAdd regression test for PR12331.\/\/ RUN: %clang_cc1 -fsyntax-only -verify %s\ntemplate\nstruct X0 {\n typedef T* type;\n \n void f0(T);\n void f1(type);\n};\n\ntemplate<> void X0::f0(char);\ntemplate<> void X0::f1(type);\n\nnamespace PR6161 {\n template\n class numpunct : public locale::facet \/\/ expected-error{{use of undeclared identifier 'locale'}} \\\n \/\/ expected-error{{expected class name}}\n {\n static locale::id id; \/\/ expected-error{{use of undeclared identifier}}\n };\n numpunct::~numpunct(); \/\/ expected-error{{expected the class name after '~' to name a destructor}}\n}\n\nnamespace PR12331 {\n template struct S {\n struct U { static const int n = 5; };\n enum E { e = U::n }; \/\/ expected-note {{implicit instantiation first required here}}\n int arr[e];\n };\n template<> struct S::U { static const int n = sizeof(int); }; \/\/ expected-error {{explicit specialization of 'U' after instantiation}}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"protocol.h\"\n\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#ifndef WIN32\n# include \n#endif\n\nnamespace NetMsgType {\n const char *VERSION=\"version\";\n const char *VERACK=\"verack\";\n const char *ADDR=\"addr\";\n const char *INV=\"inv\";\n const char *GETDATA=\"getdata\";\n const char *MERKLEBLOCK=\"merkleblock\";\n const char *GETBLOCKS=\"getblocks\";\n const char *GETHEADERS=\"getheaders\";\n const char *TX=\"tx\";\n const char *HEADERS=\"headers\";\n const char *BLOCK=\"block\";\n const char *GETADDR=\"getaddr\";\n const char *MEMPOOL=\"mempool\";\n const char *PING=\"ping\";\n const char *PONG=\"pong\";\n const char *NOTFOUND=\"notfound\";\n const char *FILTERLOAD=\"filterload\";\n const char *FILTERADD=\"filteradd\";\n const char *FILTERCLEAR=\"filterclear\";\n const char *REJECT=\"reject\";\n const char *SENDHEADERS=\"sendheaders\";\n const char *FEEFILTER=\"feefilter\";\n const char *SENDCMPCT=\"sendcmpct\";\n const char *CMPCTBLOCK=\"cmpctblock\";\n const char *GETBLOCKTXN=\"getblocktxn\";\n const char *BLOCKTXN=\"blocktxn\";\n const char *DANDELIONTX=\"dandeliontx\";\n\/\/znode\n const char *TXLOCKVOTE=\"txlvote\";\n const char *SPORK=\"spork\";\n const char *GETSPORKS=\"getsporks\";\n const char *ZNODEPAYMENTVOTE=\"mnw\";\n const char *ZNODEPAYMENTBLOCK=\"mnwb\";\n const char *ZNODEPAYMENTSYNC=\"mnget\";\n const char *MNANNOUNCE=\"mnb\";\n const char *MNPING=\"mnp\";\n const char *DSACCEPT=\"dsa\";\n const char *DSVIN=\"dsi\";\n const char *DSFINALTX=\"dsf\";\n const char *DSSIGNFINALTX=\"dss\";\n const char *DSCOMPLETE=\"dsc\";\n const char *DSSTATUSUPDATE=\"dssu\";\n const char *DSTX=\"dstx\";\n const char *DSQUEUE=\"dsq\";\n const char *DSEG=\"dseg\";\n const char *SYNCSTATUSCOUNT=\"ssc\";\n const char *MNVERIFY=\"mnv\";\n const char *TXLOCKREQUEST=\"ix\";\n const char *MNGOVERNANCESYNC=\"govsync\";\n const char *MNGOVERNANCEOBJECT=\"govobj\";\n const char *MNGOVERNANCEOBJECTVOTE=\"govobjvote\";\n const char *GETMNLISTDIFF=\"getmnlistd\";\n const char *MNLISTDIFF=\"mnlistdiff\";\n const char *QSENDRECSIGS=\"qsendrecsigs\";\n const char *QFCOMMITMENT=\"qfcommit\";\n const char *QCONTRIB=\"qcontrib\";\n const char *QCOMPLAINT=\"qcomplaint\";\n const char *QJUSTIFICATION=\"qjustify\";\n const char *QPCOMMITMENT=\"qpcommit\";\n const char *QWATCH=\"qwatch\";\n const char *QSIGSESANN=\"qsigsesann\";\n const char *QSIGSHARESINV=\"qsigsinv\";\n const char *QGETSIGSHARES=\"qgetsigs\";\n const char *QBSIGSHARES=\"qbsigs\";\n const char *QSIGREC=\"qsigrec\";\n const char *CLSIG=\"clsig\";\n const char *ISLOCK=\"islock\";\n const char *MNAUTH=\"mnauth\";\n};\n\n\/** All known message types. Keep this in the same order as the list of\n * messages above and in protocol.h.\n *\/\nconst static std::string allNetMessageTypes[] = {\n NetMsgType::VERSION,\n NetMsgType::VERACK,\n NetMsgType::ADDR,\n NetMsgType::INV,\n NetMsgType::GETDATA,\n NetMsgType::MERKLEBLOCK,\n NetMsgType::GETBLOCKS,\n NetMsgType::GETHEADERS,\n NetMsgType::TX,\n NetMsgType::HEADERS,\n NetMsgType::BLOCK,\n NetMsgType::GETADDR,\n NetMsgType::MEMPOOL,\n NetMsgType::PING,\n NetMsgType::PONG,\n NetMsgType::NOTFOUND,\n NetMsgType::FILTERLOAD,\n NetMsgType::FILTERADD,\n NetMsgType::FILTERCLEAR,\n NetMsgType::REJECT,\n NetMsgType::SENDHEADERS,\n NetMsgType::FEEFILTER,\n NetMsgType::SENDCMPCT,\n NetMsgType::CMPCTBLOCK,\n NetMsgType::GETBLOCKTXN,\n NetMsgType::BLOCKTXN,\n NetMsgType::DANDELIONTX,\n \/\/znode\n NetMsgType::TXLOCKREQUEST,\n NetMsgType::TXLOCKVOTE,\n NetMsgType::ZNODEPAYMENTVOTE,\n NetMsgType::ZNODEPAYMENTBLOCK,\n NetMsgType::ZNODEPAYMENTSYNC,\n NetMsgType::SPORK,\n NetMsgType::GETSPORKS,\n NetMsgType::MNANNOUNCE,\n NetMsgType::MNPING,\n NetMsgType::GETMNLISTDIFF,\n NetMsgType::MNLISTDIFF,\n NetMsgType::SYNCSTATUSCOUNT,\n NetMsgType::MNVERIFY,\n NetMsgType::QSENDRECSIGS,\n NetMsgType::QFCOMMITMENT,\n NetMsgType::QCONTRIB,\n NetMsgType::QCOMPLAINT,\n NetMsgType::QJUSTIFICATION,\n NetMsgType::QPCOMMITMENT,\n NetMsgType::QWATCH,\n NetMsgType::QSIGSESANN,\n NetMsgType::QSIGSHARESINV,\n NetMsgType::QGETSIGSHARES,\n NetMsgType::QBSIGSHARES,\n NetMsgType::QSIGREC,\n NetMsgType::CLSIG,\n NetMsgType::ISLOCK,\n NetMsgType::MNAUTH,\n};\nconst static std::vector allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));\n\nCMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)\n{\n memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n nMessageSize = -1;\n memset(pchChecksum, 0, CHECKSUM_SIZE);\n}\n\nCMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)\n{\n memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n strncpy(pchCommand, pszCommand, COMMAND_SIZE);\n nMessageSize = nMessageSizeIn;\n memset(pchChecksum, 0, CHECKSUM_SIZE);\n}\n\nstd::string CMessageHeader::GetCommand() const\n{\n return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));\n}\n\nbool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const\n{\n \/\/ Check start string\n if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)\n return false;\n\n \/\/ Check the command string for errors\n for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)\n {\n if (*p1 == 0)\n {\n \/\/ Must be all zeros after the first zero\n for (; p1 < pchCommand + COMMAND_SIZE; p1++)\n if (*p1 != 0)\n return false;\n }\n else if (*p1 < ' ' || *p1 > 0x7E)\n return false;\n }\n\n \/\/ Message size\n if (nMessageSize > MAX_SIZE)\n {\n LogPrintf(\"CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\\n\", GetCommand(), nMessageSize);\n return false;\n }\n\n return true;\n}\n\n\n\nCAddress::CAddress() : CService()\n{\n Init();\n}\n\nCAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)\n{\n Init();\n nServices = nServicesIn;\n}\n\nvoid CAddress::Init()\n{\n nServices = NODE_NONE;\n nTime = 100000000;\n}\n\nCInv::CInv()\n{\n type = 0;\n hash.SetNull();\n}\n\nCInv::CInv(int typeIn, const uint256& hashIn)\n{\n type = typeIn;\n hash = hashIn;\n}\n\nbool operator<(const CInv& a, const CInv& b)\n{\n return (a.type < b.type || (a.type == b.type && a.hash < b.hash));\n}\n\nstd::string CInv::GetCommand() const\n{\n std::string cmd;\n if (type & MSG_WITNESS_FLAG)\n cmd.append(\"witness-\");\n int masked = type & MSG_TYPE_MASK;\n \/\/ TODO: switch(masked)\n switch (type)\n {\n case MSG_TX: return cmd.append(NetMsgType::TX);\n case MSG_BLOCK: return cmd.append(NetMsgType::BLOCK);\n case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);\n case MSG_CMPCT_BLOCK: return cmd.append(NetMsgType::CMPCTBLOCK);\n case MSG_DANDELION_TX: return cmd.append(NetMsgType::DANDELIONTX);\n\n case MSG_TXLOCK_REQUEST: return cmd.append(NetMsgType::TXLOCKREQUEST);\n case MSG_TXLOCK_VOTE: return cmd.append(NetMsgType::TXLOCKVOTE);\n case MSG_SPORK: return cmd.append(NetMsgType::SPORK);\n case MSG_ZNODE_PAYMENT_VOTE: return cmd.append(NetMsgType::ZNODEPAYMENTVOTE);\n case MSG_ZNODE_PAYMENT_BLOCK: return cmd.append(NetMsgType::ZNODEPAYMENTBLOCK);\n case MSG_ZNODE_ANNOUNCE: return cmd.append(NetMsgType::MNANNOUNCE);\n case MSG_ZNODE_PING: return cmd.append(NetMsgType::MNPING);\n case MSG_DSTX: return cmd.append(NetMsgType::DSTX);\n case MSG_ZNODE_VERIFY: return cmd.append(NetMsgType::MNVERIFY);\n default:\n throw std::out_of_range(strprintf(\"CInv::GetCommand(): type=%d unknown type\", type));\n }\n}\n\nstd::string CInv::ToString() const\n{\n try {\n return strprintf(\"%s %s\", GetCommand(), hash.ToString());\n } catch(const std::out_of_range &) {\n return strprintf(\"0x%08x %s\", type, hash.ToString());\n }\n}\n\nconst std::vector &getAllNetMessageTypes()\n{\n return allNetMessageTypesVec;\n}\nAdded znode evo command network names\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"protocol.h\"\n\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#ifndef WIN32\n# include \n#endif\n\nnamespace NetMsgType {\n const char *VERSION=\"version\";\n const char *VERACK=\"verack\";\n const char *ADDR=\"addr\";\n const char *INV=\"inv\";\n const char *GETDATA=\"getdata\";\n const char *MERKLEBLOCK=\"merkleblock\";\n const char *GETBLOCKS=\"getblocks\";\n const char *GETHEADERS=\"getheaders\";\n const char *TX=\"tx\";\n const char *HEADERS=\"headers\";\n const char *BLOCK=\"block\";\n const char *GETADDR=\"getaddr\";\n const char *MEMPOOL=\"mempool\";\n const char *PING=\"ping\";\n const char *PONG=\"pong\";\n const char *NOTFOUND=\"notfound\";\n const char *FILTERLOAD=\"filterload\";\n const char *FILTERADD=\"filteradd\";\n const char *FILTERCLEAR=\"filterclear\";\n const char *REJECT=\"reject\";\n const char *SENDHEADERS=\"sendheaders\";\n const char *FEEFILTER=\"feefilter\";\n const char *SENDCMPCT=\"sendcmpct\";\n const char *CMPCTBLOCK=\"cmpctblock\";\n const char *GETBLOCKTXN=\"getblocktxn\";\n const char *BLOCKTXN=\"blocktxn\";\n const char *DANDELIONTX=\"dandeliontx\";\n\/\/znode\n const char *TXLOCKVOTE=\"txlvote\";\n const char *SPORK=\"spork\";\n const char *GETSPORKS=\"getsporks\";\n const char *ZNODEPAYMENTVOTE=\"mnw\";\n const char *ZNODEPAYMENTBLOCK=\"mnwb\";\n const char *ZNODEPAYMENTSYNC=\"mnget\";\n const char *MNANNOUNCE=\"mnb\";\n const char *MNPING=\"mnp\";\n const char *DSACCEPT=\"dsa\";\n const char *DSVIN=\"dsi\";\n const char *DSFINALTX=\"dsf\";\n const char *DSSIGNFINALTX=\"dss\";\n const char *DSCOMPLETE=\"dsc\";\n const char *DSSTATUSUPDATE=\"dssu\";\n const char *DSTX=\"dstx\";\n const char *DSQUEUE=\"dsq\";\n const char *DSEG=\"dseg\";\n const char *SYNCSTATUSCOUNT=\"ssc\";\n const char *MNVERIFY=\"mnv\";\n const char *TXLOCKREQUEST=\"ix\";\n const char *MNGOVERNANCESYNC=\"govsync\";\n const char *MNGOVERNANCEOBJECT=\"govobj\";\n const char *MNGOVERNANCEOBJECTVOTE=\"govobjvote\";\n const char *GETMNLISTDIFF=\"getmnlistd\";\n const char *MNLISTDIFF=\"mnlistdiff\";\n const char *QSENDRECSIGS=\"qsendrecsigs\";\n const char *QFCOMMITMENT=\"qfcommit\";\n const char *QCONTRIB=\"qcontrib\";\n const char *QCOMPLAINT=\"qcomplaint\";\n const char *QJUSTIFICATION=\"qjustify\";\n const char *QPCOMMITMENT=\"qpcommit\";\n const char *QWATCH=\"qwatch\";\n const char *QSIGSESANN=\"qsigsesann\";\n const char *QSIGSHARESINV=\"qsigsinv\";\n const char *QGETSIGSHARES=\"qgetsigs\";\n const char *QBSIGSHARES=\"qbsigs\";\n const char *QSIGREC=\"qsigrec\";\n const char *CLSIG=\"clsig\";\n const char *ISLOCK=\"islock\";\n const char *MNAUTH=\"mnauth\";\n};\n\n\/** All known message types. Keep this in the same order as the list of\n * messages above and in protocol.h.\n *\/\nconst static std::string allNetMessageTypes[] = {\n NetMsgType::VERSION,\n NetMsgType::VERACK,\n NetMsgType::ADDR,\n NetMsgType::INV,\n NetMsgType::GETDATA,\n NetMsgType::MERKLEBLOCK,\n NetMsgType::GETBLOCKS,\n NetMsgType::GETHEADERS,\n NetMsgType::TX,\n NetMsgType::HEADERS,\n NetMsgType::BLOCK,\n NetMsgType::GETADDR,\n NetMsgType::MEMPOOL,\n NetMsgType::PING,\n NetMsgType::PONG,\n NetMsgType::NOTFOUND,\n NetMsgType::FILTERLOAD,\n NetMsgType::FILTERADD,\n NetMsgType::FILTERCLEAR,\n NetMsgType::REJECT,\n NetMsgType::SENDHEADERS,\n NetMsgType::FEEFILTER,\n NetMsgType::SENDCMPCT,\n NetMsgType::CMPCTBLOCK,\n NetMsgType::GETBLOCKTXN,\n NetMsgType::BLOCKTXN,\n NetMsgType::DANDELIONTX,\n \/\/znode\n NetMsgType::TXLOCKREQUEST,\n NetMsgType::TXLOCKVOTE,\n NetMsgType::ZNODEPAYMENTVOTE,\n NetMsgType::ZNODEPAYMENTBLOCK,\n NetMsgType::ZNODEPAYMENTSYNC,\n NetMsgType::SPORK,\n NetMsgType::GETSPORKS,\n NetMsgType::MNANNOUNCE,\n NetMsgType::MNPING,\n NetMsgType::GETMNLISTDIFF,\n NetMsgType::MNLISTDIFF,\n NetMsgType::SYNCSTATUSCOUNT,\n NetMsgType::MNVERIFY,\n NetMsgType::QSENDRECSIGS,\n NetMsgType::QFCOMMITMENT,\n NetMsgType::QCONTRIB,\n NetMsgType::QCOMPLAINT,\n NetMsgType::QJUSTIFICATION,\n NetMsgType::QPCOMMITMENT,\n NetMsgType::QWATCH,\n NetMsgType::QSIGSESANN,\n NetMsgType::QSIGSHARESINV,\n NetMsgType::QGETSIGSHARES,\n NetMsgType::QBSIGSHARES,\n NetMsgType::QSIGREC,\n NetMsgType::CLSIG,\n NetMsgType::ISLOCK,\n NetMsgType::MNAUTH,\n};\nconst static std::vector allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));\n\nCMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)\n{\n memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n nMessageSize = -1;\n memset(pchChecksum, 0, CHECKSUM_SIZE);\n}\n\nCMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)\n{\n memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n strncpy(pchCommand, pszCommand, COMMAND_SIZE);\n nMessageSize = nMessageSizeIn;\n memset(pchChecksum, 0, CHECKSUM_SIZE);\n}\n\nstd::string CMessageHeader::GetCommand() const\n{\n return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));\n}\n\nbool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const\n{\n \/\/ Check start string\n if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)\n return false;\n\n \/\/ Check the command string for errors\n for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)\n {\n if (*p1 == 0)\n {\n \/\/ Must be all zeros after the first zero\n for (; p1 < pchCommand + COMMAND_SIZE; p1++)\n if (*p1 != 0)\n return false;\n }\n else if (*p1 < ' ' || *p1 > 0x7E)\n return false;\n }\n\n \/\/ Message size\n if (nMessageSize > MAX_SIZE)\n {\n LogPrintf(\"CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\\n\", GetCommand(), nMessageSize);\n return false;\n }\n\n return true;\n}\n\n\n\nCAddress::CAddress() : CService()\n{\n Init();\n}\n\nCAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)\n{\n Init();\n nServices = nServicesIn;\n}\n\nvoid CAddress::Init()\n{\n nServices = NODE_NONE;\n nTime = 100000000;\n}\n\nCInv::CInv()\n{\n type = 0;\n hash.SetNull();\n}\n\nCInv::CInv(int typeIn, const uint256& hashIn)\n{\n type = typeIn;\n hash = hashIn;\n}\n\nbool operator<(const CInv& a, const CInv& b)\n{\n return (a.type < b.type || (a.type == b.type && a.hash < b.hash));\n}\n\nstd::string CInv::GetCommand() const\n{\n std::string cmd;\n if (type & MSG_WITNESS_FLAG)\n cmd.append(\"witness-\");\n int masked = type & MSG_TYPE_MASK;\n \/\/ TODO: switch(masked)\n switch (type)\n {\n case MSG_TX: return cmd.append(NetMsgType::TX);\n case MSG_BLOCK: return cmd.append(NetMsgType::BLOCK);\n case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);\n case MSG_CMPCT_BLOCK: return cmd.append(NetMsgType::CMPCTBLOCK);\n case MSG_DANDELION_TX: return cmd.append(NetMsgType::DANDELIONTX);\n\n case MSG_TXLOCK_REQUEST: return cmd.append(NetMsgType::TXLOCKREQUEST);\n case MSG_TXLOCK_VOTE: return cmd.append(NetMsgType::TXLOCKVOTE);\n case MSG_SPORK: return cmd.append(NetMsgType::SPORK);\n case MSG_ZNODE_PAYMENT_VOTE: return cmd.append(NetMsgType::ZNODEPAYMENTVOTE);\n case MSG_ZNODE_PAYMENT_BLOCK: return cmd.append(NetMsgType::ZNODEPAYMENTBLOCK);\n case MSG_ZNODE_ANNOUNCE: return cmd.append(NetMsgType::MNANNOUNCE);\n case MSG_ZNODE_PING: return cmd.append(NetMsgType::MNPING);\n case MSG_DSTX: return cmd.append(NetMsgType::DSTX);\n case MSG_ZNODE_VERIFY: return cmd.append(NetMsgType::MNVERIFY);\n\n case MSG_QUORUM_FINAL_COMMITMENT: return cmd.append(NetMsgType::QFCOMMITMENT);\n case MSG_QUORUM_CONTRIB: return cmd.append(NetMsgType::QCONTRIB);\n case MSG_QUORUM_COMPLAINT: return cmd.append(NetMsgType::QCOMPLAINT);\n case MSG_QUORUM_JUSTIFICATION: return cmd.append(NetMsgType::QJUSTIFICATION);\n case MSG_QUORUM_PREMATURE_COMMITMENT: return cmd.append(NetMsgType::QPCOMMITMENT);\n case MSG_QUORUM_RECOVERED_SIG: return cmd.append(NetMsgType::QSIGREC);\n case MSG_CLSIG: return cmd.append(NetMsgType::CLSIG);\n case MSG_ISLOCK: return cmd.append(NetMsgType::ISLOCK);\n default:\n throw std::out_of_range(strprintf(\"CInv::GetCommand(): type=%d unknown type\", type));\n }\n}\n\nstd::string CInv::ToString() const\n{\n try {\n return strprintf(\"%s %s\", GetCommand(), hash.ToString());\n } catch(const std::out_of_range &) {\n return strprintf(\"0x%08x %s\", type, hash.ToString());\n }\n}\n\nconst std::vector &getAllNetMessageTypes()\n{\n return allNetMessageTypesVec;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2019 The DigiByte Core developers\n\/\/ Copyright (c) 2014-2019 The Auroracoin Developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/* Total required space (in GB) depending on user choice (prune, not prune) *\/\nstatic uint64_t requiredSpace;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n explicit FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic Q_SLOTS:\n void check();\n\nQ_SIGNALS:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \n\nFreespaceChecker::FreespaceChecker(Intro *_intro)\n{\n this->intro = _intro;\n}\n\nvoid FreespaceChecker::check()\n{\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch (const fs::filesystem_error&)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(nullptr),\n signalled(false),\n m_blockchain_size(blockchain_size),\n m_chain_state_size(chain_state_size)\n{\n ui->setupUi(this);\n ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME));\n ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME));\n\n ui->lblExplanation1->setText(ui->lblExplanation1->text()\n .arg(PACKAGE_NAME)\n .arg(m_blockchain_size)\n .arg(2014)\n .arg(tr(\"Auroracoin\"))\n );\n ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME));\n\n uint64_t pruneTarget = std::max(0, gArgs.GetArg(\"-prune\", 0));\n if (pruneTarget > 1) { \/\/ -prune=1 means enabled, above that it's a size in MB\n ui->prune->setChecked(true);\n ui->prune->setEnabled(false);\n }\n ui->prune->setText(tr(\"Discard blocks after verification, except most recent %1 GB (prune)\").arg(pruneTarget ? pruneTarget \/ 1000 : 2));\n requiredSpace = m_blockchain_size;\n QString storageRequiresMsg = tr(\"At least %1 GB of data will be stored in this directory, and it will grow over time.\");\n if (pruneTarget) {\n uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 \/ GB_BYTES);\n if (prunedGBs <= requiredSpace) {\n requiredSpace = prunedGBs;\n storageRequiresMsg = tr(\"Approximately %1 GB of data will be stored in this directory.\");\n }\n ui->lblExplanation3->setVisible(true);\n } else {\n ui->lblExplanation3->setVisible(false);\n }\n requiredSpace += m_chain_state_size;\n ui->sizeWarningLabel->setText(\n tr(\"%1 will download and store a copy of the Auroracoin block chain.\").arg(PACKAGE_NAME) + \" \" +\n storageRequiresMsg.arg(requiredSpace) + \" \" +\n tr(\"The wallet will also be stored in this directory.\")\n );\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n thread->quit();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == GUIUtil::getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nbool Intro::showIfNeeded(interfaces::Node& node, bool& did_show_intro, bool& prune)\n{\n did_show_intro = false;\n\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!gArgs.GetArg(\"-datadir\", \"\").empty())\n return true;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = GUIUtil::getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg(\"-choosedatadir\", DEFAULT_CHOOSE_DATADIR) || settings.value(\"fReset\", false).toBool() || gArgs.GetBoolArg(\"-resetguisettings\", false))\n {\n \/* Use selectParams here to guarantee Params() can be used by node interface *\/\n try {\n node.selectParams(gArgs.GetChainName());\n } catch (const std::exception&) {\n return false;\n }\n\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize());\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/auroracoin\"));\n did_show_intro = true;\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n return false;\n }\n dataDir = intro.getDataDirectory();\n try {\n if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {\n \/\/ If a new data directory has been created, make wallets subdirectory too\n TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) \/ \"wallets\");\n }\n break;\n } catch (const fs::filesystem_error&) {\n QMessageBox::critical(nullptr, PACKAGE_NAME,\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n \/\/ Additional preferences:\n prune = intro.ui->prune->isChecked();\n\n settings.setValue(\"strDataDir\", dataDir);\n settings.setValue(\"fReset\", false);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the auroracoin.conf file in the default data directory\n * (to be consistent with auroracoind behavior)\n *\/\n if(dataDir != GUIUtil::getDefaultDataDirectory()) {\n node.softSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n }\n return true;\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < requiredSpace * GB_BYTES)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(GUIUtil::getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);\n connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);\n \/* make sure executor object is deleted in its own thread *\/\n connect(thread, &QThread::finished, executor, &QObject::deleteLater);\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n Q_EMIT requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\nBitcoin: 9924bce317b96ab0c57efb99330abd11b6f16b9a ([gui] intro: enable pruning by default unless disk is big).\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Copyright (c) 2014-2019 The DigiByte Core developers\n\/\/ Copyright (c) 2014-2019 The Auroracoin Developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/* Total required space (in GB) depending on user choice (prune, not prune) *\/\nstatic uint64_t requiredSpace;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n explicit FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic Q_SLOTS:\n void check();\n\nQ_SIGNALS:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \n\nFreespaceChecker::FreespaceChecker(Intro *_intro)\n{\n this->intro = _intro;\n}\n\nvoid FreespaceChecker::check()\n{\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch (const fs::filesystem_error&)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(nullptr),\n signalled(false),\n m_blockchain_size(blockchain_size),\n m_chain_state_size(chain_state_size)\n{\n ui->setupUi(this);\n ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME));\n ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME));\n\n ui->lblExplanation1->setText(ui->lblExplanation1->text()\n .arg(PACKAGE_NAME)\n .arg(m_blockchain_size)\n .arg(2014)\n .arg(tr(\"Auroracoin\"))\n );\n ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME));\n\n uint64_t pruneTarget = std::max(0, gArgs.GetArg(\"-prune\", 0));\n if (pruneTarget > 1) { \/\/ -prune=1 means enabled, above that it's a size in MB\n ui->prune->setChecked(true);\n ui->prune->setEnabled(false);\n }\n ui->prune->setText(tr(\"Discard blocks after verification, except most recent %1 GB (prune)\").arg(pruneTarget ? pruneTarget \/ 1000 : 2));\n requiredSpace = m_blockchain_size;\n QString storageRequiresMsg = tr(\"At least %1 GB of data will be stored in this directory, and it will grow over time.\");\n if (pruneTarget) {\n uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 \/ GB_BYTES);\n if (prunedGBs <= requiredSpace) {\n requiredSpace = prunedGBs;\n storageRequiresMsg = tr(\"Approximately %1 GB of data will be stored in this directory.\");\n }\n ui->lblExplanation3->setVisible(true);\n } else {\n ui->lblExplanation3->setVisible(false);\n }\n requiredSpace += m_chain_state_size;\n ui->sizeWarningLabel->setText(\n tr(\"%1 will download and store a copy of the Auroracoin block chain.\").arg(PACKAGE_NAME) + \" \" +\n storageRequiresMsg.arg(requiredSpace) + \" \" +\n tr(\"The wallet will also be stored in this directory.\")\n );\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n thread->quit();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == GUIUtil::getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nbool Intro::showIfNeeded(interfaces::Node& node, bool& did_show_intro, bool& prune)\n{\n did_show_intro = false;\n\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!gArgs.GetArg(\"-datadir\", \"\").empty())\n return true;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = GUIUtil::getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg(\"-choosedatadir\", DEFAULT_CHOOSE_DATADIR) || settings.value(\"fReset\", false).toBool() || gArgs.GetBoolArg(\"-resetguisettings\", false))\n {\n \/* Use selectParams here to guarantee Params() can be used by node interface *\/\n try {\n node.selectParams(gArgs.GetChainName());\n } catch (const std::exception&) {\n return false;\n }\n\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize());\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/auroracoin\"));\n did_show_intro = true;\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n return false;\n }\n dataDir = intro.getDataDirectory();\n try {\n if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {\n \/\/ If a new data directory has been created, make wallets subdirectory too\n TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) \/ \"wallets\");\n }\n break;\n } catch (const fs::filesystem_error&) {\n QMessageBox::critical(nullptr, PACKAGE_NAME,\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n \/\/ Additional preferences:\n prune = intro.ui->prune->isChecked();\n\n settings.setValue(\"strDataDir\", dataDir);\n settings.setValue(\"fReset\", false);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the auroracoin.conf file in the default data directory\n * (to be consistent with auroracoind behavior)\n *\/\n if(dataDir != GUIUtil::getDefaultDataDirectory()) {\n node.softSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n }\n return true;\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < requiredSpace * GB_BYTES)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n ui->prune->setChecked(true);\n } else if (bytesAvailable \/ GB_BYTES - requiredSpace < 10) {\n freeString += \" \" + tr(\"(%n GB needed for full chain)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #999900 }\");\n ui->prune->setChecked(true);\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(GUIUtil::getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);\n connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);\n \/* make sure executor object is deleted in its own thread *\/\n connect(thread, &QThread::finished, executor, &QObject::deleteLater);\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n Q_EMIT requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/mathmore:$Id$\n\/\/ Authors: L. Moneta, A. Zsenei 08\/2005\n \/**********************************************************************\n * *\n * Copyright (c) 2004 moneta, CERN\/PH-SFT *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this library (see file COPYING); if not, write *\n * to the Free Software Foundation, Inc., 59 Temple Place, Suite *\n * 330, Boston, MA 02111-1307 USA, or contact the author. *\n * *\n **********************************************************************\/\n\n\/\/ Implementation file for class GSLMinimizer1D\n\/\/ \n\/\/ Created by: moneta at Wed Dec 1 15:04:51 2004\n\/\/ \n\/\/ Last update: Wed Dec 1 15:04:51 2004\n\/\/ \n\n#include \n\n#include \"Math\/GSLMinimizer1D.h\"\n#include \"Math\/Error.h\"\n\n#include \"GSLFunctionWrapper.h\"\n#include \"GSL1DMinimizerWrapper.h\"\n\n\n#include \"gsl\/gsl_min.h\"\n#include \"gsl\/gsl_errno.h\"\n\n#include \n\nnamespace ROOT { \n\nnamespace Math { \n\n\nGSLMinimizer1D::GSLMinimizer1D(Minim1D::Type type) : \n fXmin(0), fXlow(0), fXup(0), fMin(0), fLow(0), fUp(0), \n fIter(0), fStatus(-1), fIsSet(false), \n fMinimizer(0), fFunction(0)\n{\n \/\/ construct a minimizer passing the algorithm type as an enumeration\n\n const gsl_min_fminimizer_type* T = 0 ;\n switch ( type )\n {\n case Minim1D::kGOLDENSECTION : \n T = gsl_min_fminimizer_goldensection; \n break ;\n case Minim1D::kBRENT :\n T = gsl_min_fminimizer_brent; \n break ;\n default :\n \/\/ default case is brent \n T = gsl_min_fminimizer_brent; \n break ;\n }\n\n fMinimizer = new GSL1DMinimizerWrapper(T); \n fFunction = new GSLFunctionWrapper();\n\n}\n\nGSLMinimizer1D::~GSLMinimizer1D() \n{\n \/\/ destructor: clean up minimizer and function pointers \n\n if (fMinimizer) delete fMinimizer;\n if (fFunction) delete fFunction;\n}\n\nGSLMinimizer1D::GSLMinimizer1D(const GSLMinimizer1D &): IMinimizer1D()\n{\n \/\/ dummy copy ctr\n}\n\nGSLMinimizer1D & GSLMinimizer1D::operator = (const GSLMinimizer1D &rhs) \n{\n \/\/ dummy operator = \n if (this == &rhs) return *this; \/\/ time saving self-test\n return *this;\n}\n\nvoid GSLMinimizer1D::SetFunction( GSLFuncPointer f, void * p, double xmin, double xlow, double xup) { \n \/\/ set the function to be minimized \n assert(fFunction);\n assert(fMinimizer);\n fXlow = xlow; \n fXup = xup;\n fXmin = xmin;\n fFunction->SetFuncPointer( f ); \n fFunction->SetParams( p ); \n\n#ifdef DEBUG\n std::cout << \" [ \"<< xlow << \" , \" << xup << \" ]\" << std::endl;\n#endif\n\n int status = gsl_min_fminimizer_set( fMinimizer->Get(), fFunction->GetFunc(), xmin, xlow, xup);\n if (status != GSL_SUCCESS) \n std::cerr <<\"GSLMinimizer1D: Error: Interval [ \"<< xlow << \" , \" << xup << \" ] does not contain a minimum\" << std::endl; \n\n\n fIsSet = true; \n fStatus = -1;\n return;\n}\n\nint GSLMinimizer1D::Iterate() {\n \/\/ perform an iteration and update values \n if (!fIsSet) {\n std::cerr << \"GSLMinimizer1D- Error: Function has not been set in Minimizer\" << std::endl;\n return -1; \n }\n \n int status = gsl_min_fminimizer_iterate(fMinimizer->Get());\n \/\/ update values\n fXmin = gsl_min_fminimizer_x_minimum(fMinimizer->Get() );\n fMin = gsl_min_fminimizer_f_minimum(fMinimizer->Get() );\n \/\/ update interval values\n fXlow = gsl_min_fminimizer_x_lower(fMinimizer->Get() ); \n fXup = gsl_min_fminimizer_x_upper(fMinimizer->Get() );\n fLow = gsl_min_fminimizer_f_lower(fMinimizer->Get() ); \n fUp = gsl_min_fminimizer_f_upper(fMinimizer->Get() );\n return status;\n}\n\ndouble GSLMinimizer1D::XMinimum() const { \n \/\/ return x value at function minimum\n return fXmin;\n}\n\ndouble GSLMinimizer1D::XLower() const { \n \/\/ return lower x value of bracketing interval\n return fXlow; \n}\n\ndouble GSLMinimizer1D::XUpper() const { \n \/\/ return upper x value of bracketing interval\n return fXup;\n}\n\ndouble GSLMinimizer1D::FValMinimum() const { \n \/\/ return function value at minimum\n return fMin;\n}\n\ndouble GSLMinimizer1D::FValLower() const { \n \/\/ return function value at x lower\n return fLow; \n}\n\ndouble GSLMinimizer1D::FValUpper() const { \n \/\/ return function value at x upper\n return fUp;\n}\n\nconst char * GSLMinimizer1D::Name() const {\n \/\/ return name of minimization algorithm\n return gsl_min_fminimizer_name(fMinimizer->Get() ); \n}\n\nbool GSLMinimizer1D::Minimize (int maxIter, double absTol, double relTol) \n{ \n \/\/ find the minimum via multiple iterations\n fStatus = -1; \n int iter = 0; \n int status = 0; \n do { \n iter++;\n status = Iterate();\n if (status != GSL_SUCCESS) { \n MATH_ERROR_MSG(\"GSLMinimizer1D::Minimize\",\"error returned when performing an iteration\");\n fStatus = status; \n return false; \n }\n\n#ifdef DEBUG\n std::cout << \"Min1D - iteration \" << iter << \" interval : [ \" << fXlow << \" , \" << fXup << \" ] min = \" << fXmin\n << \" fmin \" << fMin << \" f(a) \" << fLow << \" f(b) \" << fUp << std::endl;\n#endif\n\n \n status = TestInterval(fXlow, fXup, absTol, relTol); \n if (status == GSL_SUCCESS) { \n fIter = iter;\n fStatus = status;\n return true; \n }\n }\n while (status == GSL_CONTINUE && iter < maxIter); \n if (status == GSL_CONTINUE) { \n double tol = std::abs(fXup-fXlow);\n MATH_INFO_MSGVAL(\"GSLMinimizer1D::Minimize\",\"exceeded max iterations, reached tolerance is not sufficient\",tol);\n }\n fStatus = status; \n return false;\n}\n\n\nint GSLMinimizer1D::TestInterval( double xlow, double xup, double epsAbs, double epsRel) { \n\/\/ static function to test interval \n return gsl_min_test_interval(xlow, xup, epsAbs, epsRel);\n}\n\n} \/\/ end namespace Math\n\n} \/\/ end namespace ROOT\n\nadd missing include to cmath\/\/ @(#)root\/mathmore:$Id$\n\/\/ Authors: L. Moneta, A. Zsenei 08\/2005\n \/**********************************************************************\n * *\n * Copyright (c) 2004 moneta, CERN\/PH-SFT *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this library (see file COPYING); if not, write *\n * to the Free Software Foundation, Inc., 59 Temple Place, Suite *\n * 330, Boston, MA 02111-1307 USA, or contact the author. *\n * *\n **********************************************************************\/\n\n\/\/ Implementation file for class GSLMinimizer1D\n\/\/ \n\/\/ Created by: moneta at Wed Dec 1 15:04:51 2004\n\/\/ \n\/\/ Last update: Wed Dec 1 15:04:51 2004\n\/\/ \n\n#include \n\n#include \"Math\/GSLMinimizer1D.h\"\n#include \"Math\/Error.h\"\n\n#include \"GSLFunctionWrapper.h\"\n#include \"GSL1DMinimizerWrapper.h\"\n\n\n#include \"gsl\/gsl_min.h\"\n#include \"gsl\/gsl_errno.h\"\n\n#include \n#include \n\nnamespace ROOT { \n\nnamespace Math { \n\n\nGSLMinimizer1D::GSLMinimizer1D(Minim1D::Type type) : \n fXmin(0), fXlow(0), fXup(0), fMin(0), fLow(0), fUp(0), \n fIter(0), fStatus(-1), fIsSet(false), \n fMinimizer(0), fFunction(0)\n{\n \/\/ construct a minimizer passing the algorithm type as an enumeration\n\n const gsl_min_fminimizer_type* T = 0 ;\n switch ( type )\n {\n case Minim1D::kGOLDENSECTION : \n T = gsl_min_fminimizer_goldensection; \n break ;\n case Minim1D::kBRENT :\n T = gsl_min_fminimizer_brent; \n break ;\n default :\n \/\/ default case is brent \n T = gsl_min_fminimizer_brent; \n break ;\n }\n\n fMinimizer = new GSL1DMinimizerWrapper(T); \n fFunction = new GSLFunctionWrapper();\n\n}\n\nGSLMinimizer1D::~GSLMinimizer1D() \n{\n \/\/ destructor: clean up minimizer and function pointers \n\n if (fMinimizer) delete fMinimizer;\n if (fFunction) delete fFunction;\n}\n\nGSLMinimizer1D::GSLMinimizer1D(const GSLMinimizer1D &): IMinimizer1D()\n{\n \/\/ dummy copy ctr\n}\n\nGSLMinimizer1D & GSLMinimizer1D::operator = (const GSLMinimizer1D &rhs) \n{\n \/\/ dummy operator = \n if (this == &rhs) return *this; \/\/ time saving self-test\n return *this;\n}\n\nvoid GSLMinimizer1D::SetFunction( GSLFuncPointer f, void * p, double xmin, double xlow, double xup) { \n \/\/ set the function to be minimized \n assert(fFunction);\n assert(fMinimizer);\n fXlow = xlow; \n fXup = xup;\n fXmin = xmin;\n fFunction->SetFuncPointer( f ); \n fFunction->SetParams( p ); \n\n#ifdef DEBUG\n std::cout << \" [ \"<< xlow << \" , \" << xup << \" ]\" << std::endl;\n#endif\n\n int status = gsl_min_fminimizer_set( fMinimizer->Get(), fFunction->GetFunc(), xmin, xlow, xup);\n if (status != GSL_SUCCESS) \n std::cerr <<\"GSLMinimizer1D: Error: Interval [ \"<< xlow << \" , \" << xup << \" ] does not contain a minimum\" << std::endl; \n\n\n fIsSet = true; \n fStatus = -1;\n return;\n}\n\nint GSLMinimizer1D::Iterate() {\n \/\/ perform an iteration and update values \n if (!fIsSet) {\n std::cerr << \"GSLMinimizer1D- Error: Function has not been set in Minimizer\" << std::endl;\n return -1; \n }\n \n int status = gsl_min_fminimizer_iterate(fMinimizer->Get());\n \/\/ update values\n fXmin = gsl_min_fminimizer_x_minimum(fMinimizer->Get() );\n fMin = gsl_min_fminimizer_f_minimum(fMinimizer->Get() );\n \/\/ update interval values\n fXlow = gsl_min_fminimizer_x_lower(fMinimizer->Get() ); \n fXup = gsl_min_fminimizer_x_upper(fMinimizer->Get() );\n fLow = gsl_min_fminimizer_f_lower(fMinimizer->Get() ); \n fUp = gsl_min_fminimizer_f_upper(fMinimizer->Get() );\n return status;\n}\n\ndouble GSLMinimizer1D::XMinimum() const { \n \/\/ return x value at function minimum\n return fXmin;\n}\n\ndouble GSLMinimizer1D::XLower() const { \n \/\/ return lower x value of bracketing interval\n return fXlow; \n}\n\ndouble GSLMinimizer1D::XUpper() const { \n \/\/ return upper x value of bracketing interval\n return fXup;\n}\n\ndouble GSLMinimizer1D::FValMinimum() const { \n \/\/ return function value at minimum\n return fMin;\n}\n\ndouble GSLMinimizer1D::FValLower() const { \n \/\/ return function value at x lower\n return fLow; \n}\n\ndouble GSLMinimizer1D::FValUpper() const { \n \/\/ return function value at x upper\n return fUp;\n}\n\nconst char * GSLMinimizer1D::Name() const {\n \/\/ return name of minimization algorithm\n return gsl_min_fminimizer_name(fMinimizer->Get() ); \n}\n\nbool GSLMinimizer1D::Minimize (int maxIter, double absTol, double relTol) \n{ \n \/\/ find the minimum via multiple iterations\n fStatus = -1; \n int iter = 0; \n int status = 0; \n do { \n iter++;\n status = Iterate();\n if (status != GSL_SUCCESS) { \n MATH_ERROR_MSG(\"GSLMinimizer1D::Minimize\",\"error returned when performing an iteration\");\n fStatus = status; \n return false; \n }\n\n#ifdef DEBUG\n std::cout << \"Min1D - iteration \" << iter << \" interval : [ \" << fXlow << \" , \" << fXup << \" ] min = \" << fXmin\n << \" fmin \" << fMin << \" f(a) \" << fLow << \" f(b) \" << fUp << std::endl;\n#endif\n\n \n status = TestInterval(fXlow, fXup, absTol, relTol); \n if (status == GSL_SUCCESS) { \n fIter = iter;\n fStatus = status;\n return true; \n }\n }\n while (status == GSL_CONTINUE && iter < maxIter); \n if (status == GSL_CONTINUE) { \n double tol = std::abs(fXup-fXlow);\n MATH_INFO_MSGVAL(\"GSLMinimizer1D::Minimize\",\"exceeded max iterations, reached tolerance is not sufficient\",tol);\n }\n fStatus = status; \n return false;\n}\n\n\nint GSLMinimizer1D::TestInterval( double xlow, double xup, double epsAbs, double epsRel) { \n\/\/ static function to test interval \n return gsl_min_test_interval(xlow, xup, epsAbs, epsRel);\n}\n\n} \/\/ end namespace Math\n\n} \/\/ end namespace ROOT\n\n<|endoftext|>"} {"text":"\/*\n * gnoproj\n *\n * Copyright (c) 2013-2014 FOXEL SA - http:\/\/foxel.ch\n * Please read for more information.\n *\n *\n * Author(s):\n *\n * Stéphane Flotron \n *\n * Contributor(s):\n *\n * Luc Deschenaux \n *\n *\n * This file is part of the FOXEL project .\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\n *\n * Additional Terms:\n *\n * You are required to preserve legal notices and author attributions in\n * that material or in the Appropriate Legal Notices displayed by works\n * containing it.\n *\n * You are required to attribute the work as explained in the \"Usage and\n * Attribution\" section of .\n *\/\n\n\n#include \"gnoproj.hpp\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace elphelphg;\n\nint main(int argc, char** argv) {\n\n \/* Usage branch *\/\n if ( argc<3 || argc>4 || !strcmp( argv[1], \"help\" ) || !strcmp(argv[1],\"-h\") || !strcmp(argv[1],\"--help\") ) {\n \/* Display help *\/\n printf( \"Usage : %s [ ]\\n\\n\",argv[0]);\n return 1;\n }\n\n \/\/ load inputs\n char *imagej_prefs_xml=argv[1]; \/\/imagej xml configuration file\n char *input_image_filename=argv[2]; \/\/ eqr image (input) filename\n std::string output_image_filename; \/\/ output image filename\n\n \/\/ check is a focal length is given, and update method if necessary\n int normalizedFocal(0); \/\/ gnomonic projection method. 0 elphel method (default), 1 with constant focal\n double focal = 0.0; \/\/ focal length (in mm)\n double minFocal = 0.05 ; \/\/ lower bound for focal length\n double maxFocal = 500.0; \/\/ upper bound for focal length\n std::string inputFocal((argc==4)?argv[3]:\"\");\n\n \/\/ verify if input is present, and if yes, if it is consistant\n if(inputFocal.length())\n {\n focal = atof(inputFocal.c_str());\n normalizedFocal = 1;\n\n \/\/ check input focal\n if( focal < minFocal || focal > maxFocal)\n {\n std::cerr << \"Focal length is less than \" << minFocal << \" mm or bigger than \" << maxFocal << \" mm. \";\n std::cerr << \"Input focal is \" << inputFocal << endl;\n return 0;\n }\n }\n\n \/\/ now load image, and do gnomonic projection\n try {\n CameraArray e4pi(CameraArray::EYESIS4PI_CAMERA,imagej_prefs_xml);\n\n struct utils::imagefile_info *info=utils::imagefile_parsename(input_image_filename);\n\n int channel_index=atoi(info->channel);\n Channel *channel=e4pi.channel(channel_index);\n EqrData *eqr=channel->eqr;\n SensorData *sensor=channel->sensor;\n\n \/\/ load image\n IplImage* eqr_img = cvLoadImage(input_image_filename, CV_LOAD_IMAGE_COLOR );\n\n \/* Initialize output image structure *\/\n IplImage* out_img = cvCreateImage( cvSize( channel->sensor->pixelCorrectionWidth, channel->sensor->pixelCorrectionHeight ), IPL_DEPTH_8U , eqr_img->nChannels );\n\n if(!normalizedFocal){\n \/* Gnomonic projection of the equirectangular tile *\/\n lg_ttg_uc(\n ( inter_C8_t *) eqr_img->imageData,\n eqr_img->width,\n eqr_img->height,\n eqr_img->nChannels,\n ( inter_C8_t *) out_img->imageData,\n out_img->width,\n out_img->height,\n out_img->nChannels,\n sensor->px0,\n sensor->py0,\n eqr->imageFullWidth,\n eqr->imageFullLength-1, \/\/ there's an extra pixel for wrapping\n eqr->xPosition,\n eqr->yPosition,\n rad(sensor->roll),\n rad(sensor->azimuth),\n rad(sensor->elevation),\n rad(sensor->heading),\n 0.001*sensor->pixelSize,\n sensor->focalLength,\n li_bilinearf\n );\n\n \/\/ create output image name\n output_image_filename+=std::string(info->dir)+\"\/\"+info->timestamp+\"-\"+info->channel+\"-RECT-SENSOR.\"+info->extension;\n }\n else\n {\n \/* Gnomonic projection of the equirectangular tile *\/\n lg_ttg_focal(\n ( inter_C8_t *) eqr_img->imageData,\n eqr_img->width,\n eqr_img->height,\n eqr_img->nChannels,\n ( inter_C8_t *) out_img->imageData,\n out_img->width,\n out_img->height,\n out_img->nChannels,\n eqr->imageFullWidth,\n eqr->imageFullLength-1,\n eqr->xPosition,\n eqr->yPosition,\n rad(sensor->azimuth)+rad(sensor->heading)+LG_PI,\n rad(sensor->elevation),\n rad(sensor->roll),\n focal,\n 0.001*sensor->pixelSize,\n li_bilinearf\n );\n\n \/\/ create output image name\n output_image_filename+=std::string(info->dir)+\"\/\"+info->timestamp+\"-\"+info->channel+\"-RECT-CONFOC.\"+info->extension;\n }\n\n \/* Gnomonic image exportation *\/\n cvSaveImage(output_image_filename.c_str() , out_img, NULL );\n\n } catch(std::exception &e) {\n std::cerr << e.what() << std::endl;\n return 1;\n } catch(std::string &msg) {\n std::cerr << msg << std::endl;\n return 1;\n } catch(...) {\n std::cerr << \"unhandled exception\\n\";\n return 1;\n }\n}\nuse bicubic interpolation instead of bilinear\/*\n * gnoproj\n *\n * Copyright (c) 2013-2014 FOXEL SA - http:\/\/foxel.ch\n * Please read for more information.\n *\n *\n * Author(s):\n *\n * Stéphane Flotron \n *\n * Contributor(s):\n *\n * Luc Deschenaux \n *\n *\n * This file is part of the FOXEL project .\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\n *\n * Additional Terms:\n *\n * You are required to preserve legal notices and author attributions in\n * that material or in the Appropriate Legal Notices displayed by works\n * containing it.\n *\n * You are required to attribute the work as explained in the \"Usage and\n * Attribution\" section of .\n *\/\n\n\n#include \"gnoproj.hpp\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace elphelphg;\n\nint main(int argc, char** argv) {\n\n \/* Usage branch *\/\n if ( argc<3 || argc>4 || !strcmp( argv[1], \"help\" ) || !strcmp(argv[1],\"-h\") || !strcmp(argv[1],\"--help\") ) {\n \/* Display help *\/\n printf( \"Usage : %s [ ]\\n\\n\",argv[0]);\n return 1;\n }\n\n \/\/ load inputs\n char *imagej_prefs_xml=argv[1]; \/\/imagej xml configuration file\n char *input_image_filename=argv[2]; \/\/ eqr image (input) filename\n std::string output_image_filename; \/\/ output image filename\n\n \/\/ check is a focal length is given, and update method if necessary\n int normalizedFocal(0); \/\/ gnomonic projection method. 0 elphel method (default), 1 with constant focal\n double focal = 0.0; \/\/ focal length (in mm)\n double minFocal = 0.05 ; \/\/ lower bound for focal length\n double maxFocal = 500.0; \/\/ upper bound for focal length\n std::string inputFocal((argc==4)?argv[3]:\"\");\n\n \/\/ verify if input is present, and if yes, if it is consistant\n if(inputFocal.length())\n {\n focal = atof(inputFocal.c_str());\n normalizedFocal = 1;\n\n \/\/ check input focal\n if( focal < minFocal || focal > maxFocal)\n {\n std::cerr << \"Focal length is less than \" << minFocal << \" mm or bigger than \" << maxFocal << \" mm. \";\n std::cerr << \"Input focal is \" << inputFocal << endl;\n return 0;\n }\n }\n\n \/\/ now load image, and do gnomonic projection\n try {\n CameraArray e4pi(CameraArray::EYESIS4PI_CAMERA,imagej_prefs_xml);\n\n struct utils::imagefile_info *info=utils::imagefile_parsename(input_image_filename);\n\n int channel_index=atoi(info->channel);\n Channel *channel=e4pi.channel(channel_index);\n EqrData *eqr=channel->eqr;\n SensorData *sensor=channel->sensor;\n\n \/\/ load image\n IplImage* eqr_img = cvLoadImage(input_image_filename, CV_LOAD_IMAGE_COLOR );\n\n \/* Initialize output image structure *\/\n IplImage* out_img = cvCreateImage( cvSize( channel->sensor->pixelCorrectionWidth, channel->sensor->pixelCorrectionHeight ), IPL_DEPTH_8U , eqr_img->nChannels );\n\n if(!normalizedFocal){\n \/* Gnomonic projection of the equirectangular tile *\/\n lg_ttg_uc(\n ( inter_C8_t *) eqr_img->imageData,\n eqr_img->width,\n eqr_img->height,\n eqr_img->nChannels,\n ( inter_C8_t *) out_img->imageData,\n out_img->width,\n out_img->height,\n out_img->nChannels,\n sensor->px0,\n sensor->py0,\n eqr->imageFullWidth,\n eqr->imageFullLength-1, \/\/ there's an extra pixel for wrapping\n eqr->xPosition,\n eqr->yPosition,\n rad(sensor->roll),\n rad(sensor->azimuth),\n rad(sensor->elevation),\n rad(sensor->heading),\n 0.001*sensor->pixelSize,\n sensor->focalLength,\n li_bicubicf\n );\n\n \/\/ create output image name\n output_image_filename+=std::string(info->dir)+\"\/\"+info->timestamp+\"-\"+info->channel+\"-RECT-SENSOR.\"+info->extension;\n }\n else\n {\n \/* Gnomonic projection of the equirectangular tile *\/\n lg_ttg_focal(\n ( inter_C8_t *) eqr_img->imageData,\n eqr_img->width,\n eqr_img->height,\n eqr_img->nChannels,\n ( inter_C8_t *) out_img->imageData,\n out_img->width,\n out_img->height,\n out_img->nChannels,\n eqr->imageFullWidth,\n eqr->imageFullLength-1,\n eqr->xPosition,\n eqr->yPosition,\n rad(sensor->azimuth)+rad(sensor->heading)+LG_PI,\n rad(sensor->elevation),\n rad(sensor->roll),\n focal,\n 0.001*sensor->pixelSize,\n li_bicubicf\n );\n\n \/\/ create output image name\n output_image_filename+=std::string(info->dir)+\"\/\"+info->timestamp+\"-\"+info->channel+\"-RECT-CONFOC.\"+info->extension;\n }\n\n \/* Gnomonic image exportation *\/\n cvSaveImage(output_image_filename.c_str() , out_img, NULL );\n\n } catch(std::exception &e) {\n std::cerr << e.what() << std::endl;\n return 1;\n } catch(std::string &msg) {\n std::cerr << msg << std::endl;\n return 1;\n } catch(...) {\n std::cerr << \"unhandled exception\\n\";\n return 1;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2013 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rule.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"grit.h\"\n#include \"grit\/libaddressinput_strings.h\"\n#include \"region_data_constants.h\"\n#include \"util\/json.h\"\n#include \"util\/string_split.h\"\n\nnamespace i18n {\nnamespace addressinput {\n\nnamespace {\n\nbool ParseToken(char c, AddressField* field) {\n assert(field != NULL);\n switch (c) {\n case 'R':\n *field = COUNTRY;\n return true;\n case 'S':\n *field = ADMIN_AREA;\n return true;\n case 'C':\n *field = LOCALITY;\n return true;\n case 'D':\n *field = DEPENDENT_LOCALITY;\n return true;\n case 'X':\n *field = SORTING_CODE;\n return true;\n case 'Z':\n *field = POSTAL_CODE;\n return true;\n case 'A':\n *field = STREET_ADDRESS;\n return true;\n case 'O':\n *field = ORGANIZATION;\n return true;\n case 'N':\n *field = RECIPIENT;\n return true;\n default:\n return false;\n }\n}\n\n\/\/ Clears |lines|, parses |format|, and adds the address fields and literals to\n\/\/ |lines|.\n\/\/\n\/\/ For example, the address format in Finland is \"%O%n%N%n%A%nAX-%Z %C%nÅLAND\".\n\/\/ It includes the allowed fields prefixed with %, newlines denoted %n, and the\n\/\/ extra text that should be included on an envelope. It is parsed into:\n\/\/ {\n\/\/ {ORGANIZATION},\n\/\/ {RECIPIENT},\n\/\/ {STREET_ADDRESS},\n\/\/ {\"AX-\", POSTAL_CODE, \" \", LOCALITY},\n\/\/ {\"ÅLAND\"}\n\/\/ }\nvoid ParseAddressFieldsFormat(const std::string& format,\n std::vector >* lines) {\n assert(lines != NULL);\n lines->clear();\n lines->resize(1);\n\n std::vector format_parts;\n SplitString(format, '%', &format_parts);\n\n \/\/ If the address format starts with a literal, then it will be in the first\n \/\/ element of |format_parts|. This literal does not begin with % and should\n \/\/ not be parsed as a token.\n if (!format_parts.empty() && !format_parts[0].empty()) {\n lines->back().push_back(FormatElement(format_parts[0]));\n }\n\n \/\/ The rest of the elements in |format_parts| begin with %.\n for (size_t i = 1; i < format_parts.size(); ++i) {\n if (format_parts[i].empty()) {\n continue;\n }\n\n \/\/ The first character after % denotes a field or a newline token.\n const char control_character = format_parts[i][0];\n\n \/\/ The rest of the string after the token is a literal.\n const std::string literal = format_parts[i].substr(1);\n\n AddressField field = COUNTRY;\n if (ParseToken(control_character, &field)) {\n lines->back().push_back(FormatElement(field));\n } else if (control_character == 'n') {\n lines->push_back(std::vector());\n }\n\n if (!literal.empty()) {\n lines->back().push_back(FormatElement(literal));\n }\n }\n}\n\n\/\/ Clears |fields|, parses |required|, and adds the required fields to |fields|.\n\/\/ For example, parses \"SCDX\" into {ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY,\n\/\/ SORTING_CODE}.\nvoid ParseAddressFieldsRequired(const std::string& required,\n std::vector* fields) {\n assert(fields != NULL);\n fields->clear();\n for (size_t i = 0; i < required.length(); ++i) {\n AddressField field = COUNTRY;\n if (ParseToken(required[i], &field)) {\n fields->push_back(field);\n }\n }\n}\n\nint GetAdminAreaMessageId(const std::string& admin_area_type, bool error) {\n if (admin_area_type == \"area\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_AREA\n : IDS_LIBADDRESSINPUT_I18N_AREA;\n }\n if (admin_area_type == \"county\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_COUNTY_LABEL\n : IDS_LIBADDRESSINPUT_I18N_COUNTY_LABEL;\n }\n if (admin_area_type == \"department\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_DEPARTMENT\n : IDS_LIBADDRESSINPUT_I18N_DEPARTMENT;\n }\n if (admin_area_type == \"district\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_DEPENDENT_LOCALITY_LABEL\n : IDS_LIBADDRESSINPUT_I18N_DEPENDENT_LOCALITY_LABEL;\n }\n if (admin_area_type == \"do_si\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_DO_SI\n : IDS_LIBADDRESSINPUT_I18N_DO_SI;\n }\n if (admin_area_type == \"emirate\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_EMIRATE\n : IDS_LIBADDRESSINPUT_I18N_EMIRATE;\n }\n if (admin_area_type == \"island\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_ISLAND\n : IDS_LIBADDRESSINPUT_I18N_ISLAND;\n }\n if (admin_area_type == \"parish\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_PARISH\n : IDS_LIBADDRESSINPUT_I18N_PARISH;\n }\n if (admin_area_type == \"prefecture\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_PREFECTURE\n : IDS_LIBADDRESSINPUT_I18N_PREFECTURE;\n }\n if (admin_area_type == \"province\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_PROVINCE\n : IDS_LIBADDRESSINPUT_I18N_PROVINCE;\n }\n if (admin_area_type == \"state\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_STATE_LABEL\n : IDS_LIBADDRESSINPUT_I18N_STATE_LABEL;\n }\n return INVALID_MESSAGE_ID;\n}\n\nint GetPostalCodeMessageId(const std::string& postal_code_type, bool error) {\n if (postal_code_type == \"postal\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_POSTAL_CODE_LABEL\n : IDS_LIBADDRESSINPUT_I18N_POSTAL_CODE_LABEL;\n }\n if (postal_code_type == \"zip\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_ZIP_CODE_LABEL\n : IDS_LIBADDRESSINPUT_I18N_ZIP_CODE_LABEL;\n }\n return INVALID_MESSAGE_ID;\n}\n\n} \/\/ namespace\n\nFormatElement::FormatElement(AddressField field)\n : field(field), literal() {}\n\nFormatElement::FormatElement(const std::string& literal)\n : field(COUNTRY), literal(literal) {\n assert(!literal.empty());\n}\n\nFormatElement::~FormatElement() {}\n\nbool FormatElement::operator==(const FormatElement& other) const {\n return field == other.field && literal == other.literal;\n}\n\nRule::Rule()\n : format_(),\n required_(),\n sub_keys_(),\n languages_(),\n language_(),\n postal_code_format_(),\n admin_area_name_message_id_(INVALID_MESSAGE_ID),\n postal_code_name_message_id_(INVALID_MESSAGE_ID) {}\n\nRule::~Rule() {}\n\n\/\/ static\nconst Rule& Rule::GetDefault() {\n \/\/ Allocated once and leaked on shutdown.\n static Rule* default_rule = NULL;\n if (default_rule == NULL) {\n default_rule = new Rule;\n default_rule->ParseSerializedRule(\n RegionDataConstants::GetDefaultRegionData());\n }\n return *default_rule;\n}\n\nvoid Rule::CopyFrom(const Rule& rule) {\n format_ = rule.format_;\n required_ = rule.required_;\n sub_keys_ = rule.sub_keys_;\n languages_ = rule.languages_;\n language_ = rule.language_;\n postal_code_format_ = rule.postal_code_format_;\n admin_area_name_message_id_ = rule.admin_area_name_message_id_;\n invalid_admin_area_message_id_ = rule.invalid_admin_area_message_id_;\n postal_code_name_message_id_ = rule.postal_code_name_message_id_;\n invalid_postal_code_message_id_ = rule.invalid_postal_code_message_id_;\n}\n\nbool Rule::ParseSerializedRule(const std::string& serialized_rule) {\n scoped_ptr json(Json::Build());\n if (!json->ParseObject(serialized_rule)) {\n return false;\n }\n ParseJsonRule(*json);\n return true;\n}\n\nvoid Rule::ParseJsonRule(const Json& json_rule) {\n std::string value;\n if (json_rule.GetStringValueForKey(\"fmt\", &value)) {\n ParseAddressFieldsFormat(value, &format_);\n }\n\n if (json_rule.GetStringValueForKey(\"require\", &value)) {\n ParseAddressFieldsRequired(value, &required_);\n }\n\n \/\/ Used as a separator in a list of items. For example, the list of supported\n \/\/ languages can be \"de~fr~it\".\n static const char kSeparator = '~';\n if (json_rule.GetStringValueForKey(\"sub_keys\", &value)) {\n SplitString(value, kSeparator, &sub_keys_);\n }\n\n if (json_rule.GetStringValueForKey(\"languages\", &value)) {\n SplitString(value, kSeparator, &languages_);\n }\n\n if (json_rule.GetStringValueForKey(\"lang\", &value)) {\n language_ = value;\n }\n\n if (json_rule.GetStringValueForKey(\"zip\", &value)) {\n postal_code_format_ = value;\n }\n\n if (json_rule.GetStringValueForKey(\"state_name_type\", &value)) {\n admin_area_name_message_id_ = GetAdminAreaMessageId(value, false);\n invalid_admin_area_message_id_ = GetAdminAreaMessageId(value, true);\n }\n\n if (json_rule.GetStringValueForKey(\"zip_name_type\", &value)) {\n postal_code_name_message_id_ = GetPostalCodeMessageId(value, false);\n invalid_postal_code_message_id_ = GetPostalCodeMessageId(value, true);\n }\n}\n\nint Rule::GetInvalidFieldMessageId(AddressField field) const {\n switch (field) {\n case ADMIN_AREA:\n return invalid_admin_area_message_id_;\n case LOCALITY:\n return IDS_LIBADDRESSINPUT_I18N_INVALID_LOCALITY_LABEL;\n case DEPENDENT_LOCALITY:\n return IDS_LIBADDRESSINPUT_I18N_INVALID_DEPENDENT_LOCALITY_LABEL;\n case POSTAL_CODE:\n return invalid_postal_code_message_id_;\n default:\n return IDS_LIBADDRESSINPUT_I18N_INVALID_ENTRY;\n }\n}\n\n} \/\/ namespace addressinput\n} \/\/ namespace i18n\nlibaddressinput - minor optimization: don't copy a couple of small strings\/\/ Copyright (C) 2013 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rule.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"grit.h\"\n#include \"grit\/libaddressinput_strings.h\"\n#include \"region_data_constants.h\"\n#include \"util\/json.h\"\n#include \"util\/string_split.h\"\n\nnamespace i18n {\nnamespace addressinput {\n\nnamespace {\n\nbool ParseToken(char c, AddressField* field) {\n assert(field != NULL);\n switch (c) {\n case 'R':\n *field = COUNTRY;\n return true;\n case 'S':\n *field = ADMIN_AREA;\n return true;\n case 'C':\n *field = LOCALITY;\n return true;\n case 'D':\n *field = DEPENDENT_LOCALITY;\n return true;\n case 'X':\n *field = SORTING_CODE;\n return true;\n case 'Z':\n *field = POSTAL_CODE;\n return true;\n case 'A':\n *field = STREET_ADDRESS;\n return true;\n case 'O':\n *field = ORGANIZATION;\n return true;\n case 'N':\n *field = RECIPIENT;\n return true;\n default:\n return false;\n }\n}\n\n\/\/ Clears |lines|, parses |format|, and adds the address fields and literals to\n\/\/ |lines|.\n\/\/\n\/\/ For example, the address format in Finland is \"%O%n%N%n%A%nAX-%Z %C%nÅLAND\".\n\/\/ It includes the allowed fields prefixed with %, newlines denoted %n, and the\n\/\/ extra text that should be included on an envelope. It is parsed into:\n\/\/ {\n\/\/ {ORGANIZATION},\n\/\/ {RECIPIENT},\n\/\/ {STREET_ADDRESS},\n\/\/ {\"AX-\", POSTAL_CODE, \" \", LOCALITY},\n\/\/ {\"ÅLAND\"}\n\/\/ }\nvoid ParseAddressFieldsFormat(const std::string& format,\n std::vector >* lines) {\n assert(lines != NULL);\n lines->clear();\n lines->resize(1);\n\n std::vector format_parts;\n SplitString(format, '%', &format_parts);\n\n \/\/ If the address format starts with a literal, then it will be in the first\n \/\/ element of |format_parts|. This literal does not begin with % and should\n \/\/ not be parsed as a token.\n if (!format_parts.empty() && !format_parts[0].empty()) {\n lines->back().push_back(FormatElement(format_parts[0]));\n }\n\n \/\/ The rest of the elements in |format_parts| begin with %.\n for (size_t i = 1; i < format_parts.size(); ++i) {\n if (format_parts[i].empty()) {\n continue;\n }\n\n \/\/ The first character after % denotes a field or a newline token.\n const char control_character = format_parts[i][0];\n\n \/\/ The rest of the string after the token is a literal.\n const std::string literal = format_parts[i].substr(1);\n\n AddressField field = COUNTRY;\n if (ParseToken(control_character, &field)) {\n lines->back().push_back(FormatElement(field));\n } else if (control_character == 'n') {\n lines->push_back(std::vector());\n }\n\n if (!literal.empty()) {\n lines->back().push_back(FormatElement(literal));\n }\n }\n}\n\n\/\/ Clears |fields|, parses |required|, and adds the required fields to |fields|.\n\/\/ For example, parses \"SCDX\" into {ADMIN_AREA, LOCALITY, DEPENDENT_LOCALITY,\n\/\/ SORTING_CODE}.\nvoid ParseAddressFieldsRequired(const std::string& required,\n std::vector* fields) {\n assert(fields != NULL);\n fields->clear();\n for (size_t i = 0; i < required.length(); ++i) {\n AddressField field = COUNTRY;\n if (ParseToken(required[i], &field)) {\n fields->push_back(field);\n }\n }\n}\n\nint GetAdminAreaMessageId(const std::string& admin_area_type, bool error) {\n if (admin_area_type == \"area\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_AREA\n : IDS_LIBADDRESSINPUT_I18N_AREA;\n }\n if (admin_area_type == \"county\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_COUNTY_LABEL\n : IDS_LIBADDRESSINPUT_I18N_COUNTY_LABEL;\n }\n if (admin_area_type == \"department\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_DEPARTMENT\n : IDS_LIBADDRESSINPUT_I18N_DEPARTMENT;\n }\n if (admin_area_type == \"district\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_DEPENDENT_LOCALITY_LABEL\n : IDS_LIBADDRESSINPUT_I18N_DEPENDENT_LOCALITY_LABEL;\n }\n if (admin_area_type == \"do_si\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_DO_SI\n : IDS_LIBADDRESSINPUT_I18N_DO_SI;\n }\n if (admin_area_type == \"emirate\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_EMIRATE\n : IDS_LIBADDRESSINPUT_I18N_EMIRATE;\n }\n if (admin_area_type == \"island\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_ISLAND\n : IDS_LIBADDRESSINPUT_I18N_ISLAND;\n }\n if (admin_area_type == \"parish\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_PARISH\n : IDS_LIBADDRESSINPUT_I18N_PARISH;\n }\n if (admin_area_type == \"prefecture\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_PREFECTURE\n : IDS_LIBADDRESSINPUT_I18N_PREFECTURE;\n }\n if (admin_area_type == \"province\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_PROVINCE\n : IDS_LIBADDRESSINPUT_I18N_PROVINCE;\n }\n if (admin_area_type == \"state\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_STATE_LABEL\n : IDS_LIBADDRESSINPUT_I18N_STATE_LABEL;\n }\n return INVALID_MESSAGE_ID;\n}\n\nint GetPostalCodeMessageId(const std::string& postal_code_type, bool error) {\n if (postal_code_type == \"postal\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_POSTAL_CODE_LABEL\n : IDS_LIBADDRESSINPUT_I18N_POSTAL_CODE_LABEL;\n }\n if (postal_code_type == \"zip\") {\n return error ? IDS_LIBADDRESSINPUT_I18N_INVALID_ZIP_CODE_LABEL\n : IDS_LIBADDRESSINPUT_I18N_ZIP_CODE_LABEL;\n }\n return INVALID_MESSAGE_ID;\n}\n\n} \/\/ namespace\n\nFormatElement::FormatElement(AddressField field)\n : field(field), literal() {}\n\nFormatElement::FormatElement(const std::string& literal)\n : field(COUNTRY), literal(literal) {\n assert(!literal.empty());\n}\n\nFormatElement::~FormatElement() {}\n\nbool FormatElement::operator==(const FormatElement& other) const {\n return field == other.field && literal == other.literal;\n}\n\nRule::Rule()\n : format_(),\n required_(),\n sub_keys_(),\n languages_(),\n language_(),\n postal_code_format_(),\n admin_area_name_message_id_(INVALID_MESSAGE_ID),\n postal_code_name_message_id_(INVALID_MESSAGE_ID) {}\n\nRule::~Rule() {}\n\n\/\/ static\nconst Rule& Rule::GetDefault() {\n \/\/ Allocated once and leaked on shutdown.\n static Rule* default_rule = NULL;\n if (default_rule == NULL) {\n default_rule = new Rule;\n default_rule->ParseSerializedRule(\n RegionDataConstants::GetDefaultRegionData());\n }\n return *default_rule;\n}\n\nvoid Rule::CopyFrom(const Rule& rule) {\n format_ = rule.format_;\n required_ = rule.required_;\n sub_keys_ = rule.sub_keys_;\n languages_ = rule.languages_;\n language_ = rule.language_;\n postal_code_format_ = rule.postal_code_format_;\n admin_area_name_message_id_ = rule.admin_area_name_message_id_;\n invalid_admin_area_message_id_ = rule.invalid_admin_area_message_id_;\n postal_code_name_message_id_ = rule.postal_code_name_message_id_;\n invalid_postal_code_message_id_ = rule.invalid_postal_code_message_id_;\n}\n\nbool Rule::ParseSerializedRule(const std::string& serialized_rule) {\n scoped_ptr json(Json::Build());\n if (!json->ParseObject(serialized_rule)) {\n return false;\n }\n ParseJsonRule(*json);\n return true;\n}\n\nvoid Rule::ParseJsonRule(const Json& json_rule) {\n std::string value;\n if (json_rule.GetStringValueForKey(\"fmt\", &value)) {\n ParseAddressFieldsFormat(value, &format_);\n }\n\n if (json_rule.GetStringValueForKey(\"require\", &value)) {\n ParseAddressFieldsRequired(value, &required_);\n }\n\n \/\/ Used as a separator in a list of items. For example, the list of supported\n \/\/ languages can be \"de~fr~it\".\n static const char kSeparator = '~';\n if (json_rule.GetStringValueForKey(\"sub_keys\", &value)) {\n SplitString(value, kSeparator, &sub_keys_);\n }\n\n if (json_rule.GetStringValueForKey(\"languages\", &value)) {\n SplitString(value, kSeparator, &languages_);\n }\n\n if (json_rule.GetStringValueForKey(\"lang\", &value)) {\n language_.swap(value);\n }\n\n if (json_rule.GetStringValueForKey(\"zip\", &value)) {\n postal_code_format_.swap(value);\n }\n\n if (json_rule.GetStringValueForKey(\"state_name_type\", &value)) {\n admin_area_name_message_id_ = GetAdminAreaMessageId(value, false);\n invalid_admin_area_message_id_ = GetAdminAreaMessageId(value, true);\n }\n\n if (json_rule.GetStringValueForKey(\"zip_name_type\", &value)) {\n postal_code_name_message_id_ = GetPostalCodeMessageId(value, false);\n invalid_postal_code_message_id_ = GetPostalCodeMessageId(value, true);\n }\n}\n\nint Rule::GetInvalidFieldMessageId(AddressField field) const {\n switch (field) {\n case ADMIN_AREA:\n return invalid_admin_area_message_id_;\n case LOCALITY:\n return IDS_LIBADDRESSINPUT_I18N_INVALID_LOCALITY_LABEL;\n case DEPENDENT_LOCALITY:\n return IDS_LIBADDRESSINPUT_I18N_INVALID_DEPENDENT_LOCALITY_LABEL;\n case POSTAL_CODE:\n return invalid_postal_code_message_id_;\n default:\n return IDS_LIBADDRESSINPUT_I18N_INVALID_ENTRY;\n }\n}\n\n} \/\/ namespace addressinput\n} \/\/ namespace i18n\n<|endoftext|>"} {"text":"#include \n#include \"pulsemover.h\"\n\nint DURATION = 1000; \/\/ Pulse should be given for one second.\n\/* int BASE = 1; *\/\n\/* int ACTUATED = 2; *\/\n\nPulseMover::PulseMover(int pin_base,\n int pin_actuated){\n PulseMover::pin_base = pin_base;\n PulseMover::pin_actuated = pin_actuated;\n\n stop_pulse_again = millis();\n done = true;\n}\n\nvoid PulseMover::init(){\n pinMode(pin_base, OUTPUT);\n digitalWrite(pin_base, LOW);\n pinMode(pin_actuated, OUTPUT);\n digitalWrite(pin_actuated, LOW);\n move_to_base();\n \/* digitalWrite(pin_base, HIGH); *\/\n \/* stop_pulse_again = millis() + PERIOD; *\/\n}\n\nvoid PulseMover::move_to_base(){\n done = false;\n digitalWrite(pin_actuated, LOW);\n digitalWrite(pin_base, HIGH);\n stop_pulse_again = millis() + DURATION;\n}\n\nvoid PulseMover::move_to_actuated(){\n done = false;\n digitalWrite(pin_base, LOW);\n digitalWrite(pin_actuated, HIGH);\n stop_pulse_again = millis() + DURATION;\n}\n\nvoid PulseMover::perhaps_update(){\n if (!done && stop_pulse_again < millis()) {\n digitalWrite(pin_base, LOW);\n digitalWrite(pin_actuated, LOW);\n done = true;\n }\n}\ncleanup#include \n#include \"pulsemover.h\"\n\nint DURATION = 1000; \/\/ Pulse should be given for one second.\n\nPulseMover::PulseMover(int pin_base,\n int pin_actuated){\n PulseMover::pin_base = pin_base;\n PulseMover::pin_actuated = pin_actuated;\n\n stop_pulse_again = millis();\n done = true;\n}\n\nvoid PulseMover::init(){\n pinMode(pin_base, OUTPUT);\n digitalWrite(pin_base, LOW);\n pinMode(pin_actuated, OUTPUT);\n digitalWrite(pin_actuated, LOW);\n move_to_base();\n \/* digitalWrite(pin_base, HIGH); *\/\n \/* stop_pulse_again = millis() + PERIOD; *\/\n}\n\nvoid PulseMover::move_to_base(){\n done = false;\n digitalWrite(pin_actuated, LOW);\n digitalWrite(pin_base, HIGH);\n stop_pulse_again = millis() + DURATION;\n}\n\nvoid PulseMover::move_to_actuated(){\n done = false;\n digitalWrite(pin_base, LOW);\n digitalWrite(pin_actuated, HIGH);\n stop_pulse_again = millis() + DURATION;\n}\n\nvoid PulseMover::perhaps_update(){\n if (!done && stop_pulse_again < millis()) {\n digitalWrite(pin_base, LOW);\n digitalWrite(pin_actuated, LOW);\n done = true;\n }\n}\n<|endoftext|>"} {"text":"\/\/ MS WARNINGS MACRO\n#define _SCL_SECURE_NO_WARNINGS\n\n\/\/ Macro: Program Settings\n#define ENABLE_NETWORK_IO 1\n\n#include \n#include \n#include \n#include \n#include \n#include \"data_type.hpp\"\n#include \"pixel_sorter.hpp\"\n#include \"ppm_reader.hpp\"\n#include \"splitter.hpp\"\n#include \"algorithm.hpp\"\n#include \"algorithm_2.hpp\"\n#include \"gui.hpp\"\n#include \"network.hpp\"\n#include \"test_tool.hpp\"\n\n#include \n#include \n#include \n#include \n\nclass position_manager : boost::noncopyable\n{\npublic:\n typedef question_data position_type;\n\n position_manager() = default;\n virtual ~position_manager() = default;\n\n template\n void add(T && pos)\n {\n std::lock_guard lock(mutex_);\n items_.push_back(std::forward(pos));\n }\n\n position_type get()\n {\n std::lock_guard lock(mutex_);\n auto res = items_.front();\n items_.pop_front();\n return res;\n }\n\n bool empty()\n {\n return items_.empty();\n }\n\nprivate:\n std::mutex mutex_;\n std::deque items_;\n};\n\nclass analyzer : boost::noncopyable\n{\npublic:\n explicit analyzer(\n std::string const& server_addr,\n int const problem_id, std::string const& player_id,\n bool const is_auto, bool const is_blur\n )\n : client_(server_addr), problem_id_(problem_id), player_id_(player_id),\n is_auto_(is_auto), is_blur_(is_blur)\n {\n }\n virtual ~analyzer() = default;\n\n void operator() (position_manager& manager)\n {\n splitter sp;\n\n \/\/ 問題文の入手\n raw_data_ = get_raw_question();\n data_ = get_skelton_question(raw_data_);\n\n \/\/ 2次元画像に分割\n split_image_ = sp.split_image(raw_data_);\n if(is_blur_) split_image_ = sp.split_image_gaussianblur(split_image_);\n auto const image_comp = sorter_.image_comp(raw_data_, split_image_);\n\t\tauto const image_comp_dx = sorter_dx.image_comp(raw_data_, split_image_);\n \/\/ 原画像推測部\n yrange2 yrange2_(raw_data_, image_comp);\n Murakami murakami_(raw_data_, image_comp,true);\n \/\/ GUI Threadの起動\n gui::manager gui_thread(\n [this, &manager](std::vector> const& data)\n {\n \/\/ 回答としてマーク -> 回答ジョブに追加\n auto clone = data_.clone();\n clone.block = data;\n manager.add(convert_block(clone));\n });\n\n \/\/ YRange2 -> YRange5 Thread\n boost::thread y_thread(\n [&, this]()\n {\n \/\/ YRange2\n auto yrange2_resolve = yrange2_();\n if (!yrange2_resolve.empty())\n\t\t {\n \/\/ Shoot\n if(is_auto_)\n {\n auto clone = data_.clone();\n clone.block = yrange2_resolve[0].points;\n manager.add(convert_block(clone));\n }\n\n \/\/ GUI\n\t\t\t for (int y2 = yrange2_resolve.size() - 1; y2 >= 0; --y2)\n\t\t\t {\n gui_thread.push_back(\n boost::bind(gui::make_mansort_window, split_image_, yrange2_resolve.at(y2).points, \"yrange2\")\n );\n\t\t\t }\n\t\t }\n \n \/\/ YRange5\n auto yrange5_resolve = yrange5(raw_data_, image_comp)(yrange2_.sorted_matrix());\n if (!yrange5_resolve.empty())\n\t\t {\n \/\/ GUI\n\t\t\t for (int y5 = yrange5_resolve.size() - 1; y5 >= 0; --y5)\n\t\t\t {\n gui_thread.push_back(\n boost::bind(gui::make_mansort_window, split_image_, yrange5_resolve.at(y5).points, \"yrange5\")\n );\n\t\t\t }\n }\n });\n\n \/\/ Murakami Thread\n boost::thread m_thread(\n [&]()\n {\n \/\/ Murakami\n\t\t\tstd::cout << \"村上モード\" << std::endl;\n auto murakami_resolve = murakami_()[0].points;\n\t\t\t\tstd::vector> murakami_dx_resolve, murakami_w_resolve, murakami_dx_w_resolve;\n\t\t\t\tif (!murakami_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_resolve, \"Murakami\"));\n\t\t\t\tif (murakami_resolve.empty()){\n\t\t\t\t\tstd::cout << \"デラックス村上モード\" << std::endl;\n\t\t\t\t\tMurakami murakami_dx(raw_data_, image_comp_dx, true);\n\t\t\t\t\tmurakami_dx_resolve = murakami_dx()[0].points;\n\t\t\t\t\tif (!murakami_dx_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_dx_resolve, \"Murakami_dx\"));\n\t\t\t\t\tif (murakami_dx_resolve.empty()){\n\t\t\t\t\t\tstd::cout << \"W村上モード\" << std::endl;\n\t\t\t\t\t\tMurakami murakami_w(raw_data_, image_comp, false);\n\t\t\t\t\t\tmurakami_w_resolve = murakami_w()[0].points;\n\t\t\t\t\t\tif (!murakami_w_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_w_resolve, \"Murakami_w\"));\n\t\t\t\t\t\tif (murakami_w_resolve.empty()){\n\t\t\t\t\t\t\tstd::cout << \"デラックスW村上モード\" << std::endl;\n\t\t\t\t\t\t\tMurakami murakami_dx_w(raw_data_, image_comp_dx, false);\n\t\t\t\t\t\t\tmurakami_dx_w_resolve = murakami_w()[0].points;\n\t\t\t\t\t\t\tif (!murakami_dx_w_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_dx_w_resolve, \"Murakami_dx_w\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n });\n\n gui_thread.push_back(\n boost::bind(gui::make_mansort_window, split_image_, \"Yor are the sorter!!! Sort this!\")\n );\n\n \/\/ 各Threadの待機\n y_thread.join();\n m_thread.join();\n gui_thread.wait_all_window();\n }\n\n std::string submit(answer_type const& ans) const\n {\n auto submit_result = client_.submit(problem_id_, player_id_, ans);\n return submit_result.get();\n }\n\nprivate:\n question_raw_data get_raw_question() const\n {\n#if ENABLE_NETWORK_IO\n \/\/ ネットワーク通信から\n std::string const data = client_.get_problem(problem_id_).get();\n return ppm_reader().from_data(data);\n#else\n \/\/ ファイルから\n std::string const path(\"prob01.ppm\");\n return ppm_reader().from_file(path);\n#endif\n }\n\n question_data get_skelton_question(question_raw_data const& raw) const\n {\n question_data formed = {\n problem_id_,\n player_id_,\n raw.split_num,\n raw.selectable_num,\n raw.cost.first,\n raw.cost.second,\n std::vector>()\n };\n\n return formed;\n }\n\n question_data convert_block(question_data const& data) const\n {\n auto res = data.clone();\n\n for(int i = 0; i < data.size.second; ++i)\n {\n for(int j = 0; j < data.size.first; ++j)\n {\n auto const& target = data.block[i][j];\n res.block[target.y][target.x] = point_type{j, i};\n\t\t}\n }\n\n return res;\n }\n\n int const problem_id_;\n std::string const player_id_;\n bool const is_auto_;\n bool const is_blur_;\n\n question_raw_data raw_data_;\n question_data data_;\n split_image_type split_image_;\n\tsplit_image_type split_image_gaussianblur;\n\n mutable network::client client_;\n pixel_sorter sorter_;\n\tpixel_sorter sorter_dx;\n};\n\nvoid submit_func(question_data question, analyzer const& analyze)\n{\n algorithm algo;\n algorithm_2 algo2;\n algo.reset(question);\n\n auto const answer = algo.get();\n if(answer) \/\/ 解が見つかった\n {\n#if ENABLE_NETWORK_IO\n \/\/ TODO: 前より良くなったら提出など(普通にいらないかも.提出前に目grepしてるわけだし)\n auto result = analyze.submit(answer.get());\n std::cout << \"Submit Result: \" << result << std::endl;\n\n\t\/\/ FIXME: 汚いしセグフォする\n\tint wrong_number = std::stoi(result.substr(result.find(\" \")));\n\tif(wrong_number == 0)\n\t{\n algo2.reset(question);\n\t\tauto const answer = algo2.get();\n\t\tif (answer)\n\t\t{\n\t\t\tauto result = analyze.submit(answer.get());\n\t\t\tstd::cout << \"Submit Result: \" << result << std::endl;\n\t\t\tstd::cout << \"勝った!\" << std::endl;\n\t\t}\n\t}\n#else\n test_tool::emulator emu(question);\n auto result = emu.start(answer.get());\n std::cout << \"Wrong: \" << result.wrong << std::endl;\n std::cout << \"Cost : \" << result.cost << std::endl;\n std::cout << \"---\" << std::endl;\n#endif\n }\n}\n\nint main(int const argc, char const* argv[])\n{\n std::string server_addr;\n\tint problemid = 0;\n auto const token = \"3935105806\";\n bool is_auto;\n bool is_blur;\n\n try\n {\n namespace po = boost::program_options;\n po::options_description opt(\"option\");\n opt.add_options()\n (\"help,h\" , \"produce help message\")\n (\"auto,a\" , \"auto submit flag\")\n (\"blur,b\" , \"gaussian blur to image\")\n#if ENABLE_NETWORK_IO\n (\"server,s\" , po::value(&server_addr), \"(require)set server ip address\")\n (\"problem,p\" , po::value(&problemid) , \"(require)set problem_id\")\n#endif\n ;\n\n po::variables_map argmap;\n po::store(po::parse_command_line(argc, argv, opt), argmap);\n po::notify(argmap);\n\n#if ENABLE_NETWORK_IO\n if(argmap.count(\"help\") || !argmap.count(\"server\") || !argmap.count(\"problem\"))\n#else\n if(argmap.count(\"help\"))\n#endif\n {\n std::cout << opt << std::endl;\n return 0;\n }\n\n is_auto = argmap.count(\"auto\");\n is_blur = argmap.count(\"blur\");\n }\n catch(boost::program_options::error_with_option_name const& e)\n {\n std::cout << e.what() << std::endl;\n std::exit(-1);\n }\n\n analyzer analyze(server_addr, problemid, token, is_auto, is_blur);\n position_manager manager;\n\n boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager)));\n boost::thread_group submit_threads;\n\n while(thread.joinable())\n {\n if(!manager.empty())\n {\n auto question = manager.get();\n\n \/\/ 手順探索部\n submit_threads.create_thread(\n boost::bind(submit_func, question, boost::ref(analyze))\n );\n }\n }\n\n thread.join();\n submit_threads.join_all();\n \n return 0;\n}\n\n手動並び替えの場合にも,ぼかしが入らないように.\/\/ MS WARNINGS MACRO\n#define _SCL_SECURE_NO_WARNINGS\n\n\/\/ Macro: Program Settings\n#define ENABLE_NETWORK_IO 1\n\n#include \n#include \n#include \n#include \n#include \n#include \"data_type.hpp\"\n#include \"pixel_sorter.hpp\"\n#include \"ppm_reader.hpp\"\n#include \"splitter.hpp\"\n#include \"algorithm.hpp\"\n#include \"algorithm_2.hpp\"\n#include \"gui.hpp\"\n#include \"network.hpp\"\n#include \"test_tool.hpp\"\n\n#include \n#include \n#include \n#include \n\nclass position_manager : boost::noncopyable\n{\npublic:\n typedef question_data position_type;\n\n position_manager() = default;\n virtual ~position_manager() = default;\n\n template\n void add(T && pos)\n {\n std::lock_guard lock(mutex_);\n items_.push_back(std::forward(pos));\n }\n\n position_type get()\n {\n std::lock_guard lock(mutex_);\n auto res = items_.front();\n items_.pop_front();\n return res;\n }\n\n bool empty()\n {\n return items_.empty();\n }\n\nprivate:\n std::mutex mutex_;\n std::deque items_;\n};\n\nclass analyzer : boost::noncopyable\n{\npublic:\n explicit analyzer(\n std::string const& server_addr,\n int const problem_id, std::string const& player_id,\n bool const is_auto, bool const is_blur\n )\n : client_(server_addr), problem_id_(problem_id), player_id_(player_id),\n is_auto_(is_auto), is_blur_(is_blur)\n {\n }\n virtual ~analyzer() = default;\n\n void operator() (position_manager& manager)\n {\n splitter sp;\n\n \/\/ 問題文の入手\n raw_data_ = get_raw_question();\n data_ = get_skelton_question(raw_data_);\n\n \/\/ 2次元画像に分割\n split_image_ = sp.split_image(raw_data_);\n\n \/\/ compare用の画像を作成\n auto const arranged_split = is_blur_ ? sp.split_image_gaussianblur(split_image_) : split_image_;\n auto const image_comp = sorter_.image_comp(raw_data_, arranged_split);\n\t\tauto const image_comp_dx = sorter_dx.image_comp(raw_data_, arranged_split);\n\n \/\/ 原画像推測部\n yrange2 yrange2_(raw_data_, image_comp);\n Murakami murakami_(raw_data_, image_comp,true);\n\n \/\/ GUI Threadの起動\n gui::manager gui_thread(\n [this, &manager](std::vector> const& data)\n {\n \/\/ 回答としてマーク -> 回答ジョブに追加\n auto clone = data_.clone();\n clone.block = data;\n manager.add(convert_block(clone));\n });\n\n \/\/ YRange2 -> YRange5 Thread\n boost::thread y_thread(\n [&, this]()\n {\n \/\/ YRange2\n auto yrange2_resolve = yrange2_();\n if (!yrange2_resolve.empty())\n\t\t {\n \/\/ Shoot\n if(is_auto_)\n {\n auto clone = data_.clone();\n clone.block = yrange2_resolve[0].points;\n manager.add(convert_block(clone));\n }\n\n \/\/ GUI\n\t\t\t for (int y2 = yrange2_resolve.size() - 1; y2 >= 0; --y2)\n\t\t\t {\n gui_thread.push_back(\n boost::bind(gui::make_mansort_window, split_image_, yrange2_resolve.at(y2).points, \"yrange2\")\n );\n\t\t\t }\n\t\t }\n \n \/\/ YRange5\n auto yrange5_resolve = yrange5(raw_data_, image_comp)(yrange2_.sorted_matrix());\n if (!yrange5_resolve.empty())\n\t\t {\n \/\/ GUI\n\t\t\t for (int y5 = yrange5_resolve.size() - 1; y5 >= 0; --y5)\n\t\t\t {\n gui_thread.push_back(\n boost::bind(gui::make_mansort_window, split_image_, yrange5_resolve.at(y5).points, \"yrange5\")\n );\n\t\t\t }\n }\n });\n\n \/\/ Murakami Thread\n boost::thread m_thread(\n [&]()\n {\n \/\/ Murakami\n\t\t\tstd::cout << \"村上モード\" << std::endl;\n auto murakami_resolve = murakami_()[0].points;\n\t\t\t\tstd::vector> murakami_dx_resolve, murakami_w_resolve, murakami_dx_w_resolve;\n\t\t\t\tif (!murakami_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_resolve, \"Murakami\"));\n\t\t\t\tif (murakami_resolve.empty()){\n\t\t\t\t\tstd::cout << \"デラックス村上モード\" << std::endl;\n\t\t\t\t\tMurakami murakami_dx(raw_data_, image_comp_dx, true);\n\t\t\t\t\tmurakami_dx_resolve = murakami_dx()[0].points;\n\t\t\t\t\tif (!murakami_dx_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_dx_resolve, \"Murakami_dx\"));\n\t\t\t\t\tif (murakami_dx_resolve.empty()){\n\t\t\t\t\t\tstd::cout << \"W村上モード\" << std::endl;\n\t\t\t\t\t\tMurakami murakami_w(raw_data_, image_comp, false);\n\t\t\t\t\t\tmurakami_w_resolve = murakami_w()[0].points;\n\t\t\t\t\t\tif (!murakami_w_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_w_resolve, \"Murakami_w\"));\n\t\t\t\t\t\tif (murakami_w_resolve.empty()){\n\t\t\t\t\t\t\tstd::cout << \"デラックスW村上モード\" << std::endl;\n\t\t\t\t\t\t\tMurakami murakami_dx_w(raw_data_, image_comp_dx, false);\n\t\t\t\t\t\t\tmurakami_dx_w_resolve = murakami_w()[0].points;\n\t\t\t\t\t\t\tif (!murakami_dx_w_resolve.empty())gui_thread.push_back(boost::bind(gui::make_mansort_window, split_image_, murakami_dx_w_resolve, \"Murakami_dx_w\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n });\n\n gui_thread.push_back(\n boost::bind(gui::make_mansort_window, split_image_, \"Yor are the sorter!!! Sort this!\")\n );\n\n \/\/ 各Threadの待機\n y_thread.join();\n m_thread.join();\n gui_thread.wait_all_window();\n }\n\n std::string submit(answer_type const& ans) const\n {\n auto submit_result = client_.submit(problem_id_, player_id_, ans);\n return submit_result.get();\n }\n\nprivate:\n question_raw_data get_raw_question() const\n {\n#if ENABLE_NETWORK_IO\n \/\/ ネットワーク通信から\n std::string const data = client_.get_problem(problem_id_).get();\n return ppm_reader().from_data(data);\n#else\n \/\/ ファイルから\n std::string const path(\"prob01.ppm\");\n return ppm_reader().from_file(path);\n#endif\n }\n\n question_data get_skelton_question(question_raw_data const& raw) const\n {\n question_data formed = {\n problem_id_,\n player_id_,\n raw.split_num,\n raw.selectable_num,\n raw.cost.first,\n raw.cost.second,\n std::vector>()\n };\n\n return formed;\n }\n\n question_data convert_block(question_data const& data) const\n {\n auto res = data.clone();\n\n for(int i = 0; i < data.size.second; ++i)\n {\n for(int j = 0; j < data.size.first; ++j)\n {\n auto const& target = data.block[i][j];\n res.block[target.y][target.x] = point_type{j, i};\n\t\t}\n }\n\n return res;\n }\n\n int const problem_id_;\n std::string const player_id_;\n bool const is_auto_;\n bool const is_blur_;\n\n question_raw_data raw_data_;\n question_data data_;\n split_image_type split_image_;\n\tsplit_image_type split_image_gaussianblur;\n\n mutable network::client client_;\n pixel_sorter sorter_;\n\tpixel_sorter sorter_dx;\n};\n\nvoid submit_func(question_data question, analyzer const& analyze)\n{\n algorithm algo;\n algorithm_2 algo2;\n algo.reset(question);\n\n auto const answer = algo.get();\n if(answer) \/\/ 解が見つかった\n {\n#if ENABLE_NETWORK_IO\n \/\/ TODO: 前より良くなったら提出など(普通にいらないかも.提出前に目grepしてるわけだし)\n auto result = analyze.submit(answer.get());\n std::cout << \"Submit Result: \" << result << std::endl;\n\n\t\/\/ FIXME: 汚いしセグフォする\n\tint wrong_number = std::stoi(result.substr(result.find(\" \")));\n\tif(wrong_number == 0)\n\t{\n algo2.reset(question);\n\t\tauto const answer = algo2.get();\n\t\tif (answer)\n\t\t{\n\t\t\tauto result = analyze.submit(answer.get());\n\t\t\tstd::cout << \"Submit Result: \" << result << std::endl;\n\t\t\tstd::cout << \"勝った!\" << std::endl;\n\t\t}\n\t}\n#else\n test_tool::emulator emu(question);\n auto result = emu.start(answer.get());\n std::cout << \"Wrong: \" << result.wrong << std::endl;\n std::cout << \"Cost : \" << result.cost << std::endl;\n std::cout << \"---\" << std::endl;\n#endif\n }\n}\n\nint main(int const argc, char const* argv[])\n{\n std::string server_addr;\n\tint problemid = 0;\n auto const token = \"3935105806\";\n bool is_auto;\n bool is_blur;\n\n try\n {\n namespace po = boost::program_options;\n po::options_description opt(\"option\");\n opt.add_options()\n (\"help,h\" , \"produce help message\")\n (\"auto,a\" , \"auto submit flag\")\n (\"blur,b\" , \"gaussian blur to image\")\n#if ENABLE_NETWORK_IO\n (\"server,s\" , po::value(&server_addr), \"(require)set server ip address\")\n (\"problem,p\" , po::value(&problemid) , \"(require)set problem_id\")\n#endif\n ;\n\n po::variables_map argmap;\n po::store(po::parse_command_line(argc, argv, opt), argmap);\n po::notify(argmap);\n\n#if ENABLE_NETWORK_IO\n if(argmap.count(\"help\") || !argmap.count(\"server\") || !argmap.count(\"problem\"))\n#else\n if(argmap.count(\"help\"))\n#endif\n {\n std::cout << opt << std::endl;\n return 0;\n }\n\n is_auto = argmap.count(\"auto\");\n is_blur = argmap.count(\"blur\");\n }\n catch(boost::program_options::error_with_option_name const& e)\n {\n std::cout << e.what() << std::endl;\n std::exit(-1);\n }\n\n analyzer analyze(server_addr, problemid, token, is_auto, is_blur);\n position_manager manager;\n\n boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager)));\n boost::thread_group submit_threads;\n\n while(thread.joinable())\n {\n if(!manager.empty())\n {\n auto question = manager.get();\n\n \/\/ 手順探索部\n submit_threads.create_thread(\n boost::bind(submit_func, question, boost::ref(analyze))\n );\n }\n }\n\n thread.join();\n submit_threads.join_all();\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dependency.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:02:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CODEMAKER_DEPENDENCY_HXX_\n#define _CODEMAKER_DEPENDENCY_HXX_\n\n#include \n\n#ifndef _REGISTRY_REGISTRY_HXX_\n#include \n#endif\n#ifndef __REGISTRY_REFLREAD_HXX__\n#include \n#endif\n\n#ifndef _CODEMAKER_TYPEMANAGER_HXX_\n#include \n#endif\n#ifndef _CODEMAKER_GLOBAL_HXX_\n#include \n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#define TYPEUSE_NORMAL 0x0001\n#define TYPEUSE_SUPER 0x0002\n#define TYPEUSE_MEMBER 0x0004\n#define TYPEUSE_INPARAM 0x0008\n#define TYPEUSE_OUTPARAM 0x0010\n#define TYPEUSE_INOUTPARAM 0x0020\n#define TYPEUSE_RETURN 0x0040\n#define TYPEUSE_EXCEPTION 0x0080\n#define TYPEUSE_SCOPE 0x0100\n\n\/**\n * Flag shows the state of the code generation. If the Flag is set\n * the code for this type is generated.\n *\/\n#define CODEGEN_DEFAULT 0x0001\n\nstruct TypeUsing\n{\n TypeUsing(const ::rtl::OString& type, sal_uInt16 use)\n : m_type(type)\n , m_use(use)\n {}\n\n ::rtl::OString m_type;\n sal_uInt16 m_use;\n\n sal_Bool operator == (const TypeUsing & typeUsing) const\n {\n OSL_ASSERT(0);\n return m_type == typeUsing.m_type && m_use == typeUsing.m_use;\n }\n};\n\nstruct LessTypeUsing\n{\n sal_Bool operator()(const TypeUsing& tuse1, const TypeUsing& tuse2) const\n {\n return (tuse1.m_type < tuse2.m_type);\n }\n};\n\ntypedef ::std::set< TypeUsing, LessTypeUsing > TypeUsingSet;\n\n\n#if (defined( _MSC_VER ) && ( _MSC_VER < 1200 ))\ntypedef ::std::__hash_map__\n<\n ::rtl::OString,\n TypeUsingSet,\n HashString,\n EqualString,\n NewAlloc\n> DependencyMap;\n\ntypedef ::std::__hash_map__\n<\n ::rtl::OString,\n sal_uInt16,\n HashString,\n EqualString,\n NewAlloc\n> GenerationMap;\n#else\ntypedef ::std::hash_map\n<\n ::rtl::OString,\n TypeUsingSet,\n HashString,\n EqualString\n> DependencyMap;\n\ntypedef ::std::hash_map\n<\n ::rtl::OString,\n sal_uInt16,\n HashString,\n EqualString\n> GenerationMap;\n\n#endif\n\nstruct TypeDependencyImpl\n{\n TypeDependencyImpl()\n : m_refCount(0)\n {}\n\n sal_Int32 m_refCount;\n DependencyMap m_dependencies;\n GenerationMap m_generatedTypes;\n};\n\nclass TypeDependency\n{\npublic:\n TypeDependency();\n ~TypeDependency();\n\n TypeDependency( const TypeDependency& value )\n : m_pImpl( value.m_pImpl )\n {\n acquire();\n }\n\n TypeDependency& operator = ( const TypeDependency& value )\n {\n release();\n m_pImpl = value.m_pImpl;\n acquire();\n return *this;\n }\n\n sal_Bool insert(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);\n TypeUsingSet getDependencies(const ::rtl::OString& type);\n sal_Bool lookupDependency(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);\n sal_Bool hasDependencies(const ::rtl::OString& type);\n\n void setGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);\n sal_Bool isGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);\n\n sal_Int32 getSize() { return m_pImpl->m_generatedTypes.size(); }\nprotected:\n void acquire();\n void release();\n\nprotected:\n TypeDependencyImpl* m_pImpl;\n};\n\nsal_Bool checkTypeDependencies(TypeManager& typeMgr, TypeDependency& dependencies, const ::rtl::OString& type, sal_Bool bDepend = sal_False);\n\n#endif \/\/ _CODEMAKER_DEPENDENCY_HXX_\nINTEGRATION: CWS changefileheader (1.4.48); FILE MERGED 2008\/04\/01 15:22:57 thb 1.4.48.3: #i85898# Stripping all external header guards 2008\/04\/01 12:32:32 thb 1.4.48.2: #i85898# Stripping all external header guards 2008\/03\/31 07:25:05 rt 1.4.48.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dependency.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _CODEMAKER_DEPENDENCY_HXX_\n#define _CODEMAKER_DEPENDENCY_HXX_\n\n#include \n#include \n#ifndef __REGISTRY_REFLREAD_HXX__\n#include \n#endif\n#include \n#include \n#include \n\n#define TYPEUSE_NORMAL 0x0001\n#define TYPEUSE_SUPER 0x0002\n#define TYPEUSE_MEMBER 0x0004\n#define TYPEUSE_INPARAM 0x0008\n#define TYPEUSE_OUTPARAM 0x0010\n#define TYPEUSE_INOUTPARAM 0x0020\n#define TYPEUSE_RETURN 0x0040\n#define TYPEUSE_EXCEPTION 0x0080\n#define TYPEUSE_SCOPE 0x0100\n\n\/**\n * Flag shows the state of the code generation. If the Flag is set\n * the code for this type is generated.\n *\/\n#define CODEGEN_DEFAULT 0x0001\n\nstruct TypeUsing\n{\n TypeUsing(const ::rtl::OString& type, sal_uInt16 use)\n : m_type(type)\n , m_use(use)\n {}\n\n ::rtl::OString m_type;\n sal_uInt16 m_use;\n\n sal_Bool operator == (const TypeUsing & typeUsing) const\n {\n OSL_ASSERT(0);\n return m_type == typeUsing.m_type && m_use == typeUsing.m_use;\n }\n};\n\nstruct LessTypeUsing\n{\n sal_Bool operator()(const TypeUsing& tuse1, const TypeUsing& tuse2) const\n {\n return (tuse1.m_type < tuse2.m_type);\n }\n};\n\ntypedef ::std::set< TypeUsing, LessTypeUsing > TypeUsingSet;\n\n\n#if (defined( _MSC_VER ) && ( _MSC_VER < 1200 ))\ntypedef ::std::__hash_map__\n<\n ::rtl::OString,\n TypeUsingSet,\n HashString,\n EqualString,\n NewAlloc\n> DependencyMap;\n\ntypedef ::std::__hash_map__\n<\n ::rtl::OString,\n sal_uInt16,\n HashString,\n EqualString,\n NewAlloc\n> GenerationMap;\n#else\ntypedef ::std::hash_map\n<\n ::rtl::OString,\n TypeUsingSet,\n HashString,\n EqualString\n> DependencyMap;\n\ntypedef ::std::hash_map\n<\n ::rtl::OString,\n sal_uInt16,\n HashString,\n EqualString\n> GenerationMap;\n\n#endif\n\nstruct TypeDependencyImpl\n{\n TypeDependencyImpl()\n : m_refCount(0)\n {}\n\n sal_Int32 m_refCount;\n DependencyMap m_dependencies;\n GenerationMap m_generatedTypes;\n};\n\nclass TypeDependency\n{\npublic:\n TypeDependency();\n ~TypeDependency();\n\n TypeDependency( const TypeDependency& value )\n : m_pImpl( value.m_pImpl )\n {\n acquire();\n }\n\n TypeDependency& operator = ( const TypeDependency& value )\n {\n release();\n m_pImpl = value.m_pImpl;\n acquire();\n return *this;\n }\n\n sal_Bool insert(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);\n TypeUsingSet getDependencies(const ::rtl::OString& type);\n sal_Bool lookupDependency(const ::rtl::OString& type, const ::rtl::OString& depend, sal_uInt16);\n sal_Bool hasDependencies(const ::rtl::OString& type);\n\n void setGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);\n sal_Bool isGenerated(const ::rtl::OString& type, sal_uInt16 genFlag=CODEGEN_DEFAULT);\n\n sal_Int32 getSize() { return m_pImpl->m_generatedTypes.size(); }\nprotected:\n void acquire();\n void release();\n\nprotected:\n TypeDependencyImpl* m_pImpl;\n};\n\nsal_Bool checkTypeDependencies(TypeManager& typeMgr, TypeDependency& dependencies, const ::rtl::OString& type, sal_Bool bDepend = sal_False);\n\n#endif \/\/ _CODEMAKER_DEPENDENCY_HXX_\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: rdbmaker.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: tbe $ $Date: 2001-05-11 09:39:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n\n#ifndef _OSL_FILE_HXX_\n#include \n#endif\n#ifndef _OSL_PROCESS_H_\n#include \n#endif\n#ifndef _CODEMAKER_TYPEMANAGER_HXX_\n#include \n#endif\n#ifndef _CODEMAKER_DEPENDENCY_HXX_\n#include \n#endif\n\n#ifndef _RTL_OSTRINGBUFFER_HXX_\n#include \n#endif\n\n#if defined(SAL_W32) || defined(SAL_OS2)\n#include \n#include \n#include \n#endif\n\n#ifdef UNX\n#include \n#include \n#include \n#include \n#endif\n\n#include \"specialtypemanager.hxx\"\n#include \"rdboptions.hxx\"\n#include \"rdbtype.hxx\"\n\n#define PATH_DELEMITTER '\/'\n\nusing namespace rtl;\nusing namespace osl;\n\nFileStream listFile;\nRegistryKey rootKey;\nRegistryLoader loader;\nRegistry regFile(loader);\nsal_Bool useSpecial;\nTypeManager* pTypeMgr = NULL;\nStringList dirEntries;\nStringSet filterTypes;\n\nOString getFullNameOfApplicatRdb()\n{\n OUString bootReg;\n OUString uTmpStr;\n if( osl_getExecutableFile(&uTmpStr.pData) == osl_Process_E_None )\n {\n sal_uInt32 lastIndex = uTmpStr.lastIndexOf(PATH_DELEMITTER);\n OUString tmpReg;\n\n if ( lastIndex > 0 )\n {\n tmpReg =uTmpStr.copy(0, lastIndex + 1);\n }\n\n tmpReg += OUString( RTL_CONSTASCII_USTRINGPARAM(\"applicat.rdb\") );\n\n FileBase::getSystemPathFromNormalizedPath(tmpReg, bootReg);\n }\n\n return OUStringToOString(bootReg, RTL_TEXTENCODING_ASCII_US);\n}\n\nvoid initFilterTypes(RdbOptions* pOptions)\n{\n if (pOptions->isValid(\"-FT\"))\n {\n OString fOption(pOptions->getOption(\"-FT\"));\n sal_Bool ret = sal_False;\n sal_Int32 nIndex = 0;\n do\n {\n filterTypes.insert( fOption.getToken( 0, ';', nIndex ).replace('.', '\/') );\n }\n while ( nIndex >= 0 );\n }\n if (pOptions->isValid(\"-F\"))\n {\n FILE *f = fopen(pOptions->getOption(\"-F\").getStr(), \"r\");\n\n if (f)\n {\n sal_Char buffer[1024+1];\n sal_Char *pBuf = fgets(buffer, 1024, f);\n sal_Char *s = NULL;\n sal_Char *p = NULL;\n while ( pBuf && !feof(f))\n {\n p = pBuf;\n if (*p != '\\n' && *p != '\\r')\n {\n while (*p == ' ' && *p =='\\t')\n p++;\n\n s = p;\n while (*p != '\\n' && *p != '\\r' && *p != ' ' && *p != '\\t')\n p++;\n\n *p = '\\0';\n filterTypes.insert( OString(s).replace('.', '\/') );\n }\n\n pBuf = fgets(buffer, 1024, f);\n }\n\n fclose(f);\n }\n }\n}\n\nsal_Bool checkFilterTypes(const OString& type)\n{\n StringSet::iterator iter = filterTypes.begin();\n while ( iter != filterTypes.end() )\n {\n if ( type.indexOf( *iter ) == 0 )\n {\n return sal_True;\n }\n\n iter++;\n }\n\n return sal_False;\n}\n\nvoid cleanUp( sal_Bool bError)\n{\n if ( pTypeMgr )\n {\n delete pTypeMgr;\n }\n if (useSpecial)\n {\n pTypeMgr = new SpecialTypeManager();\n }else\n {\n pTypeMgr = new RegistryTypeManager();\n }\n\n if ( rootKey.isValid() )\n {\n rootKey.closeKey();\n }\n if ( regFile.isValid() )\n {\n if ( bError )\n {\n regFile.destroy(OUString());\n } else\n {\n regFile.close();\n }\n }\n if ( listFile.isValid() )\n {\n listFile.closeFile();\n unlink(listFile.getName().getStr());\n }\n\n StringList::reverse_iterator iter = dirEntries.rbegin();\n while ( iter != dirEntries.rend() )\n {\n if (rmdir((char*)(*iter).getStr()) == -1)\n {\n break;\n }\n\n iter++;\n }\n}\n\nOString createFileName(const OString& path)\n{\n OString fileName(path);\n\n sal_Char token;\n#ifdef SAL_UNX\n fileName = fileName.replace('\\\\', '\/');\n token = '\/';\n#else\n fileName = fileName.replace('\/', '\\\\');\n token = '\\\\';\n#endif\n\n OStringBuffer nameBuffer( path.getLength() );\n\n sal_Int32 nIndex = 0;\n do\n {\n nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());\n if ( nIndex == -1 ) break;\n\n if (nameBuffer.getLength() == 0 || OString(\".\") == nameBuffer.getStr())\n {\n nameBuffer.append(token);\n continue;\n }\n\n#ifdef SAL_UNX\n if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)\n#else\n if (mkdir((char*)nameBuffer.getStr()) == -1)\n#endif\n {\n if ( errno == ENOENT )\n return OString();\n } else\n {\n dirEntries.push_back(nameBuffer.getStr());\n }\n\n nameBuffer.append(token);\n }\n while ( nIndex >= 0 );\n\n return fileName;\n}\n\nsal_Bool produceAllTypes(const OString& typeName,\n TypeManager& typeMgr,\n TypeDependency& typeDependencies,\n RdbOptions* pOptions,\n sal_Bool bFullScope,\n FileStream& o,\n RegistryKey& regKey,\n StringSet& filterTypes)\n throw( CannotDumpException )\n{\n if (!produceType(typeName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n pOptions->getProgramName().getStr(),\n OString(\"cannot dump Type '\" + typeName + \"'\").getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n RegistryKey typeKey = typeMgr.getTypeKey(typeName);\n RegistryKeyNames subKeys;\n\n if (typeKey.getKeyNames(OUString(), subKeys))\n return sal_False;\n\n OString tmpName;\n for (sal_uInt32 i=0; i < subKeys.getLength(); i++)\n {\n tmpName = OUStringToOString(subKeys.getElement(i), RTL_TEXTENCODING_UTF8);\n\n if (pOptions->isValid(\"-B\"))\n tmpName = tmpName.copy(tmpName.indexOf('\/', 1) + 1);\n else\n tmpName = tmpName.copy(1);\n\n if (bFullScope)\n {\n if (!produceAllTypes(tmpName, typeMgr, typeDependencies, pOptions, sal_True,\n o, regKey, filterTypes))\n return sal_False;\n } else\n {\n if (!produceType(tmpName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))\n return sal_False;\n }\n }\n\n return sal_True;\n}\n\n\n#if (defined UNX) || (defined OS2)\nint main( int argc, char * argv[] )\n#else\nint _cdecl main( int argc, char * argv[] )\n#endif\n{\n RdbOptions options;\n\n try\n {\n if (!options.initOptions(argc, argv))\n {\n cleanUp(sal_True);\n exit(1);\n }\n }\n catch( IllegalArgument& e)\n {\n fprintf(stderr, \"Illegal option: %s\\n\", e.m_message.getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n TypeDependency typeDependencies;\n\n OString bootReg;\n\n if ( options.isValid(\"-R\") )\n {\n bootReg = options.getOption(\"-R\");\n } else\n {\n if (options.getInputFiles().empty())\n {\n bootReg = getFullNameOfApplicatRdb();\n }\n }\n\n if ( bootReg.getLength() )\n {\n pTypeMgr = new SpecialTypeManager();\n useSpecial = sal_True;\n } else\n {\n pTypeMgr = new RegistryTypeManager();\n useSpecial = sal_False;\n }\n\n TypeManager& typeMgr = *pTypeMgr;\n\n if ( useSpecial && !typeMgr.init( bootReg ) )\n {\n fprintf(stderr, \"%s : init typemanager failed, check your environment for bootstrapping uno.\\n\", options.getProgramName().getStr());\n cleanUp(sal_True);\n exit(99);\n }\n if ( !useSpecial && !typeMgr.init(!options.isValid(\"-T\"), options.getInputFiles()))\n {\n fprintf(stderr, \"%s : init registries failed, check your registry files.\\n\", options.getProgramName().getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n initFilterTypes(&options);\n\n if (options.isValid(\"-B\"))\n {\n typeMgr.setBase(options.getOption(\"-B\"));\n }\n\n if ( !options.isValid(\"-O\") )\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"no output file is specified.\");\n cleanUp(sal_True);\n exit(99);\n }\n\n if ( options.generateTypeList() )\n {\n OString fileName = createFileName( options.getOption(\"-O\") );\n listFile.openFile(fileName);\n\n if ( !listFile.isValid() )\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"could not open output file.\");\n cleanUp(sal_True);\n exit(99);\n }\n } else\n {\n OUString fileName( OStringToOUString(createFileName( options.getOption(\"-O\") ), RTL_TEXTENCODING_UTF8) );\n if ( regFile.create(fileName) )\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"could not create registry output file.\");\n cleanUp(sal_True);\n exit(99);\n }\n\n\n if (options.isValid(\"-b\"))\n {\n RegistryKey tmpKey;\n regFile.openRootKey(tmpKey);\n\n tmpKey.createKey( OStringToOUString(options.getOption(\"-b\"), RTL_TEXTENCODING_UTF8), rootKey);\n } else\n {\n regFile.openRootKey(rootKey);\n }\n }\n\n try\n {\n if (options.isValid(\"-T\"))\n {\n OString tOption(options.getOption(\"-T\"));\n OString typeName, tmpName;\n sal_Bool ret = sal_False;\n sal_Int32 nIndex = 0;\n do\n {\n typeName = tOption.getToken( 0, ';', nIndex);\n sal_Int32 lastIndex = typeName.lastIndexOf('.');\n tmpName = typeName.copy( lastIndex+1 );\n if (tmpName == \"*\")\n {\n if (bootReg.getLength())\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"dumping all types of a scope is not possible if -R option is used.\");\n exit(99);\n }\n \/\/ produce this type and his scope, but the scope is not recursively generated.\n if (typeName.equals(\"*\"))\n {\n tmpName = \"\/\";\n } else\n {\n tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '\/');\n if (tmpName.getLength() == 0)\n tmpName = \"\/\";\n else\n tmpName.replace('.', '\/');\n }\n ret = produceAllTypes(tmpName, typeMgr, typeDependencies, &options, sal_False,\n listFile, rootKey, filterTypes);\n } else\n {\n \/\/ produce only this type\n ret = produceType(typeName.replace('.', '\/'), typeMgr, typeDependencies,\n &options, listFile, rootKey, filterTypes);\n }\n\/*\n \/\/ produce only this type\n ret = produceType(typeName.replace('.', '\/'), typeMgr, typeDependencies,\n &options, listFile, rootKey, filterTypes);\n*\/\n if (!ret)\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n OString(\"cannot dump Type '\" + typeName + \"'\").getStr());\n cleanUp(sal_True);\n exit(99);\n }\n }\n while ( nIndex >= 0 );\n } else\n if (options.isValid(\"-X\"))\n {\n } else\n {\n if (!bootReg.getLength())\n {\n \/\/ produce all types\n if (!produceAllTypes(\"\/\", typeMgr, typeDependencies, &options, sal_True,\n listFile, rootKey, filterTypes))\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"an error occurs while dumping all types.\");\n exit(99);\n }\n } else\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"dumping all types is not possible if -R option is used.\");\n exit(99);\n }\n }\n }\n catch( CannotDumpException& e)\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n e.m_message.getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n cleanUp(sal_False);\n return 0;\n}\n\n\n#87132# Merge OSL file api changes from TFU630 to SRC633\/*************************************************************************\n *\n * $RCSfile: rdbmaker.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hro $ $Date: 2001-05-21 15:45:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n\n#ifndef _OSL_FILE_HXX_\n#include \n#endif\n#ifndef _OSL_PROCESS_H_\n#include \n#endif\n#ifndef _CODEMAKER_TYPEMANAGER_HXX_\n#include \n#endif\n#ifndef _CODEMAKER_DEPENDENCY_HXX_\n#include \n#endif\n\n#ifndef _RTL_OSTRINGBUFFER_HXX_\n#include \n#endif\n\n#if defined(SAL_W32) || defined(SAL_OS2)\n#include \n#include \n#include \n#endif\n\n#ifdef UNX\n#include \n#include \n#include \n#include \n#endif\n\n#include \"specialtypemanager.hxx\"\n#include \"rdboptions.hxx\"\n#include \"rdbtype.hxx\"\n\n#define PATH_DELEMITTER '\/'\n\nusing namespace rtl;\nusing namespace osl;\n\nFileStream listFile;\nRegistryKey rootKey;\nRegistryLoader loader;\nRegistry regFile(loader);\nsal_Bool useSpecial;\nTypeManager* pTypeMgr = NULL;\nStringList dirEntries;\nStringSet filterTypes;\n\nOString getFullNameOfApplicatRdb()\n{\n OUString bootReg;\n OUString uTmpStr;\n if( osl_getExecutableFile(&uTmpStr.pData) == osl_Process_E_None )\n {\n sal_uInt32 lastIndex = uTmpStr.lastIndexOf(PATH_DELEMITTER);\n OUString tmpReg;\n\n if ( lastIndex > 0 )\n {\n tmpReg =uTmpStr.copy(0, lastIndex + 1);\n }\n\n tmpReg += OUString( RTL_CONSTASCII_USTRINGPARAM(\"applicat.rdb\") );\n\n FileBase::getSystemPathFromFileURL(tmpReg, bootReg);\n }\n\n return OUStringToOString(bootReg, RTL_TEXTENCODING_ASCII_US);\n}\n\nvoid initFilterTypes(RdbOptions* pOptions)\n{\n if (pOptions->isValid(\"-FT\"))\n {\n OString fOption(pOptions->getOption(\"-FT\"));\n sal_Bool ret = sal_False;\n sal_Int32 nIndex = 0;\n do\n {\n filterTypes.insert( fOption.getToken( 0, ';', nIndex ).replace('.', '\/') );\n }\n while ( nIndex >= 0 );\n }\n if (pOptions->isValid(\"-F\"))\n {\n FILE *f = fopen(pOptions->getOption(\"-F\").getStr(), \"r\");\n\n if (f)\n {\n sal_Char buffer[1024+1];\n sal_Char *pBuf = fgets(buffer, 1024, f);\n sal_Char *s = NULL;\n sal_Char *p = NULL;\n while ( pBuf && !feof(f))\n {\n p = pBuf;\n if (*p != '\\n' && *p != '\\r')\n {\n while (*p == ' ' && *p =='\\t')\n p++;\n\n s = p;\n while (*p != '\\n' && *p != '\\r' && *p != ' ' && *p != '\\t')\n p++;\n\n *p = '\\0';\n filterTypes.insert( OString(s).replace('.', '\/') );\n }\n\n pBuf = fgets(buffer, 1024, f);\n }\n\n fclose(f);\n }\n }\n}\n\nsal_Bool checkFilterTypes(const OString& type)\n{\n StringSet::iterator iter = filterTypes.begin();\n while ( iter != filterTypes.end() )\n {\n if ( type.indexOf( *iter ) == 0 )\n {\n return sal_True;\n }\n\n iter++;\n }\n\n return sal_False;\n}\n\nvoid cleanUp( sal_Bool bError)\n{\n if ( pTypeMgr )\n {\n delete pTypeMgr;\n }\n if (useSpecial)\n {\n pTypeMgr = new SpecialTypeManager();\n }else\n {\n pTypeMgr = new RegistryTypeManager();\n }\n\n if ( rootKey.isValid() )\n {\n rootKey.closeKey();\n }\n if ( regFile.isValid() )\n {\n if ( bError )\n {\n regFile.destroy(OUString());\n } else\n {\n regFile.close();\n }\n }\n if ( listFile.isValid() )\n {\n listFile.closeFile();\n unlink(listFile.getName().getStr());\n }\n\n StringList::reverse_iterator iter = dirEntries.rbegin();\n while ( iter != dirEntries.rend() )\n {\n if (rmdir((char*)(*iter).getStr()) == -1)\n {\n break;\n }\n\n iter++;\n }\n}\n\nOString createFileName(const OString& path)\n{\n OString fileName(path);\n\n sal_Char token;\n#ifdef SAL_UNX\n fileName = fileName.replace('\\\\', '\/');\n token = '\/';\n#else\n fileName = fileName.replace('\/', '\\\\');\n token = '\\\\';\n#endif\n\n OStringBuffer nameBuffer( path.getLength() );\n\n sal_Int32 nIndex = 0;\n do\n {\n nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());\n if ( nIndex == -1 ) break;\n\n if (nameBuffer.getLength() == 0 || OString(\".\") == nameBuffer.getStr())\n {\n nameBuffer.append(token);\n continue;\n }\n\n#ifdef SAL_UNX\n if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)\n#else\n if (mkdir((char*)nameBuffer.getStr()) == -1)\n#endif\n {\n if ( errno == ENOENT )\n return OString();\n } else\n {\n dirEntries.push_back(nameBuffer.getStr());\n }\n\n nameBuffer.append(token);\n }\n while ( nIndex >= 0 );\n\n return fileName;\n}\n\nsal_Bool produceAllTypes(const OString& typeName,\n TypeManager& typeMgr,\n TypeDependency& typeDependencies,\n RdbOptions* pOptions,\n sal_Bool bFullScope,\n FileStream& o,\n RegistryKey& regKey,\n StringSet& filterTypes)\n throw( CannotDumpException )\n{\n if (!produceType(typeName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n pOptions->getProgramName().getStr(),\n OString(\"cannot dump Type '\" + typeName + \"'\").getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n RegistryKey typeKey = typeMgr.getTypeKey(typeName);\n RegistryKeyNames subKeys;\n\n if (typeKey.getKeyNames(OUString(), subKeys))\n return sal_False;\n\n OString tmpName;\n for (sal_uInt32 i=0; i < subKeys.getLength(); i++)\n {\n tmpName = OUStringToOString(subKeys.getElement(i), RTL_TEXTENCODING_UTF8);\n\n if (pOptions->isValid(\"-B\"))\n tmpName = tmpName.copy(tmpName.indexOf('\/', 1) + 1);\n else\n tmpName = tmpName.copy(1);\n\n if (bFullScope)\n {\n if (!produceAllTypes(tmpName, typeMgr, typeDependencies, pOptions, sal_True,\n o, regKey, filterTypes))\n return sal_False;\n } else\n {\n if (!produceType(tmpName, typeMgr, typeDependencies, pOptions, o, regKey, filterTypes))\n return sal_False;\n }\n }\n\n return sal_True;\n}\n\n\n#if (defined UNX) || (defined OS2)\nint main( int argc, char * argv[] )\n#else\nint _cdecl main( int argc, char * argv[] )\n#endif\n{\n RdbOptions options;\n\n try\n {\n if (!options.initOptions(argc, argv))\n {\n cleanUp(sal_True);\n exit(1);\n }\n }\n catch( IllegalArgument& e)\n {\n fprintf(stderr, \"Illegal option: %s\\n\", e.m_message.getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n TypeDependency typeDependencies;\n\n OString bootReg;\n\n if ( options.isValid(\"-R\") )\n {\n bootReg = options.getOption(\"-R\");\n } else\n {\n if (options.getInputFiles().empty())\n {\n bootReg = getFullNameOfApplicatRdb();\n }\n }\n\n if ( bootReg.getLength() )\n {\n pTypeMgr = new SpecialTypeManager();\n useSpecial = sal_True;\n } else\n {\n pTypeMgr = new RegistryTypeManager();\n useSpecial = sal_False;\n }\n\n TypeManager& typeMgr = *pTypeMgr;\n\n if ( useSpecial && !typeMgr.init( bootReg ) )\n {\n fprintf(stderr, \"%s : init typemanager failed, check your environment for bootstrapping uno.\\n\", options.getProgramName().getStr());\n cleanUp(sal_True);\n exit(99);\n }\n if ( !useSpecial && !typeMgr.init(!options.isValid(\"-T\"), options.getInputFiles()))\n {\n fprintf(stderr, \"%s : init registries failed, check your registry files.\\n\", options.getProgramName().getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n initFilterTypes(&options);\n\n if (options.isValid(\"-B\"))\n {\n typeMgr.setBase(options.getOption(\"-B\"));\n }\n\n if ( !options.isValid(\"-O\") )\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"no output file is specified.\");\n cleanUp(sal_True);\n exit(99);\n }\n\n if ( options.generateTypeList() )\n {\n OString fileName = createFileName( options.getOption(\"-O\") );\n listFile.openFile(fileName);\n\n if ( !listFile.isValid() )\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"could not open output file.\");\n cleanUp(sal_True);\n exit(99);\n }\n } else\n {\n OUString fileName( OStringToOUString(createFileName( options.getOption(\"-O\") ), RTL_TEXTENCODING_UTF8) );\n if ( regFile.create(fileName) )\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"could not create registry output file.\");\n cleanUp(sal_True);\n exit(99);\n }\n\n\n if (options.isValid(\"-b\"))\n {\n RegistryKey tmpKey;\n regFile.openRootKey(tmpKey);\n\n tmpKey.createKey( OStringToOUString(options.getOption(\"-b\"), RTL_TEXTENCODING_UTF8), rootKey);\n } else\n {\n regFile.openRootKey(rootKey);\n }\n }\n\n try\n {\n if (options.isValid(\"-T\"))\n {\n OString tOption(options.getOption(\"-T\"));\n OString typeName, tmpName;\n sal_Bool ret = sal_False;\n sal_Int32 nIndex = 0;\n do\n {\n typeName = tOption.getToken( 0, ';', nIndex);\n sal_Int32 lastIndex = typeName.lastIndexOf('.');\n tmpName = typeName.copy( lastIndex+1 );\n if (tmpName == \"*\")\n {\n if (bootReg.getLength())\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"dumping all types of a scope is not possible if -R option is used.\");\n exit(99);\n }\n \/\/ produce this type and his scope, but the scope is not recursively generated.\n if (typeName.equals(\"*\"))\n {\n tmpName = \"\/\";\n } else\n {\n tmpName = typeName.copy(0, typeName.lastIndexOf('.')).replace('.', '\/');\n if (tmpName.getLength() == 0)\n tmpName = \"\/\";\n else\n tmpName.replace('.', '\/');\n }\n ret = produceAllTypes(tmpName, typeMgr, typeDependencies, &options, sal_False,\n listFile, rootKey, filterTypes);\n } else\n {\n \/\/ produce only this type\n ret = produceType(typeName.replace('.', '\/'), typeMgr, typeDependencies,\n &options, listFile, rootKey, filterTypes);\n }\n\/*\n \/\/ produce only this type\n ret = produceType(typeName.replace('.', '\/'), typeMgr, typeDependencies,\n &options, listFile, rootKey, filterTypes);\n*\/\n if (!ret)\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n OString(\"cannot dump Type '\" + typeName + \"'\").getStr());\n cleanUp(sal_True);\n exit(99);\n }\n }\n while ( nIndex >= 0 );\n } else\n if (options.isValid(\"-X\"))\n {\n } else\n {\n if (!bootReg.getLength())\n {\n \/\/ produce all types\n if (!produceAllTypes(\"\/\", typeMgr, typeDependencies, &options, sal_True,\n listFile, rootKey, filterTypes))\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"an error occurs while dumping all types.\");\n exit(99);\n }\n } else\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n \"dumping all types is not possible if -R option is used.\");\n exit(99);\n }\n }\n }\n catch( CannotDumpException& e)\n {\n fprintf(stderr, \"%s ERROR: %s\\n\",\n options.getProgramName().getStr(),\n e.m_message.getStr());\n cleanUp(sal_True);\n exit(99);\n }\n\n cleanUp(sal_False);\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"\/*\n\tCopyright 2014 Justin White\n\tSee included LICENSE file for details.\n*\/\n\n#include \n#include \n\n#include \n#include \n\nusing std::string;\n\n#include \n#include \n\n#include \"log4cpp\/Category.hh\"\n#include \"log4cpp\/Appender.hh\"\n#include \"log4cpp\/FileAppender.hh\"\n#include \"log4cpp\/OstreamAppender.hh\"\n#include \"log4cpp\/Layout.hh\"\n#include \"log4cpp\/BasicLayout.hh\"\n#include \"log4cpp\/PatternLayout.hh\"\n#include \"log4cpp\/Priority.hh\"\n\n#include \"GameSprite.h\"\n\n\/\/ short names for log4cpp Priorities;\nconst int DEBUG = log4cpp::Priority::DEBUG;\nconst int INFO = log4cpp::Priority::INFO;\nconst int WARN = log4cpp::Priority::WARN;\nconst int ERROR = log4cpp::Priority::ERROR;\n\n\/\/system data\nconst int version = 0;\nconst int revision = 1;\nconst int width = 1280;\nconst int height = 720;\nconst string title = \"SpaceFight\";\nsf::RenderWindow* window;\nstring fileLogName = title + \".log\";\nlog4cpp::Category& alog = log4cpp::Category::getRoot();\nlog4cpp::Category& clog = log4cpp::Category::getInstance(\"cons\");\nlog4cpp::Category& flog = log4cpp::Category::getInstance(\"file\");\n\n\/\/ game data\nconst float deadZone = 15;\nconst float keySpeed = 75;\nGameSprite* logo;\n\n\n\/\/ system functions\nvoid initializeSystem();\nvoid processEvents();\nvoid updateControls();\nvoid updateWorld(sf::Time);\nvoid renderWorld();\n\n\nvoid initializeSystem()\n{\n\twindow = new sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close);\n\tif (window->isOpen()) {\n\t\tsf::ContextSettings settings = window->getSettings();\n\t\talog.info(\"Using OpenGL v%d.%d\",settings.majorVersion, settings.minorVersion);\n\t\talog.info(\"Created the main window %dx%d\", width, height);\n\t} else {\n\t\talog.error(\"Could not create main window\");\n\t\texit(EXIT_FAILURE);\n\t}\n\talog.info(\"Enabling VSync\");\n\twindow->setVerticalSyncEnabled(true);\n\n\tlogo = new GameSprite(\"cb.bmp\");\n\tlogo->setPosition(width \/ 2, height \/ 2);\n\talog.info(\"Loaded sprite\");\n}\n\nvoid processEvents()\n{\n\tstatic sf::Event event;\n\n\twhile(window->pollEvent(event)) {\n\t\tswitch(event.type) {\n\t\tcase sf::Event::Closed:\n\t\t\talog.info(\"Window closed\");\n\t\t\twindow->close();\n\t\t\tbreak;\n\t\tcase sf::Event::KeyPressed:\n\t\t\tswitch(event.key.code) {\n\t\t\tcase sf::Keyboard::Escape:\n\t\t\t\talog.info(\"Player exited\");\n\t\t\t\twindow->close();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase sf::Event::KeyReleased:\n\t\t\tswitch(event.key.code) {\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid updateControls()\n{\n\tfloat x, y = 0;\n\n\tfloat joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n\tfloat joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\tx = abs(joy0_X) < deadZone ? 0 : joy0_X;\n\ty = abs(joy0_y) < deadZone ? 0 : joy0_y;\n\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {\n\t\ty += -keySpeed;\n\t}\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {\n\t\tx += keySpeed;\n\t}\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {\n\t\ty += keySpeed;\n\t}\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {\n\t\tx += -keySpeed;\n\t}\n\tlogo->moveBy(x, y);\n}\n\nvoid updateWorld(sf::Time elapsed)\n{\n\tconst int millis = elapsed.asMilliseconds();\n\tlogo->update(millis);\n}\n\nvoid renderWorld()\n{\n\twindow->clear(sf::Color::Black);\n\twindow->draw(*logo);\n\twindow->display();\n}\n\n\nint main()\n{\n\tlog4cpp::Category::setRootPriority(DEBUG);\n\n\t\/\/ console log: 'time priority message'\n\tlog4cpp::PatternLayout* consLogLayout = new log4cpp::PatternLayout();\n\tconsLogLayout->setConversionPattern(\"%d{%H:%M:%S,%l} %p %m%n\");\n\tlog4cpp::Appender* consLog = new log4cpp::OstreamAppender(\"cons\", &std::clog);\n\tconsLog->setLayout(consLogLayout);\n\t\/\/ show debug priority & above when debugging\n#ifdef DO_DEBUG\n\tconsLog->setThreshold(DEBUG);\n#else\n\t\/\/ show only info priority & above normally\n\tconsLog->setThreshold(INFO);\n#endif\n\n\t\/\/ file log: 'date time priority message'\n\tlog4cpp::PatternLayout* fileLogLayout = new log4cpp::PatternLayout();\n\tfileLogLayout->setConversionPattern(\"%d{%Y-%m-%d %H:%M:%S,%l} %p %m%n\");\n\tlog4cpp::Appender* fileLog = new log4cpp::FileAppender(\"file\", fileLogName, false);\n\tfileLog->setLayout(fileLogLayout);\n\t\/\/ always show debug priority & above\n\tfileLog->setThreshold(DEBUG);\n\n\talog.addAppender(consLog);\n\talog.addAppender(fileLog);\n\n\tclog.addAppender(consLog);\n\tclog.setAdditivity(false);\n\tflog.addAppender(fileLog);\n\tflog.setAdditivity(false);\n\n\tflog << DEBUG << \"Opened logFile \" << fileLogName;\n\n\talog.info(\"Spacefight v%d.%d\", version, revision);\n\talog.info(\"Built %s %s\", __DATE__, __TIME__);\n\talog.info(\"GCC %s\", __VERSION__);\n\talog.info(\"SFML %d.%d\", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);\n\tinitializeSystem();\n\tsf::Clock gameClock;\n\tsf::Time elapsed;\n\talog.info(\"Running...\");\n\twhile(window->isOpen()) {\n\t\telapsed = gameClock.restart();\n\t\tprocessEvents();\n\t\tupdateControls();\n\t\tupdateWorld(elapsed);\n\t\trenderWorld();\n\t}\n\talog.info(\"Stopped\");\n\n\tflog << DEBUG << \"Closed logFile \" << fileLogName;\n\tfileLog->close();\n\n\treturn EXIT_SUCCESS;\n}\nRename logo to player.\/*\n\tCopyright 2014 Justin White\n\tSee included LICENSE file for details.\n*\/\n\n#include \n#include \n\n#include \n#include \n\nusing std::string;\n\n#include \n#include \n\n#include \"log4cpp\/Category.hh\"\n#include \"log4cpp\/Appender.hh\"\n#include \"log4cpp\/FileAppender.hh\"\n#include \"log4cpp\/OstreamAppender.hh\"\n#include \"log4cpp\/Layout.hh\"\n#include \"log4cpp\/BasicLayout.hh\"\n#include \"log4cpp\/PatternLayout.hh\"\n#include \"log4cpp\/Priority.hh\"\n\n#include \"GameSprite.h\"\n\n\/\/ short names for log4cpp Priorities;\nconst int DEBUG = log4cpp::Priority::DEBUG;\nconst int INFO = log4cpp::Priority::INFO;\nconst int WARN = log4cpp::Priority::WARN;\nconst int ERROR = log4cpp::Priority::ERROR;\n\n\/\/system data\nconst int version = 0;\nconst int revision = 1;\nconst int width = 1280;\nconst int height = 720;\nconst string title = \"SpaceFight\";\nsf::RenderWindow* window;\nstring fileLogName = title + \".log\";\nlog4cpp::Category& alog = log4cpp::Category::getRoot();\nlog4cpp::Category& clog = log4cpp::Category::getInstance(\"cons\");\nlog4cpp::Category& flog = log4cpp::Category::getInstance(\"file\");\n\n\/\/ game data\nconst float deadZone = 15;\nconst float keySpeed = 75;\nGameSprite* player;\n\n\n\/\/ system functions\nvoid initializeSystem();\nvoid processEvents();\nvoid updateControls();\nvoid updateWorld(sf::Time);\nvoid renderWorld();\n\n\nvoid initializeSystem()\n{\n\twindow = new sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Titlebar | sf::Style::Close);\n\tif (window->isOpen()) {\n\t\tsf::ContextSettings settings = window->getSettings();\n\t\talog.info(\"Using OpenGL v%d.%d\",settings.majorVersion, settings.minorVersion);\n\t\talog.info(\"Created the main window %dx%d\", width, height);\n\t} else {\n\t\talog.error(\"Could not create main window\");\n\t\texit(EXIT_FAILURE);\n\t}\n\talog.info(\"Enabling VSync\");\n\twindow->setVerticalSyncEnabled(true);\n\twindow->setPosition(sf::Vector2i(100,100));\n\n\tplayer = new GameSprite(sf::Color::Blue);\n\tplayer->setPosition(width \/ 2, height \/ 2);\n\talog.info(\"Loaded sprite\");\n}\n\nvoid processEvents()\n{\n\tstatic sf::Event event;\n\n\twhile(window->pollEvent(event)) {\n\t\tswitch(event.type) {\n\t\tcase sf::Event::Closed:\n\t\t\talog.info(\"Window closed\");\n\t\t\twindow->close();\n\t\t\tbreak;\n\t\tcase sf::Event::KeyPressed:\n\t\t\tswitch(event.key.code) {\n\t\t\tcase sf::Keyboard::Escape:\n\t\t\t\talog.info(\"Player exited\");\n\t\t\t\twindow->close();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase sf::Event::KeyReleased:\n\t\t\tswitch(event.key.code) {\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid updateControls()\n{\n\tfloat x, y = 0;\n\n\tfloat joy0_X = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n\tfloat joy0_y = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\tx = abs(joy0_X) < deadZone ? 0 : joy0_X;\n\ty = abs(joy0_y) < deadZone ? 0 : joy0_y;\n\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {\n\t\ty += -keySpeed;\n\t}\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {\n\t\tx += keySpeed;\n\t}\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {\n\t\ty += keySpeed;\n\t}\n\tif(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {\n\t\tx += -keySpeed;\n\t}\n\tplayer->moveBy(x, y);\n}\n\nvoid updateWorld(sf::Time elapsed)\n{\n\tconst int millis = elapsed.asMilliseconds();\n\tplayer->update(millis);\n}\n\nvoid renderWorld()\n{\n\twindow->clear(sf::Color::Black);\n\twindow->draw(*player);\n\twindow->display();\n}\n\n\nint main()\n{\n\tlog4cpp::Category::setRootPriority(DEBUG);\n\n\t\/\/ console log: 'time priority message'\n\tlog4cpp::PatternLayout* consLogLayout = new log4cpp::PatternLayout();\n\tconsLogLayout->setConversionPattern(\"%d{%H:%M:%S,%l} %p %m%n\");\n\tlog4cpp::Appender* consLog = new log4cpp::OstreamAppender(\"cons\", &std::clog);\n\tconsLog->setLayout(consLogLayout);\n\t\/\/ show debug priority & above when debugging\n#ifdef DO_DEBUG\n\tconsLog->setThreshold(DEBUG);\n#else\n\t\/\/ show only info priority & above normally\n\tconsLog->setThreshold(INFO);\n#endif\n\n\t\/\/ file log: 'date time priority message'\n\tlog4cpp::PatternLayout* fileLogLayout = new log4cpp::PatternLayout();\n\tfileLogLayout->setConversionPattern(\"%d{%Y-%m-%d %H:%M:%S,%l} %p %m%n\");\n\tlog4cpp::Appender* fileLog = new log4cpp::FileAppender(\"file\", fileLogName, false);\n\tfileLog->setLayout(fileLogLayout);\n\t\/\/ always show debug priority & above\n\tfileLog->setThreshold(DEBUG);\n\n\talog.addAppender(consLog);\n\talog.addAppender(fileLog);\n\n\tclog.addAppender(consLog);\n\tclog.setAdditivity(false);\n\tflog.addAppender(fileLog);\n\tflog.setAdditivity(false);\n\n\tflog << DEBUG << \"Opened logFile \" << fileLogName;\n\n\talog.info(\"Spacefight v%d.%d\", version, revision);\n\talog.info(\"Built %s %s\", __DATE__, __TIME__);\n\talog.info(\"GCC %s\", __VERSION__);\n\talog.info(\"SFML %d.%d\", SFML_VERSION_MAJOR, SFML_VERSION_MINOR);\n\tinitializeSystem();\n\tsf::Clock gameClock;\n\tsf::Time elapsed;\n\talog.info(\"Running...\");\n\twhile(window->isOpen()) {\n\t\telapsed = gameClock.restart();\n\t\tprocessEvents();\n\t\tupdateControls();\n\t\tupdateWorld(elapsed);\n\t\trenderWorld();\n\t}\n\talog.info(\"Stopped\");\n\n\tflog << DEBUG << \"Closed logFile \" << fileLogName;\n\tfileLog->close();\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \"jitpp\/arm\/Disassembler.h\"\n#include \"jitpp\/arm\/ArmTranslatorFactory.h\"\n#include \"jitpp\/arm\/ArmTranslator.h\"\n#include \"jitpp\/ACState.h\"\n#include \"jitpp\/CodeCache.h\"\n\n#include \n#include \n\n#include \n\nnamespace {\n\nuint64_t *emulation_pml2[4] = \n{\n\tnullptr, nullptr, nullptr, nullptr,\n};\n\nuint64_t *emulation_pml3 = nullptr;\n\nvoid mapArmPhysicalMem()\n{\n\temulation_pml2[0] = (uint64_t*)os::mm::allocate_page();\n\temulation_pml2[1] = (uint64_t*)os::mm::allocate_page();\n\temulation_pml2[2] = (uint64_t*)os::mm::allocate_page();\n\temulation_pml2[3] = (uint64_t*)os::mm::allocate_page();\n\n\temulation_pml3 = (uint64_t*)os::mm::allocate_page();\n\n\tconst int NUM_PAGE_TABLE_ENTRIES_PER_PAGE = (4096 \/ sizeof(uint64_t));\n\n\tfor( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {\n\t\temulation_pml3[ii] = 0;\n\t}\n\n\tfor( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {\n\t\tfor( int jj = 0; jj < 4; jj++ ) {\n\t\t\tconst uint64_t PHYS_PAGE = ((2 * 1024 * 1024) * ii) + \n\t\t\t ((1 * 1024 * 1024 *1024) * jj) + \n\t\t\t 0x100000000UL;\n\t\t\temulation_pml2[jj][ii] = PHYS_PAGE | 0x83;\n\t\t}\n\t}\n\n\tfor( int ii = 0; ii < 4; ii++ ) {\n\t\tconst uint64_t pml2_phys_addr = ((uint64_t)emulation_pml2[ii]) - 0xFFFFFFFF80000000UL;\n\n\t\temulation_pml3[ii] = pml2_phys_addr | 1;\n\t}\n\n\tos::mm::set_lower_pml3(emulation_pml3, 0);\n}\n\nclass VMMCodeCacheRandomStrategy\n{\nprotected:\n\tstatic int get_rand_way( int ways ) {\n\t\treturn os::board::high_performance_timer() % ways;\n\t}\n};\n\nclass DeletionEvictionPolicy\n{\nprotected:\n\tstatic void on_item_evicted( remu::jitpp::CodePage<4096, remu::jitpp::arm::ArmTranslator> **evicted ) {\n\t\tdelete *evicted;\n\t}\n};\n\nclass NoMmuHostPageSelectionStrategy\n{\nprotected:\n\tstatic void* get_host_page( const remu::jitpp::ACFarPointer& ip ) {\n\t\treturn reinterpret_cast( ip.program_counter & ~4095 );\n\t}\n};\n\nusing Arm11CpuCodeCache = remu::jitpp::CodeCache<4,1024,4096,\n VMMCodeCacheRandomStrategy,\n DeletionEvictionPolicy,\n remu::jitpp::arm::ArmTranslatorFactory,\n remu::jitpp::arm::ArmTranslator,\n NoMmuHostPageSelectionStrategy>;\n\n} \/*anonymous namespace*\/\n\nvoid appMain()\n{\n\tmapArmPhysicalMem();\n\n\tremu::jitpp::arm::Disassembler dis;\n\tremu::jitpp::ACState cpu_state;\n\tArm11CpuCodeCache *code_cache = new Arm11CpuCodeCache();\n\n\tcpu_state.clear();\n\tcpu_state.ip.program_counter = 0x00008000;\n\n\tbool running = true;\n\n\twhile( running ) {\n\t\tauto code_page = code_cache->getPageForFarPointer( cpu_state.ip );\n\t\tprintf(\"code_page: %p (host_page=%p guest_page=%0lx:%lx)\\n\", code_page, code_page->getHostBase(),\n\t\t cpu_state.ip.code_segment, cpu_state.ip.program_counter );\n\t\trunning = code_page->execute( cpu_state );\n\t\trunning = false;\n\t}\n\n\tuint32_t *first_instr = reinterpret_cast(cpu_state.ip.program_counter);\n\n\tchar buffer[64];\n\n\tfor( int ii = 0; ii < 75; ii++ ) {\n\t\tconst uint64_t cur_addr = 0x8000 + (sizeof(uint32_t) * ii);\n\t\tconst uint32_t instr = first_instr[ii];\n\n\t\tdis.disassemble(instr, cur_addr, buffer, 64);\n\n\t\tprintf(\"%08lx : %08x : %s\\n\", cur_addr, instr, buffer);\n\t}\n\n\tchar* ptr1 = new char[1 * 1024 * 1024];\n\tprintf(\"ptr1 = %p\\n\", ptr1);\n\tchar* ptr2 = new char[1 * 1024 * 1024];\n\tprintf(\"ptr2 = %p\\n\", ptr2);\n\tdelete ptr1;\n\tprintf(\"free(ptr1)\\n\");\n\tptr1 = new char[10];\n\tprintf(\"ptr1 = %p\\n\", ptr1);\n}\n\nRemove test print code from vmm app main#include \"jitpp\/arm\/ArmTranslatorFactory.h\"\n#include \"jitpp\/arm\/ArmTranslator.h\"\n#include \"jitpp\/ACState.h\"\n#include \"jitpp\/CodeCache.h\"\n\n#include \n#include \n\n#include \n\nnamespace {\n\nuint64_t *emulation_pml2[4] = \n{\n\tnullptr, nullptr, nullptr, nullptr,\n};\n\nuint64_t *emulation_pml3 = nullptr;\n\nvoid mapArmPhysicalMem()\n{\n\temulation_pml2[0] = (uint64_t*)os::mm::allocate_page();\n\temulation_pml2[1] = (uint64_t*)os::mm::allocate_page();\n\temulation_pml2[2] = (uint64_t*)os::mm::allocate_page();\n\temulation_pml2[3] = (uint64_t*)os::mm::allocate_page();\n\n\temulation_pml3 = (uint64_t*)os::mm::allocate_page();\n\n\tconst int NUM_PAGE_TABLE_ENTRIES_PER_PAGE = (4096 \/ sizeof(uint64_t));\n\n\tfor( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {\n\t\temulation_pml3[ii] = 0;\n\t}\n\n\tfor( int ii = 0; ii < NUM_PAGE_TABLE_ENTRIES_PER_PAGE; ii++ ) {\n\t\tfor( int jj = 0; jj < 4; jj++ ) {\n\t\t\tconst uint64_t PHYS_PAGE = ((2 * 1024 * 1024) * ii) + \n\t\t\t ((1 * 1024 * 1024 *1024) * jj) + \n\t\t\t 0x100000000UL;\n\t\t\temulation_pml2[jj][ii] = PHYS_PAGE | 0x83;\n\t\t}\n\t}\n\n\tfor( int ii = 0; ii < 4; ii++ ) {\n\t\tconst uint64_t pml2_phys_addr = ((uint64_t)emulation_pml2[ii]) - 0xFFFFFFFF80000000UL;\n\n\t\temulation_pml3[ii] = pml2_phys_addr | 1;\n\t}\n\n\tos::mm::set_lower_pml3(emulation_pml3, 0);\n}\n\nclass VMMCodeCacheRandomStrategy\n{\nprotected:\n\tstatic int get_rand_way( int ways ) {\n\t\treturn os::board::high_performance_timer() % ways;\n\t}\n};\n\nclass DeletionEvictionPolicy\n{\nprotected:\n\tstatic void on_item_evicted( remu::jitpp::CodePage<4096, remu::jitpp::arm::ArmTranslator> **evicted ) {\n\t\tdelete *evicted;\n\t}\n};\n\nclass NoMmuHostPageSelectionStrategy\n{\nprotected:\n\tstatic void* get_host_page( const remu::jitpp::ACFarPointer& ip ) {\n\t\treturn reinterpret_cast( ip.program_counter & ~4095 );\n\t}\n};\n\nusing Arm11CpuCodeCache = remu::jitpp::CodeCache<4,1024,4096,\n VMMCodeCacheRandomStrategy,\n DeletionEvictionPolicy,\n remu::jitpp::arm::ArmTranslatorFactory,\n remu::jitpp::arm::ArmTranslator,\n NoMmuHostPageSelectionStrategy>;\n\n} \/*anonymous namespace*\/\n\nvoid appMain()\n{\n\tmapArmPhysicalMem();\n\n\tremu::jitpp::ACState cpu_state;\n\tArm11CpuCodeCache *code_cache = new Arm11CpuCodeCache();\n\n\tcpu_state.clear();\n\tcpu_state.ip.program_counter = 0x00008000;\n\n\tbool running = true;\n\n\twhile( running ) {\n\t\tauto code_page = code_cache->getPageForFarPointer( cpu_state.ip );\n\t\tprintf(\"code_page: %p (host_page=%p guest_page=%0lx:%lx)\\n\", code_page, code_page->getHostBase(),\n\t\t cpu_state.ip.code_segment, cpu_state.ip.program_counter );\n\t\trunning = code_page->execute( cpu_state );\n\t\trunning = false;\n\t}\n}\n\n<|endoftext|>"} {"text":"\n#include \"diff_system.h\"\n#include \"libmesh_logging.h\"\n#include \"linear_solver.h\"\n#include \"newton_solver.h\"\n#include \"numeric_vector.h\"\n#include \"sparse_matrix.h\"\n\n\nNewtonSolver::NewtonSolver (sys_type& s)\n : Parent(s),\n linear_solver(LinearSolver::build())\n{\n}\n\n\n\nNewtonSolver::~NewtonSolver ()\n{\n}\n\n\n\nvoid NewtonSolver::reinit()\n{\n Parent::reinit();\n\n linear_solver->clear();\n}\n\n\n\nvoid NewtonSolver::solve()\n{\n START_LOG(\"solve()\", \"NewtonSolver\");\n\n\/\/ Reduce Newton step length to keep residual from increasing?\nconst bool require_residual_reduction = false;\n\/\/ Maximum amount by which to reduce Newton steps\nconst Real minsteplength = 0.1;\n\/\/ Amount by which nonlinear residual should exceed linear solver\n\/\/ tolerance\nconst Real relative_tolerance = 1.e-3;\n\n\n NumericVector &solution = *(_system.solution);\n NumericVector &newton_iterate =\n _system.get_vector(\"_nonlinear_solution\");\n NumericVector &rhs = *(_system.rhs);\n\n SparseMatrix &matrix = *(_system.matrix);\n\n \/\/ Prepare to take incomplete steps\n Real last_residual=0.;\n\n \/\/ Set starting linear tolerance\n Real current_linear_tolerance = initial_linear_tolerance;\n\n \/\/ Now we begin the nonlinear loop\n for (unsigned int l=0; l current_residual * relative_tolerance)\n {\n current_linear_tolerance = current_residual * relative_tolerance;\n }\n\n \/\/ But don't let it be zero\n if (current_linear_tolerance < TOLERANCE * TOLERANCE)\n {\n current_linear_tolerance = TOLERANCE * TOLERANCE;\n }\n\n \/\/ At this point newton_iterate is the current guess, and\n \/\/ solution is now about to become the NEGATIVE of the next\n \/\/ Newton step.\n\n \/\/ Our best initial guess for the solution is zero!\n solution.zero();\n\n if (!quiet)\n std::cout << \"Linear solve starting\" << std::endl;\n\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n \/\/ Solve the linear system. Two cases:\n const std::pair rval =\n (_system.have_matrix(\"Preconditioner\")) ?\n \/\/ 1.) User-supplied preconditioner\n linear_solver->solve (matrix, _system.get_matrix(\"Preconditioner\"),\n solution, rhs, current_linear_tolerance,\n max_linear_iterations) :\n \/\/ 2.) Use system matrix for the preconditioner\n linear_solver->solve (matrix, solution, rhs,\n current_linear_tolerance, \n max_linear_iterations);\n \/\/ We may need to localize a parallel solution\n _system.update ();\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n if (!quiet)\n std::cout << \"Linear solve finished, step \" << rval.first\n << \", residual \" << rval.second\n << \", tolerance \" << current_linear_tolerance\n << std::endl;\n\n \/\/ Compute the l2 norm of the nonlinear update\n Real norm_delta = solution.l2_norm();\n\n if (!quiet)\n std::cout << \"Trying full Newton step\" << std::endl;\n \/\/ Take a full Newton step\n newton_iterate.add (-1., solution);\n newton_iterate.close();\n\n \/\/ Check residual with full Newton step\n Real steplength = 1.;\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly(true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n rhs.close();\n current_residual = rhs.l2_norm();\n\n \/\/ backtrack if necessary\n if (require_residual_reduction)\n {\n while (current_residual > last_residual)\n {\n \/\/ Reduce step size to 1\/2, 1\/4, etc.\n steplength \/= 2.;\n norm_delta \/= 2.;\n if (!quiet)\n std::cout << \"Shrinking Newton step to \"\n << steplength << std::endl;\n newton_iterate.add (steplength, solution);\n newton_iterate.close();\n\n \/\/ Check residual with fractional Newton step\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly (true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n current_residual = rhs.l2_norm();\n if (!quiet)\n std::cout << \"Current Residual: \"\n << current_residual << std::endl;\n\n if (steplength\/2. < minsteplength && \n current_residual > last_residual)\n {\n if (!quiet)\n std::cout << \"Inexact Newton step FAILED at step \"\n << l << std::endl;\n\n error();\n }\n }\n }\n\n \/\/ Compute the l2 norm of the whole solution\n const Real norm_total = newton_iterate.l2_norm();\n\n max_solution_norm = std::max(max_solution_norm, norm_total);\n\n \/\/ Print out information for the \n \/\/ nonlinear iterations.\n if (!quiet)\n std::cout << \" Nonlinear step: |du|\/|u| = \"\n << norm_delta \/ norm_total\n << \", |du| = \" << norm_delta\n << std::endl;\n\n \/\/ We haven't converged unless we pass a convergence test\n bool has_converged = false;\n\n \/\/ Is our absolute residual low enough?\n if (current_residual < absolute_residual_tolerance)\n {\n if (!quiet)\n\t std::cout << \" Nonlinear solver converged, step \" << l\n << \", residual \" << current_residual\n << std::endl;\n has_converged = true;\n }\n else if (absolute_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver current_residual \"\n << current_residual << \" > \"\n\t\t << (absolute_residual_tolerance) << std::endl;\n }\n\n \/\/ Is our relative residual low enough?\n if ((current_residual \/ max_residual_norm) <\n relative_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver converged, step \" << l\n << \", residual reduction \"\n << current_residual \/ max_residual_norm\n << \" < \" << relative_residual_tolerance\n << std::endl;\n has_converged = true;\n }\n else if (relative_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver relative residual \"\n << (current_residual \/ max_residual_norm)\n << \" > \" << relative_residual_tolerance\n << std::endl;\n }\n\n \/\/ Is our absolute Newton step size small enough?\n if (norm_delta \/ steplength < absolute_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver converged, step \" << l\n << \", absolute step size \"\n << norm_delta \/ steplength\n << \" < \" << absolute_step_tolerance\n << std::endl;\n has_converged = true;\n }\n else if (absolute_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver absolute step size \"\n << (norm_delta \/ steplength)\n << \" > \" << absolute_step_tolerance\n << std::endl;\n }\n\n \/\/ Is our relative Newton step size small enough?\n if (norm_delta \/ steplength \/ max_solution_norm <\n relative_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver converged, step \" << l\n << \", relative step size \"\n << (norm_delta \/ steplength \/ max_solution_norm)\n << \" < \" << relative_step_tolerance\n << std::endl;\n has_converged = true;\n }\n else if (relative_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver relative step size \"\n << (norm_delta \/ steplength \/ max_solution_norm)\n << \" > \" << relative_step_tolerance\n << std::endl;\n }\n\n \/\/ Terminate the solution iteration if the difference between\n \/\/ this iteration and the last is sufficiently small.\n if (has_converged)\n {\n break;\n }\n if (l >= max_nonlinear_iterations - 1)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver DIVERGED at step \" << l\n << std::endl;\n error();\n continue;\n }\n } \/\/ end nonlinear loop\n\n \/\/ Copy the final nonlinear iterate into the current_solution,\n \/\/ for other libMesh functions that expect it\n\n solution = newton_iterate;\n solution.close();\n\n STOP_LOG(\"solve()\", \"NewtonSolver\");\n}\nMake sure current_local_solution is up to date\n#include \"diff_system.h\"\n#include \"libmesh_logging.h\"\n#include \"linear_solver.h\"\n#include \"newton_solver.h\"\n#include \"numeric_vector.h\"\n#include \"sparse_matrix.h\"\n\n\nNewtonSolver::NewtonSolver (sys_type& s)\n : Parent(s),\n linear_solver(LinearSolver::build())\n{\n}\n\n\n\nNewtonSolver::~NewtonSolver ()\n{\n}\n\n\n\nvoid NewtonSolver::reinit()\n{\n Parent::reinit();\n\n linear_solver->clear();\n}\n\n\n\nvoid NewtonSolver::solve()\n{\n START_LOG(\"solve()\", \"NewtonSolver\");\n\n\/\/ Reduce Newton step length to keep residual from increasing?\nconst bool require_residual_reduction = false;\n\/\/ Maximum amount by which to reduce Newton steps\nconst Real minsteplength = 0.1;\n\/\/ Amount by which nonlinear residual should exceed linear solver\n\/\/ tolerance\nconst Real relative_tolerance = 1.e-3;\n\n\n NumericVector &solution = *(_system.solution);\n NumericVector &newton_iterate =\n _system.get_vector(\"_nonlinear_solution\");\n NumericVector &rhs = *(_system.rhs);\n\n SparseMatrix &matrix = *(_system.matrix);\n\n \/\/ Prepare to take incomplete steps\n Real last_residual=0.;\n\n \/\/ Set starting linear tolerance\n Real current_linear_tolerance = initial_linear_tolerance;\n\n \/\/ Now we begin the nonlinear loop\n for (unsigned int l=0; l current_residual * relative_tolerance)\n {\n current_linear_tolerance = current_residual * relative_tolerance;\n }\n\n \/\/ But don't let it be zero\n if (current_linear_tolerance < TOLERANCE * TOLERANCE)\n {\n current_linear_tolerance = TOLERANCE * TOLERANCE;\n }\n\n \/\/ At this point newton_iterate is the current guess, and\n \/\/ solution is now about to become the NEGATIVE of the next\n \/\/ Newton step.\n\n \/\/ Our best initial guess for the solution is zero!\n solution.zero();\n\n if (!quiet)\n std::cout << \"Linear solve starting\" << std::endl;\n\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n \/\/ Solve the linear system. Two cases:\n const std::pair rval =\n (_system.have_matrix(\"Preconditioner\")) ?\n \/\/ 1.) User-supplied preconditioner\n linear_solver->solve (matrix, _system.get_matrix(\"Preconditioner\"),\n solution, rhs, current_linear_tolerance,\n max_linear_iterations) :\n \/\/ 2.) Use system matrix for the preconditioner\n linear_solver->solve (matrix, solution, rhs,\n current_linear_tolerance, \n max_linear_iterations);\n \/\/ We may need to localize a parallel solution\n _system.update ();\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n if (!quiet)\n std::cout << \"Linear solve finished, step \" << rval.first\n << \", residual \" << rval.second\n << \", tolerance \" << current_linear_tolerance\n << std::endl;\n\n \/\/ Compute the l2 norm of the nonlinear update\n Real norm_delta = solution.l2_norm();\n\n if (!quiet)\n std::cout << \"Trying full Newton step\" << std::endl;\n \/\/ Take a full Newton step\n newton_iterate.add (-1., solution);\n newton_iterate.close();\n\n \/\/ Check residual with full Newton step\n Real steplength = 1.;\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly(true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n rhs.close();\n current_residual = rhs.l2_norm();\n\n \/\/ backtrack if necessary\n if (require_residual_reduction)\n {\n while (current_residual > last_residual)\n {\n \/\/ Reduce step size to 1\/2, 1\/4, etc.\n steplength \/= 2.;\n norm_delta \/= 2.;\n if (!quiet)\n std::cout << \"Shrinking Newton step to \"\n << steplength << std::endl;\n newton_iterate.add (steplength, solution);\n newton_iterate.close();\n\n \/\/ Check residual with fractional Newton step\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly (true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n current_residual = rhs.l2_norm();\n if (!quiet)\n std::cout << \"Current Residual: \"\n << current_residual << std::endl;\n\n if (steplength\/2. < minsteplength && \n current_residual > last_residual)\n {\n if (!quiet)\n std::cout << \"Inexact Newton step FAILED at step \"\n << l << std::endl;\n\n error();\n }\n }\n }\n\n \/\/ Compute the l2 norm of the whole solution\n const Real norm_total = newton_iterate.l2_norm();\n\n max_solution_norm = std::max(max_solution_norm, norm_total);\n\n \/\/ Print out information for the \n \/\/ nonlinear iterations.\n if (!quiet)\n std::cout << \" Nonlinear step: |du|\/|u| = \"\n << norm_delta \/ norm_total\n << \", |du| = \" << norm_delta\n << std::endl;\n\n \/\/ We haven't converged unless we pass a convergence test\n bool has_converged = false;\n\n \/\/ Is our absolute residual low enough?\n if (current_residual < absolute_residual_tolerance)\n {\n if (!quiet)\n\t std::cout << \" Nonlinear solver converged, step \" << l\n << \", residual \" << current_residual\n << std::endl;\n has_converged = true;\n }\n else if (absolute_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver current_residual \"\n << current_residual << \" > \"\n\t\t << (absolute_residual_tolerance) << std::endl;\n }\n\n \/\/ Is our relative residual low enough?\n if ((current_residual \/ max_residual_norm) <\n relative_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver converged, step \" << l\n << \", residual reduction \"\n << current_residual \/ max_residual_norm\n << \" < \" << relative_residual_tolerance\n << std::endl;\n has_converged = true;\n }\n else if (relative_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver relative residual \"\n << (current_residual \/ max_residual_norm)\n << \" > \" << relative_residual_tolerance\n << std::endl;\n }\n\n \/\/ Is our absolute Newton step size small enough?\n if (norm_delta \/ steplength < absolute_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver converged, step \" << l\n << \", absolute step size \"\n << norm_delta \/ steplength\n << \" < \" << absolute_step_tolerance\n << std::endl;\n has_converged = true;\n }\n else if (absolute_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver absolute step size \"\n << (norm_delta \/ steplength)\n << \" > \" << absolute_step_tolerance\n << std::endl;\n }\n\n \/\/ Is our relative Newton step size small enough?\n if (norm_delta \/ steplength \/ max_solution_norm <\n relative_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver converged, step \" << l\n << \", relative step size \"\n << (norm_delta \/ steplength \/ max_solution_norm)\n << \" < \" << relative_step_tolerance\n << std::endl;\n has_converged = true;\n }\n else if (relative_step_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver relative step size \"\n << (norm_delta \/ steplength \/ max_solution_norm)\n << \" > \" << relative_step_tolerance\n << std::endl;\n }\n\n \/\/ Terminate the solution iteration if the difference between\n \/\/ this iteration and the last is sufficiently small.\n if (has_converged)\n {\n break;\n }\n if (l >= max_nonlinear_iterations - 1)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver DIVERGED at step \" << l\n << std::endl;\n error();\n continue;\n }\n } \/\/ end nonlinear loop\n\n \/\/ Copy the final nonlinear iterate into the current_solution,\n \/\/ for other libMesh functions that expect it\n\n solution = newton_iterate;\n solution.close();\n\n \/\/ We may need to localize a parallel solution\n _system.update ();\n\n STOP_LOG(\"solve()\", \"NewtonSolver\");\n}\n<|endoftext|>"} {"text":"\n#include \"cmath\" \/\/ For isnan(), when it's defined\n\n#include \"diff_system.h\"\n#include \"equation_systems.h\"\n#include \"libmesh_logging.h\"\n#include \"linear_solver.h\"\n#include \"newton_solver.h\"\n#include \"numeric_vector.h\"\n#include \"sparse_matrix.h\"\n#include \"dof_map.h\"\n\n\nNewtonSolver::NewtonSolver (sys_type& s)\n : Parent(s),\n require_residual_reduction(true),\n minsteplength(1e-5),\n linear_tolerance_multiplier(1e-3),\n linear_solver(LinearSolver::build())\n{\n}\n\n\n\nNewtonSolver::~NewtonSolver ()\n{\n}\n\n\n\nvoid NewtonSolver::reinit()\n{\n Parent::reinit();\n\n linear_solver->clear();\n}\n\n\n\nvoid NewtonSolver::solve()\n{\n START_LOG(\"solve()\", \"NewtonSolver\");\n\n NumericVector &solution = *(_system.solution);\n NumericVector &newton_iterate =\n _system.get_vector(\"_nonlinear_solution\");\n newton_iterate.close();\n solution.close();\n\n solution = newton_iterate;\n _system.get_dof_map().enforce_constraints_exactly(_system);\n newton_iterate = solution;\n\n NumericVector &rhs = *(_system.rhs);\n\n SparseMatrix &matrix = *(_system.matrix);\n\n \/\/ Prepare to take incomplete steps\n Real last_residual=0.;\n\n \/\/ Set starting linear tolerance\n Real current_linear_tolerance = initial_linear_tolerance;\n\n \/\/ Now we begin the nonlinear loop\n for (unsigned int l=0; l rval =\n (_system.have_matrix(\"Preconditioner\")) ?\n \/\/ 1.) User-supplied preconditioner\n linear_solver->solve (matrix, _system.get_matrix(\"Preconditioner\"),\n solution, rhs, current_linear_tolerance,\n max_linear_iterations) :\n \/\/ 2.) Use system matrix for the preconditioner\n linear_solver->solve (matrix, solution, rhs,\n current_linear_tolerance, \n max_linear_iterations);\n \/\/ We may need to localize a parallel solution\n _system.update ();\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n \/\/ The linear solver may not have fit our constraints exactly\n _system.get_dof_map().enforce_constraints_exactly(_system);\n\n const unsigned int linear_steps = rval.first;\n assert(linear_steps <= max_linear_iterations);\n const bool linear_solve_finished = \n !(linear_steps == max_linear_iterations);\n\n if (!quiet)\n std::cout << \"Linear solve finished, step \" << linear_steps\n << \", residual \" << rval.second\n << \", tolerance \" << current_linear_tolerance\n << std::endl;\n\n \/\/ Compute the l2 norm of the nonlinear update\n Real norm_delta = solution.l2_norm();\n\n if (!quiet)\n std::cout << \"Trying full Newton step\" << std::endl;\n \/\/ Take a full Newton step\n newton_iterate.add (-1., solution);\n newton_iterate.close();\n\n \/\/ Check residual with full Newton step\n Real steplength = 1.;\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly(true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n rhs.close();\n current_residual = rhs.l2_norm();\n\n \/\/ backtrack if necessary\n if (require_residual_reduction)\n {\n \/\/ but don't fiddle around if we've already converged\n if (test_convergence(current_residual, norm_delta,\n linear_solve_finished))\n {\n if (!quiet)\n\t\tprint_convergence(l, current_residual, norm_delta,\n linear_solve_finished);\n break;\n }\n\n while (current_residual > last_residual)\n {\n \/\/ Reduce step size to 1\/2, 1\/4, etc.\n steplength \/= 2.;\n norm_delta \/= 2.;\n if (!quiet)\n std::cout << \"Shrinking Newton step to \"\n << steplength << std::endl;\n newton_iterate.add (steplength, solution);\n newton_iterate.close();\n\n \/\/ Check residual with fractional Newton step\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly (true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n rhs.close();\n current_residual = rhs.l2_norm();\n if (!quiet)\n std::cout << \"Current Residual: \"\n << current_residual << std::endl;\n\n if (steplength\/2. < minsteplength && \n current_residual > last_residual)\n {\n std::cout << \"Inexact Newton step FAILED at step \"\n << l << std::endl;\n\n error();\n }\n }\n }\n\n \/\/ Compute the l2 norm of the whole solution\n norm_total = newton_iterate.l2_norm();\n\n max_solution_norm = std::max(max_solution_norm, norm_total);\n\n \/\/ Print out information for the \n \/\/ nonlinear iterations.\n if (!quiet)\n std::cout << \" Nonlinear step: |du|\/|u| = \"\n << norm_delta \/ norm_total\n << \", |du| = \" << norm_delta\n << std::endl;\n\n \/\/ Terminate the solution iteration if the difference between\n \/\/ this iteration and the last is sufficiently small.\n if (!quiet)\n print_convergence(l, current_residual,\n norm_delta \/ steplength,\n linear_solve_finished);\n if (test_convergence(current_residual, norm_delta \/ steplength,\n linear_solve_finished))\n {\n break;\n }\n if (l >= max_nonlinear_iterations - 1)\n {\n std::cout << \" Nonlinear solver FAILED TO CONVERGE by step \" << l\n << \" with norm \" << norm_total\n << std::endl;\n error();\n continue;\n }\n } \/\/ end nonlinear loop\n\n \/\/ Copy the final nonlinear iterate into the current_solution,\n \/\/ for other libMesh functions that expect it\n\n solution = newton_iterate;\n\/\/ solution.close();\n\n \/\/ The linear solver may not have fit our constraints exactly\n _system.get_dof_map().enforce_constraints_exactly(_system);\n newton_iterate = solution;\n\n \/\/ We may need to localize a parallel solution\n _system.update ();\n\n STOP_LOG(\"solve()\", \"NewtonSolver\");\n}\n\n\n\nbool NewtonSolver::test_convergence(Real current_residual,\n Real step_norm,\n bool linear_solve_finished)\n{\n \/\/ We haven't converged unless we pass a convergence test\n bool has_converged = false;\n\n \/\/ Is our absolute residual low enough?\n if (current_residual < absolute_residual_tolerance)\n has_converged = true;\n\n \/\/ Is our relative residual low enough?\n if ((current_residual \/ max_residual_norm) <\n relative_residual_tolerance)\n has_converged = true;\n\n \/\/ For incomplete linear solves, it's not safe to test step sizes\n if (!linear_solve_finished)\n return has_converged;\n\n \/\/ Is our absolute Newton step size small enough?\n if (step_norm < absolute_step_tolerance)\n has_converged = true;\n\n \/\/ Is our relative Newton step size small enough?\n if (step_norm \/ max_solution_norm <\n relative_step_tolerance)\n has_converged = true;\n\n return has_converged;\n}\n\n\nvoid NewtonSolver::print_convergence(unsigned int step_num,\n Real current_residual,\n Real step_norm,\n bool linear_solve_finished)\n{\n \/\/ Is our absolute residual low enough?\n if (current_residual < absolute_residual_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", residual \" << current_residual\n << std::endl;\n }\n else if (absolute_residual_tolerance)\n {\n std::cout << \" Nonlinear solver current_residual \"\n << current_residual << \" > \"\n << (absolute_residual_tolerance) << std::endl;\n }\n\n \/\/ Is our relative residual low enough?\n if ((current_residual \/ max_residual_norm) <\n relative_residual_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", residual reduction \"\n << current_residual \/ max_residual_norm\n << \" < \" << relative_residual_tolerance\n << std::endl;\n }\n else if (relative_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver relative residual \"\n << (current_residual \/ max_residual_norm)\n << \" > \" << relative_residual_tolerance\n << std::endl;\n }\n\n \/\/ For incomplete linear solves, it's not safe to test step sizes\n if (!linear_solve_finished)\n return;\n\n \/\/ Is our absolute Newton step size small enough?\n if (step_norm < absolute_step_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", absolute step size \"\n << step_norm\n << \" < \" << absolute_step_tolerance\n << std::endl;\n }\n else if (absolute_step_tolerance)\n {\n std::cout << \" Nonlinear solver absolute step size \"\n << step_norm\n << \" > \" << absolute_step_tolerance\n << std::endl;\n }\n\n \/\/ Is our relative Newton step size small enough?\n if (step_norm \/ max_solution_norm <\n relative_step_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", relative step size \"\n << (step_norm \/ max_solution_norm)\n << \" < \" << relative_step_tolerance\n << std::endl;\n }\n else if (relative_step_tolerance)\n {\n std::cout << \" Nonlinear solver relative step size \"\n << (step_norm \/ max_solution_norm)\n << \" > \" << relative_step_tolerance\n << std::endl;\n }\n}\nMore paranoia in parallel\n#include \"cmath\" \/\/ For isnan(), when it's defined\n\n#include \"diff_system.h\"\n#include \"equation_systems.h\"\n#include \"libmesh_logging.h\"\n#include \"linear_solver.h\"\n#include \"newton_solver.h\"\n#include \"numeric_vector.h\"\n#include \"sparse_matrix.h\"\n#include \"dof_map.h\"\n\n\nNewtonSolver::NewtonSolver (sys_type& s)\n : Parent(s),\n require_residual_reduction(true),\n minsteplength(1e-5),\n linear_tolerance_multiplier(1e-3),\n linear_solver(LinearSolver::build())\n{\n}\n\n\n\nNewtonSolver::~NewtonSolver ()\n{\n}\n\n\n\nvoid NewtonSolver::reinit()\n{\n Parent::reinit();\n\n linear_solver->clear();\n}\n\n\n\nvoid NewtonSolver::solve()\n{\n START_LOG(\"solve()\", \"NewtonSolver\");\n\n NumericVector &solution = *(_system.solution);\n NumericVector &newton_iterate =\n _system.get_vector(\"_nonlinear_solution\");\n newton_iterate.close();\n solution.close();\n\n solution = newton_iterate;\n _system.get_dof_map().enforce_constraints_exactly(_system);\n newton_iterate = solution;\n\n NumericVector &rhs = *(_system.rhs);\n\n SparseMatrix &matrix = *(_system.matrix);\n\n \/\/ Prepare to take incomplete steps\n Real last_residual=0.;\n\n \/\/ Set starting linear tolerance\n Real current_linear_tolerance = initial_linear_tolerance;\n\n \/\/ Now we begin the nonlinear loop\n for (unsigned int l=0; l rval =\n (_system.have_matrix(\"Preconditioner\")) ?\n \/\/ 1.) User-supplied preconditioner\n linear_solver->solve (matrix, _system.get_matrix(\"Preconditioner\"),\n solution, rhs, current_linear_tolerance,\n max_linear_iterations) :\n \/\/ 2.) Use system matrix for the preconditioner\n linear_solver->solve (matrix, solution, rhs,\n current_linear_tolerance, \n max_linear_iterations);\n \/\/ We may need to localize a parallel solution\n _system.update ();\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n \/\/ The linear solver may not have fit our constraints exactly\n _system.get_dof_map().enforce_constraints_exactly(_system);\n\n const unsigned int linear_steps = rval.first;\n assert(linear_steps <= max_linear_iterations);\n const bool linear_solve_finished = \n !(linear_steps == max_linear_iterations);\n\n if (!quiet)\n std::cout << \"Linear solve finished, step \" << linear_steps\n << \", residual \" << rval.second\n << \", tolerance \" << current_linear_tolerance\n << std::endl;\n\n \/\/ Compute the l2 norm of the nonlinear update\n Real norm_delta = solution.l2_norm();\n\n if (!quiet)\n std::cout << \"Trying full Newton step\" << std::endl;\n \/\/ Take a full Newton step\n newton_iterate.add (-1., solution);\n newton_iterate.close();\n\n \/\/ Check residual with full Newton step\n Real steplength = 1.;\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly(true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n rhs.close();\n current_residual = rhs.l2_norm();\n\n \/\/ backtrack if necessary\n if (require_residual_reduction)\n {\n \/\/ but don't fiddle around if we've already converged\n if (test_convergence(current_residual, norm_delta,\n linear_solve_finished))\n {\n if (!quiet)\n\t\tprint_convergence(l, current_residual, norm_delta,\n linear_solve_finished);\n break;\n }\n\n while (current_residual > last_residual)\n {\n \/\/ Reduce step size to 1\/2, 1\/4, etc.\n steplength \/= 2.;\n norm_delta \/= 2.;\n if (!quiet)\n std::cout << \"Shrinking Newton step to \"\n << steplength << std::endl;\n newton_iterate.add (steplength, solution);\n newton_iterate.close();\n\n \/\/ Check residual with fractional Newton step\n PAUSE_LOG(\"solve()\", \"NewtonSolver\");\n _system.assembly (true, false);\n RESTART_LOG(\"solve()\", \"NewtonSolver\");\n\n rhs.close();\n current_residual = rhs.l2_norm();\n if (!quiet)\n std::cout << \"Current Residual: \"\n << current_residual << std::endl;\n\n if (steplength\/2. < minsteplength && \n current_residual > last_residual)\n {\n std::cout << \"Inexact Newton step FAILED at step \"\n << l << std::endl;\n\n error();\n }\n }\n }\n\n \/\/ Compute the l2 norm of the whole solution\n norm_total = newton_iterate.l2_norm();\n\n max_solution_norm = std::max(max_solution_norm, norm_total);\n\n \/\/ Print out information for the \n \/\/ nonlinear iterations.\n if (!quiet)\n std::cout << \" Nonlinear step: |du|\/|u| = \"\n << norm_delta \/ norm_total\n << \", |du| = \" << norm_delta\n << std::endl;\n\n \/\/ Terminate the solution iteration if the difference between\n \/\/ this iteration and the last is sufficiently small.\n if (!quiet)\n print_convergence(l, current_residual,\n norm_delta \/ steplength,\n linear_solve_finished);\n if (test_convergence(current_residual, norm_delta \/ steplength,\n linear_solve_finished))\n {\n break;\n }\n if (l >= max_nonlinear_iterations - 1)\n {\n std::cout << \" Nonlinear solver FAILED TO CONVERGE by step \" << l\n << \" with norm \" << norm_total\n << std::endl;\n error();\n continue;\n }\n } \/\/ end nonlinear loop\n\n \/\/ Copy the final nonlinear iterate into the current_solution,\n \/\/ for other libMesh functions that expect it\n\n solution = newton_iterate;\n solution.close();\n\n \/\/ The linear solver may not have fit our constraints exactly\n _system.get_dof_map().enforce_constraints_exactly(_system);\n newton_iterate = solution;\n solution.close();\n\n \/\/ We may need to localize a parallel solution\n _system.update ();\n\n STOP_LOG(\"solve()\", \"NewtonSolver\");\n}\n\n\n\nbool NewtonSolver::test_convergence(Real current_residual,\n Real step_norm,\n bool linear_solve_finished)\n{\n \/\/ We haven't converged unless we pass a convergence test\n bool has_converged = false;\n\n \/\/ Is our absolute residual low enough?\n if (current_residual < absolute_residual_tolerance)\n has_converged = true;\n\n \/\/ Is our relative residual low enough?\n if ((current_residual \/ max_residual_norm) <\n relative_residual_tolerance)\n has_converged = true;\n\n \/\/ For incomplete linear solves, it's not safe to test step sizes\n if (!linear_solve_finished)\n return has_converged;\n\n \/\/ Is our absolute Newton step size small enough?\n if (step_norm < absolute_step_tolerance)\n has_converged = true;\n\n \/\/ Is our relative Newton step size small enough?\n if (step_norm \/ max_solution_norm <\n relative_step_tolerance)\n has_converged = true;\n\n return has_converged;\n}\n\n\nvoid NewtonSolver::print_convergence(unsigned int step_num,\n Real current_residual,\n Real step_norm,\n bool linear_solve_finished)\n{\n \/\/ Is our absolute residual low enough?\n if (current_residual < absolute_residual_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", residual \" << current_residual\n << std::endl;\n }\n else if (absolute_residual_tolerance)\n {\n std::cout << \" Nonlinear solver current_residual \"\n << current_residual << \" > \"\n << (absolute_residual_tolerance) << std::endl;\n }\n\n \/\/ Is our relative residual low enough?\n if ((current_residual \/ max_residual_norm) <\n relative_residual_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", residual reduction \"\n << current_residual \/ max_residual_norm\n << \" < \" << relative_residual_tolerance\n << std::endl;\n }\n else if (relative_residual_tolerance)\n {\n if (!quiet)\n std::cout << \" Nonlinear solver relative residual \"\n << (current_residual \/ max_residual_norm)\n << \" > \" << relative_residual_tolerance\n << std::endl;\n }\n\n \/\/ For incomplete linear solves, it's not safe to test step sizes\n if (!linear_solve_finished)\n return;\n\n \/\/ Is our absolute Newton step size small enough?\n if (step_norm < absolute_step_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", absolute step size \"\n << step_norm\n << \" < \" << absolute_step_tolerance\n << std::endl;\n }\n else if (absolute_step_tolerance)\n {\n std::cout << \" Nonlinear solver absolute step size \"\n << step_norm\n << \" > \" << absolute_step_tolerance\n << std::endl;\n }\n\n \/\/ Is our relative Newton step size small enough?\n if (step_norm \/ max_solution_norm <\n relative_step_tolerance)\n {\n std::cout << \" Nonlinear solver converged, step \" << step_num\n << \", relative step size \"\n << (step_norm \/ max_solution_norm)\n << \" < \" << relative_step_tolerance\n << std::endl;\n }\n else if (relative_step_tolerance)\n {\n std::cout << \" Nonlinear solver relative step size \"\n << (step_norm \/ max_solution_norm)\n << \" > \" << relative_step_tolerance\n << std::endl;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * test_RepresentationTransformation.cpp\n *\n * Created on: Nov 25, 2015\n * Author: sni\n *\/\n\n#include \n#include \n\n#include \"ice\/representation\/Representation.h\"\n#include \"ice\/representation\/GContainer.h\"\n#include \"ice\/representation\/GContainerFactory.h\"\n#include \"ice\/representation\/Transformation.h\"\n#include \"ice\/representation\/XMLTransformationReader.h\"\n\n#include \"ice\/ICEngine.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace\n{\n\nTEST(RepresentationTransformationTest, useOperation)\n{\n std::shared_ptr factory = std::make_shared();\n\n std::unique_ptr> lines(new std::vector);\n lines->push_back(\"testRep1;dim1;doubleRep\");\n lines->push_back(\"testRep1;dim2;integerRep\");\n lines->push_back(\"|\");\n lines->push_back(\"testRep2;dim1;integerRep\");\n lines->push_back(\"testRep2;dim2;doubleRep\");\n\n factory->fromCSVStrings(std::move(lines));\n\n auto rep1 = factory->getRepresentation(\"testRep1\");\n auto rep2 = factory->getRepresentation(\"testRep2\");\n\n auto dim11 = rep1->accessPath( {\"dim1\"});\n auto dim12 = rep1->accessPath( {\"dim2\"});\n auto dim21 = rep2->accessPath( {\"dim1\"});\n auto dim22 = rep2->accessPath( {\"dim2\"});\n\n const double testValDouble = 4.2f;\n const int testValInt = 358735;\n\n auto rep1Ind = factory->makeInstance(rep1);\n rep1Ind->set(dim11, &testValDouble);\n rep1Ind->set(dim12, &testValInt);\n\n EXPECT_EQ(testValDouble, *((double* ) rep1Ind->get(dim11)));\n EXPECT_EQ(testValInt, *((int* ) rep1Ind->get(dim12)));\n\n ice::Transformation trans(factory, \"TestTransformation\", rep2);\n\n ice::TransformationOperation* o;\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = dim11;\n\/\/ o.valueType = ice::BasicRepresentationType::DOUBLE;\n\/\/ o.value = ;\n o->type = ice::TransformationOperationType::USE;\n o->targetDimension = dim22;\n trans.getOperations().push_back(o);\n\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = dim12;\n\/\/ o.valueType = ice::BasicRepresentationType::DOUBLE;\n\/\/ o.value = ;\n o->type = ice::TransformationOperationType::USE;\n o->targetDimension = dim21;\n trans.getOperations().push_back(o);\n\n auto rep2Ind = trans.transform(&rep1Ind);\n\n EXPECT_EQ(testValDouble, rep2Ind->getValue(dim22));\n EXPECT_EQ(testValInt, rep2Ind->getValue(dim21));\n\n\/\/ rep1Ind->print();\n\/\/ std::cout << \"----------------------------------------------\" << std::endl;\n\/\/ rep2Ind->print();\n}\n\nTEST(RepresentationTransformationTest, defaultOperation)\n{\n std::shared_ptr factory = std::make_shared();\n\n std::unique_ptr> lines(new std::vector);\n lines->push_back(\"testRep1;dim1;doubleRep\");\n lines->push_back(\"testRep1;dim2;integerRep\");\n lines->push_back(\"|\");\n lines->push_back(\"testRep2;dim1;integerRep\");\n lines->push_back(\"testRep2;dim2;doubleRep\");\n\n factory->fromCSVStrings(std::move(lines));\n\n auto rep1 = factory->getRepresentation(\"testRep1\");\n auto rep2 = factory->getRepresentation(\"testRep2\");\n\n auto dim11 = rep1->accessPath( {\"dim1\"});\n auto dim12 = rep1->accessPath( {\"dim2\"});\n auto dim21 = rep2->accessPath( {\"dim1\"});\n auto dim22 = rep2->accessPath( {\"dim2\"});\n\n const double testValDouble = 4.2f;\n const int testValInt = 358735;\n\n auto rep1Ind = factory->makeInstance(rep1);\n rep1Ind->set(dim11, &testValDouble);\n rep1Ind->set(dim12, &testValInt);\n\n EXPECT_EQ(testValDouble, *((double* ) rep1Ind->get(dim11)));\n EXPECT_EQ(testValInt, *((int* ) rep1Ind->get(dim12)));\n\n ice::Transformation trans(factory, \"TestTransformation\", rep2);\n\n ice::TransformationOperation* o;\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = rep1->accessPath( {\"dim1\"});\n\/\/ o.valueType = ice::BasicRepresentationType::DOUBLE;\n\/\/ o.value = ;\n o->type = ice::TransformationOperationType::USE;\n o->targetDimension = rep2->accessPath( {\"dim2\"});\n trans.getOperations().push_back(o);\n\n o = new ice::TransformationOperation();\n\/\/ o.sourceIndex = 0;\n\/\/ o.sourceDimension = rep1->accessPath({\"dim2\"});\n o->valueType = ice::BasicRepresentationType::INT;\n o->value = new int(0);\n o->type = ice::TransformationOperationType::DEFAULT;\n o->targetDimension = rep2->accessPath( {\"dim1\"});\n trans.getOperations().push_back(o);\n\n auto rep2Ind = trans.transform(&rep1Ind);\n\n EXPECT_EQ(testValDouble, rep2Ind->getValue(dim22));\n EXPECT_EQ(0, rep2Ind->getValue(dim21));\n\n\/\/ rep1Ind->print();\n\/\/ std::cout << \"----------------------------------------------\" << std::endl;\n\/\/ rep2Ind->print();\n}\n\nTEST(RepresentationTransformationTest, xmlReader)\n{\n std::string path = ros::package::getPath(\"ice\");\n bool result;\n\n auto oi = std::make_shared(path + \"\/java\/lib\/\");\n oi->addIRIMapper(path + \"\/ontology\/\");\n\n ASSERT_FALSE(oi->errorOccurred());\n\n result = oi->addOntologyIRI(\"http:\/\/vs.uni-kassel.de\/IceTest\");\n\n ASSERT_FALSE(oi->errorOccurred());\n ASSERT_TRUE(result);\n\n result = oi->loadOntologies();\n\n ASSERT_FALSE(oi->errorOccurred());\n ASSERT_TRUE(result);\n\n result = oi->isConsistent();\n\n ASSERT_FALSE(oi->errorOccurred());\n ASSERT_TRUE(result);\n\n std::shared_ptr factory = std::make_shared();\n factory->setOntologyInterface(oi);\n factory->init();\n\n ice::XMLTransformationReader reader;\n\n result = reader.readFile(\"data\/transformation_example_1.xml\");\n\n ASSERT_TRUE(result);\n\n auto p2dRep = factory->getRepresentation(\"o0_Pos2D\");\n auto p3dRep = factory->getRepresentation(\"o0_Pos3D\");\n auto p3dRotRep = factory->getRepresentation(\"o0_Pos3DRot\");\n\n ASSERT_TRUE(p2dRep != false);\n ASSERT_TRUE(p3dRep != false);\n ASSERT_TRUE(p3dRotRep != false);\n\n auto p2dX = p2dRep->accessPath({\"o2_XCoordinate\"});\n auto p2dY = p2dRep->accessPath({\"o2_YCoordinate\"});\n\n auto p3dX = p3dRep->accessPath({\"o2_XCoordinate\"});\n auto p3dY = p3dRep->accessPath({\"o2_YCoordinate\"});\n auto p3dZ = p3dRep->accessPath({\"o2_ZCoordinate\"});\n\n auto p3dRotX = p3dRotRep->accessPath({\"o2_XCoordinate\"});\n auto p3dRotY = p3dRotRep->accessPath({\"o2_YCoordinate\"});\n auto p3dRotZ = p3dRotRep->accessPath({\"o2_ZCoordinate\"});\n auto p3dRotOri = p3dRotRep->accessPath({\"o2_Orientation\"});\n\n auto p3dRotOriA = p3dRotRep->accessPath({\"o2_Orientation\", \"o2_Alpha\"});\n auto p3dRotOriB = p3dRotRep->accessPath({\"o2_Orientation\", \"o2_Beta\"});\n auto p3dRotOriC = p3dRotRep->accessPath({\"o2_Orientation\", \"o2_Gamma\"});\n\n bool foundP2toP3 = false;\n bool foundP3toP2 = false;\n bool foundP3Rot = false;\n\n for (auto desc : reader.getTransformations())\n {\n auto trans = factory->fromXMLDesc(desc);\n\n ASSERT_TRUE(trans != false);\n\n if (trans->getName() == \"P2Dto3D\")\n {\n auto p2d = factory->makeInstance(p2dRep);\n\n double val1 = 3.5;\n double val2 = 35.5;\n\n p2d->set(p2dX, &val1);\n p2d->set(p2dY, &val2);\n\n auto p3d = trans->transform(&p2d);\n\n ASSERT_EQ(p3d->getValue(p3dX), val1);\n ASSERT_EQ(p3d->getValue(p3dY), val2);\n ASSERT_EQ(p3d->getValue(p3dZ), 1.0);\n\n foundP2toP3 = true;\n }\n else if (trans->getName() == \"P3Dto2D\")\n {\n auto p3d = factory->makeInstance(p3dRep);\n\n double val1 = 3.5;\n double val2 = 35.5;\n double val3 = 315.5;\n\n p3d->set(p3dX, &val1);\n p3d->set(p3dY, &val2);\n p3d->set(p3dZ, &val3);\n\n auto p2d = trans->transform(&p3d);\n\n ASSERT_EQ(p2d->getValue(p2dX), val1);\n ASSERT_EQ(p2d->getValue(p2dY), val2);\n\n foundP3toP2 = true;\n }\n else if (trans->getName() == \"TestComplex1\")\n {\n auto p3dRo1 = factory->makeInstance(p3dRotRep);\n\n double val1 = 3.5;\n double val2 = 35.5;\n double val3 = 315.5;\n\n double vala = 13.5;\n double valb = 135.5;\n double valc = 1315.5;\n\n p3dRo1->set(p3dRotX, &val1);\n p3dRo1->set(p3dRotY, &val2);\n p3dRo1->set(p3dRotZ, &val3);\n\n p3dRo1->set(p3dRotOriA, &vala);\n p3dRo1->set(p3dRotOriB, &valb);\n p3dRo1->set(p3dRotOriC, &valc);\n\n auto p3dRo2 = trans->transform(&p3dRo1);\n\n ASSERT_EQ(p3dRo2->getValue(p3dRotX), val1);\n ASSERT_EQ(p3dRo2->getValue(p3dRotY), val2);\n ASSERT_EQ(p3dRo2->getValue(p3dRotZ), val3);\n\n ASSERT_EQ(p3dRo2->getValue(p3dRotOriA), vala);\n ASSERT_EQ(p3dRo2->getValue(p3dRotOriB), valb);\n ASSERT_EQ(p3dRo2->getValue(p3dRotOriC), valc);\n\n foundP3Rot = true;\n }\n else\n {\n ASSERT_FALSE(true);\n }\n }\n\n ASSERT_TRUE(foundP2toP3);\n ASSERT_TRUE(foundP3toP2);\n ASSERT_TRUE(foundP3Rot);\n}\n\n}\n\nAdd formulaOperation test\/*\n * test_RepresentationTransformation.cpp\n *\n * Created on: Nov 25, 2015\n * Author: sni\n *\/\n\n#include \n#include \n\n#include \"ice\/representation\/Representation.h\"\n#include \"ice\/representation\/GContainer.h\"\n#include \"ice\/representation\/GContainerFactory.h\"\n#include \"ice\/representation\/Transformation.h\"\n#include \"ice\/representation\/XMLTransformationReader.h\"\n\n#include \"ice\/ICEngine.h\"\n\n#include \"gtest\/gtest.h\"\n\nnamespace\n{\n\nTEST(RepresentationTransformationTest, useOperation)\n{\n std::shared_ptr factory = std::make_shared();\n\n std::unique_ptr> lines(new std::vector);\n lines->push_back(\"testRep1;dim1;doubleRep\");\n lines->push_back(\"testRep1;dim2;integerRep\");\n lines->push_back(\"|\");\n lines->push_back(\"testRep2;dim1;integerRep\");\n lines->push_back(\"testRep2;dim2;doubleRep\");\n\n factory->fromCSVStrings(std::move(lines));\n\n auto rep1 = factory->getRepresentation(\"testRep1\");\n auto rep2 = factory->getRepresentation(\"testRep2\");\n\n auto dim11 = rep1->accessPath( {\"dim1\"});\n auto dim12 = rep1->accessPath( {\"dim2\"});\n auto dim21 = rep2->accessPath( {\"dim1\"});\n auto dim22 = rep2->accessPath( {\"dim2\"});\n\n const double testValDouble = 4.2f;\n const int testValInt = 358735;\n\n auto rep1Ind = factory->makeInstance(rep1);\n rep1Ind->set(dim11, &testValDouble);\n rep1Ind->set(dim12, &testValInt);\n\n EXPECT_EQ(testValDouble, *((double* ) rep1Ind->get(dim11)));\n EXPECT_EQ(testValInt, *((int* ) rep1Ind->get(dim12)));\n\n ice::Transformation trans(factory, \"TestTransformation\", rep2);\n\n ice::TransformationOperation* o;\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = dim11;\n\/\/ o.valueType = ice::BasicRepresentationType::DOUBLE;\n\/\/ o.value = ;\n o->type = ice::TransformationOperationType::USE;\n o->targetDimension = dim22;\n trans.getOperations().push_back(o);\n\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = dim12;\n\/\/ o.valueType = ice::BasicRepresentationType::DOUBLE;\n\/\/ o.value = ;\n o->type = ice::TransformationOperationType::USE;\n o->targetDimension = dim21;\n trans.getOperations().push_back(o);\n\n auto rep2Ind = trans.transform(&rep1Ind);\n\n EXPECT_EQ(testValDouble, rep2Ind->getValue(dim22));\n EXPECT_EQ(testValInt, rep2Ind->getValue(dim21));\n\n\/\/ rep1Ind->print();\n\/\/ std::cout << \"----------------------------------------------\" << std::endl;\n\/\/ rep2Ind->print();\n}\n\nTEST(RepresentationTransformationTest, defaultOperation)\n{\n std::shared_ptr factory = std::make_shared();\n\n std::unique_ptr> lines(new std::vector);\n lines->push_back(\"testRep1;dim1;doubleRep\");\n lines->push_back(\"testRep1;dim2;integerRep\");\n lines->push_back(\"|\");\n lines->push_back(\"testRep2;dim1;integerRep\");\n lines->push_back(\"testRep2;dim2;doubleRep\");\n\n factory->fromCSVStrings(std::move(lines));\n\n auto rep1 = factory->getRepresentation(\"testRep1\");\n auto rep2 = factory->getRepresentation(\"testRep2\");\n\n auto dim11 = rep1->accessPath( {\"dim1\"});\n auto dim12 = rep1->accessPath( {\"dim2\"});\n auto dim21 = rep2->accessPath( {\"dim1\"});\n auto dim22 = rep2->accessPath( {\"dim2\"});\n\n const double testValDouble = 4.2f;\n const int testValInt = 358735;\n\n auto rep1Ind = factory->makeInstance(rep1);\n rep1Ind->set(dim11, &testValDouble);\n rep1Ind->set(dim12, &testValInt);\n\n EXPECT_EQ(testValDouble, *((double* ) rep1Ind->get(dim11)));\n EXPECT_EQ(testValInt, *((int* ) rep1Ind->get(dim12)));\n\n ice::Transformation trans(factory, \"TestTransformation\", rep2);\n\n ice::TransformationOperation* o;\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = rep1->accessPath( {\"dim1\"});\n\/\/ o.valueType = ice::BasicRepresentationType::DOUBLE;\n\/\/ o.value = ;\n o->type = ice::TransformationOperationType::USE;\n o->targetDimension = rep2->accessPath( {\"dim2\"});\n trans.getOperations().push_back(o);\n\n o = new ice::TransformationOperation();\n\/\/ o.sourceIndex = 0;\n\/\/ o.sourceDimension = rep1->accessPath({\"dim2\"});\n o->valueType = ice::BasicRepresentationType::INT;\n o->value = new int(0);\n o->type = ice::TransformationOperationType::DEFAULT;\n o->targetDimension = rep2->accessPath( {\"dim1\"});\n trans.getOperations().push_back(o);\n\n auto rep2Ind = trans.transform(&rep1Ind);\n\n EXPECT_EQ(testValDouble, rep2Ind->getValue(dim22));\n EXPECT_EQ(0, rep2Ind->getValue(dim21));\n\n\/\/ rep1Ind->print();\n\/\/ std::cout << \"----------------------------------------------\" << std::endl;\n\/\/ rep2Ind->print();\n}\n\nTEST(RepresentationTransformationTest, formulaOperation)\n{\n std::shared_ptr factory = std::make_shared();\n\n std::unique_ptr> lines(new std::vector);\n lines->push_back(\"testRep1;dim1;doubleRep\");\n lines->push_back(\"testRep1;dim2;integerRep\");\n lines->push_back(\"|\");\n lines->push_back(\"testRep2;dim1;integerRep\");\n lines->push_back(\"testRep2;dim2;doubleRep\");\n\n factory->fromCSVStrings(std::move(lines));\n\n auto rep1 = factory->getRepresentation(\"testRep1\");\n auto rep2 = factory->getRepresentation(\"testRep2\");\n\n auto dim11 = rep1->accessPath( {\"dim1\"});\n auto dim12 = rep1->accessPath( {\"dim2\"});\n auto dim21 = rep2->accessPath( {\"dim1\"});\n auto dim22 = rep2->accessPath( {\"dim2\"});\n\n const double testValDouble = 4.2f;\n const int testValInt = 8;\n\n auto rep1Ind = factory->makeInstance(rep1);\n\n rep1Ind->set(dim11, &testValDouble);\n rep1Ind->set(dim12, &testValInt);\n\n EXPECT_EQ(testValDouble, *((double* ) rep1Ind->get(dim11)));\n EXPECT_EQ(testValInt, *((int* ) rep1Ind->get(dim12)));\n\n ice::Transformation trans(factory, \"TestSquaredTransformation\", rep2);\n ice::TransformationOperation* o;\n\n o = new ice::TransformationOperation();\n o->sourceIndex = 0;\n o->sourceDimension = rep1->accessPath( {\"dim1\"});\n o->type = ice::TransformationOperationType::FORMULA;\n o->targetDimension = rep2->accessPath( {\"dim1\"});\n trans.getOperations().push_back(o);\n\n o = new ice::TransformationOperation();\n o->sourceIndex = 1;\n o->sourceDimension = rep1->accessPath( {\"dim2\"});\n o->type = ice::TransformationOperationType::FORMULA;\n o->targetDimension = rep2->accessPath( {\"dim2\"});\n trans.getOperations().push_back(o);\n\n auto rep2Ind = trans.transform(&rep1Ind);\n\n EXPECT_EQ(testValDouble*testValDouble, rep2Ind->getValue(dim22));\n EXPECT_EQ(testValInt*testValInt, rep2Ind->getValue(dim21));\n\n}\n\nTEST(RepresentationTransformationTest, xmlReader)\n{\n std::string path = ros::package::getPath(\"ice\");\n bool result;\n\n auto oi = std::make_shared(path + \"\/java\/lib\/\");\n oi->addIRIMapper(path + \"\/ontology\/\");\n\n ASSERT_FALSE(oi->errorOccurred());\n\n result = oi->addOntologyIRI(\"http:\/\/vs.uni-kassel.de\/IceTest\");\n\n ASSERT_FALSE(oi->errorOccurred());\n ASSERT_TRUE(result);\n\n result = oi->loadOntologies();\n\n ASSERT_FALSE(oi->errorOccurred());\n ASSERT_TRUE(result);\n\n result = oi->isConsistent();\n\n ASSERT_FALSE(oi->errorOccurred());\n ASSERT_TRUE(result);\n\n std::shared_ptr factory = std::make_shared();\n factory->setOntologyInterface(oi);\n factory->init();\n\n ice::XMLTransformationReader reader;\n\n result = reader.readFile(\"data\/transformation_example_1.xml\");\n\n ASSERT_TRUE(result);\n\n auto p2dRep = factory->getRepresentation(\"o0_Pos2D\");\n auto p3dRep = factory->getRepresentation(\"o0_Pos3D\");\n auto p3dRotRep = factory->getRepresentation(\"o0_Pos3DRot\");\n\n ASSERT_TRUE(p2dRep != false);\n ASSERT_TRUE(p3dRep != false);\n ASSERT_TRUE(p3dRotRep != false);\n\n auto p2dX = p2dRep->accessPath({\"o2_XCoordinate\"});\n auto p2dY = p2dRep->accessPath({\"o2_YCoordinate\"});\n\n auto p3dX = p3dRep->accessPath({\"o2_XCoordinate\"});\n auto p3dY = p3dRep->accessPath({\"o2_YCoordinate\"});\n auto p3dZ = p3dRep->accessPath({\"o2_ZCoordinate\"});\n\n auto p3dRotX = p3dRotRep->accessPath({\"o2_XCoordinate\"});\n auto p3dRotY = p3dRotRep->accessPath({\"o2_YCoordinate\"});\n auto p3dRotZ = p3dRotRep->accessPath({\"o2_ZCoordinate\"});\n auto p3dRotOri = p3dRotRep->accessPath({\"o2_Orientation\"});\n\n auto p3dRotOriA = p3dRotRep->accessPath({\"o2_Orientation\", \"o2_Alpha\"});\n auto p3dRotOriB = p3dRotRep->accessPath({\"o2_Orientation\", \"o2_Beta\"});\n auto p3dRotOriC = p3dRotRep->accessPath({\"o2_Orientation\", \"o2_Gamma\"});\n\n bool foundP2toP3 = false;\n bool foundP3toP2 = false;\n bool foundP3Rot = false;\n\n for (auto desc : reader.getTransformations())\n {\n auto trans = factory->fromXMLDesc(desc);\n\n ASSERT_TRUE(trans != false);\n\n if (trans->getName() == \"P2Dto3D\")\n {\n auto p2d = factory->makeInstance(p2dRep);\n\n double val1 = 3.5;\n double val2 = 35.5;\n\n p2d->set(p2dX, &val1);\n p2d->set(p2dY, &val2);\n\n auto p3d = trans->transform(&p2d);\n\n ASSERT_EQ(p3d->getValue(p3dX), val1);\n ASSERT_EQ(p3d->getValue(p3dY), val2);\n ASSERT_EQ(p3d->getValue(p3dZ), 1.0);\n\n foundP2toP3 = true;\n }\n else if (trans->getName() == \"P3Dto2D\")\n {\n auto p3d = factory->makeInstance(p3dRep);\n\n double val1 = 3.5;\n double val2 = 35.5;\n double val3 = 315.5;\n\n p3d->set(p3dX, &val1);\n p3d->set(p3dY, &val2);\n p3d->set(p3dZ, &val3);\n\n auto p2d = trans->transform(&p3d);\n\n ASSERT_EQ(p2d->getValue(p2dX), val1);\n ASSERT_EQ(p2d->getValue(p2dY), val2);\n\n foundP3toP2 = true;\n }\n else if (trans->getName() == \"TestComplex1\")\n {\n auto p3dRo1 = factory->makeInstance(p3dRotRep);\n\n double val1 = 3.5;\n double val2 = 35.5;\n double val3 = 315.5;\n\n double vala = 13.5;\n double valb = 135.5;\n double valc = 1315.5;\n\n p3dRo1->set(p3dRotX, &val1);\n p3dRo1->set(p3dRotY, &val2);\n p3dRo1->set(p3dRotZ, &val3);\n\n p3dRo1->set(p3dRotOriA, &vala);\n p3dRo1->set(p3dRotOriB, &valb);\n p3dRo1->set(p3dRotOriC, &valc);\n\n auto p3dRo2 = trans->transform(&p3dRo1);\n\n ASSERT_EQ(p3dRo2->getValue(p3dRotX), val1);\n ASSERT_EQ(p3dRo2->getValue(p3dRotY), val2);\n ASSERT_EQ(p3dRo2->getValue(p3dRotZ), val3);\n\n ASSERT_EQ(p3dRo2->getValue(p3dRotOriA), vala);\n ASSERT_EQ(p3dRo2->getValue(p3dRotOriB), valb);\n ASSERT_EQ(p3dRo2->getValue(p3dRotOriC), valc);\n\n foundP3Rot = true;\n }\n else\n {\n ASSERT_FALSE(true);\n }\n }\n\n ASSERT_TRUE(foundP2toP3);\n ASSERT_TRUE(foundP3toP2);\n ASSERT_TRUE(foundP3Rot);\n}\n\n}\n\n<|endoftext|>"} {"text":"#include \"SyntaxTree.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"parser.tab.hh\"\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n Node::~Node()\n {\n }\n\n int Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n int Node::getHash(vector* referencingStack) { return 0; }\n string* Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n \/\/ list* commands;\n \/\/ string* fileName;\n \/\/ public:\n NodeKst::NodeKst(list* _commands, string* _fileName) : Node()\n {\n commands = _commands;\n fileName = _fileName;\n }\n\n int NodeKst::getType()\n {\n return CsNodeType::kst;\n }\n\n int NodeKst::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeKst::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << boost::format(TCS_HEADER) % *fileName;\n parsed << TCS_USINGS;\n\n string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n list::iterator i = commands->begin();\n list::iterator end = commands->end();\n\n string* temp;\n\n for (; i != end; ++i)\n {\n temp = (*i)->getParsed(CsParseAs::Default);\n temp = indent(temp);\n parsed << *temp;\n parsed << \"\\n\";\n }\n\n parsed << TCS_NAMESPACE_END;\n\n parsed << \"\\n\\n\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodeInclude::NodeInclude(string* _value) : Node()\n {\n value = _value;\n }\n\n int NodeInclude::getType()\n {\n return CsNodeType::include;\n }\n\n int NodeInclude::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeInclude::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << \"#include \\\"\";\n parsed << *(value);\n parsed << \"\\\"\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/ string* packetName;\n\/\/ list* packetMembers;\n\/\/ public:\n NodePacket::NodePacket(string* _packetName, list* _packetMembers) : Node()\n {\n packetName = _packetName;\n packetMembers = _packetMembers;\n }\n\n int NodePacket::getType()\n {\n return CsNodeType::packet;\n }\n\n int NodePacket::getHash(vector* referencingStack)\n {\n if (referencingStack == NULL)\n {\n referencingStack = new vector();\n }\n\n referencingStack->push_back(this);\n\n size_t packetHash = getHashCode(packetName);\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n combineHashCode(packetHash, (*i)->getHash(referencingStack));\n }\n\n return (int) packetHash;\n }\n\n string* NodePacket::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n parsed << \"\\t packet hash: \" << getHash(NULL) << \"\\n\";\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n parsed << \"\\t\" << *((*i)->getParsed(CsParseAs::Default));\n }\n parsed << TCS_PACKET_END;\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/ Node* memberType;\n\/\/ Node* memberName;\n\/\/ public:\n NodePacketMember::NodePacketMember(Node* _memberType, Node* _memberName) : Node()\n {\n memberType = _memberType;\n memberName = _memberName;\n }\n\n int NodePacketMember::getType()\n {\n return CsNodeType::packetMember;\n }\n\n int NodePacketMember::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberHash = memberType->getHash(referencingStack);\n combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n return (int) packetMemberHash;\n }\n\n string* NodePacketMember::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n % *(memberType->getParsed(CsParseAs::Default))\n % *(memberName->getParsed(CsParseAs::Default));\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/ int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/ string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/ Node* generic1; \/\/ LIST\n\/\/ Node* generic2; \/\/ MAP \n\/\/ Node* generic3; \/\/ reserved\n\/\/ public:\n NodePacketMemberType::NodePacketMemberType(int _type, string* _value) : Node()\n {\n typeType = _type;\n value = _value;\n generic1 = NULL;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1) : Node()\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2) : Node()\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node()\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = _generic3;\n }\n\n int NodePacketMemberType::getType()\n {\n return CsNodeType::packetMemberType;\n }\n\n int NodePacketMemberType::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberTypeHash = 0;\n switch(typeType)\n {\n case Rakjin::Krystal::Parser::token::PRIMITIVE_DATA_TYPE:\n packetMemberTypeHash = getHashCode(value);\n break;\n }\n\n return (int) packetMemberTypeHash;\n }\n\n string* NodePacketMemberType::getParsed(int as)\n {\n stringstream parsed;\n\n switch (typeType) {\n\n case Rakjin::Krystal::Parser::token::PRIMITIVE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Rakjin::Krystal::Parser::token::REFERENCE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Rakjin::Krystal::Parser::token::MAP:\n parsed << \"Dictionary\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n case Rakjin::Krystal::Parser::token::LIST:\n parsed << \"List\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n default:\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodePacketMemberName::NodePacketMemberName(string* _value) : Node()\n {\n value = _value;\n }\n\n int NodePacketMemberName::getType()\n {\n return CsNodeType::packetMemberName;\n }\n\n int NodePacketMemberName::getHash(vector* referencingStack)\n {\n size_t packetMemberNameHash = getHashCode(value);\n return (int) packetMemberNameHash;\n }\n\n string* NodePacketMemberName::getParsed(int as)\n {\n return value;\n }\n\/\/ };\n\n(trivial) using namespace#include \"SyntaxTree.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"parser.tab.hh\"\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\nusing namespace Rakjin::Krystal;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n Node::~Node()\n {\n }\n\n int Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n int Node::getHash(vector* referencingStack) { return 0; }\n string* Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n \/\/ list* commands;\n \/\/ string* fileName;\n \/\/ public:\n NodeKst::NodeKst(list* _commands, string* _fileName) : Node()\n {\n commands = _commands;\n fileName = _fileName;\n }\n\n int NodeKst::getType()\n {\n return CsNodeType::kst;\n }\n\n int NodeKst::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeKst::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << boost::format(TCS_HEADER) % *fileName;\n parsed << TCS_USINGS;\n\n string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n list::iterator i = commands->begin();\n list::iterator end = commands->end();\n\n string* temp;\n\n for (; i != end; ++i)\n {\n temp = (*i)->getParsed(CsParseAs::Default);\n temp = indent(temp);\n parsed << *temp;\n parsed << \"\\n\";\n }\n\n parsed << TCS_NAMESPACE_END;\n\n parsed << \"\\n\\n\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodeInclude::NodeInclude(string* _value) : Node()\n {\n value = _value;\n }\n\n int NodeInclude::getType()\n {\n return CsNodeType::include;\n }\n\n int NodeInclude::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* NodeInclude::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << \"#include \\\"\";\n parsed << *(value);\n parsed << \"\\\"\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/ string* packetName;\n\/\/ list* packetMembers;\n\/\/ public:\n NodePacket::NodePacket(string* _packetName, list* _packetMembers) : Node()\n {\n packetName = _packetName;\n packetMembers = _packetMembers;\n }\n\n int NodePacket::getType()\n {\n return CsNodeType::packet;\n }\n\n int NodePacket::getHash(vector* referencingStack)\n {\n if (referencingStack == NULL)\n {\n referencingStack = new vector();\n }\n\n referencingStack->push_back(this);\n\n size_t packetHash = getHashCode(packetName);\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n combineHashCode(packetHash, (*i)->getHash(referencingStack));\n }\n\n return (int) packetHash;\n }\n\n string* NodePacket::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n parsed << \"\\t packet hash: \" << getHash(NULL) << \"\\n\";\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n parsed << \"\\t\" << *((*i)->getParsed(CsParseAs::Default));\n }\n parsed << TCS_PACKET_END;\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/ Node* memberType;\n\/\/ Node* memberName;\n\/\/ public:\n NodePacketMember::NodePacketMember(Node* _memberType, Node* _memberName) : Node()\n {\n memberType = _memberType;\n memberName = _memberName;\n }\n\n int NodePacketMember::getType()\n {\n return CsNodeType::packetMember;\n }\n\n int NodePacketMember::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberHash = memberType->getHash(referencingStack);\n combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n return (int) packetMemberHash;\n }\n\n string* NodePacketMember::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n % *(memberType->getParsed(CsParseAs::Default))\n % *(memberName->getParsed(CsParseAs::Default));\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/ int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/ string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/ Node* generic1; \/\/ LIST\n\/\/ Node* generic2; \/\/ MAP \n\/\/ Node* generic3; \/\/ reserved\n\/\/ public:\n NodePacketMemberType::NodePacketMemberType(int _type, string* _value) : Node()\n {\n typeType = _type;\n value = _value;\n generic1 = NULL;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1) : Node()\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2) : Node()\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = NULL;\n }\n\n NodePacketMemberType::NodePacketMemberType(int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node()\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = _generic3;\n }\n\n int NodePacketMemberType::getType()\n {\n return CsNodeType::packetMemberType;\n }\n\n int NodePacketMemberType::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberTypeHash = 0;\n switch(typeType)\n {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n packetMemberTypeHash = getHashCode(value);\n break;\n }\n\n return (int) packetMemberTypeHash;\n }\n\n string* NodePacketMemberType::getParsed(int as)\n {\n stringstream parsed;\n\n switch (typeType) {\n\n case Parser::token::PRIMITIVE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n parsed << *value;\n break;\n\n case Parser::token::MAP:\n parsed << \"Dictionary\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n case Parser::token::LIST:\n parsed << \"List\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n break;\n\n default:\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n NodePacketMemberName::NodePacketMemberName(string* _value) : Node()\n {\n value = _value;\n }\n\n int NodePacketMemberName::getType()\n {\n return CsNodeType::packetMemberName;\n }\n\n int NodePacketMemberName::getHash(vector* referencingStack)\n {\n size_t packetMemberNameHash = getHashCode(value);\n return (int) packetMemberNameHash;\n }\n\n string* NodePacketMemberName::getParsed(int as)\n {\n return value;\n }\n\/\/ };\n\n<|endoftext|>"} {"text":"#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tI\/O ユーティリティー @n\n\t\t\tCopyright 2013,2016 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \n\nnamespace device {\n\n\t\/\/ RL78\n\ttypedef uint32_t address_type;\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr8_(address_type adr, uint8_t data) {\n\t\t*reinterpret_cast(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint8_t rd8_(address_type adr) {\n\t\treturn *reinterpret_cast(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr16_(address_type adr, uint16_t data) {\n\t\t*reinterpret_cast(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint16_t rd16_(address_type adr) {\n\t\treturn *reinterpret_cast(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr32_(address_type adr, uint32_t data) {\n\t\t*reinterpret_cast(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint32_t rd32_(address_type adr) {\n\t\treturn *reinterpret_cast(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct rw8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr8_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd8_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct ro8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd8_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct wo8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(uint8_t data) { wr8_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct rw16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(uint16_t data) { wr16_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic uint16_t read() { return rd16_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct ro16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic uint16_t read() { return rd16_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct wo16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(uint16_t data) { wr16_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期位置\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct bit_rw_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() >> pos) & 1;\n\t\t}\n\t\tstatic void set(bool v) {\n\t\t\tif(v) {\n\t\t\t\tT::write(T::read() | (static_cast(v) << pos));\n\t\t\t} else {\n\t\t\t\tT::write(T::read() & ~(static_cast(1) << pos));\n\t\t\t}\n\t\t}\n\n\t typename T::value_type b(bool v) const {\n\t\t\treturn v << pos;\n\t\t}\n\n\t\tvoid operator = (bool v) const { set(v); }\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct bits_rw_t {\n\t\tstatic typename T::value_type get() {\n\t\t\treturn (typename T::read() >> pos) & ((1 << len) - 1);\n\t\t}\n\t\tstatic void set(typename T::value_type v) {\n\t\t\tauto m = static_cast(((1 << len) - 1) << pos);\n\t\t\tT::write((T::read() & ~m) | (static_cast(v) << pos));\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const {\n\t\t\treturn (((1 << len) - 1) & v) << pos;\n\t\t}\n\n\t\tvoid operator = (typename T::value_type v) const { set(v); }\n\t\ttypename T::value_type operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct bit_ro_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() >> pos) & 1;\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const {\n\t\t\treturn 1 << pos;\n\t\t}\n\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 標準 Read\/Write アクセス・テンプレート\n\t\t@param[in]\tT\tアクセステンプレート\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct basic_rw_t : public T {\n\n\t\tusing T::operator =;\n\t\tusing T::operator ();\n\t\tusing T::operator |=;\n\t\tusing T::operator &=;\n\n\t\tbit_rw_t B7;\t\/\/\/< B7 アクセス\n\t\tbit_rw_t B6;\t\/\/\/< B6 アクセス\n\t\tbit_rw_t B5;\t\/\/\/< B5 アクセス\n\t\tbit_rw_t B4;\t\/\/\/< B4 アクセス\n\t\tbit_rw_t B3;\t\/\/\/< B3 アクセス\n\t\tbit_rw_t B2;\t\/\/\/< B2 アクセス\n\t\tbit_rw_t B1;\t\/\/\/< B1 アクセス\n\t\tbit_rw_t B0;\t\/\/\/< B0 アクセス\n\t};\n}\nfix bitpos enum class#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tI\/O ユーティリティー @n\n\t\t\tCopyright 2013,2016 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \n\nnamespace device {\n\n\t\/\/ RL78\n\ttypedef uint32_t address_type;\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr8_(address_type adr, uint8_t data) {\n\t\t*reinterpret_cast(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint8_t rd8_(address_type adr) {\n\t\treturn *reinterpret_cast(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr16_(address_type adr, uint16_t data) {\n\t\t*reinterpret_cast(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint16_t rd16_(address_type adr) {\n\t\treturn *reinterpret_cast(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr32_(address_type adr, uint32_t data) {\n\t\t*reinterpret_cast(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint32_t rd32_(address_type adr) {\n\t\treturn *reinterpret_cast(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct rw8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr8_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd8_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct ro8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd8_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct wo8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(uint8_t data) { wr8_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct rw16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(uint16_t data) { wr16_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic uint16_t read() { return rd16_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct ro16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic uint16_t read() { return rd16_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct wo16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(uint16_t data) { wr16_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief ビット位置定義\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tenum class bitpos : uint8_t {\n\t\tB0,\t\t\/\/\/< ビット0\n\t\tB1,\t\t\/\/\/< ビット1\n\t\tB2,\t\t\/\/\/< ビット2\n\t\tB3,\t\t\/\/\/< ビット3\n\t\tB4,\t\t\/\/\/< ビット4\n\t\tB5,\t\t\/\/\/< ビット5\n\t\tB6,\t\t\/\/\/< ビット6\n\t\tB7,\t\t\/\/\/< ビット7\n\t\tB8,\t\t\/\/\/< ビット8\n\t\tB9,\t\t\/\/\/< ビット9\n\t\tB10,\t\/\/\/< ビット10\n\t\tB11,\t\/\/\/< ビット11\n\t\tB12,\t\/\/\/< ビット12\n\t\tB13,\t\/\/\/< ビット13\n\t\tB14,\t\/\/\/< ビット14\n\t\tB15,\t\/\/\/< ビット15\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct bit_rw_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() >> static_cast(pos)) & 1;\n\t\t}\n\t\tstatic void set(bool v) {\n\t\t\tif(v) {\n\t\t\t\tT::write(T::read() | (static_cast(v) << static_cast(pos)));\n\t\t\t} else {\n\t\t\t\tT::write(T::read() & ~(static_cast(1) << static_cast(pos)));\n\t\t\t}\n\t\t}\n\n\t typename T::value_type b(bool v) const {\n\t\t\treturn v << static_cast(pos);\n\t\t}\n\n\t\tvoid operator = (bool v) const { set(v); }\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期ビット位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct bits_rw_t {\n\t\tstatic typename T::value_type get() {\n\t\t\treturn (typename T::read() >> static_cast(pos)) & ((1 << len) - 1);\n\t\t}\n\t\tstatic void set(typename T::value_type v) {\n\t\t\tauto m = static_cast(((1 << len) - 1) << static_cast(pos));\n\t\t\tT::write((T::read() & ~m) | (static_cast(v) << static_cast(pos)));\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const {\n\t\t\treturn (((1 << len) - 1) & v) << static_cast(pos);\n\t\t}\n\n\t\tvoid operator = (typename T::value_type v) const { set(v); }\n\t\ttypename T::value_type operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct bit_ro_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() >> static_cast(pos)) & 1;\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const {\n\t\t\treturn 1 << static_cast(pos);\n\t\t}\n\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 標準 Read\/Write アクセス・テンプレート\n\t\t@param[in]\tT\tアクセステンプレート\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct basic_rw_t : public T {\n\n\t\tusing T::operator =;\n\t\tusing T::operator ();\n\t\tusing T::operator |=;\n\t\tusing T::operator &=;\n\n\t\tbit_rw_t B7;\t\/\/\/< B7 アクセス\n\t\tbit_rw_t B6;\t\/\/\/< B6 アクセス\n\t\tbit_rw_t B5;\t\/\/\/< B5 アクセス\n\t\tbit_rw_t B4;\t\/\/\/< B4 アクセス\n\t\tbit_rw_t B3;\t\/\/\/< B3 アクセス\n\t\tbit_rw_t B2;\t\/\/\/< B2 アクセス\n\t\tbit_rw_t B1;\t\/\/\/< B1 アクセス\n\t\tbit_rw_t B0;\t\/\/\/< B0 アクセス\n\t};\n}\n<|endoftext|>"} {"text":"\/\/===- JITTest.cpp - Unit tests for the JIT -------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/ExecutionEngine\/JITMemoryManager.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Support\/TypeBuilder.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\n#include \"llvm\/Type.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nFunction *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {\n std::vector params;\n const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),\n params, false);\n Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);\n BasicBlock *Entry = BasicBlock::Create(M->getContext(), \"entry\", F);\n IRBuilder<> builder(Entry);\n Value *Load = builder.CreateLoad(G);\n const Type *GTy = G->getType()->getElementType();\n Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));\n builder.CreateStore(Add, G);\n builder.CreateRet(Add);\n return F;\n}\n\nclass JITTest : public testing::Test {\n protected:\n virtual void SetUp() {\n M = new Module(\"
\", Context);\n std::string Error;\n TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)\n .setErrorStr(&Error).create());\n ASSERT_TRUE(TheJIT.get() != NULL) << Error;\n }\n\n LLVMContext Context;\n Module *M; \/\/ Owned by ExecutionEngine.\n OwningPtr TheJIT;\n};\n\n\/\/ Regression test for a bug. The JIT used to allocate globals inside the same\n\/\/ memory block used for the function, and when the function code was freed,\n\/\/ the global was left in the same place. This test allocates a function\n\/\/ that uses and global, deallocates it, and then makes sure that the global\n\/\/ stays alive after that.\nTEST(JIT, GlobalInFunction) {\n LLVMContext context;\n Module *M = new Module(\"
\", context);\n ExistingModuleProvider *MP = new ExistingModuleProvider(M);\n\n JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();\n \/\/ Tell the memory manager to poison freed memory so that accessing freed\n \/\/ memory is more easily tested.\n MemMgr->setPoisonMemory(true);\n std::string Error;\n OwningPtr JIT(EngineBuilder(MP)\n .setEngineKind(EngineKind::JIT)\n .setErrorStr(&Error)\n .setJITMemoryManager(MemMgr)\n \/\/ The next line enables the fix:\n .setAllocateGVsWithCode(false)\n .create());\n ASSERT_EQ(Error, \"\");\n\n \/\/ Create a global variable.\n const Type *GTy = Type::getInt32Ty(context);\n GlobalVariable *G = new GlobalVariable(\n *M,\n GTy,\n false, \/\/ Not constant.\n GlobalValue::InternalLinkage,\n Constant::getNullValue(GTy),\n \"myglobal\");\n\n \/\/ Make a function that points to a global.\n Function *F1 = makeReturnGlobal(\"F1\", G, M);\n\n \/\/ Get the pointer to the native code to force it to JIT the function and\n \/\/ allocate space for the global.\n void (*F1Ptr)();\n \/\/ Hack to avoid ISO C++ warning about casting function pointers.\n *(void**)(void*)&F1Ptr = JIT->getPointerToFunction(F1);\n\n \/\/ Since F1 was codegen'd, a pointer to G should be available.\n int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);\n ASSERT_NE((int32_t*)NULL, GPtr);\n EXPECT_EQ(0, *GPtr);\n\n \/\/ F1() should increment G.\n F1Ptr();\n EXPECT_EQ(1, *GPtr);\n\n \/\/ Make a second function identical to the first, referring to the same\n \/\/ global.\n Function *F2 = makeReturnGlobal(\"F2\", G, M);\n \/\/ Hack to avoid ISO C++ warning about casting function pointers.\n void (*F2Ptr)();\n *(void**)(void*)&F2Ptr = JIT->getPointerToFunction(F2);\n\n \/\/ F2() should increment G.\n F2Ptr();\n EXPECT_EQ(2, *GPtr);\n\n \/\/ Deallocate F1.\n JIT->freeMachineCodeForFunction(F1);\n\n \/\/ F2() should *still* increment G.\n F2Ptr();\n EXPECT_EQ(3, *GPtr);\n}\n\nint PlusOne(int arg) {\n return arg + 1;\n}\n\nTEST_F(JITTest, FarCallToKnownFunction) {\n \/\/ x86-64 can only make direct calls to functions within 32 bits of\n \/\/ the current PC. To call anything farther away, we have to load\n \/\/ the address into a register and call through the register. The\n \/\/ current JIT does this by allocating a stub for any far call.\n \/\/ There was a bug in which the JIT tried to emit a direct call when\n \/\/ the target was already in the JIT's global mappings and lazy\n \/\/ compilation was disabled.\n\n Function *KnownFunction = Function::Create(\n TypeBuilder::get(Context),\n GlobalValue::ExternalLinkage, \"known\", M);\n TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);\n\n \/\/ int test() { return known(7); }\n Function *TestFunction = Function::Create(\n TypeBuilder::get(Context),\n GlobalValue::ExternalLinkage, \"test\", M);\n BasicBlock *Entry = BasicBlock::Create(Context, \"entry\", TestFunction);\n IRBuilder<> Builder(Entry);\n Value *result = Builder.CreateCall(\n KnownFunction,\n ConstantInt::get(TypeBuilder::get(Context), 7));\n Builder.CreateRet(result);\n\n TheJIT->EnableDlsymStubs(false);\n TheJIT->DisableLazyCompilation();\n int (*TestFunctionPtr)() = reinterpret_cast(\n (intptr_t)TheJIT->getPointerToFunction(TestFunction));\n \/\/ This used to crash in trying to call PlusOne().\n EXPECT_EQ(8, TestFunctionPtr());\n}\n\n\/\/ This code is copied from JITEventListenerTest, but it only runs once for all\n\/\/ the tests in this directory. Everything seems fine, but that's strange\n\/\/ behavior.\nclass JITEnvironment : public testing::Environment {\n virtual void SetUp() {\n \/\/ Required to create a JIT.\n InitializeNativeTarget();\n }\n};\ntesting::Environment* const jit_env =\n testing::AddGlobalTestEnvironment(new JITEnvironment);\n\n}\nFix illegal cross-type aliasing. Found by baldrick on a newer gcc.\/\/===- JITTest.cpp - Unit tests for the JIT -------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/ExecutionEngine\/JITMemoryManager.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Support\/TypeBuilder.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\n#include \"llvm\/Type.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nFunction *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {\n std::vector params;\n const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),\n params, false);\n Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);\n BasicBlock *Entry = BasicBlock::Create(M->getContext(), \"entry\", F);\n IRBuilder<> builder(Entry);\n Value *Load = builder.CreateLoad(G);\n const Type *GTy = G->getType()->getElementType();\n Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));\n builder.CreateStore(Add, G);\n builder.CreateRet(Add);\n return F;\n}\n\nclass JITTest : public testing::Test {\n protected:\n virtual void SetUp() {\n M = new Module(\"
\", Context);\n std::string Error;\n TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)\n .setErrorStr(&Error).create());\n ASSERT_TRUE(TheJIT.get() != NULL) << Error;\n }\n\n LLVMContext Context;\n Module *M; \/\/ Owned by ExecutionEngine.\n OwningPtr TheJIT;\n};\n\n\/\/ Regression test for a bug. The JIT used to allocate globals inside the same\n\/\/ memory block used for the function, and when the function code was freed,\n\/\/ the global was left in the same place. This test allocates a function\n\/\/ that uses and global, deallocates it, and then makes sure that the global\n\/\/ stays alive after that.\nTEST(JIT, GlobalInFunction) {\n LLVMContext context;\n Module *M = new Module(\"
\", context);\n ExistingModuleProvider *MP = new ExistingModuleProvider(M);\n\n JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();\n \/\/ Tell the memory manager to poison freed memory so that accessing freed\n \/\/ memory is more easily tested.\n MemMgr->setPoisonMemory(true);\n std::string Error;\n OwningPtr JIT(EngineBuilder(MP)\n .setEngineKind(EngineKind::JIT)\n .setErrorStr(&Error)\n .setJITMemoryManager(MemMgr)\n \/\/ The next line enables the fix:\n .setAllocateGVsWithCode(false)\n .create());\n ASSERT_EQ(Error, \"\");\n\n \/\/ Create a global variable.\n const Type *GTy = Type::getInt32Ty(context);\n GlobalVariable *G = new GlobalVariable(\n *M,\n GTy,\n false, \/\/ Not constant.\n GlobalValue::InternalLinkage,\n Constant::getNullValue(GTy),\n \"myglobal\");\n\n \/\/ Make a function that points to a global.\n Function *F1 = makeReturnGlobal(\"F1\", G, M);\n\n \/\/ Get the pointer to the native code to force it to JIT the function and\n \/\/ allocate space for the global.\n void (*F1Ptr)() =\n reinterpret_cast((intptr_t)JIT->getPointerToFunction(F1));\n\n \/\/ Since F1 was codegen'd, a pointer to G should be available.\n int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);\n ASSERT_NE((int32_t*)NULL, GPtr);\n EXPECT_EQ(0, *GPtr);\n\n \/\/ F1() should increment G.\n F1Ptr();\n EXPECT_EQ(1, *GPtr);\n\n \/\/ Make a second function identical to the first, referring to the same\n \/\/ global.\n Function *F2 = makeReturnGlobal(\"F2\", G, M);\n void (*F2Ptr)() =\n reinterpret_cast((intptr_t)JIT->getPointerToFunction(F2));\n\n \/\/ F2() should increment G.\n F2Ptr();\n EXPECT_EQ(2, *GPtr);\n\n \/\/ Deallocate F1.\n JIT->freeMachineCodeForFunction(F1);\n\n \/\/ F2() should *still* increment G.\n F2Ptr();\n EXPECT_EQ(3, *GPtr);\n}\n\nint PlusOne(int arg) {\n return arg + 1;\n}\n\nTEST_F(JITTest, FarCallToKnownFunction) {\n \/\/ x86-64 can only make direct calls to functions within 32 bits of\n \/\/ the current PC. To call anything farther away, we have to load\n \/\/ the address into a register and call through the register. The\n \/\/ current JIT does this by allocating a stub for any far call.\n \/\/ There was a bug in which the JIT tried to emit a direct call when\n \/\/ the target was already in the JIT's global mappings and lazy\n \/\/ compilation was disabled.\n\n Function *KnownFunction = Function::Create(\n TypeBuilder::get(Context),\n GlobalValue::ExternalLinkage, \"known\", M);\n TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);\n\n \/\/ int test() { return known(7); }\n Function *TestFunction = Function::Create(\n TypeBuilder::get(Context),\n GlobalValue::ExternalLinkage, \"test\", M);\n BasicBlock *Entry = BasicBlock::Create(Context, \"entry\", TestFunction);\n IRBuilder<> Builder(Entry);\n Value *result = Builder.CreateCall(\n KnownFunction,\n ConstantInt::get(TypeBuilder::get(Context), 7));\n Builder.CreateRet(result);\n\n TheJIT->EnableDlsymStubs(false);\n TheJIT->DisableLazyCompilation();\n int (*TestFunctionPtr)() = reinterpret_cast(\n (intptr_t)TheJIT->getPointerToFunction(TestFunction));\n \/\/ This used to crash in trying to call PlusOne().\n EXPECT_EQ(8, TestFunctionPtr());\n}\n\n\/\/ This code is copied from JITEventListenerTest, but it only runs once for all\n\/\/ the tests in this directory. Everything seems fine, but that's strange\n\/\/ behavior.\nclass JITEnvironment : public testing::Environment {\n virtual void SetUp() {\n \/\/ Required to create a JIT.\n InitializeNativeTarget();\n }\n};\ntesting::Environment* const jit_env =\n testing::AddGlobalTestEnvironment(new JITEnvironment);\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011, 2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CounterImp.h\"\n\nnamespace org\n{\nnamespace w3c\n{\nnamespace dom\n{\nnamespace bootstrap\n{\n\nnamespace {\n\nstruct AdditiveGlyph\n{\n int weight;\n char16_t* glyph;\n};\n\n\/\/ 1 4999\nAdditiveGlyph upperRoman[] =\n{\n 1000, u\"M\",\n 900, u\"CM\",\n 500, u\"D\",\n 400, u\"CD\",\n 100, u\"C\",\n 90, u\"XC\",\n 50, u\"L\",\n 40, u\"XL\",\n 10, u\"X\",\n 9, u\"IX\",\n 5, u\"V\",\n 4, u\"IV\",\n 1, u\"I\",\n 0, 0\n};\n\n\/\/ 1 4999\nAdditiveGlyph lowerRoman[] =\n{\n 1000, u\"m\",\n 900, u\"cm\",\n 500, u\"d\",\n 400, u\"cd\",\n 100, u\"c\",\n 90, u\"xc\",\n 50, u\"l\",\n 40, u\"xl\",\n 10, u\"x\",\n 9, u\"ix\",\n 5, u\"v\",\n 4, u\"iv\",\n 1, u\"i\",\n 0, 0\n};\n\nstd::u16string convertToRoman(int n, AdditiveGlyph* glyphList)\n{\n if (n < 0 || 5000 <= n)\n return toString(n);\n std::u16string value;\n for (AdditiveGlyph* i = glyphList; i->glyph; ++i) {\n int t = n \/ i->weight;\n while (0 < t--)\n value += i->glyph;\n }\n return value;\n}\n\nstd::u16string emit(int i, unsigned type)\n{\n std::u16string value;\n switch (type) {\n case CSSListStyleTypeValueImp::Decimal:\n value = toString(i);\n break;\n case CSSListStyleTypeValueImp::DecimalLeadingZero:\n value = toString(i % 100);\n if (value.length() == 1)\n value = u\"0\" + value;\n break;\n case CSSListStyleTypeValueImp::LowerAlpha:\n case CSSListStyleTypeValueImp::LowerLatin:\n value = std::u16string(1, u'a' + static_cast(i) % 26 - 1);\n break;\n case CSSListStyleTypeValueImp::UpperAlpha:\n case CSSListStyleTypeValueImp::UpperLatin:\n value = std::u16string(1, u'A' + static_cast(i) % 26 - 1);\n break;\n case CSSListStyleTypeValueImp::LowerGreek:\n \/\/ This style is only defined because CSS2.1 has it.\n \/\/ It doesn't appear to actually be used in Greek texts.\n value = std::u16string(1, u\"αβγδεζηθικλμνξοπρστυφχψω\"[static_cast(i - 1) % 24]);\n break;\n case CSSListStyleTypeValueImp::LowerRoman:\n value = convertToRoman(i, lowerRoman);\n break;\n case CSSListStyleTypeValueImp::UpperRoman:\n value = convertToRoman(i, upperRoman);\n break;\n case CSSListStyleTypeValueImp::Armenian:\n case CSSListStyleTypeValueImp::Georgian:\n default:\n value = toString(i);\n break;\n }\n return value;\n}\n\n}\n\nvoid CounterImp::reset(int number)\n{\n counters.push_back(number);\n}\n\nvoid CounterImp::increment(int number)\n{\n if (counters.empty())\n counters.push_back(0);\n counters.back() += number;\n}\n\nbool CounterImp::restore()\n{\n counters.pop_back();\n return counters.empty();\n}\n\nstd::u16string CounterImp::eval(const std::u16string& separator, unsigned type)\n{\n this->separator = separator;\n this->listStyle.setValue(type);\n if (counters.empty())\n return u\"\";\n std::u16string value;\n if (separator.empty())\n value = emit(counters.back(), type);\n else {\n for (auto i = counters.begin(); i != counters.end(); ++i) {\n if (i != counters.begin())\n value += separator;\n value += emit(*i, type);\n }\n }\n return value;\n}\n\nstd::u16string CounterImp::getIdentifier()\n{\n return identifier;\n}\n\nstd::u16string CounterImp::getListStyle()\n{\n return listStyle.getCssText();\n}\n\nstd::u16string CounterImp::getSeparator()\n{\n return separator;\n}\n\n}\n}\n}\n}\n(convertToRoman) : Fix a bug.\/*\n * Copyright 2011, 2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"CounterImp.h\"\n\nnamespace org\n{\nnamespace w3c\n{\nnamespace dom\n{\nnamespace bootstrap\n{\n\nnamespace {\n\nstruct AdditiveGlyph\n{\n int weight;\n char16_t* glyph;\n};\n\n\/\/ 1 4999\nAdditiveGlyph upperRoman[] =\n{\n 1000, u\"M\",\n 900, u\"CM\",\n 500, u\"D\",\n 400, u\"CD\",\n 100, u\"C\",\n 90, u\"XC\",\n 50, u\"L\",\n 40, u\"XL\",\n 10, u\"X\",\n 9, u\"IX\",\n 5, u\"V\",\n 4, u\"IV\",\n 1, u\"I\",\n 0, 0\n};\n\n\/\/ 1 4999\nAdditiveGlyph lowerRoman[] =\n{\n 1000, u\"m\",\n 900, u\"cm\",\n 500, u\"d\",\n 400, u\"cd\",\n 100, u\"c\",\n 90, u\"xc\",\n 50, u\"l\",\n 40, u\"xl\",\n 10, u\"x\",\n 9, u\"ix\",\n 5, u\"v\",\n 4, u\"iv\",\n 1, u\"i\",\n 0, 0\n};\n\nstd::u16string convertToRoman(int n, AdditiveGlyph* glyphList)\n{\n if (n < 0 || 5000 <= n)\n return toString(n);\n std::u16string value;\n for (AdditiveGlyph* i = glyphList; i->glyph; ++i) {\n int t = n \/ i->weight;\n if (0 < t) {\n n -= t * i->weight;\n while (0 < t--)\n value += i->glyph;\n }\n }\n return value;\n}\n\nstd::u16string emit(int i, unsigned type)\n{\n std::u16string value;\n switch (type) {\n case CSSListStyleTypeValueImp::Decimal:\n value = toString(i);\n break;\n case CSSListStyleTypeValueImp::DecimalLeadingZero:\n value = toString(i % 100);\n if (value.length() == 1)\n value = u\"0\" + value;\n break;\n case CSSListStyleTypeValueImp::LowerAlpha:\n case CSSListStyleTypeValueImp::LowerLatin:\n value = std::u16string(1, u'a' + static_cast(i) % 26 - 1);\n break;\n case CSSListStyleTypeValueImp::UpperAlpha:\n case CSSListStyleTypeValueImp::UpperLatin:\n value = std::u16string(1, u'A' + static_cast(i) % 26 - 1);\n break;\n case CSSListStyleTypeValueImp::LowerGreek:\n \/\/ This style is only defined because CSS2.1 has it.\n \/\/ It doesn't appear to actually be used in Greek texts.\n value = std::u16string(1, u\"αβγδεζηθικλμνξοπρστυφχψω\"[static_cast(i - 1) % 24]);\n break;\n case CSSListStyleTypeValueImp::LowerRoman:\n value = convertToRoman(i, lowerRoman);\n break;\n case CSSListStyleTypeValueImp::UpperRoman:\n value = convertToRoman(i, upperRoman);\n break;\n case CSSListStyleTypeValueImp::Armenian:\n case CSSListStyleTypeValueImp::Georgian:\n default:\n value = toString(i);\n break;\n }\n return value;\n}\n\n}\n\nvoid CounterImp::reset(int number)\n{\n counters.push_back(number);\n}\n\nvoid CounterImp::increment(int number)\n{\n if (counters.empty())\n counters.push_back(0);\n counters.back() += number;\n}\n\nbool CounterImp::restore()\n{\n counters.pop_back();\n return counters.empty();\n}\n\nstd::u16string CounterImp::eval(const std::u16string& separator, unsigned type)\n{\n this->separator = separator;\n this->listStyle.setValue(type);\n if (counters.empty())\n return u\"\";\n std::u16string value;\n if (separator.empty())\n value = emit(counters.back(), type);\n else {\n for (auto i = counters.begin(); i != counters.end(); ++i) {\n if (i != counters.begin())\n value += separator;\n value += emit(*i, type);\n }\n }\n return value;\n}\n\nstd::u16string CounterImp::getIdentifier()\n{\n return identifier;\n}\n\nstd::u16string CounterImp::getListStyle()\n{\n return listStyle.getCssText();\n}\n\nstd::u16string CounterImp::getSeparator()\n{\n return separator;\n}\n\n}\n}\n}\n}\n<|endoftext|>"} {"text":"#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Data\/Segmentation.hpp\"\n#include \"FAST\/Data\/PointSet.hpp\"\n#include \"FAST\/DeviceManager.hpp\"\n#include \"FAST\/Algorithms\/GaussianSmoothingFilter\/GaussianSmoothingFilter.hpp\"\n#include \"FAST\/Algorithms\/ImageGradient\/ImageGradient.hpp\"\n#include \"FAST\/Utility.hpp\"\n#include \"FAST\/SceneGraph.hpp\"\n#include \n#include \n#include \"FAST\/Algorithms\/UltrasoundVesselDetection\/UltrasoundVesselDetection.hpp\"\n#include \"FAST\/Algorithms\/ImageCropper\/ImageCropper.hpp\"\n#include \"FAST\/Algorithms\/ImageClassifier\/ImageClassifier.hpp\"\n\nnamespace fast {\n\nProcessObjectPort UltrasoundVesselDetection::getOutputSegmentationPort() {\n mCreateSegmentation = true;\n return getOutputPort(0);\n}\n\nUltrasoundVesselDetection::UltrasoundVesselDetection() {\n createInputPort(0);\n createOutputPort(0, OUTPUT_DEPENDS_ON_INPUT, 0);\n createOpenCLProgram(std::string(FAST_SOURCE_DIR) + \"Algorithms\/UltrasoundVesselDetection\/UltrasoundVesselDetection.cl\");\n mCreateSegmentation = false;\n\n\tmClassifier = ImageClassifier::New();\n\tstd::string modelFile = \"\/home\/smistad\/vessel_detection_model\/deploy.prototxt\";\n\tstd::string trainingFile = \"\/home\/smistad\/vessel_detection_model\/snapshot_iter_540.caffemodel\";\n\tstd::string meanFile = \"\/home\/smistad\/vessel_detection_model\/mean.binaryproto\";\n\t\/\/std::string modelFile = \"\/home\/smistad\/vessel_detection_model2\/deploy.prototxt\";\n\t\/\/std::string trainingFile = \"\/home\/smistad\/vessel_detection_model2\/snapshot_iter_960.caffemodel\";\n\t\/\/std::string meanFile = \"\/home\/smistad\/vessel_detection_model2\/mean.binaryproto\";\n\tmClassifier->loadModel(modelFile, trainingFile, meanFile);\n\n}\n\nstruct Candidate {\n\tfloat score;\n\tVesselCrossSection::pointer crossSection;\n};\n\nclass CandidateComparison {\n\tpublic:\n\t\tbool operator() (const Candidate& lhs, const Candidate& rhs) const {\n\t\t\treturn lhs.score < rhs.score;\n\t\t}\n};\n\nvoid UltrasoundVesselDetection::execute() {\n Image::pointer input = getStaticInputData();\n if(input->getDimensions() != 2) {\n throw Exception(\"The UltrasoundVesselDetection algorithm is only for 2D\");\n }\n\n mRuntimeManager->startRegularTimer(\"ellipse fitting\");\n \/\/ Create kernel\n OpenCLDevice::pointer device = getMainDevice();\n cl::Program program = getOpenCLProgram(device);\n cl::Kernel kernel(program, \"vesselDetection\");\n\n \/\/ Run GaussianSmoothing on input\n GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();\n filter->setInputData(input);\n filter->setMaskSize(5);\n filter->setStandardDeviation(2);\n filter->update();\n Image::pointer smoothedImage = filter->getOutputData();\n\n \/\/ Run ImageGradient on input\n ImageGradient::pointer imageGradient = ImageGradient::New();\n imageGradient->setInputConnection(filter->getOutputPort());\n imageGradient->update();\n Image::pointer gradients = imageGradient->getOutputData();\n OpenCLImageAccess::pointer inputImageAccess = input->getOpenCLImageAccess(ACCESS_READ, device);\n OpenCLImageAccess::pointer imageAccess = smoothedImage->getOpenCLImageAccess(ACCESS_READ, device);\n OpenCLImageAccess::pointer gradientAccess = gradients->getOpenCLImageAccess(ACCESS_READ, device);\n\n \/\/ Create output image\n boost::shared_array zeros(new float[input->getWidth()*input->getHeight()*4]());\n cl::Image2D result = cl::Image2D(\n device->getContext(),\n CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,\n getOpenCLImageFormat(device, CL_MEM_OBJECT_IMAGE2D, TYPE_FLOAT, 4),\n input->getWidth(), input->getHeight(),\n\t\t\t0,\n\t\t\tzeros.get()\n );\n\n \/\/ Run vessel detection kernel on smoothed image and gradient\n kernel.setArg(0, *inputImageAccess->get2DImage());\n kernel.setArg(1, *gradientAccess->get2DImage());\n kernel.setArg(2, result);\n kernel.setArg(3, input->getSpacing().x());\n\n const float minimumDepthInMM = 5;\n const float spacing = input->getSpacing().y();\n \/\/const float maximumDepthInMM = 20;\n const float maximumDepthInMM = input->getHeight()*spacing*0.85;\n int startPosY = round(minimumDepthInMM\/spacing);\n int endPosY = round(maximumDepthInMM\/spacing);\n\n \/\/ Only process every second pixel\n cl::NDRange globalSize(input->getWidth() \/ 4, (endPosY-startPosY) \/ 4);\n cl::NDRange kernelOffset(0, startPosY \/ 4);\n device->getCommandQueue().enqueueNDRangeKernel(\n kernel,\n\t\t\tkernelOffset,\n\t\t\tglobalSize,\n cl::NullRange\n );\n\n \/\/ Get result back\n boost::shared_array data(new float[input->getWidth()*input->getHeight()*4]);\n device->getCommandQueue().enqueueReadImage(\n result,\n CL_TRUE,\n createOrigoRegion(),\n createRegion(input->getWidth(),input->getHeight(),1),\n 0,0,\n data.get()\n );\n mRuntimeManager->stopRegularTimer(\"ellipse fitting\");\n mRuntimeManager->startRegularTimer(\"candidate selection\");\n\n\tAffineTransformation::pointer transform = SceneGraph::getAffineTransformationFromData(input);\n\ttransform->scale(input->getSpacing());\n\n \/\/ Find best ellipses\n\tstd::priority_queue, CandidateComparison> candidates;\n\tint startPosY2 = (startPosY \/ 4)*4;\n for(int x = 0; x < input->getWidth(); x+=4) {\n for(int y = startPosY2; y < endPosY; y+=4) {\n int i = x + y*input->getWidth();\n\n if(data[i*4] > 1.5) { \/\/ If score is higher than a threshold\n\t\t\t\tfloat posY = floor(data[i*4+3]\/input->getWidth());\n\t\t\t\tfloat posX = data[i*4+3]-posY*input->getWidth();\n\t\t\t\tVector3f voxelPosition(posX, posY, 0);\n\t\t\t\tVector3f position = transform->multiply(voxelPosition);\n\t\t\t\tVesselCrossSection::pointer crossSection = VesselCrossSection::New();\n\t\t\t\tcrossSection->create(position, voxelPosition.head(2), data[i*4+1], data[i*4+2]*data[i*4+1]);\n\t\t\t\tCandidate candidate;\n\t\t\t\tcandidate.score = data[i*4];\n\t\t\t\tcandidate.crossSection = crossSection;\n\t\t\t\tcandidates.push(candidate);\n\n }\n }\n }\n\n\tmCrossSections.clear();\n\t\/\/ Go through all candidates\n\twhile(!candidates.empty()) {\n\t\tCandidate next = candidates.top();\n\t\tcandidates.pop();\n\n\t\t\/\/ Check if valid\n\t\tbool invalid = false;\n\t\tfor(VesselCrossSection::pointer crossSection : mCrossSections) {\n\t\t\tVesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ);\n\t\t\tVector2f imageCenter = access->getImageCenterPosition();\n\t\t\tfloat majorRadius = access->getMajorRadius();\n\t\t\tVesselCrossSectionAccess::pointer access2 = next.crossSection->getAccess(ACCESS_READ);\n\t\t\tif((access2->getImageCenterPosition() - imageCenter).norm() < majorRadius) {\n\t\t\t\tinvalid = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(!invalid) {\n\t\t\tmCrossSections.push_back(next.crossSection);\n\t\t}\n\t}\n\tstd::cout << mCrossSections.size() << \" candidate vessels\" << std::endl;\n mRuntimeManager->stopRegularTimer(\"candidate selection\");\n mRuntimeManager->startRegularTimer(\"classifier\");\n\n\n Vector3ui imageSize = input->getSize();\n\n\t\/\/ Create sub images and send to classifier\n\tstd::vector subImages;\n for(int i = 0; i < std::min((int)mCrossSections.size(), 8); ++i) {\n VesselCrossSectionAccess::pointer access = mCrossSections[i]->getAccess(ACCESS_READ);\n Vector2f imageCenter = access->getImageCenterPosition();\n\n \/\/ Radius in pixels\n const float majorRadius = access->getMajorRadius();\n const float minorRadius = access->getMinorRadius();\n\t\tconst int frameSize = std::max((int)round(majorRadius), 50); \/\/ Nr if pixels to include around vessel\n\n Vector2i offset(\n round(imageCenter.x() - majorRadius) - frameSize,\n round(imageCenter.y() - minorRadius) - frameSize\n );\n Vector2ui size(\n 2*majorRadius + 2*frameSize,\n 2*minorRadius + 2*frameSize\n );\n\n \/\/ Clamp to image bounds\n if(offset.x() < 0)\n offset.x() = 0;\n if(offset.y() < 0)\n offset.y() = 0;\n if(offset.x() + size.x() > imageSize.x())\n size.x() = imageSize.x() - offset.x();\n if(offset.y() + size.y() > imageSize.y())\n size.y() = imageSize.y() - offset.y();\n\n ImageCropper::pointer cropper = ImageCropper::New();\n cropper->setInputData(input);\n cropper->setOffset(offset.cast());\n cropper->setSize(size);\n cropper->update();\n subImages.push_back(cropper->getOutputData());\n }\n\tstd::vector acceptedVessels;\n\tif(subImages.size() > 0) {\n\t\tmClassifier->setLabels({\"Not vessel\", \"Vessel\"});\n\t\tmClassifier->setInputData(subImages);\n\t\tmClassifier->update();\n\n\t\tstd::vector > classifierResult = mClassifier->getResult();\n\t\tint i = 0;\n\t\tfor(std::map res : classifierResult) {\n\t\t\tif(res[\"Vessel\"] > 0.9) {\n\t\t\t\tacceptedVessels.push_back(mCrossSections[i]);\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t}\n mRuntimeManager->stopRegularTimer(\"classifier\");\n\n if(mCreateSegmentation) {\n\t\tmRuntimeManager->startRegularTimer(\"segmentation\");\n Segmentation::pointer segmentation = getStaticOutputData(0);\n segmentation->createFromImage(input);\n\n\n OpenCLDevice::pointer device = getMainDevice();\n\n \/\/ Copy contents\n OpenCLImageAccess::pointer writeAccess = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);\n cl::Image2D* outputData = writeAccess->get2DImage();\n \/\/ Create all zero data\n boost::shared_array zeroData(new uchar[input->getWidth()*input->getHeight()]());\n device->getCommandQueue().enqueueWriteImage(\n *outputData,\n CL_TRUE,\n createOrigoRegion(),\n createRegion(input->getWidth(), input->getHeight(), 1),\n 0, 0,\n zeroData.get()\n );\n cl::Kernel kernel(program, \"createSegmentation\");\n\n for(VesselCrossSection::pointer crossSection : acceptedVessels) {\n VesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ);\n Vector2f imageCenter = access->getImageCenterPosition();\n kernel.setArg(0, *outputData);\n kernel.setArg(1, imageCenter.x());\n kernel.setArg(2, imageCenter.y());\n kernel.setArg(3, access->getMajorRadius());\n kernel.setArg(4, access->getMinorRadius());\n\n device->getCommandQueue().enqueueNDRangeKernel(\n kernel,\n cl::NullRange,\n cl::NDRange(input->getWidth(), input->getHeight()),\n cl::NullRange\n );\n }\n\t\tmRuntimeManager->stopRegularTimer(\"segmentation\");\n }\n}\n\nstd::vector UltrasoundVesselDetection::getCrossSections() {\n\treturn mCrossSections;\n}\n\n} \/\/ end namespace fast\n\nCode cleanup#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Data\/Segmentation.hpp\"\n#include \"FAST\/Data\/PointSet.hpp\"\n#include \"FAST\/DeviceManager.hpp\"\n#include \"FAST\/Algorithms\/GaussianSmoothingFilter\/GaussianSmoothingFilter.hpp\"\n#include \"FAST\/Algorithms\/ImageGradient\/ImageGradient.hpp\"\n#include \"FAST\/Utility.hpp\"\n#include \"FAST\/SceneGraph.hpp\"\n#include \n#include \n#include \"FAST\/Algorithms\/UltrasoundVesselDetection\/UltrasoundVesselDetection.hpp\"\n#include \"FAST\/Algorithms\/ImageCropper\/ImageCropper.hpp\"\n#include \"FAST\/Algorithms\/ImageClassifier\/ImageClassifier.hpp\"\n\nnamespace fast {\n\nProcessObjectPort UltrasoundVesselDetection::getOutputSegmentationPort() {\n mCreateSegmentation = true;\n return getOutputPort(0);\n}\n\nUltrasoundVesselDetection::UltrasoundVesselDetection() {\n createInputPort(0);\n createOutputPort(0, OUTPUT_DEPENDS_ON_INPUT, 0);\n createOpenCLProgram(std::string(FAST_SOURCE_DIR) + \"Algorithms\/UltrasoundVesselDetection\/UltrasoundVesselDetection.cl\");\n mCreateSegmentation = false;\n\n\tmClassifier = ImageClassifier::New();\n\tstd::string modelFile = \"\/home\/smistad\/vessel_detection_model\/deploy.prototxt\";\n\tstd::string trainingFile = \"\/home\/smistad\/vessel_detection_model\/snapshot_iter_540.caffemodel\";\n\tstd::string meanFile = \"\/home\/smistad\/vessel_detection_model\/mean.binaryproto\";\n\t\/\/std::string modelFile = \"\/home\/smistad\/vessel_detection_model2\/deploy.prototxt\";\n\t\/\/std::string trainingFile = \"\/home\/smistad\/vessel_detection_model2\/snapshot_iter_960.caffemodel\";\n\t\/\/std::string meanFile = \"\/home\/smistad\/vessel_detection_model2\/mean.binaryproto\";\n\tmClassifier->loadModel(modelFile, trainingFile, meanFile);\n\n}\n\nstruct Candidate {\n\tfloat score;\n\tVesselCrossSection::pointer crossSection;\n};\n\nclass CandidateComparison {\n\tpublic:\n\t\tbool operator() (const Candidate& lhs, const Candidate& rhs) const {\n\t\t\treturn lhs.score < rhs.score;\n\t\t}\n};\n\nvoid UltrasoundVesselDetection::execute() {\n Image::pointer input = getStaticInputData();\n if(input->getDimensions() != 2) {\n throw Exception(\"The UltrasoundVesselDetection algorithm is only for 2D\");\n }\n\n mRuntimeManager->startRegularTimer(\"ellipse fitting\");\n \/\/ Create kernel\n OpenCLDevice::pointer device = getMainDevice();\n cl::Program program = getOpenCLProgram(device);\n cl::Kernel kernel(program, \"vesselDetection\");\n\n \/\/ Run GaussianSmoothing on input\n GaussianSmoothingFilter::pointer filter = GaussianSmoothingFilter::New();\n filter->setInputData(input);\n filter->setMaskSize(5);\n filter->setStandardDeviation(2);\n filter->update();\n Image::pointer smoothedImage = filter->getOutputData();\n\n \/\/ Run ImageGradient on input\n ImageGradient::pointer imageGradient = ImageGradient::New();\n imageGradient->setInputConnection(filter->getOutputPort());\n imageGradient->update();\n Image::pointer gradients = imageGradient->getOutputData();\n OpenCLImageAccess::pointer inputImageAccess = input->getOpenCLImageAccess(ACCESS_READ, device);\n OpenCLImageAccess::pointer imageAccess = smoothedImage->getOpenCLImageAccess(ACCESS_READ, device);\n OpenCLImageAccess::pointer gradientAccess = gradients->getOpenCLImageAccess(ACCESS_READ, device);\n\n \/\/ Create output image\n boost::shared_array zeros(new float[input->getWidth()*input->getHeight()*4]());\n cl::Image2D result = cl::Image2D(\n device->getContext(),\n CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR,\n getOpenCLImageFormat(device, CL_MEM_OBJECT_IMAGE2D, TYPE_FLOAT, 4),\n input->getWidth(), input->getHeight(),\n\t\t\t0,\n\t\t\tzeros.get()\n );\n\n \/\/ Run vessel detection kernel on smoothed image and gradient\n kernel.setArg(0, *inputImageAccess->get2DImage());\n kernel.setArg(1, *gradientAccess->get2DImage());\n kernel.setArg(2, result);\n kernel.setArg(3, input->getSpacing().x());\n\n const float minimumDepthInMM = 5;\n const float spacing = input->getSpacing().y();\n \/\/const float maximumDepthInMM = 20;\n const float maximumDepthInMM = input->getHeight()*spacing*0.85;\n int startPosY = round(minimumDepthInMM\/spacing);\n int endPosY = round(maximumDepthInMM\/spacing);\n\n \/\/ Only process every second pixel\n cl::NDRange globalSize(input->getWidth() \/ 4, (endPosY-startPosY) \/ 4);\n cl::NDRange kernelOffset(0, startPosY \/ 4);\n device->getCommandQueue().enqueueNDRangeKernel(\n kernel,\n\t\t\tkernelOffset,\n\t\t\tglobalSize,\n cl::NullRange\n );\n\n \/\/ Get result back\n boost::shared_array data(new float[input->getWidth()*input->getHeight()*4]);\n device->getCommandQueue().enqueueReadImage(\n result,\n CL_TRUE,\n createOrigoRegion(),\n createRegion(input->getWidth(),input->getHeight(),1),\n 0,0,\n data.get()\n );\n mRuntimeManager->stopRegularTimer(\"ellipse fitting\");\n mRuntimeManager->startRegularTimer(\"candidate selection\");\n\n\tAffineTransformation::pointer transform = SceneGraph::getAffineTransformationFromData(input);\n\ttransform->scale(input->getSpacing());\n\n \/\/ Find best ellipses\n\tstd::priority_queue, CandidateComparison> candidates;\n\tint startPosY2 = (startPosY \/ 4)*4;\n for(int x = 0; x < input->getWidth(); x+=4) {\n for(int y = startPosY2; y < endPosY; y+=4) {\n int i = x + y*input->getWidth();\n\n if(data[i*4] > 1.5) { \/\/ If score is higher than a threshold\n\t\t\t\tfloat posY = floor(data[i*4+3]\/input->getWidth());\n\t\t\t\tfloat posX = data[i*4+3]-posY*input->getWidth();\n\t\t\t\tVector3f voxelPosition(posX, posY, 0);\n\t\t\t\tVector3f position = transform->multiply(voxelPosition);\n\t\t\t\tVesselCrossSection::pointer crossSection = VesselCrossSection::New();\n\t\t\t\tcrossSection->create(position, voxelPosition.head(2), data[i*4+1], data[i*4+2]*data[i*4+1]);\n\t\t\t\tCandidate candidate;\n\t\t\t\tcandidate.score = data[i*4];\n\t\t\t\tcandidate.crossSection = crossSection;\n\t\t\t\tcandidates.push(candidate);\n\n }\n }\n }\n\n\tmCrossSections.clear();\n\t\/\/ Go through all candidates\n\twhile(!candidates.empty()) {\n\t\tCandidate next = candidates.top();\n\t\tcandidates.pop();\n\n\t\t\/\/ Check if valid\n\t\tbool invalid = false;\n\t\tVesselCrossSectionAccess::pointer access2 = next.crossSection->getAccess(ACCESS_READ);\n\t\tVector2f candidateImageCenter = access2->getImageCenterPosition();\n\t\tfor(VesselCrossSection::pointer crossSection : mCrossSections) {\n\t\t\tVesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ);\n\t\t\tVector2f imageCenter = access->getImageCenterPosition();\n\t\t\tfloat majorRadius = access->getMajorRadius();\n\t\t\tif((candidateImageCenter - imageCenter).norm() < majorRadius) {\n\t\t\t\tinvalid = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(!invalid) {\n\t\t\tmCrossSections.push_back(next.crossSection);\n\t\t}\n\t}\n\tstd::cout << mCrossSections.size() << \" candidate vessels\" << std::endl;\n mRuntimeManager->stopRegularTimer(\"candidate selection\");\n mRuntimeManager->startRegularTimer(\"classifier\");\n\n\n Vector3ui imageSize = input->getSize();\n\n\t\/\/ Create sub images and send to classifier\n\tstd::vector subImages;\n for(int i = 0; i < std::min((int)mCrossSections.size(), 8); ++i) {\n VesselCrossSectionAccess::pointer access = mCrossSections[i]->getAccess(ACCESS_READ);\n Vector2f imageCenter = access->getImageCenterPosition();\n\n \/\/ Radius in pixels\n const float majorRadius = access->getMajorRadius();\n const float minorRadius = access->getMinorRadius();\n\t\tconst int frameSize = std::max((int)round(majorRadius), 50); \/\/ Nr if pixels to include around vessel\n\n Vector2i offset(\n round(imageCenter.x() - majorRadius) - frameSize,\n round(imageCenter.y() - minorRadius) - frameSize\n );\n Vector2ui size(\n 2*majorRadius + 2*frameSize,\n 2*minorRadius + 2*frameSize\n );\n\n \/\/ Clamp to image bounds\n if(offset.x() < 0)\n offset.x() = 0;\n if(offset.y() < 0)\n offset.y() = 0;\n if(offset.x() + size.x() > imageSize.x())\n size.x() = imageSize.x() - offset.x();\n if(offset.y() + size.y() > imageSize.y())\n size.y() = imageSize.y() - offset.y();\n\n ImageCropper::pointer cropper = ImageCropper::New();\n cropper->setInputData(input);\n cropper->setOffset(offset.cast());\n cropper->setSize(size);\n cropper->update();\n subImages.push_back(cropper->getOutputData());\n }\n\tstd::vector acceptedVessels;\n\tif(subImages.size() > 0) {\n\t\tmClassifier->setLabels({\"Not vessel\", \"Vessel\"});\n\t\tmClassifier->setInputData(subImages);\n\t\tmClassifier->update();\n\n\t\tstd::vector > classifierResult = mClassifier->getResult();\n\t\tint i = 0;\n\t\tfor(std::map res : classifierResult) {\n\t\t\tif(res[\"Vessel\"] > 0.9) {\n\t\t\t\tacceptedVessels.push_back(mCrossSections[i]);\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t}\n mRuntimeManager->stopRegularTimer(\"classifier\");\n\n if(mCreateSegmentation) {\n\t\tmRuntimeManager->startRegularTimer(\"segmentation\");\n Segmentation::pointer segmentation = getStaticOutputData(0);\n segmentation->createFromImage(input);\n\n\n OpenCLDevice::pointer device = getMainDevice();\n\n \/\/ Copy contents\n OpenCLImageAccess::pointer writeAccess = segmentation->getOpenCLImageAccess(ACCESS_READ_WRITE, device);\n cl::Image2D* outputData = writeAccess->get2DImage();\n \/\/ Create all zero data\n boost::shared_array zeroData(new uchar[input->getWidth()*input->getHeight()]());\n device->getCommandQueue().enqueueWriteImage(\n *outputData,\n CL_TRUE,\n createOrigoRegion(),\n createRegion(input->getWidth(), input->getHeight(), 1),\n 0, 0,\n zeroData.get()\n );\n cl::Kernel kernel(program, \"createSegmentation\");\n\n for(VesselCrossSection::pointer crossSection : acceptedVessels) {\n VesselCrossSectionAccess::pointer access = crossSection->getAccess(ACCESS_READ);\n Vector2f imageCenter = access->getImageCenterPosition();\n kernel.setArg(0, *outputData);\n kernel.setArg(1, imageCenter.x());\n kernel.setArg(2, imageCenter.y());\n kernel.setArg(3, access->getMajorRadius());\n kernel.setArg(4, access->getMinorRadius());\n\n device->getCommandQueue().enqueueNDRangeKernel(\n kernel,\n cl::NullRange,\n cl::NDRange(input->getWidth(), input->getHeight()),\n cl::NullRange\n );\n }\n\t\tmRuntimeManager->stopRegularTimer(\"segmentation\");\n }\n}\n\nstd::vector UltrasoundVesselDetection::getCrossSections() {\n\treturn mCrossSections;\n}\n\n} \/\/ end namespace fast\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ main.cpp\n\/\/ parsetool\n\/\/\n\/\/ Created by Andrew Hunter on 24\/09\/2011.\n\/\/ \n\/\/ Copyright (c) 2011-2012 Andrew Hunter\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy \n\/\/ of this software and associated documentation files (the \\\"Software\\\"), to \n\/\/ deal in the Software without restriction, including without limitation the \n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or \n\/\/ sell copies of the Software, and to permit persons to whom the Software is \n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS \n\/\/ IN THE SOFTWARE.\n\/\/\n\n#include \"TameParse\/TameParse.h\"\n#include \"boost_console.h\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace dfa;\nusing namespace contextfree;\nusing namespace lr;\nusing namespace tameparse;\nusing namespace language;\nusing namespace compiler;\n\nint main (int argc, const char * argv[])\n{\n \/\/ Create the console\n boost_console console(argc, argv);\n console_container cons(&console, false);\n \n try {\n \/\/ Give up if the console is set not to start\n if (!console.can_start()) {\n return 1;\n }\n \n \/\/ Startup message\n console.message_stream() << L\"TameParse \" << version::major_version << \".\" << version::minor_version << \".\" << version::revision << endl;\n console.verbose_stream() << endl;\n \n \/\/ Parse the input file\n parser_stage parserStage(cons, console.input_file());\n parserStage.compile();\n \n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n \n \/\/ The definition file should exist\n if (!parserStage.definition_file().item()) {\n console.report_error(error(error::sev_bug, console.input_file(), L\"BUG_NO_FILE_DATA\", L\"File did not produce any data\", position(-1, -1, -1)));\n return error::sev_bug;\n }\n \n \/\/ Parse any imported files\n import_stage importStage(cons, console.input_file(), parserStage.definition_file());\n importStage.compile();\n\n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n\n \/\/ Run any tests that were specified\n if (!console.get_option(L\"run-tests\").empty()) {\n test_stage tests(cons, console.input_file(), parserStage.definition_file(), &importStage);\n tests.compile();\n\n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n\n \/\/ If --run-tests is specified and no explicit options for generating an output file is supplied then stop here\n if (console.get_option(L\"output-file\").empty()\n && console.get_option(L\"start-symbol\").empty()\n && console.get_option(L\"output-language\").empty()\n && console.get_option(L\"test\").empty()\n && console.get_option(L\"show-parser\").empty()) {\n return console.exit_code();\n }\n }\n \n \/\/ Convert to grammars & NDFAs\n language_builder_stage builderStage(cons, console.input_file(), &importStage);\n builderStage.compile();\n \n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n \n \/\/ Work out the name of the language to build and the start symbols\n wstring buildLanguageName = console.get_option(L\"compile-language\");\n wstring buildClassName = console.get_option(L\"class-name\");\n vector startSymbols = console.get_option_list(L\"start-symbol\");\n wstring targetLanguage = console.get_option(L\"target-language\");\n wstring buildNamespaceName = console.get_option(L\"namespace-name\");\n position parseBlockPosition = position(-1, -1, -1);\n \n \/\/ Use the options by default\n if (console.get_option(L\"compile-language\").empty()) {\n \/\/ TODO: get information from the parser block\n \/\/ TODO: the class-name option overrides the name specified in the parser block (but gives a warning)\n \/\/ TODO: use the position of the parser block to report \n \/\/ TODO: deal with multiple parser blocks somehow (error? generate multiple classes?)\n }\n \n \/\/ If there is only one language in the original file and none specified, then we will generate that\n if (buildLanguageName.empty()) {\n int languageCount = 0;\n \n \/\/ Find all of the language blocks\n for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {\n if ((*defnBlock)->language()) {\n ++languageCount;\n if (languageCount > 1) {\n \/\/ Multiple languages: can't infer one\n buildLanguageName.clear();\n break;\n } else {\n \/\/ This is the first language: use its identifier as the language to build\n buildLanguageName = (*defnBlock)->language()->identifier();\n }\n }\n }\n \n \/\/ Tell the user about this\n if (!buildLanguageName.empty()) {\n wstringstream msg;\n msg << L\"Language name not explicitly specified: will use '\" << buildLanguageName << L\"'\";\n console.report_error(error(error::sev_info, console.input_file(), L\"INFERRED_LANGUAGE\", msg.str(), parseBlockPosition));\n }\n }\n \n \/\/ Error if there is no language specified\n if (buildLanguageName.empty()) {\n console.report_error(error(error::sev_error, console.input_file(), L\"NO_LANGUAGE_SPECIFIED\", L\"Could not determine which language block to compile\", parseBlockPosition));\n return error::sev_error;\n }\n \n \/\/ Infer the class name to use if none is specified (same as the language name)\n if (buildClassName.empty()) {\n buildClassName = buildLanguageName;\n }\n \n \/\/ Get the language that we're going to compile\n const language_block* compileLanguage = importStage.language_with_name(buildLanguageName);\n language_stage* compileLanguageStage = builderStage.language_with_name(buildLanguageName);\n if (!compileLanguage || !compileLanguageStage) {\n \/\/ The language could not be found\n wstringstream msg;\n msg << L\"Could not find the target language '\" << buildLanguageName << L\"'\";\n console.report_error(error(error::sev_error, console.input_file(), L\"MISSING_TARGET_LANGUAGE\", msg.str(), parseBlockPosition));\n return error::sev_error;\n }\n \n \/\/ Report any unused symbols in the language\n compileLanguageStage->report_unused_symbols();\n \n \/\/ Infer the start symbols if there are none\n if (startSymbols.empty()) {\n \/\/ TODO: Use the first nonterminal defined in the language block\n \/\/ TODO: warn if we establish a start symbol this way\n }\n \n if (startSymbols.empty()) {\n \/\/ Error if we can't find any start symbols at all\n console.report_error(error(error::sev_error, console.input_file(), L\"NO_START_SYMBOLS\", L\"Could not determine a start symbol for the language (use the start-symbol option to specify one manually)\", parseBlockPosition));\n return error::sev_error;\n }\n \n \/\/ Generate the lexer for the target language\n lexer_stage lexerStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage);\n lexerStage.compile();\n\n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n\n \/\/ Generate the parser\n lr_parser_stage lrParserStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage, &lexerStage, startSymbols);\n lrParserStage.compile();\n \n \/\/ Write the parser out if requested\n if (!console.get_option(L\"show-parser\").empty() || !console.get_option(L\"show-parser-closure\").empty()) {\n wcout << endl << L\"== Parser tables:\" << endl << formatter::to_string(*lrParserStage.get_parser(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals(), !console.get_option(L\"show-parser-closure\").empty()) << endl;\n }\n\n \/\/ Display the propagation tables if requested\n if (!console.get_option(L\"show-propagation\").empty()) {\n \/\/ Get the parser builder\n lalr_builder* builder = lrParserStage.get_parser();\n typedef lalr_builder::lr_item_id lr_item_id;\n\n if (builder) {\n \/\/ Write out a header\n wcout << endl << L\"== Symbol propagation:\" << endl;\n\n \/\/ Iterate through the states\n for (int stateId = 0; stateId < builder->machine().count_states(); stateId++) {\n const lalr_state& state = *builder->machine().state_with_id(stateId);\n\n \/\/ Write out the state ID\n wcout << L\"State #\" << stateId << endl;\n\n \/\/ Go through the items\n for (int itemId = 0; itemId < state.count_items(); itemId++) {\n \/\/ Get the spontaneous lookahead generation for this item\n const set& spontaneous = builder->spontaneous_for_item(stateId, itemId);\n const set& propagate = builder->propagations_for_item(stateId, itemId);\n\n \/\/ Ignore any items that have no items in them\n if (spontaneous.empty() && propagate.empty()) continue;\n\n wcout << L\" \" \n << formatter::to_string(*state[itemId], *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) \n << L\" \" << formatter::to_string(state.lookahead_for(itemId), *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << endl;\n\n \/\/ Write out which items generate spontaneous lookaheads\n for (set::const_iterator spont = spontaneous.begin(); spont != spontaneous.end(); spont++) {\n const item_set& lookahead = builder->lookahead_for_spontaneous(stateId, itemId, spont->state_id, spont->item_id);\n\n wcout << L\" Spontaneous -> state #\" << spont->state_id << \": \" \n << formatter::to_string(*(*builder->machine().state_with_id(spont->state_id))[spont->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << L\" \" << formatter::to_string(lookahead, *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << endl;\n }\n\n \/\/ Write out which items propagate lookaheads\n for (set::const_iterator prop = propagate.begin(); prop != propagate.end(); prop++) {\n wcout << L\" Propagate -> state #\" << prop->state_id << \": \" \n << formatter::to_string(*(*builder->machine().state_with_id(prop->state_id))[prop->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << endl;\n }\n }\n }\n }\n }\n \n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n \n \/\/ The --test option sets the target language to 'test'\n if (!console.get_option(L\"test\").empty()) {\n targetLanguage = L\"test\";\n }\n \n \/\/ Target language is C++ if no language is specified\n if (targetLanguage.empty()) {\n targetLanguage = L\"cplusplus\";\n }\n \n \/\/ Work out the prefix filename\n wstring prefixFilename = console.get_option(L\"output-language\");\n if (prefixFilename.empty()) {\n \/\/ Derive from the input file\n \/\/ This works provided the target language \n prefixFilename = console.input_file();\n }\n \n \/\/ Create the output stage \n auto_ptr outputStage(NULL);\n \n if (targetLanguage == L\"cplusplus\") {\n \/\/ Use the C++ language generator\n outputStage = auto_ptr(new output_cplusplus(cons, importStage.file_with_language(buildLanguageName), &lexerStage, compileLanguageStage, &lrParserStage, prefixFilename, buildClassName, buildNamespaceName));\n } else if (targetLanguage == L\"test\") {\n \/\/ Special case: read from stdin, and try to parse the source language\n ast_parser parser(*lrParserStage.get_tables());\n \n \/\/ Create the parser\n lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);\n ast_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));\n \n \/\/ Parse stdin\n if (stdInParser->parse()) {\n console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;\n } else {\n position failPos(-1, -1, -1);\n if (stdInParser->look().item()) {\n failPos = stdInParser->look()->pos();\n }\n \n console.report_error(error(error::sev_error, L\"stdin\", L\"TEST_PARSER_ERROR\", L\"Syntax error\", failPos));\n }\n } else {\n \/\/ Unknown target language\n wstringstream msg;\n msg << L\"Output language '\" << targetLanguage << L\"' is not known\";\n console.report_error(error(error::sev_error, console.input_file(), L\"UNKNOWN_OUTPUT_LANGUAGE_TYPE\", msg.str(), position(-1, -1, -1)));\n return error::sev_error;\n }\n \n \/\/ Compile the final output\n if (outputStage.get()) {\n outputStage->compile();\n }\n \n \/\/ Done\n return console.exit_code();\n } catch (...) {\n console.report_error(error(error::sev_bug, L\"\", L\"BUG_UNCAUGHT_EXCEPTION\", L\"Uncaught exception\", position(-1, -1, -1)));\n throw;\n }\n}\n\nFixed an issue with the way the target language is parsed. Added a new 'fake' language which runs tests using the parser in diagnostic mode.\/\/\n\/\/ main.cpp\n\/\/ parsetool\n\/\/\n\/\/ Created by Andrew Hunter on 24\/09\/2011.\n\/\/ \n\/\/ Copyright (c) 2011-2012 Andrew Hunter\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy \n\/\/ of this software and associated documentation files (the \\\"Software\\\"), to \n\/\/ deal in the Software without restriction, including without limitation the \n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or \n\/\/ sell copies of the Software, and to permit persons to whom the Software is \n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS \n\/\/ IN THE SOFTWARE.\n\/\/\n\n#include \"TameParse\/TameParse.h\"\n#include \"boost_console.h\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace util;\nusing namespace dfa;\nusing namespace contextfree;\nusing namespace lr;\nusing namespace tameparse;\nusing namespace language;\nusing namespace compiler;\n\nint main (int argc, const char * argv[])\n{\n \/\/ Create the console\n boost_console console(argc, argv);\n console_container cons(&console, false);\n \n try {\n \/\/ Give up if the console is set not to start\n if (!console.can_start()) {\n return 1;\n }\n \n \/\/ Startup message\n console.message_stream() << L\"TameParse \" << version::major_version << \".\" << version::minor_version << \".\" << version::revision << endl;\n console.verbose_stream() << endl;\n \n \/\/ Parse the input file\n parser_stage parserStage(cons, console.input_file());\n parserStage.compile();\n \n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n \n \/\/ The definition file should exist\n if (!parserStage.definition_file().item()) {\n console.report_error(error(error::sev_bug, console.input_file(), L\"BUG_NO_FILE_DATA\", L\"File did not produce any data\", position(-1, -1, -1)));\n return error::sev_bug;\n }\n \n \/\/ Parse any imported files\n import_stage importStage(cons, console.input_file(), parserStage.definition_file());\n importStage.compile();\n\n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n\n \/\/ Run any tests that were specified\n if (!console.get_option(L\"run-tests\").empty()) {\n test_stage tests(cons, console.input_file(), parserStage.definition_file(), &importStage);\n tests.compile();\n\n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n\n \/\/ If --run-tests is specified and no explicit options for generating an output file is supplied then stop here\n if (console.get_option(L\"output-file\").empty()\n && console.get_option(L\"start-symbol\").empty()\n && console.get_option(L\"output-language\").empty()\n && console.get_option(L\"test\").empty()\n && console.get_option(L\"show-parser\").empty()) {\n return console.exit_code();\n }\n }\n \n \/\/ Convert to grammars & NDFAs\n language_builder_stage builderStage(cons, console.input_file(), &importStage);\n builderStage.compile();\n \n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n \n \/\/ Work out the name of the language to build and the start symbols\n wstring buildLanguageName = console.get_option(L\"compile-language\");\n wstring buildClassName = console.get_option(L\"class-name\");\n vector startSymbols = console.get_option_list(L\"start-symbol\");\n wstring targetLanguage = console.get_option(L\"output-language\");\n wstring buildNamespaceName = console.get_option(L\"namespace-name\");\n position parseBlockPosition = position(-1, -1, -1);\n \n \/\/ Use the options by default\n if (console.get_option(L\"compile-language\").empty()) {\n \/\/ TODO: get information from the parser block\n \/\/ TODO: the class-name option overrides the name specified in the parser block (but gives a warning)\n \/\/ TODO: use the position of the parser block to report \n \/\/ TODO: deal with multiple parser blocks somehow (error? generate multiple classes?)\n }\n \n \/\/ If there is only one language in the original file and none specified, then we will generate that\n if (buildLanguageName.empty()) {\n int languageCount = 0;\n \n \/\/ Find all of the language blocks\n for (definition_file::iterator defnBlock = parserStage.definition_file()->begin(); defnBlock != parserStage.definition_file()->end(); ++defnBlock) {\n if ((*defnBlock)->language()) {\n ++languageCount;\n if (languageCount > 1) {\n \/\/ Multiple languages: can't infer one\n buildLanguageName.clear();\n break;\n } else {\n \/\/ This is the first language: use its identifier as the language to build\n buildLanguageName = (*defnBlock)->language()->identifier();\n }\n }\n }\n \n \/\/ Tell the user about this\n if (!buildLanguageName.empty()) {\n wstringstream msg;\n msg << L\"Language name not explicitly specified: will use '\" << buildLanguageName << L\"'\";\n console.report_error(error(error::sev_info, console.input_file(), L\"INFERRED_LANGUAGE\", msg.str(), parseBlockPosition));\n }\n }\n \n \/\/ Error if there is no language specified\n if (buildLanguageName.empty()) {\n console.report_error(error(error::sev_error, console.input_file(), L\"NO_LANGUAGE_SPECIFIED\", L\"Could not determine which language block to compile\", parseBlockPosition));\n return error::sev_error;\n }\n \n \/\/ Infer the class name to use if none is specified (same as the language name)\n if (buildClassName.empty()) {\n buildClassName = buildLanguageName;\n }\n \n \/\/ Get the language that we're going to compile\n const language_block* compileLanguage = importStage.language_with_name(buildLanguageName);\n language_stage* compileLanguageStage = builderStage.language_with_name(buildLanguageName);\n if (!compileLanguage || !compileLanguageStage) {\n \/\/ The language could not be found\n wstringstream msg;\n msg << L\"Could not find the target language '\" << buildLanguageName << L\"'\";\n console.report_error(error(error::sev_error, console.input_file(), L\"MISSING_TARGET_LANGUAGE\", msg.str(), parseBlockPosition));\n return error::sev_error;\n }\n \n \/\/ Report any unused symbols in the language\n compileLanguageStage->report_unused_symbols();\n \n \/\/ Infer the start symbols if there are none\n if (startSymbols.empty()) {\n \/\/ TODO: Use the first nonterminal defined in the language block\n \/\/ TODO: warn if we establish a start symbol this way\n }\n \n if (startSymbols.empty()) {\n \/\/ Error if we can't find any start symbols at all\n console.report_error(error(error::sev_error, console.input_file(), L\"NO_START_SYMBOLS\", L\"Could not determine a start symbol for the language (use the start-symbol option to specify one manually)\", parseBlockPosition));\n return error::sev_error;\n }\n \n \/\/ Generate the lexer for the target language\n lexer_stage lexerStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage);\n lexerStage.compile();\n\n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n\n \/\/ Generate the parser\n lr_parser_stage lrParserStage(cons, importStage.file_with_language(buildLanguageName), compileLanguageStage, &lexerStage, startSymbols);\n lrParserStage.compile();\n \n \/\/ Write the parser out if requested\n if (!console.get_option(L\"show-parser\").empty() || !console.get_option(L\"show-parser-closure\").empty()) {\n wcout << endl << L\"== Parser tables:\" << endl << formatter::to_string(*lrParserStage.get_parser(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals(), !console.get_option(L\"show-parser-closure\").empty()) << endl;\n }\n\n \/\/ Display the propagation tables if requested\n if (!console.get_option(L\"show-propagation\").empty()) {\n \/\/ Get the parser builder\n lalr_builder* builder = lrParserStage.get_parser();\n typedef lalr_builder::lr_item_id lr_item_id;\n\n if (builder) {\n \/\/ Write out a header\n wcout << endl << L\"== Symbol propagation:\" << endl;\n\n \/\/ Iterate through the states\n for (int stateId = 0; stateId < builder->machine().count_states(); stateId++) {\n const lalr_state& state = *builder->machine().state_with_id(stateId);\n\n \/\/ Write out the state ID\n wcout << L\"State #\" << stateId << endl;\n\n \/\/ Go through the items\n for (int itemId = 0; itemId < state.count_items(); itemId++) {\n \/\/ Get the spontaneous lookahead generation for this item\n const set& spontaneous = builder->spontaneous_for_item(stateId, itemId);\n const set& propagate = builder->propagations_for_item(stateId, itemId);\n\n \/\/ Ignore any items that have no items in them\n if (spontaneous.empty() && propagate.empty()) continue;\n\n wcout << L\" \" \n << formatter::to_string(*state[itemId], *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) \n << L\" \" << formatter::to_string(state.lookahead_for(itemId), *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << endl;\n\n \/\/ Write out which items generate spontaneous lookaheads\n for (set::const_iterator spont = spontaneous.begin(); spont != spontaneous.end(); spont++) {\n const item_set& lookahead = builder->lookahead_for_spontaneous(stateId, itemId, spont->state_id, spont->item_id);\n\n wcout << L\" Spontaneous -> state #\" << spont->state_id << \": \" \n << formatter::to_string(*(*builder->machine().state_with_id(spont->state_id))[spont->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << L\" \" << formatter::to_string(lookahead, *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << endl;\n }\n\n \/\/ Write out which items propagate lookaheads\n for (set::const_iterator prop = propagate.begin(); prop != propagate.end(); prop++) {\n wcout << L\" Propagate -> state #\" << prop->state_id << \": \" \n << formatter::to_string(*(*builder->machine().state_with_id(prop->state_id))[prop->item_id], *compileLanguageStage->grammar(), *compileLanguageStage->terminals())\n << endl;\n }\n }\n }\n }\n }\n \n \/\/ Stop if we have an error\n if (console.exit_code()) {\n return console.exit_code();\n }\n \n \/\/ The --test option sets the target language to 'test'\n if (!console.get_option(L\"test\").empty()) {\n targetLanguage = L\"test\";\n }\n \n \/\/ Target language is C++ if no language is specified\n if (targetLanguage.empty()) {\n targetLanguage = L\"cplusplus\";\n }\n \n \/\/ Work out the prefix filename\n wstring prefixFilename = console.get_option(L\"output-language\");\n if (prefixFilename.empty()) {\n \/\/ Derive from the input file\n \/\/ This works provided the target language \n prefixFilename = console.input_file();\n }\n \n \/\/ Create the output stage \n auto_ptr outputStage(NULL);\n \n if (targetLanguage == L\"cplusplus\") {\n \/\/ Use the C++ language generator\n outputStage = auto_ptr(new output_cplusplus(cons, importStage.file_with_language(buildLanguageName), &lexerStage, compileLanguageStage, &lrParserStage, prefixFilename, buildClassName, buildNamespaceName));\n } else if (targetLanguage == L\"test\") {\n \/\/ Special case: read from stdin, and try to parse the source language\n ast_parser parser(*lrParserStage.get_tables());\n \n \/\/ Create the parser\n lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);\n ast_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));\n \n \/\/ Parse stdin\n if (stdInParser->parse()) {\n console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;\n } else {\n position failPos(-1, -1, -1);\n if (stdInParser->look().item()) {\n failPos = stdInParser->look()->pos();\n }\n \n console.report_error(error(error::sev_error, L\"stdin\", L\"TEST_PARSER_ERROR\", L\"Syntax error\", failPos));\n }\n } else if (targetLanguage == L\"test-trace\") {\n \/\/ Special case: same as for test, but use the debug version of the parser\n typedef parser > trace_parser;\n trace_parser parser(*lrParserStage.get_tables());\n \n \/\/ Create the parser\n lexeme_stream* stdinStream = lexerStage.get_lexer()->create_stream_from(wcin);\n trace_parser::state* stdInParser = parser.create_parser(new ast_parser_actions(stdinStream));\n \n \/\/ Parse stdin\n if (stdInParser->parse()) {\n console.verbose_stream() << formatter::to_string(*stdInParser->get_item(), *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;\n } else {\n position failPos(-1, -1, -1);\n if (stdInParser->look().item()) {\n failPos = stdInParser->look()->pos();\n }\n \n console.report_error(error(error::sev_error, L\"stdin\", L\"TEST_PARSER_ERROR\", L\"Syntax error\", failPos));\n\n \/\/ Report the stack at the point of failure\n trace_parser::stack stack = stdInParser->get_stack();\n console.verbose_stream() << endl << L\"Stack:\" << endl;\n do {\n console.verbose_stream() << formatter::to_string(*stack->item, *compileLanguageStage->grammar(), *compileLanguageStage->terminals()) << endl;\n } while (stack.pop());\n }\n } else {\n \/\/ Unknown target language\n wstringstream msg;\n msg << L\"Output language '\" << targetLanguage << L\"' is not known\";\n console.report_error(error(error::sev_error, console.input_file(), L\"UNKNOWN_OUTPUT_LANGUAGE_TYPE\", msg.str(), position(-1, -1, -1)));\n return error::sev_error;\n }\n \n \/\/ Compile the final output\n if (outputStage.get()) {\n outputStage->compile();\n }\n \n \/\/ Done\n return console.exit_code();\n } catch (...) {\n console.report_error(error(error::sev_bug, L\"\", L\"BUG_UNCAUGHT_EXCEPTION\", L\"Uncaught exception\", position(-1, -1, -1)));\n throw;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n\/\/ [[CITE]] Tarjan's strongly connected components algorithm\n\/\/ Tarjan, R. E. (1972), \"Depth-first search and linear graph algorithms\", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137\/0201010\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Tarjan's_strongly_connected_components_algorithm\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/log.h\"\n#include \n#include \n#include \n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SccWorker\n{\n\tRTLIL::Design *design;\n\tRTLIL::Module *module;\n\tSigMap sigmap;\n\tCellTypes ct;\n\n\tstd::set workQueue;\n\tstd::map> cellToNextCell;\n\tstd::map cellToPrevSig, cellToNextSig;\n\n\tstd::map> cellLabels;\n\tstd::map cellDepth;\n\tstd::set cellsOnStack;\n\tstd::vector cellStack;\n\tint labelCounter;\n\n\tstd::map cell2scc;\n\tstd::vector> sccList;\n\n\tvoid run(RTLIL::Cell *cell, int depth, int maxDepth)\n\t{\n\t\tlog_assert(workQueue.count(cell) > 0);\n\n\t\tworkQueue.erase(cell);\n\t\tcellLabels[cell] = std::pair(labelCounter, labelCounter);\n\t\tlabelCounter++;\n\n\t\tcellsOnStack.insert(cell);\n\t\tcellStack.push_back(cell);\n\n\t\tif (maxDepth >= 0)\n\t\t\tcellDepth[cell] = depth;\n\n\t\tfor (auto nextCell : cellToNextCell[cell])\n\t\t\tif (cellLabels.count(nextCell) == 0) {\n\t\t\t\trun(nextCell, depth+1, maxDepth);\n\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t} else\n\t\t\tif (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {\n\t\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t}\n\n\t\tif (cellLabels[cell].first == cellLabels[cell].second)\n\t\t{\n\t\t\tif (cellStack.back() == cell)\n\t\t\t{\n\t\t\t\tcellStack.pop_back();\n\t\t\t\tcellsOnStack.erase(cell);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set scc;\n\t\t\t\twhile (cellsOnStack.count(cell) > 0) {\n\t\t\t\t\tRTLIL::Cell *c = cellStack.back();\n\t\t\t\t\tcellStack.pop_back();\n\t\t\t\t\tcellsOnStack.erase(c);\n\t\t\t\t\tlog(\" %s\", RTLIL::id2cstr(c->name));\n\t\t\t\t\tcell2scc[c] = sccList.size();\n\t\t\t\t\tscc.insert(c);\n\t\t\t\t}\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tSccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :\n\t\t\tdesign(design), module(module), sigmap(module)\n\t{\n\t\tif (module->processes.size() > 0) {\n\t\t\tlog(\"Skipping module %s as it contains processes (run 'proc' pass first).\\n\", module->name.c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tif (allCellTypes) {\n\t\t\tct.setup(design);\n\t\t} else {\n\t\t\tct.setup_internals();\n\t\t\tct.setup_stdcells();\n\t\t}\n\n\t\tSigPool selectedSignals;\n\t\tSigSet sigToNextCells;\n\n\t\tfor (auto &it : module->wires_)\n\t\t\tif (design->selected(module, it.second))\n\t\t\t\tselectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));\n\n\t\tfor (auto &it : module->cells_)\n\t\t{\n\t\t\tRTLIL::Cell *cell = it.second;\n\n\t\t\tif (!design->selected(module, cell))\n\t\t\t\tcontinue;\n\n\t\t\tif (!allCellTypes && !ct.cell_known(cell->type))\n\t\t\t\tcontinue;\n\n\t\t\tworkQueue.insert(cell);\n\n\t\t\tRTLIL::SigSpec inputSignals, outputSignals;\n\n\t\t\tfor (auto &conn : cell->connections())\n\t\t\t{\n\t\t\t\tbool isInput = true, isOutput = true;\n\n\t\t\t\tif (ct.cell_known(cell->type)) {\n\t\t\t\t\tisInput = ct.cell_input(cell->type, conn.first);\n\t\t\t\t\tisOutput = ct.cell_output(cell->type, conn.first);\n\t\t\t\t}\n\n\t\t\t\tRTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));\n\t\t\t\tsig.sort_and_unify();\n\n\t\t\t\tif (isInput)\n\t\t\t\t\tinputSignals.append(sig);\n\t\t\t\tif (isOutput)\n\t\t\t\t\toutputSignals.append(sig);\n\t\t\t}\n\n\t\t\tinputSignals.sort_and_unify();\n\t\t\toutputSignals.sort_and_unify();\n\n\t\t\tcellToPrevSig[cell] = inputSignals;\n\t\t\tcellToNextSig[cell] = outputSignals;\n\t\t\tsigToNextCells.insert(inputSignals, cell);\n\t\t}\n\n\t\tfor (auto cell : workQueue)\n\t\t{\n\t\t\tcellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);\n\n\t\t\tif (!nofeedbackMode && cellToNextCell[cell].count(cell)) {\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set scc;\n\t\t\t\tlog(\" %s\", RTLIL::id2cstr(cell->name));\n\t\t\t\tcell2scc[cell] = sccList.size();\n\t\t\t\tscc.insert(cell);\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\n\t\tlabelCounter = 0;\n\t\tcellLabels.clear();\n\n\t\twhile (!workQueue.empty())\n\t\t{\n\t\t\tRTLIL::Cell *cell = *workQueue.begin();\n\t\t\tlog_assert(cellStack.size() == 0);\n\t\t\tcellDepth.clear();\n\n\t\t\trun(cell, 0, maxDepth);\n\t\t}\n\n\t\tlog(\"Found %d SCCs in module %s.\\n\", int(sccList.size()), RTLIL::id2cstr(module->name));\n\t}\n\n\tvoid select(RTLIL::Selection &sel)\n\t{\n\t\tfor (int i = 0; i < int(sccList.size()); i++)\n\t\t{\n\t\t\tstd::set &cells = sccList[i];\n\t\t\tRTLIL::SigSpec prevsig, nextsig, sig;\n\n\t\t\tfor (auto cell : cells) {\n\t\t\t\tsel.selected_members[module->name].insert(cell->name);\n\t\t\t\tprevsig.append(cellToPrevSig[cell]);\n\t\t\t\tnextsig.append(cellToNextSig[cell]);\n\t\t\t}\n\n\t\t\tprevsig.sort_and_unify();\n\t\t\tnextsig.sort_and_unify();\n\t\t\tsig = prevsig.extract(nextsig);\n\n\t\t\tfor (auto &chunk : sig.chunks())\n\t\t\t\tif (chunk.wire != NULL)\n\t\t\t\t\tsel.selected_members[module->name].insert(chunk.wire->name);\n\t\t}\n\t}\n};\n\nstruct SccPass : public Pass {\n\tSccPass() : Pass(\"scc\", \"detect strongly connected components (logic loops)\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" scc [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command identifies strongly connected components (aka logic loops) in the\\n\");\n\t\tlog(\"design.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -expect \\n\");\n\t\tlog(\" expect to find exactly SSCs. A different number of SSCs will\\n\");\n\t\tlog(\" produce an error.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -max_depth \\n\");\n\t\tlog(\" limit to loops not longer than the specified number of cells. This\\n\");\n\t\tlog(\" can e.g. be useful in identifying small local loops in a module that\\n\");\n\t\tlog(\" implements one large SCC.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nofeedback\\n\");\n\t\tlog(\" do not count cells that have their output fed back into one of their\\n\");\n\t\tlog(\" inputs as single-cell scc.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -all_cell_types\\n\");\n\t\tlog(\" Usually this command only considers internal non-memory cells. With\\n\");\n\t\tlog(\" this option set, all cells are considered. For unknown cells all ports\\n\");\n\t\tlog(\" are assumed to be bidirectional 'inout' ports.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -set_attr \\n\");\n\t\tlog(\" set the specified attribute on all cells that are part of a logic\\n\");\n\t\tlog(\" loop. the special token {} in the value is replaced with a unique\\n\");\n\t\tlog(\" identifier for the logic loop.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -select\\n\");\n\t\tlog(\" replace the current selection with a selection of all cells and wires\\n\");\n\t\tlog(\" that are part of a found logic loop\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tstd::map setAttr;\n\t\tbool allCellTypes = false;\n\t\tbool selectMode = false;\n\t\tbool nofeedbackMode = false;\n\t\tint maxDepth = -1;\n\t\tint expect = -1;\n\n\t\tlog_header(design, \"Executing SCC pass (detecting logic loops).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-max_depth\" && argidx+1 < args.size()) {\n\t\t\t\tmaxDepth = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-expect\" && argidx+1 < args.size()) {\n\t\t\t\texpect = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nofeedback\") {\n\t\t\t\tnofeedbackMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-all_cell_types\") {\n\t\t\t\tallCellTypes = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set_attr\" && argidx+2 < args.size()) {\n\t\t\t\tsetAttr[args[argidx+1]] = args[argidx+2];\n\t\t\t\targidx += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-select\") {\n\t\t\t\tselectMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tint origSelectPos = design->selection_stack.size() - 1;\n\t\textra_args(args, argidx, design);\n\n\t\tRTLIL::Selection newSelection(false);\n\t\tint scc_counter = 0;\n\n\t\tfor (auto &mod_it : design->modules_)\n\t\t\tif (design->selected(mod_it.second))\n\t\t\t{\n\t\t\t\tSccWorker worker(design, mod_it.second, nofeedbackMode, allCellTypes, maxDepth);\n\n\t\t\t\tif (!setAttr.empty())\n\t\t\t\t{\n\t\t\t\t\tfor (const auto &cells : worker.sccList)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (auto attr : setAttr)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tIdString attr_name(RTLIL::escape_id(attr.first));\n\t\t\t\t\t\t\tstring attr_valstr = attr.second;\n\t\t\t\t\t\t\tstring index = stringf(\"%d\", scc_counter);\n\n\t\t\t\t\t\t\tfor (size_t pos = 0; (pos = attr_valstr.find(\"{}\", pos)) != string::npos; pos += index.size())\n\t\t\t\t\t\t\t\tattr_valstr.replace(pos, 2, index);\n\n\t\t\t\t\t\t\tConst attr_value(attr_valstr);\n\n\t\t\t\t\t\t\tfor (auto cell : cells)\n\t\t\t\t\t\t\t\tcell->attributes[attr_name] = attr_value;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tscc_counter++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tscc_counter += GetSize(worker.sccList);\n\t\t\t\t}\n\n\t\t\t\tif (selectMode)\n\t\t\t\t\tworker.select(newSelection);\n\t\t\t}\n\n\t\tif (expect >= 0) {\n\t\t\tif (scc_counter == expect)\n\t\t\t\tlog(\"Found and expected %d SCCs.\\n\", scc_counter);\n\t\t\telse\n\t\t\t\tlog_error(\"Found %d SCCs but expected %d.\\n\", scc_counter, expect);\n\t\t} else\n\t\t\tlog(\"Found %d SCCs.\\n\", scc_counter);\n\n\t\tif (selectMode) {\n\t\t\tlog_assert(origSelectPos >= 0);\n\t\t\tdesign->selection_stack[origSelectPos] = newSelection;\n\t\t\tdesign->selection_stack[origSelectPos].optimize(design);\n\t\t}\n\t}\n} SccPass;\n\nPRIVATE_NAMESPACE_END\nscc to use design->selected_modules() which avoids black\/white-boxes\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n\/\/ [[CITE]] Tarjan's strongly connected components algorithm\n\/\/ Tarjan, R. E. (1972), \"Depth-first search and linear graph algorithms\", SIAM Journal on Computing 1 (2): 146-160, doi:10.1137\/0201010\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Tarjan's_strongly_connected_components_algorithm\n\n#include \"kernel\/register.h\"\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/sigtools.h\"\n#include \"kernel\/log.h\"\n#include \n#include \n#include \n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SccWorker\n{\n\tRTLIL::Design *design;\n\tRTLIL::Module *module;\n\tSigMap sigmap;\n\tCellTypes ct;\n\n\tstd::set workQueue;\n\tstd::map> cellToNextCell;\n\tstd::map cellToPrevSig, cellToNextSig;\n\n\tstd::map> cellLabels;\n\tstd::map cellDepth;\n\tstd::set cellsOnStack;\n\tstd::vector cellStack;\n\tint labelCounter;\n\n\tstd::map cell2scc;\n\tstd::vector> sccList;\n\n\tvoid run(RTLIL::Cell *cell, int depth, int maxDepth)\n\t{\n\t\tlog_assert(workQueue.count(cell) > 0);\n\n\t\tworkQueue.erase(cell);\n\t\tcellLabels[cell] = std::pair(labelCounter, labelCounter);\n\t\tlabelCounter++;\n\n\t\tcellsOnStack.insert(cell);\n\t\tcellStack.push_back(cell);\n\n\t\tif (maxDepth >= 0)\n\t\t\tcellDepth[cell] = depth;\n\n\t\tfor (auto nextCell : cellToNextCell[cell])\n\t\t\tif (cellLabels.count(nextCell) == 0) {\n\t\t\t\trun(nextCell, depth+1, maxDepth);\n\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t} else\n\t\t\tif (cellsOnStack.count(nextCell) > 0 && (maxDepth < 0 || cellDepth[nextCell] + maxDepth > depth)) {\n\t\t\t\t\tcellLabels[cell].second = min(cellLabels[cell].second, cellLabels[nextCell].second);\n\t\t\t}\n\n\t\tif (cellLabels[cell].first == cellLabels[cell].second)\n\t\t{\n\t\t\tif (cellStack.back() == cell)\n\t\t\t{\n\t\t\t\tcellStack.pop_back();\n\t\t\t\tcellsOnStack.erase(cell);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set scc;\n\t\t\t\twhile (cellsOnStack.count(cell) > 0) {\n\t\t\t\t\tRTLIL::Cell *c = cellStack.back();\n\t\t\t\t\tcellStack.pop_back();\n\t\t\t\t\tcellsOnStack.erase(c);\n\t\t\t\t\tlog(\" %s\", RTLIL::id2cstr(c->name));\n\t\t\t\t\tcell2scc[c] = sccList.size();\n\t\t\t\t\tscc.insert(c);\n\t\t\t\t}\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tSccWorker(RTLIL::Design *design, RTLIL::Module *module, bool nofeedbackMode, bool allCellTypes, int maxDepth) :\n\t\t\tdesign(design), module(module), sigmap(module)\n\t{\n\t\tif (module->processes.size() > 0) {\n\t\t\tlog(\"Skipping module %s as it contains processes (run 'proc' pass first).\\n\", module->name.c_str());\n\t\t\treturn;\n\t\t}\n\n\t\tif (allCellTypes) {\n\t\t\tct.setup(design);\n\t\t} else {\n\t\t\tct.setup_internals();\n\t\t\tct.setup_stdcells();\n\t\t}\n\n\t\tSigPool selectedSignals;\n\t\tSigSet sigToNextCells;\n\n\t\tfor (auto &it : module->wires_)\n\t\t\tif (design->selected(module, it.second))\n\t\t\t\tselectedSignals.add(sigmap(RTLIL::SigSpec(it.second)));\n\n\t\tfor (auto &it : module->cells_)\n\t\t{\n\t\t\tRTLIL::Cell *cell = it.second;\n\n\t\t\tif (!design->selected(module, cell))\n\t\t\t\tcontinue;\n\n\t\t\tif (!allCellTypes && !ct.cell_known(cell->type))\n\t\t\t\tcontinue;\n\n\t\t\tworkQueue.insert(cell);\n\n\t\t\tRTLIL::SigSpec inputSignals, outputSignals;\n\n\t\t\tfor (auto &conn : cell->connections())\n\t\t\t{\n\t\t\t\tbool isInput = true, isOutput = true;\n\n\t\t\t\tif (ct.cell_known(cell->type)) {\n\t\t\t\t\tisInput = ct.cell_input(cell->type, conn.first);\n\t\t\t\t\tisOutput = ct.cell_output(cell->type, conn.first);\n\t\t\t\t}\n\n\t\t\t\tRTLIL::SigSpec sig = selectedSignals.extract(sigmap(conn.second));\n\t\t\t\tsig.sort_and_unify();\n\n\t\t\t\tif (isInput)\n\t\t\t\t\tinputSignals.append(sig);\n\t\t\t\tif (isOutput)\n\t\t\t\t\toutputSignals.append(sig);\n\t\t\t}\n\n\t\t\tinputSignals.sort_and_unify();\n\t\t\toutputSignals.sort_and_unify();\n\n\t\t\tcellToPrevSig[cell] = inputSignals;\n\t\t\tcellToNextSig[cell] = outputSignals;\n\t\t\tsigToNextCells.insert(inputSignals, cell);\n\t\t}\n\n\t\tfor (auto cell : workQueue)\n\t\t{\n\t\t\tcellToNextCell[cell] = sigToNextCells.find(cellToNextSig[cell]);\n\n\t\t\tif (!nofeedbackMode && cellToNextCell[cell].count(cell)) {\n\t\t\t\tlog(\"Found an SCC:\");\n\t\t\t\tstd::set scc;\n\t\t\t\tlog(\" %s\", RTLIL::id2cstr(cell->name));\n\t\t\t\tcell2scc[cell] = sccList.size();\n\t\t\t\tscc.insert(cell);\n\t\t\t\tsccList.push_back(scc);\n\t\t\t\tlog(\"\\n\");\n\t\t\t}\n\t\t}\n\n\t\tlabelCounter = 0;\n\t\tcellLabels.clear();\n\n\t\twhile (!workQueue.empty())\n\t\t{\n\t\t\tRTLIL::Cell *cell = *workQueue.begin();\n\t\t\tlog_assert(cellStack.size() == 0);\n\t\t\tcellDepth.clear();\n\n\t\t\trun(cell, 0, maxDepth);\n\t\t}\n\n\t\tlog(\"Found %d SCCs in module %s.\\n\", int(sccList.size()), RTLIL::id2cstr(module->name));\n\t}\n\n\tvoid select(RTLIL::Selection &sel)\n\t{\n\t\tfor (int i = 0; i < int(sccList.size()); i++)\n\t\t{\n\t\t\tstd::set &cells = sccList[i];\n\t\t\tRTLIL::SigSpec prevsig, nextsig, sig;\n\n\t\t\tfor (auto cell : cells) {\n\t\t\t\tsel.selected_members[module->name].insert(cell->name);\n\t\t\t\tprevsig.append(cellToPrevSig[cell]);\n\t\t\t\tnextsig.append(cellToNextSig[cell]);\n\t\t\t}\n\n\t\t\tprevsig.sort_and_unify();\n\t\t\tnextsig.sort_and_unify();\n\t\t\tsig = prevsig.extract(nextsig);\n\n\t\t\tfor (auto &chunk : sig.chunks())\n\t\t\t\tif (chunk.wire != NULL)\n\t\t\t\t\tsel.selected_members[module->name].insert(chunk.wire->name);\n\t\t}\n\t}\n};\n\nstruct SccPass : public Pass {\n\tSccPass() : Pass(\"scc\", \"detect strongly connected components (logic loops)\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" scc [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command identifies strongly connected components (aka logic loops) in the\\n\");\n\t\tlog(\"design.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -expect \\n\");\n\t\tlog(\" expect to find exactly SSCs. A different number of SSCs will\\n\");\n\t\tlog(\" produce an error.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -max_depth \\n\");\n\t\tlog(\" limit to loops not longer than the specified number of cells. This\\n\");\n\t\tlog(\" can e.g. be useful in identifying small local loops in a module that\\n\");\n\t\tlog(\" implements one large SCC.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nofeedback\\n\");\n\t\tlog(\" do not count cells that have their output fed back into one of their\\n\");\n\t\tlog(\" inputs as single-cell scc.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -all_cell_types\\n\");\n\t\tlog(\" Usually this command only considers internal non-memory cells. With\\n\");\n\t\tlog(\" this option set, all cells are considered. For unknown cells all ports\\n\");\n\t\tlog(\" are assumed to be bidirectional 'inout' ports.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -set_attr \\n\");\n\t\tlog(\" set the specified attribute on all cells that are part of a logic\\n\");\n\t\tlog(\" loop. the special token {} in the value is replaced with a unique\\n\");\n\t\tlog(\" identifier for the logic loop.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -select\\n\");\n\t\tlog(\" replace the current selection with a selection of all cells and wires\\n\");\n\t\tlog(\" that are part of a found logic loop\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tstd::map setAttr;\n\t\tbool allCellTypes = false;\n\t\tbool selectMode = false;\n\t\tbool nofeedbackMode = false;\n\t\tint maxDepth = -1;\n\t\tint expect = -1;\n\n\t\tlog_header(design, \"Executing SCC pass (detecting logic loops).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-max_depth\" && argidx+1 < args.size()) {\n\t\t\t\tmaxDepth = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-expect\" && argidx+1 < args.size()) {\n\t\t\t\texpect = atoi(args[++argidx].c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nofeedback\") {\n\t\t\t\tnofeedbackMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-all_cell_types\") {\n\t\t\t\tallCellTypes = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set_attr\" && argidx+2 < args.size()) {\n\t\t\t\tsetAttr[args[argidx+1]] = args[argidx+2];\n\t\t\t\targidx += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-select\") {\n\t\t\t\tselectMode = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tint origSelectPos = design->selection_stack.size() - 1;\n\t\textra_args(args, argidx, design);\n\n\t\tRTLIL::Selection newSelection(false);\n\t\tint scc_counter = 0;\n\n\t\tfor (auto mod : design->selected_modules())\n\t\t{\n\t\t\tSccWorker worker(design, mod, nofeedbackMode, allCellTypes, maxDepth);\n\n\t\t\tif (!setAttr.empty())\n\t\t\t{\n\t\t\t\tfor (const auto &cells : worker.sccList)\n\t\t\t\t{\n\t\t\t\t\tfor (auto attr : setAttr)\n\t\t\t\t\t{\n\t\t\t\t\t\tIdString attr_name(RTLIL::escape_id(attr.first));\n\t\t\t\t\t\tstring attr_valstr = attr.second;\n\t\t\t\t\t\tstring index = stringf(\"%d\", scc_counter);\n\n\t\t\t\t\t\tfor (size_t pos = 0; (pos = attr_valstr.find(\"{}\", pos)) != string::npos; pos += index.size())\n\t\t\t\t\t\t\tattr_valstr.replace(pos, 2, index);\n\n\t\t\t\t\t\tConst attr_value(attr_valstr);\n\n\t\t\t\t\t\tfor (auto cell : cells)\n\t\t\t\t\t\t\tcell->attributes[attr_name] = attr_value;\n\t\t\t\t\t}\n\n\t\t\t\t\tscc_counter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tscc_counter += GetSize(worker.sccList);\n\t\t\t}\n\n\t\t\tif (selectMode)\n\t\t\t\tworker.select(newSelection);\n\t\t}\n\n\t\tif (expect >= 0) {\n\t\t\tif (scc_counter == expect)\n\t\t\t\tlog(\"Found and expected %d SCCs.\\n\", scc_counter);\n\t\t\telse\n\t\t\t\tlog_error(\"Found %d SCCs but expected %d.\\n\", scc_counter, expect);\n\t\t} else\n\t\t\tlog(\"Found %d SCCs.\\n\", scc_counter);\n\n\t\tif (selectMode) {\n\t\t\tlog_assert(origSelectPos >= 0);\n\t\t\tdesign->selection_stack[origSelectPos] = newSelection;\n\t\t\tdesign->selection_stack[origSelectPos].optimize(design);\n\t\t}\n\t}\n} SccPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/workarounds\/adr32s_workarounds.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file workarounds\/adr32s_workarounds.C\n\/\/\/ @brief Workarounds for the ADR32s logic blocks\n\/\/\/ Workarounds are very deivce specific, so there is no attempt to generalize\n\/\/\/ this code in any way.\n\/\/\/\n\/\/ *HWP HWP Owner: Stephen Glancy \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_SYSTEM;\nusing fapi2::FAPI2_RC_SUCCESS;\n\nnamespace mss\n{\n\nnamespace workarounds\n{\n\nnamespace adr32s\n{\n\n\/\/\/\n\/\/\/ @brief Clears the FIRs mistakenly set by the DCD calibration\n\/\/\/ @param[in] i_target MCBIST target on which to operate\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/ @note Always needs to be run for DD1.* parts. unsure for DD2\n\/\/\/\nfapi2::ReturnCode clear_dcd_firs( const fapi2::Target& i_target )\n{\n FAPI_INF(\"%s clearing DCD FIRs!\", mss::c_str(i_target));\n\n \/\/ Run the fir clear to reset bits that are caused by the DCD calibration\n for( const auto& l_mca : mss::find_targets(i_target))\n {\n fir::reg l_mca_fir_reg(l_mca, fapi2::current_err);\n FAPI_TRY(fapi2::current_err, \"unable to create fir::reg for %d\", MCA_IOM_PHY0_DDRPHY_FIR_REG);\n\n \/\/ Per Steve Wyatt:\n \/\/ Bit 55 gets set during the DCD cal in the ADR\n \/\/ Bit 56\/58 get set during the DCD cal in the DP's\n \/\/ Bit 59 is set due to parity errors and must be cleared, per Tim Buccholtz\n \/\/ Clearing them all here, as the DCD cal is run on the ADR\/DP's in the same code in lib\/adr32s.C\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 55\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 56\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 58\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 59\n }\n\n return fapi2::FAPI2_RC_SUCCESS;\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Perform ADR DCD calibration - Nimbus Only\n\/\/\/ @param[in] i_target the MCBIST (controler) to perform calibration on\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\nfapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target& i_target )\n{\n typedef dutyCycleDistortionTraits TT;\n\n const auto l_mca = mss::find_targets(i_target);\n\n \/\/ Skips DCD calibration if we're a DD2 part\n if (!mss::chip_ec_feature_dcd_workaround(i_target))\n {\n FAPI_INF(\"%s Skipping DCD calibration algorithm due to part revision\", mss::c_str(i_target));\n return FAPI2_RC_SUCCESS;\n }\n\n \/\/ Clears the FIRs created by DCD calibration, if needed\n FAPI_TRY(mss::workarounds::adr32s::clear_dcd_firs(i_target));\n\n \/\/ We must calibrate each of our ports. Each has 2 ADR units and each unit needs it's A-side and B-side calibrated.\n for (const auto& p : mss::find_targets(i_target))\n {\n uint64_t l_seed = TT::DD1_DCD_ADJUST_DEFAULT;\n\n \/\/ Sets up the DLL control regs for DCD cal for this port\n FAPI_TRY(mss::dcd::setup_dll_control_regs( p ));\n\n for (const auto& r : TT::DUTY_CYCLE_DISTORTION_REG)\n {\n FAPI_TRY(mss::dcd::sw_cal_per_register(p, r, l_seed));\n }\n\n \/\/ Restores the DLL control regs for DCD cal for this port\n FAPI_TRY(mss::dcd::restore_dll_control_regs( p ));\n }\n\n \/\/ Clears the FIRs created by DCD calibration, if needed\n FAPI_TRY(mss::workarounds::adr32s::clear_dcd_firs(i_target));\n\n FAPI_INF(\"%s Cleared DCD firs\", mss::c_str(i_target));\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Retries to clear the cal update bit, as it has been seen that the bit can be \"sticky\" in hardware\n\/\/\/ @param[in] i_target MCA target on which to operate\n\/\/\/ @param[in] i_reg the register on which to operate\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\nfapi2::ReturnCode setup_dll_control_regs( const fapi2::Target& i_target, const uint64_t i_reg )\n{\n \/\/ Traits definition\n typedef dutyCycleDistortionTraits TT;\n\n \/\/ Poll limit declaration - this is an engineering judgement value from the lab's experimentation\n \/\/ The bit thus far has always unstuck after 3 loops, so 10 is more than safe\n constexpr uint64_t POLL_LIMIT = 10;\n bool l_done = false;\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n\n for(uint64_t i = 0; i < POLL_LIMIT; ++i)\n {\n fapi2::buffer l_data;\n\n FAPI_TRY(mss::getScom(i_target, i_reg, l_data), \"%s failed to getScom from register 0x%016lx\", mss::c_str(i_target),\n i_reg);\n\n \/\/ If our bit is a 0, then we're done\n l_done = !l_data.getBit();\n\n \/\/ Break out\n if(l_done)\n {\n FAPI_INF(\"%s DLL control register 0x%016lx is setup correctly after %lu attempts\", mss::c_str(i_target), i_reg, i);\n break;\n }\n\n \/\/ Stops cal from updating and disables cal good to keep parity good (these regs have parity issues on bits 60-63)\n l_data.clearBit();\n l_data.clearBit();\n\n FAPI_TRY(mss::putScom(i_target, i_reg, l_data), \"%s failed to putScom from register 0x%016lx\", mss::c_str(i_target),\n i_reg);\n }\n\n \/\/ do the error check\n FAPI_ASSERT( l_done,\n fapi2::MSS_DLL_UPDATE_BIT_STUCK()\n .set_TARGET(i_target)\n .set_REGISTER(i_reg),\n \"Failed to setup DLL control reg for %s 0x%016lx\", mss::c_str(i_target), i_reg );\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n} \/\/ close namespace adr32s\n} \/\/ close namespace workarounds\n} \/\/ close namespace mss\nL3 support for ddr_phy_reset, termination_control\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/workarounds\/adr32s_workarounds.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file workarounds\/adr32s_workarounds.C\n\/\/\/ @brief Workarounds for the ADR32s logic blocks\n\/\/\/ Workarounds are very deivce specific, so there is no attempt to generalize\n\/\/\/ this code in any way.\n\/\/\/\n\/\/ *HWP HWP Owner: Stephen Glancy \n\/\/ *HWP HWP Backup: Andre Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_SYSTEM;\nusing fapi2::FAPI2_RC_SUCCESS;\n\nnamespace mss\n{\n\nnamespace workarounds\n{\n\nnamespace adr32s\n{\n\n\/\/\/\n\/\/\/ @brief Clears the FIRs mistakenly set by the DCD calibration\n\/\/\/ @param[in] i_target MCBIST target on which to operate\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/ @note Always needs to be run for DD1.* parts. unsure for DD2\n\/\/\/\nfapi2::ReturnCode clear_dcd_firs( const fapi2::Target& i_target )\n{\n FAPI_INF(\"%s clearing DCD FIRs!\", mss::c_str(i_target));\n\n \/\/ Run the fir clear to reset bits that are caused by the DCD calibration\n for( const auto& l_mca : mss::find_targets(i_target))\n {\n fir::reg l_mca_fir_reg(l_mca, fapi2::current_err);\n FAPI_TRY(fapi2::current_err, \"unable to create fir::reg for %d\", MCA_IOM_PHY0_DDRPHY_FIR_REG);\n\n \/\/ Per Steve Wyatt:\n \/\/ Bit 55 gets set during the DCD cal in the ADR\n \/\/ Bit 56\/58 get set during the DCD cal in the DP's\n \/\/ Bit 59 is set due to parity errors and must be cleared, per Tim Buccholtz\n \/\/ Clearing them all here, as the DCD cal is run on the ADR\/DP's in the same code in lib\/adr32s.C\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 55\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 56\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 58\n FAPI_TRY(l_mca_fir_reg.clear()); \/\/ bit 59\n }\n\n return fapi2::FAPI2_RC_SUCCESS;\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Perform ADR DCD calibration - Nimbus Only\n\/\/\/ @param[in] i_target the MCBIST (controler) to perform calibration on\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\nfapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target& i_target )\n{\n typedef dutyCycleDistortionTraits TT;\n\n const auto l_mca = mss::find_targets(i_target);\n\n \/\/ Skips DCD calibration if we're a DD2 part\n if (!mss::chip_ec_feature_dcd_workaround(i_target))\n {\n FAPI_INF(\"%s Skipping DCD calibration algorithm due to part revision\", mss::c_str(i_target));\n return FAPI2_RC_SUCCESS;\n }\n\n \/\/ Clears the FIRs created by DCD calibration, if needed\n FAPI_TRY(mss::workarounds::adr32s::clear_dcd_firs(i_target));\n\n \/\/ We must calibrate each of our ports. Each has 2 ADR units and each unit needs it's A-side and B-side calibrated.\n for (const auto& p : mss::find_targets(i_target))\n {\n uint64_t l_seed = TT::DD1_DCD_ADJUST_DEFAULT;\n\n \/\/ Sets up the DLL control regs for DCD cal for this port\n FAPI_TRY(mss::dcd::setup_dll_control_regs( p ));\n\n for (const auto& r : TT::DUTY_CYCLE_DISTORTION_REG)\n {\n FAPI_TRY(mss::dcd::sw_cal_per_register(p, r, l_seed));\n }\n\n \/\/ Restores the DLL control regs for DCD cal for this port\n FAPI_TRY(mss::dcd::restore_dll_control_regs( p ));\n }\n\n \/\/ Clears the FIRs created by DCD calibration, if needed\n FAPI_TRY(mss::workarounds::adr32s::clear_dcd_firs(i_target));\n\n FAPI_INF(\"%s Cleared DCD firs\", mss::c_str(i_target));\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Retries to clear the cal update bit, as it has been seen that the bit can be \"sticky\" in hardware\n\/\/\/ @param[in] i_target MCA target on which to operate\n\/\/\/ @param[in] i_reg the register on which to operate\n\/\/\/ @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok\n\/\/\/\nfapi2::ReturnCode setup_dll_control_regs( const fapi2::Target& i_target, const uint64_t i_reg )\n{\n \/\/ Traits definition\n typedef dutyCycleDistortionTraits TT;\n\n \/\/ Poll limit declaration - this is an engineering judgement value from the lab's experimentation\n \/\/ The bit thus far has always unstuck after 3 loops, so 10 is more than safe\n constexpr uint64_t POLL_LIMIT = 10;\n bool l_done = false;\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n\n for(uint64_t i = 0; i < POLL_LIMIT; ++i)\n {\n fapi2::buffer l_data;\n\n FAPI_TRY(mss::getScom(i_target, i_reg, l_data), \"%s failed to getScom from register 0x%016lx\", mss::c_str(i_target),\n i_reg);\n\n \/\/ If our bit is a 0, then we're done\n l_done = !l_data.getBit();\n\n \/\/ Break out\n if(l_done)\n {\n FAPI_INF(\"%s DLL control register 0x%016lx is setup correctly after %lu attempts\", mss::c_str(i_target), i_reg, i);\n break;\n }\n\n \/\/ Stops cal from updating and disables cal good to keep parity good (these regs have parity issues on bits 60-63)\n l_data.clearBit();\n l_data.clearBit();\n\n FAPI_TRY(mss::putScom(i_target, i_reg, l_data), \"%s failed to putScom from register 0x%016lx\", mss::c_str(i_target),\n i_reg);\n }\n\n \/\/ do the error check\n FAPI_ASSERT( l_done,\n fapi2::MSS_DLL_UPDATE_BIT_STUCK()\n .set_MCA_TARGET(i_target)\n .set_REGISTER(i_reg),\n \"Failed to setup DLL control reg for %s 0x%016lx\", mss::c_str(i_target), i_reg );\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n} \/\/ close namespace adr32s\n} \/\/ close namespace workarounds\n} \/\/ close namespace mss\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file FlightTaskManualAcceleration.cpp\n *\/\n\n#include \"FlightTaskManualAcceleration.hpp\"\n\nusing namespace matrix;\n\nFlightTaskManualAcceleration::FlightTaskManualAcceleration() :\n\t_stick_acceleration_xy(this)\n{};\n\nbool FlightTaskManualAcceleration::activate(const vehicle_local_position_setpoint_s &last_setpoint)\n{\n\tbool ret = FlightTaskManualAltitudeSmoothVel::activate(last_setpoint);\n\n\tif (PX4_ISFINITE(last_setpoint.vx)) {\n\t\t_velocity_setpoint.xy() = Vector2f(last_setpoint.vx, last_setpoint.vy);\n\n\t} else {\n\t\t_velocity_setpoint.xy() = Vector2f(_velocity);\n\t}\n\n\tif (PX4_ISFINITE(last_setpoint.acceleration[0])) {\n\t\t_stick_acceleration_xy.resetAcceleration(Vector2f(last_setpoint.acceleration[0], last_setpoint.acceleration[1]));\n\t}\n\n\treturn ret;\n}\n\nbool FlightTaskManualAcceleration::update()\n{\n\tbool ret = FlightTaskManualAltitudeSmoothVel::update();\n\n\t_stick_yaw.generateYawSetpoint(_yawspeed_setpoint, _yaw_setpoint,\n\t\t\t\t _sticks.getPositionExpo()(3) * math::radians(_param_mpc_man_y_max.get()), _yaw, _deltatime);\n\t_stick_acceleration_xy.generateSetpoints(_sticks.getPositionExpo().slice<2, 1>(0, 0), _yaw, _yaw_setpoint, _position,\n\t\t\t_deltatime);\n\t_stick_acceleration_xy.getSetpoints(_position_setpoint, _velocity_setpoint, _acceleration_setpoint);\n\n\t_constraints.want_takeoff = _checkTakeoff();\n\treturn ret;\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerPositionXY()\n{\n\tif (PX4_ISFINITE(_position_setpoint(0))) {\n\t\t_position_setpoint(0) = _position(0);\n\t\t_position_setpoint(1) = _position(1);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerVelocityXY()\n{\n\tif (PX4_ISFINITE(_velocity_setpoint(0))) {\n\t\t_velocity_setpoint(0) = _velocity(0);\n\t\t_velocity_setpoint(1) = _velocity(1);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerPositionZ()\n{\n\tif (PX4_ISFINITE(_position_setpoint(2))) {\n\t\t_position_setpoint(2) = _position(2);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerVelocityZ()\n{\n\tif (PX4_ISFINITE(_velocity_setpoint(2))) {\n\t\t_velocity_setpoint(2) = _velocity(2);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerHeading(float delta_psi)\n{\n\tif (PX4_ISFINITE(_yaw_setpoint)) {\n\t\t_yaw_setpoint += delta_psi;\n\t}\n}\nFlightTaskManualAcceleration: reset position lock on reactivation\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file FlightTaskManualAcceleration.cpp\n *\/\n\n#include \"FlightTaskManualAcceleration.hpp\"\n\nusing namespace matrix;\n\nFlightTaskManualAcceleration::FlightTaskManualAcceleration() :\n\t_stick_acceleration_xy(this)\n{};\n\nbool FlightTaskManualAcceleration::activate(const vehicle_local_position_setpoint_s &last_setpoint)\n{\n\tbool ret = FlightTaskManualAltitudeSmoothVel::activate(last_setpoint);\n\n\tif (PX4_ISFINITE(last_setpoint.vx)) {\n\t\t_velocity_setpoint.xy() = Vector2f(last_setpoint.vx, last_setpoint.vy);\n\n\t} else {\n\t\t_velocity_setpoint.xy() = Vector2f(_velocity);\n\t}\n\n\t_stick_acceleration_xy.resetPosition();\n\n\tif (PX4_ISFINITE(last_setpoint.acceleration[0])) {\n\t\t_stick_acceleration_xy.resetAcceleration(Vector2f(last_setpoint.acceleration[0], last_setpoint.acceleration[1]));\n\t}\n\n\treturn ret;\n}\n\nbool FlightTaskManualAcceleration::update()\n{\n\tbool ret = FlightTaskManualAltitudeSmoothVel::update();\n\n\t_stick_yaw.generateYawSetpoint(_yawspeed_setpoint, _yaw_setpoint,\n\t\t\t\t _sticks.getPositionExpo()(3) * math::radians(_param_mpc_man_y_max.get()), _yaw, _deltatime);\n\t_stick_acceleration_xy.generateSetpoints(_sticks.getPositionExpo().slice<2, 1>(0, 0), _yaw, _yaw_setpoint, _position,\n\t\t\t_deltatime);\n\t_stick_acceleration_xy.getSetpoints(_position_setpoint, _velocity_setpoint, _acceleration_setpoint);\n\n\t_constraints.want_takeoff = _checkTakeoff();\n\treturn ret;\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerPositionXY()\n{\n\tif (PX4_ISFINITE(_position_setpoint(0))) {\n\t\t_position_setpoint(0) = _position(0);\n\t\t_position_setpoint(1) = _position(1);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerVelocityXY()\n{\n\tif (PX4_ISFINITE(_velocity_setpoint(0))) {\n\t\t_velocity_setpoint(0) = _velocity(0);\n\t\t_velocity_setpoint(1) = _velocity(1);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerPositionZ()\n{\n\tif (PX4_ISFINITE(_position_setpoint(2))) {\n\t\t_position_setpoint(2) = _position(2);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerVelocityZ()\n{\n\tif (PX4_ISFINITE(_velocity_setpoint(2))) {\n\t\t_velocity_setpoint(2) = _velocity(2);\n\t}\n}\n\nvoid FlightTaskManualAcceleration::_ekfResetHandlerHeading(float delta_psi)\n{\n\tif (PX4_ISFINITE(_yaw_setpoint)) {\n\t\t_yaw_setpoint += delta_psi;\n\t}\n}\n<|endoftext|>"} {"text":"\/**\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @copyright 2014 Safehaus.org\n *\/\n\/**\n * @brief SubutaiContainer.cpp\n * @class SubutaiContainer.cpp\n * @details SubutaiContainer Class is designed for getting and setting container variables and special informations.\n * \t\t This class's instance can get get useful container specific informations\n * \t\t such as IPs, UUID, hostname, macID, parentHostname, etc..\n * @author Mikhail Savochkin\n * @author Ozlem Ceren Sahin\n * @version 1.1.0\n * @date Oct 31, 2014\n *\/\n#include \"SubutaiContainer.h\"\n#include \"SubutaiConnection.h\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\/**\n * \\details Default constructor of SubutaiEnvironment class.\n *\/\nSubutaiContainer::SubutaiContainer(SubutaiLogger* logger, lxc_container* cont)\n{\n this->container = cont;\n this->containerLogger = logger;\n}\n\n\/**\n * \\details Default destructor of SubutaiEnvironment class.\n *\/\nSubutaiContainer::~SubutaiContainer()\n{\n \/\/ TODO Auto-generated destructor stub\n}\n\n\n\/**\n * \\details This method designed for Typically conversion from integer to string.\n *\/\nstring SubutaiContainer::toString(int intcont)\n{\t\t\/\/integer to string conversion\n ostringstream dummy;\n dummy << intcont;\n return dummy.str();\n}\n\nstring SubutaiContainer::RunProgram(string program, vector params) {\n ExecutionResult result = RunProgram(program, params, true);\n if (result.exit_code == 0) {\n return result.out;\n } else {\n return result.err;\n }\n}\n\nExecutionResult SubutaiContainer::RunProgram(string program, vector params, bool return_result) {\n char* _params[params.size() + 2];\n _params[0] = const_cast(program.c_str());\n vector::iterator it;\n int i = 1;\n for (it = params.begin(); it != params.end(); it++, i++) {\n _params[i] = const_cast(it->c_str());\n }\n _params[i] = NULL;\n lxc_attach_options_t opts = LXC_ATTACH_OPTIONS_DEFAULT;\n int fd[2];\n int _stdout = dup(1);\n pipe(fd);\n dup2(fd[1], 1);\n char buffer[1000];\n \/\/ TODO: if exit code not equals one - we got stderr\n ExecutionResult result;\n result.exit_code = this->container->attach_run_wait(this->container, &opts, program.c_str(), _params);\n fflush(stdout);\n close(fd[1]);\n dup2(_stdout, 1);\n close(_stdout);\n \/\/ TODO: Decide where to keep this command output\n string command_output;\n while (1) {\n ssize_t size = read(fd[0], buffer, 1000);\n command_output += buffer;\n if (size < 1000) {\n buffer[size] = '\\0';\n command_output += buffer;\n break;\n } else {\n command_output += buffer;\n }\n }\n if (result.exit_code == 0) {\n result.out = command_output;\n } else {\n result.err = command_output;\n }\n\n return result;\n}\n\n\nbool SubutaiContainer::isContainerRunning()\n{\n if(this->status == RUNNING) return true;\n return false;\n}\n\nbool SubutaiContainer::isContainerStopped()\n{\n if(this->status == STOPPED) return true;\n return false;\n}\n\nbool SubutaiContainer::isContainerFrozen()\n{\n if(this->status == FROZEN) return true;\n return false;\n}\n\nvoid SubutaiContainer::UpdateUsersList() { \n this->_users.clear();\n vector params;\n params.push_back(\"\/etc\/passwd\");\n string passwd = RunProgram(\"\/bin\/cat\", params);\n size_t n = 0;\n size_t p = 0;\n stringstream ss(passwd);\n string line;\n while (getline(ss, line, '\\n')) {\n int c = 0;\n int uid;\n string uname;\n while ((n = line.find_first_of(\":\", p)) != string::npos) {\n c++;\n if (n - p != 0) {\n if (c == 1) {\n \/\/ This is a username\n uname = line.substr(p, n - p);\n } else if (c == 3) {\n \/\/ This is a uid\n stringstream conv(line.substr(p, n - p));\n if (!(conv >> uid)) {\n uid = -1; \/\/ We failed to convert string to int\n }\n }\n }\n this->_users.insert(make_pair(uid, uname));\n }\n }\n}\n\/**\n * \\details UUID of the Subutai Agent is fetched from statically using this function.\n * \t\t Example uuid:\"ff28d7c7-54b4-4291-b246-faf3dd493544\"\n *\/\nbool SubutaiContainer::getContainerId()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/etc\/subutai-agent\/uuid.txt\");\n this-> id = RunProgram(\"\/bin\/cat\", args);\n if (this->id.empty())\t\t\/\/if uuid is null or not reading successfully\n {\n boost::uuids::random_generator gen;\n boost::uuids::uuid u = gen();\n\n const std::string tmp = boost::lexical_cast(u);\n this->id = tmp;\n\n args.clear();\n args.push_back(this->id);\n args.push_back(\">\");\n args.push_back(\"\/etc\/subutai-agent\/uuid.txt\");\n this-> id = RunProgram(\"\/bin\/echo\", args);\n containerLogger->writeLog(1,containerLogger->setLogData(\"\",\"Subutai Agent UUID: \",this->id));\n return false;\n }\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\/**\n * \\details MACID(eth0) of the KiskisAgent is fetched from statically.\n *\/\nbool SubutaiContainer::getContainerMacAddress()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/sys\/class\/net\/eth0\/address\");\n this-> macAddress = RunProgram(\"\/bin\/cat\", args);\n if(this->macAddress.empty())\t\t\/\/if mac is null or not reading successfully\n {\n containerLogger->writeLog(3,containerLogger->setLogData(\"\",\"MacAddress cannot be read !!\"));\n return false;\n }\n containerLogger->writeLog(6,containerLogger->setLogData(\"\",\"Subutai Agent MacID:\",this->macAddress));\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\/**\n * \\details Hostname of the KiskisAgent machine is fetched from statically.\n *\/\nbool SubutaiContainer::getContainerHostname()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/etc\/hostname\");\n this-> hostname = RunProgram(\"\/bin\/cat\", args);\n if(this->hostname.empty())\t\t\/\/if hostname is null or not reading successfully\n {\n return false;\n }\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\/**\n * \\details Hostname of the KiskisAgent machine is fetched from statically.\n *\/\nvoid SubutaiContainer::setContainerHostname(string hostname)\n{\n this-> hostname = hostname;\n}\n\n\/**\n * \\details Hostname of the KiskisAgent machine is fetched from statically.\n *\/\ncontainerStatus SubutaiContainer::getContainerStatus()\n{\n return this->status;\n}\n\nvoid SubutaiContainer::setContainerStatus(containerStatus status)\n{\n this->status = status;\n}\n\/**\n * \\details Parent Hostname of the Subutai Agent machine is fetched from c paramonfig file.\n *\/\nbool SubutaiContainer::getContainerParentHostname()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/etc\/hostname\");\n string config = RunProgram(\"\/bin\/cat\", args);\n if (config.empty()) \/\/file exist\n {\n ofstream file(\"\/tmp\/subutai\/config.txt\");\n file << config;\n file.close();\n boost::property_tree::ptree pt;\n boost::property_tree::ini_parser::read_ini(\"\/tmp\/subutai\/config.txt\", pt);\n parentHostname = pt.get(\"Subutai-Agent.subutai_parent_hostname\");\n containerLogger->writeLog(6,containerLogger->setLogData(\"\",\"parentHostname: \",parentHostname));\n }\n\n if(!parentHostname.empty())\n {\n return true;\n }\n else\n {\n containerLogger->writeLog(6,containerLogger->setLogData(\"\",\"parentHostname does not exist!\"));\n return false;\n }\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\n\/**\n * \\details IpAddress of the KiskisAgent machine is fetched from statically.\n *\/\nbool SubutaiContainer::getContainerIpAddress()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n\n ipAddress.clear();\n\n vector args ;\n string config = RunProgram(\"ifconfig\", args);\n\n ofstream file(\"\/tmp\/subutai\/ipaddress.txt\");\n file << config;\n file.close();\n\n FILE * fp = fopen(\"\/tmp\/subutai\/ipaddress.txt\", \"r\");\n if (fp)\n {\n char *p=NULL, *e; size_t n;\n while ((getline(&p, &n, fp) > 0) && p)\n {\n if ((p = strstr(p, \"inet addr:\")))\n {\n p+=10;\n if ((e = strchr(p, ' ')))\n {\n *e='\\0';\n ipAddress.push_back(p);\n }\n }\n }\n }\n pclose(fp);\n\n for(unsigned int i=0; i < ipAddress.size() ; i++)\n {\n containerLogger->writeLog(6,containerLogger->setLogData(\"\",\"Subutai Agent IpAddress:\",ipAddress[i]));\n }\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n containerLogger->writeLog(3,containerLogger->setLogData(\"\",\"IpAddress cannot be read !!\"));\n return false;\n}\n\n\/**\n * \\details getting Agent uuid value.\n *\/\nstring SubutaiContainer::getContainerIdValue()\n{\n return id;\n}\n\n\/**\n * \\details getting Agent hostname value.\n *\/\nstring SubutaiContainer::getContainerHostnameValue()\n{\n return hostname;\n}\n\n\/**\n * \\details getting lxc container value.\n *\/\nlxc_container* SubutaiContainer::getLxcContainerValue()\n{\n return container;\n}\n\n\/**\n * \\details getting Agent macaddress value.\n *\/\nstring SubutaiContainer::getContainerMacAddressValue()\n{\n return macAddress;\n}\n\n\/**\n * \\details getting Agent parentHostname value.\n *\/\nstring SubutaiContainer::getContainerParentHostnameValue()\n{\n return parentHostname;\n}\n\n\/**\n * \\details getting Agent Ip values.\n *\/\nvector SubutaiContainer::getContainerIpValue()\n{\n return ipAddress;\n}\n\nvoid SubutaiContainer::getContainerAllFields()\n{\n getContainerId();\n getContainerMacAddress();\n getContainerHostname();\n getContainerParentHostname();\n getContainerIpAddress();\n}\n\nvoid SubutaiContainer::write(){\n cout << id << \" \" << macAddress << \" \" << hostname << \" \" << parentHostname<< \" \" << endl;\n\n}\n\n\nvoid SubutaiContainer::registerContainer(SubutaiConnection* connection)\n{\n SubutaiResponsePack response;\n string sendout = response.createRegistrationMessage(this->id,this->macAddress,this->hostname,this->parentHostname,NULL,this->ipAddress);\n containerLogger->writeLog(7,containerLogger->setLogData(\"\",\"Registration Message:\",sendout));\n connection->sendMessage(sendout);\n}\n\n\/\/ We need to check if CWD is exist because in LXC API - if cwd does not\n\/\/ exist CWD will become root directory\nbool SubutaiContainer::checkCWD(string cwd) {\n vector params;\n params.push_back(cwd);\n ExecutionResult result = RunProgram(\"\/bin\/cd\", params, true); \n if (result.exit_code == 0) \n return true;\n else\n return false;\n}\n\n\/*\n * \/details Runs throught the list of userid:username pairs\n * and check user existence\n *\/\n\nbool SubutaiContainer::checkUser(string username) {\n if (_users.empty()) {\n UpdateUsersList();\n }\n for (user_it it = _users.begin(); it != _users.end(); it++) {\n if ((*it)->second.compare(username) == 0) {\n return true;\n }\n } \n return false;\n}\n\n\/*\n * \/details Runs through the list of userid:username pairs\n * and returns user id if username was found\n *\/\nint SubutaiContainer::getRunAsUserId(stirng username) {\n if (_users.empty()) {\n UpdateUsersList();\n }\n for (user_it it = _users.begin(); it != _users.end(); it++) {\n if ((*it)->second.compare(username) == 0) {\n return (*it)->first;\n }\n } \n return -1;\n}\nminor bug fixes\/**\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @copyright 2014 Safehaus.org\n *\/\n\/**\n * @brief SubutaiContainer.cpp\n * @class SubutaiContainer.cpp\n * @details SubutaiContainer Class is designed for getting and setting container variables and special informations.\n * \t\t This class's instance can get get useful container specific informations\n * \t\t such as IPs, UUID, hostname, macID, parentHostname, etc..\n * @author Mikhail Savochkin\n * @author Ozlem Ceren Sahin\n * @version 1.1.0\n * @date Oct 31, 2014\n *\/\n#include \"SubutaiContainer.h\"\n#include \"SubutaiConnection.h\"\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\/**\n * \\details Default constructor of SubutaiEnvironment class.\n *\/\nSubutaiContainer::SubutaiContainer(SubutaiLogger* logger, lxc_container* cont)\n{\n this->container = cont;\n this->containerLogger = logger;\n}\n\n\/**\n * \\details Default destructor of SubutaiEnvironment class.\n *\/\nSubutaiContainer::~SubutaiContainer()\n{\n \/\/ TODO Auto-generated destructor stub\n}\n\n\n\/**\n * \\details This method designed for Typically conversion from integer to string.\n *\/\nstring SubutaiContainer::toString(int intcont)\n{\t\t\/\/integer to string conversion\n ostringstream dummy;\n dummy << intcont;\n return dummy.str();\n}\n\nstring SubutaiContainer::RunProgram(string program, vector params) {\n ExecutionResult result = RunProgram(program, params, true);\n if (result.exit_code == 0) {\n return result.out;\n } else {\n return result.err;\n }\n}\n\nExecutionResult SubutaiContainer::RunProgram(string program, vector params, bool return_result) {\n char* _params[params.size() + 2];\n _params[0] = const_cast(program.c_str());\n vector::iterator it;\n int i = 1;\n for (it = params.begin(); it != params.end(); it++, i++) {\n _params[i] = const_cast(it->c_str());\n }\n _params[i] = NULL;\n lxc_attach_options_t opts = LXC_ATTACH_OPTIONS_DEFAULT;\n int fd[2];\n int _stdout = dup(1);\n pipe(fd);\n dup2(fd[1], 1);\n char buffer[1000];\n ExecutionResult result;\n result.exit_code = this->container->attach_run_wait(this->container, &opts, program.c_str(), _params);\n fflush(stdout);\n close(fd[1]);\n dup2(_stdout, 1);\n close(_stdout);\n string command_output;\n while (1) {\n ssize_t size = read(fd[0], buffer, 1000);\n command_output += buffer;\n if (size < 1000) {\n buffer[size] = '\\0';\n command_output += buffer;\n break;\n } else {\n command_output += buffer;\n }\n }\n if (result.exit_code == 0) {\n result.out = command_output;\n } else {\n result.err = command_output;\n }\n return result;\n}\n\n\nbool SubutaiContainer::isContainerRunning()\n{\n if (this->status == RUNNING) return true;\n return false;\n}\n\nbool SubutaiContainer::isContainerStopped()\n{\n if (this->status == STOPPED) return true;\n return false;\n}\n\nbool SubutaiContainer::isContainerFrozen()\n{\n if (this->status == FROZEN) return true;\n return false;\n}\n\nvoid SubutaiContainer::UpdateUsersList() { \n this->_users.clear();\n vector params;\n params.push_back(\"\/etc\/passwd\");\n string passwd = RunProgram(\"\/bin\/cat\", params);\n size_t n = 0;\n size_t p = 0;\n stringstream ss(passwd);\n string line;\n while (getline(ss, line, '\\n')) {\n int c = 0;\n int uid;\n string uname;\n while ((n = line.find_first_of(\":\", p)) != string::npos) {\n c++;\n if (n - p != 0) {\n if (c == 1) {\n \/\/ This is a username\n uname = line.substr(p, n - p);\n } else if (c == 3) {\n \/\/ This is a uid\n stringstream conv(line.substr(p, n - p));\n if (!(conv >> uid)) {\n uid = -1; \/\/ We failed to convert string to int\n }\n }\n }\n this->_users.insert(make_pair(uid, uname));\n }\n }\n}\n\/**\n * \\details UUID of the Subutai Agent is fetched from statically using this function.\n * \t\t Example uuid:\"ff28d7c7-54b4-4291-b246-faf3dd493544\"\n *\/\nbool SubutaiContainer::getContainerId()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/etc\/subutai-agent\/uuid.txt\");\n this-> id = RunProgram(\"\/bin\/cat\", args);\n if (this->id.empty())\t\t\/\/if uuid is null or not reading successfully\n {\n boost::uuids::random_generator gen;\n boost::uuids::uuid u = gen();\n const std::string tmp = boost::lexical_cast(u);\n this->id = tmp;\n args.clear();\n args.push_back(this->id);\n args.push_back(\">\");\n args.push_back(\"\/etc\/subutai-agent\/uuid.txt\");\n this-> id = RunProgram(\"\/bin\/echo\", args);\n containerLogger->writeLog(1,containerLogger->setLogData(\"\",\"Subutai Agent UUID: \",this->id));\n return false;\n }\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\/**\n * \\details MACID(eth0) of the KiskisAgent is fetched from statically.\n *\/\nbool SubutaiContainer::getContainerMacAddress()\n{\n if(this->status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/sys\/class\/net\/eth0\/address\");\n this-> macAddress = RunProgram(\"\/bin\/cat\", args);\n if(this->macAddress.empty())\t\t\/\/if mac is null or not reading successfully\n {\n containerLogger->writeLog(3,containerLogger->setLogData(\"\",\"MacAddress cannot be read !!\"));\n return false;\n }\n containerLogger->writeLog(6,containerLogger->setLogData(\"\",\"Subutai Agent MacID:\",this->macAddress));\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\/**\n * \\details Hostname of the KiskisAgent machine is fetched from statically.\n *\/\nbool SubutaiContainer::getContainerHostname()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/etc\/hostname\");\n this-> hostname = RunProgram(\"\/bin\/cat\", args);\n if(this->hostname.empty())\t\t\/\/if hostname is null or not reading successfully\n {\n return false;\n }\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\/**\n * \\details Hostname of the KiskisAgent machine is fetched from statically.\n *\/\nvoid SubutaiContainer::setContainerHostname(string hostname)\n{\n this-> hostname = hostname;\n}\n\n\/**\n * \\details Hostname of the KiskisAgent machine is fetched from statically.\n *\/\ncontainerStatus SubutaiContainer::getContainerStatus()\n{\n return this->status;\n}\n\nvoid SubutaiContainer::setContainerStatus(containerStatus status)\n{\n this->status = status;\n}\n\/**\n * \\details Parent Hostname of the Subutai Agent machine is fetched from c paramonfig file.\n *\/\nbool SubutaiContainer::getContainerParentHostname()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n vector args;\n args.push_back(\"\/etc\/hostname\");\n string config = RunProgram(\"\/bin\/cat\", args);\n if (config.empty()) \/\/file exist\n {\n ofstream file(\"\/tmp\/subutai\/config.txt\");\n file << config;\n file.close();\n boost::property_tree::ptree pt;\n boost::property_tree::ini_parser::read_ini(\"\/tmp\/subutai\/config.txt\", pt);\n parentHostname = pt.get(\"Subutai-Agent.subutai_parent_hostname\");\n containerLogger->writeLog(6, containerLogger->setLogData(\"\",\"parentHostname: \",parentHostname));\n }\n\n if (!parentHostname.empty())\n {\n return true;\n }\n else\n {\n containerLogger->writeLog(6, containerLogger->setLogData(\"\",\"parentHostname does not exist!\"));\n return false;\n }\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n return false;\n}\n\n\n\/**\n * \\details IpAddress of the KiskisAgent machine is fetched from statically.\n *\/\nbool SubutaiContainer::getContainerIpAddress()\n{\n if(this-> status != RUNNING) return false;\n try\n {\n ipAddress.clear();\n\n vector args ;\n string config = RunProgram(\"ifconfig\", args);\n\n ofstream file(\"\/tmp\/subutai\/ipaddress.txt\");\n file << config;\n file.close();\n\n FILE * fp = fopen(\"\/tmp\/subutai\/ipaddress.txt\", \"r\");\n if (fp)\n {\n char *p=NULL, *e; size_t n;\n while ((getline(&p, &n, fp) > 0) && p)\n {\n if ((p = strstr(p, \"inet addr:\")))\n {\n p+=10;\n if ((e = strchr(p, ' ')))\n {\n *e='\\0';\n ipAddress.push_back(p);\n }\n }\n }\n }\n pclose(fp);\n\n for(unsigned int i=0; i < ipAddress.size() ; i++)\n {\n containerLogger->writeLog(6,containerLogger->setLogData(\"\",\"Subutai Agent IpAddress:\",ipAddress[i]));\n }\n return true;\n }\n catch(const std::exception& error)\n {\n cout << error.what()<< endl;\n }\n containerLogger->writeLog(3,containerLogger->setLogData(\"\",\"IpAddress cannot be read !!\"));\n return false;\n}\n\n\/**\n * \\details getting Agent uuid value.\n *\/\nstring SubutaiContainer::getContainerIdValue()\n{\n return id;\n}\n\n\/**\n * \\details getting Agent hostname value.\n *\/\nstring SubutaiContainer::getContainerHostnameValue()\n{\n return hostname;\n}\n\n\/**\n * \\details getting lxc container value.\n *\/\nlxc_container* SubutaiContainer::getLxcContainerValue()\n{\n return container;\n}\n\n\/**\n * \\details getting Agent macaddress value.\n *\/\nstring SubutaiContainer::getContainerMacAddressValue()\n{\n return macAddress;\n}\n\n\/**\n * \\details getting Agent parentHostname value.\n *\/\nstring SubutaiContainer::getContainerParentHostnameValue()\n{\n return parentHostname;\n}\n\n\/**\n * \\details getting Agent Ip values.\n *\/\nvector SubutaiContainer::getContainerIpValue()\n{\n return ipAddress;\n}\n\nvoid SubutaiContainer::getContainerAllFields()\n{\n getContainerId();\n getContainerMacAddress();\n getContainerHostname();\n getContainerParentHostname();\n getContainerIpAddress();\n}\n\nvoid SubutaiContainer::write(){\n cout << id << \" \" << macAddress << \" \" << hostname << \" \" << parentHostname<< \" \" << endl;\n\n}\n\n\nvoid SubutaiContainer::registerContainer(SubutaiConnection* connection)\n{\n SubutaiResponsePack response;\n string sendout = response.createRegistrationMessage(this->id,this->macAddress,this->hostname,this->parentHostname,NULL,this->ipAddress);\n containerLogger->writeLog(7,containerLogger->setLogData(\"\",\"Registration Message:\",sendout));\n connection->sendMessage(sendout);\n}\n\n\/\/ We need to check if CWD is exist because in LXC API - if cwd does not\n\/\/ exist CWD will become root directory\nbool SubutaiContainer::checkCWD(string cwd) {\n vector params;\n params.push_back(cwd);\n ExecutionResult result = RunProgram(\"\/bin\/cd\", params, true); \n if (result.exit_code == 0) \n return true;\n else\n return false;\n}\n\n\/*\n * \/details Runs throught the list of userid:username pairs\n * and check user existence\n *\/\n\nbool SubutaiContainer::checkUser(string username) {\n if (_users.empty()) {\n UpdateUsersList();\n }\n for (user_it it = _users.begin(); it != _users.end(); it++) {\n if ((*it).second.compare(username) == 0) {\n return true;\n }\n } \n return false;\n}\n\n\/*\n * \/details Runs through the list of userid:username pairs\n * and returns user id if username was found\n *\/\nint SubutaiContainer::getRunAsUserId(string username) {\n if (_users.empty()) {\n UpdateUsersList();\n }\n for (user_it it = _users.begin(); it != _users.end(); it++) {\n if ((*it).second.compare(username) == 0) {\n return (*it).first;\n }\n } \n return -1;\n}\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2018-2019 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"ArcballCamera.h\"\n\/\/ ospray_testing\n#include \"ospray_testing.h\"\n\/\/ google benchmark\n#include \"benchmark\/benchmark.h\"\n\nusing namespace ospray;\nusing namespace ospcommon;\nusing namespace ospcommon::math;\n\n\/\/ Test init\/shutdown cylcle time \/\/\n\nstatic void ospInit_ospShutdown(benchmark::State &state)\n{\n ospShutdown();\n\n for (auto _ : state) {\n ospInit();\n ospShutdown();\n }\n\n ospInit();\n}\n\nBENCHMARK(ospInit_ospShutdown)->Unit(benchmark::kMillisecond);\n\n\/\/ Test rendering scenes from 'ospray_testing' \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct RenderingObjects\n{\n cpp::FrameBuffer f;\n cpp::Renderer r;\n cpp::Camera c;\n cpp::World w;\n};\n\nstatic RenderingObjects construct_test(std::string rendererType,\n std::string scene,\n vec2i imgSize = vec2i(1024, 768))\n{\n \/\/ Frame buffer \/\/\n\n cpp::FrameBuffer fb(\n imgSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM | OSP_FB_DEPTH);\n fb.resetAccumulation();\n\n \/\/ Scene \/\/\n\n auto builder = testing::newBuilder(scene);\n testing::setParam(builder, \"rendererType\", rendererType);\n testing::commit(builder);\n\n auto world = testing::buildWorld(builder);\n testing::release(builder);\n\n world.commit();\n\n auto worldBounds = world.getBounds();\n\n \/\/ Camera \/\/\n\n ArcballCamera arcballCamera(worldBounds, imgSize);\n\n cpp::Camera camera(\"perspective\");\n camera.setParam(\"aspect\", imgSize.x \/ (float)imgSize.y);\n camera.setParam(\"position\", arcballCamera.eyePos());\n camera.setParam(\"direction\", arcballCamera.lookDir());\n camera.setParam(\"up\", arcballCamera.upDir());\n camera.commit();\n\n \/\/ Renderer \/\/\n\n cpp::Renderer renderer(rendererType);\n renderer.commit();\n\n return {fb, renderer, camera, world};\n}\n\nvoid gravity_spheres_scivis(benchmark::State &state)\n{\n auto objs = construct_test(\"scivis\", \"gravity_spheres_volume\");\n\n for (auto _ : state) {\n objs.f.renderFrame(objs.r, objs.c, objs.w);\n }\n}\n\nvoid gravity_spheres_pathtracer(benchmark::State &state)\n{\n auto objs = construct_test(\"pathtracer\", \"gravity_spheres_volume\");\n\n for (auto _ : state) {\n objs.f.renderFrame(objs.r, objs.c, objs.w);\n }\n}\n\nBENCHMARK(gravity_spheres_scivis)->Unit(benchmark::kMillisecond);\nBENCHMARK(gravity_spheres_pathtracer)->Unit(benchmark::kMillisecond);\n\n\/\/ based on BENCHMARK_MAIN() macro from benchmark.h\nint main(int argc, char **argv)\n{\n ospInit();\n\n ::benchmark::Initialize(&argc, argv);\n if (::benchmark::ReportUnrecognizedArguments(argc, argv))\n return 1;\n ::benchmark::RunSpecifiedBenchmarks();\n\n ospShutdown();\n\n return 0;\n}\nswitch to using a Fixture\/\/ ======================================================================== \/\/\n\/\/ Copyright 2018-2019 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"ArcballCamera.h\"\n\/\/ ospray_testing\n#include \"ospray_testing.h\"\n\/\/ google benchmark\n#include \"benchmark\/benchmark.h\"\n\nusing namespace ospray;\nusing namespace ospcommon;\nusing namespace ospcommon::math;\n\n\/\/ Test init\/shutdown cycle time \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void ospInit_ospShutdown(benchmark::State &state)\n{\n ospShutdown();\n\n for (auto _ : state) {\n ospInit();\n ospShutdown();\n }\n\n ospInit();\n}\n\nBENCHMARK(ospInit_ospShutdown)->Unit(benchmark::kMillisecond);\n\n\/\/ Test rendering scenes from 'ospray_testing' \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass BaseBenchmark : public ::benchmark::Fixture\n{\n public:\n BaseBenchmark(std::string r, std::string s) : rendererType(r), scene(s) {}\n\n void SetUp(::benchmark::State &) override\n {\n framebuffer = cpp::FrameBuffer(\n imgSize, OSP_FB_SRGBA, OSP_FB_COLOR | OSP_FB_ACCUM | OSP_FB_DEPTH);\n framebuffer.resetAccumulation();\n\n auto builder = testing::newBuilder(scene);\n testing::setParam(builder, \"rendererType\", rendererType);\n testing::commit(builder);\n\n world = testing::buildWorld(builder);\n testing::release(builder);\n\n world.commit();\n\n auto worldBounds = world.getBounds();\n\n ArcballCamera arcballCamera(worldBounds, imgSize);\n\n camera = cpp::Camera(\"perspective\");\n camera.setParam(\"aspect\", imgSize.x \/ (float)imgSize.y);\n camera.setParam(\"position\", arcballCamera.eyePos());\n camera.setParam(\"direction\", arcballCamera.lookDir());\n camera.setParam(\"up\", arcballCamera.upDir());\n camera.commit();\n\n renderer = cpp::Renderer(rendererType);\n renderer.commit();\n }\n\n void BenchmarkCase(::benchmark::State &state) override\n {\n for (auto _ : state) {\n framebuffer.renderFrame(renderer, camera, world);\n }\n }\n\n protected:\n vec2i imgSize{1024, 768};\n std::string rendererType;\n std::string scene;\n\n cpp::FrameBuffer framebuffer;\n cpp::Renderer renderer;\n cpp::Camera camera;\n cpp::World world;\n};\n\nclass GravitySpheres : public BaseBenchmark\n{\n public:\n GravitySpheres() : BaseBenchmark(\"pathtracer\", \"gravity_spheres_volume\") {}\n};\n\nBENCHMARK_DEFINE_F(GravitySpheres, gravity_spheres_pathtracer)\n(benchmark::State &st)\n{\n for (auto _ : st) {\n framebuffer.renderFrame(renderer, camera, world);\n }\n}\n\nBENCHMARK_REGISTER_F(GravitySpheres, gravity_spheres_pathtracer)\n ->Unit(benchmark::kMillisecond);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ based on BENCHMARK_MAIN() macro from benchmark.h\nint main(int argc, char **argv)\n{\n ospInit();\n\n ::benchmark::Initialize(&argc, argv);\n if (::benchmark::ReportUnrecognizedArguments(argc, argv))\n return 1;\n ::benchmark::RunSpecifiedBenchmarks();\n\n ospShutdown();\n\n return 0;\n}\n<|endoftext|>"} {"text":"extern \"C\" {\n#include \"postgres.h\"\n#include \"fmgr.h\"\n#include \"catalog\/pg_type.h\"\n#include \"utils\/uuid.h\"\n#include \"executor\/spi.h\"\n#include \"provsql_utils.h\"\n \n PG_FUNCTION_INFO_V1(where_provenance);\n}\n\n#include \n\n#include \"BooleanCircuit.h\"\n\nusing namespace std;\n\n\/* copied with small changes from uuid.c *\/\n\nstatic Datum where_provenance_internal\n (Datum token)\n{\n constants_t constants;\n if(!initialize_constants(&constants)) {\n elog(ERROR, \"Cannot find provsql schema\");\n }\n\n Datum arguments[1]={token};\n Oid argtypes[1]={constants.OID_TYPE_PROVENANCE_TOKEN};\n char nulls[1] = {' '};\n \n SPI_connect();\n\n if(SPI_execute_with_args(\n \"SELECT * FROM provsql.sub_circuit_for_where($1)\", 2, argtypes, arguments, nulls, true, 0)\n == SPI_OK_SELECT) {\n \/\/ TODO\n }\n\n SPI_finish();\n\n \/\/ TODO\n\n return (Datum) 0;\n}\n\nDatum where_provenance(PG_FUNCTION_ARGS)\n{\n try {\n Datum token = PG_GETARG_DATUM(0);\n\n return where_provenance_internal(token);\n } catch(const std::exception &e) {\n elog(ERROR, \"probability_evaluate: %s\", e.what());\n } catch(...) {\n elog(ERROR, \"probability_evaluate: Unknown exception\");\n }\n\n PG_RETURN_NULL();\n}\nWorking skeleton of where_provenance functionextern \"C\" {\n\n#include \"postgres.h\"\n#include \"fmgr.h\"\n#include \"catalog\/pg_type.h\"\n#include \"utils\/uuid.h\"\n#include \"executor\/spi.h\"\n#include \"utils\/builtins.h\"\n\n#include \"provsql_utils.h\"\n \n PG_FUNCTION_INFO_V1(where_provenance);\n}\n\n#include \n\n#include \"BooleanCircuit.h\"\n\nusing namespace std;\n\n\/* copied with small changes from uuid.c *\/\n\nstatic string where_provenance_internal\n (Datum token)\n{\n constants_t constants;\n if(!initialize_constants(&constants)) {\n elog(ERROR, \"Cannot find provsql schema\");\n }\n\n Datum arguments[1]={token};\n Oid argtypes[1]={constants.OID_TYPE_PROVENANCE_TOKEN};\n char nulls[1] = {' '};\n \n SPI_connect();\n\n if(SPI_execute_with_args(\n \"SELECT * FROM provsql.sub_circuit_for_where($1)\", 2, argtypes, arguments, nulls, true, 0)\n == SPI_OK_SELECT) {\n \/\/ TODO\n }\n\n SPI_finish();\n\n \/\/ TODO\n\n return \"\";\n}\n\nDatum where_provenance(PG_FUNCTION_ARGS)\n{\n try {\n Datum token = PG_GETARG_DATUM(0);\n\n PG_RETURN_TEXT_P(cstring_to_text(where_provenance_internal(token).c_str()));\n } catch(const std::exception &e) {\n elog(ERROR, \"where_provenance: %s\", e.what());\n } catch(...) {\n elog(ERROR, \"where_provenance: Unknown exception\");\n }\n}\n<|endoftext|>"} {"text":"#define DEBUG 1\n\n\/**\n * File : C2.cpp\n * Author : Kazune Takahashi\n * Created : 2019-6-3 00:42:00\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\n\/*\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\n\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n*\/\n\n\/*\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n*\/\n\n\/\/ const ll MOD = 1000000007;\n\nll N, X;\nll b[100010], l[100010], u[100010];\nll base = 0;\ntypedef tuple test;\nvector V;\nll sum[100010];\n\nbool solve(ll T)\n{\n int cnt = T \/ X;\n ll x = T % X;\n ll ans = sum[cnt];\n ll maxi = 0;\n for (auto i = cnt; i < N; i++)\n {\n ll t, b, l, u;\n tie(t, b, l, u) = V[i];\n ll tmp = 0;\n if (x >= b)\n {\n tmp = l * b + (x - b) * u;\n }\n else\n {\n tmp = l * x;\n }\n maxi = max(maxi, tmp);\n }\n return (ans + maxi >= 0);\n}\n\nint main()\n{\n cin >> N >> X;\n for (auto i = 0; i < N; i++)\n {\n cin >> b[i] >> l[i] >> u[i];\n }\n for (auto i = 0; i < N; i++)\n {\n base -= b[i] * l[i];\n }\n for (auto i = 0; i < N; i++)\n {\n ll t = l[i] * b[i] + (X - l[i]) * u[i];\n V.emplace_back(t, b[i], l[i], u[i]);\n }\n sort(V.begin(), V.end());\n reverse(V.begin(), V.end());\n sum[0] = base;\n for (auto i = 0; i < N; i++)\n {\n sum[i + 1] = sum[i] + get<0>(V[i]);\n }\n ll ok = N * X + 1;\n ll ng = -1;\n while (abs(ok - ng) > 1)\n {\n ll t = (ok + ng) \/ 2;\n if (solve(t))\n {\n ok = t;\n }\n else\n {\n ng = t;\n }\n }\n cout << ok << endl;\n}tried C2.cpp to 'C'#define DEBUG 1\n\n\/**\n * File : C2.cpp\n * Author : Kazune Takahashi\n * Created : 2019-6-3 00:42:00\n * Powered by Visual Studio Code\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef long long ll;\n\n\/*\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\n\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n*\/\n\n\/*\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n*\/\n\n\/\/ const ll MOD = 1000000007;\n\nll N, X;\nll b[100010], l[100010], u[100010];\nll base = 0;\ntypedef tuple test;\nvector V;\nll sum[100010];\n\nbool solve(ll T)\n{\n int cnt = T \/ X;\n ll x = T % X;\n ll ans = sum[cnt];\n ll maxi = 0;\n for (auto i = cnt; i < N; i++)\n {\n ll t, b, l, u;\n tie(t, b, l, u) = V[i];\n ll tmp = 0;\n if (x >= b)\n {\n tmp = l * b + (x - b) * u;\n }\n else\n {\n tmp = l * x;\n }\n maxi = max(maxi, tmp);\n }\n#if DEBUG == 1\n cerr << \"T = \" << T << \", ans = \" << ans + maxi << endl;\n#endif\n return (ans + maxi >= 0);\n}\n\nint main()\n{\n cin >> N >> X;\n for (auto i = 0; i < N; i++)\n {\n cin >> b[i] >> l[i] >> u[i];\n }\n for (auto i = 0; i < N; i++)\n {\n base -= b[i] * l[i];\n }\n for (auto i = 0; i < N; i++)\n {\n ll t = l[i] * b[i] + (X - l[i]) * u[i];\n V.emplace_back(t, b[i], l[i], u[i]);\n }\n sort(V.begin(), V.end());\n reverse(V.begin(), V.end());\n sum[0] = base;\n for (auto i = 0; i < N; i++)\n {\n sum[i + 1] = sum[i] + get<0>(V[i]);\n }\n ll ok = N * X + 1;\n ll ng = -1;\n while (abs(ok - ng) > 1)\n {\n ll t = (ok + ng) \/ 2;\n if (solve(t))\n {\n ok = t;\n }\n else\n {\n ng = t;\n }\n }\n cout << ok << endl;\n}<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : F2.cpp\n * Author : Kazune Takahashi\n * Created : 7\/5\/2020, 3:11:13 AM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate \nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\n\/\/ ----- for C++17 -----\ntemplate ::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- MP algorithm -----\n\ntemplate \nclass MP\n{\n int N;\n Type S;\n vector A;\n\npublic:\n MP() {}\n MP(Type const &S) : N(S.size()), S{S}, A(N + 1, -1)\n {\n int j{-1};\n for (auto i{0}; i < N; i++)\n {\n while (j != -1 && S[j] != S[i])\n {\n j = A[j];\n }\n ++j;\n A[i + 1] = j;\n }\n }\n\n int operator[](int i) const { return A[i]; }\n\n int period(int i) const { return i - A[i]; }\n\n vector place(Type const &T) const\n {\n vector res;\n int j{0};\n for (auto i{size_t{0}}; i < T.size(); i++)\n {\n while (j != -1 && S[j] != T[i])\n {\n j = A[j];\n }\n ++j;\n if (j == N)\n {\n res.push_back(i - j + 1);\n j = A[j];\n }\n }\n return res;\n }\n\n vector table(Type const &T) const\n {\n vector res(T.size(), false);\n for (auto e : place(T))\n {\n res[e] = true;\n }\n return res;\n }\n};\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n string w;\n int n;\n int ans;\n MP mp, mp_rev;\n\npublic:\n Solve() : ans{0}\n {\n cin >> w;\n n = w.size();\n mp = MP{w};\n reverse(w.begin(), w.end());\n mp_rev = MP{w};\n reverse(w.begin(), w.end());\n }\n\n void flush()\n {\n if (all_of(w.begin(), w.end(), [&](auto c) { return c == w[0]; }))\n {\n cout << n << endl;\n cout << 1 << endl;\n }\n else if (is_good(mp, n))\n {\n cout << 1 << endl;\n cout << 1 << endl;\n }\n else\n {\n for (auto i{1}; i < n; ++i)\n {\n if (is_good(mp, i) && is_good(mp_rev, n - i))\n {\n ++ans;\n }\n }\n cout << 2 << endl;\n cout << ans << endl;\n }\n }\n\nprivate:\n bool is_good(MP const &mp, int s)\n {\n return s % mp.period(s) != 0;\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n Solve solve;\n solve.flush();\n}\nsubmit F2.cpp to 'F - 最良表現' (arc060) [C++ (GCC 9.2.1)]#define DEBUG 1\n\/**\n * File : F2.cpp\n * Author : Kazune Takahashi\n * Created : 7\/5\/2020, 3:11:13 AM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate \nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\n\/\/ ----- for C++17 -----\ntemplate ::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- MP algorithm -----\n\ntemplate \nclass MP\n{\n int N;\n Type S;\n vector A;\n\npublic:\n MP() {}\n MP(Type const &S) : N(S.size()), S{S}, A(N + 1, -1)\n {\n int j{-1};\n for (auto i{0}; i < N; i++)\n {\n while (j != -1 && S[j] != S[i])\n {\n j = A[j];\n }\n ++j;\n A[i + 1] = j;\n }\n }\n\n int operator[](int i) const { return A[i]; }\n\n int period(int i) const { return i - A[i]; }\n\n vector place(Type const &T) const\n {\n vector res;\n int j{0};\n for (auto i{size_t{0}}; i < T.size(); i++)\n {\n while (j != -1 && S[j] != T[i])\n {\n j = A[j];\n }\n ++j;\n if (j == N)\n {\n res.push_back(i - j + 1);\n j = A[j];\n }\n }\n return res;\n }\n\n vector table(Type const &T) const\n {\n vector res(T.size(), false);\n for (auto e : place(T))\n {\n res[e] = true;\n }\n return res;\n }\n};\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n string w;\n int n;\n int ans;\n MP mp, mp_rev;\n\npublic:\n Solve() : ans{0}\n {\n cin >> w;\n n = w.size();\n mp = MP{w};\n reverse(w.begin(), w.end());\n mp_rev = MP{w};\n reverse(w.begin(), w.end());\n }\n\n void flush()\n {\n if (all_of(w.begin(), w.end(), [&](auto c) { return c == w[0]; }))\n {\n cout << n << endl;\n cout << 1 << endl;\n }\n else if (is_good(mp, n))\n {\n cout << 1 << endl;\n cout << 1 << endl;\n }\n else\n {\n for (auto i{1}; i < n; ++i)\n {\n if (is_good(mp, i) && is_good(mp_rev, n - i))\n {\n ++ans;\n }\n }\n cout << 2 << endl;\n cout << ans << endl;\n }\n }\n\nprivate:\n bool is_good(MP const &mp, int s)\n {\n auto p{mp.period(s)};\n return p == s || s % p != 0;\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n Solve solve;\n solve.flush();\n}\n<|endoftext|>"} {"text":"#include \"widgets\/notebook.hpp\"\n#include \"debug\/log.hpp\"\n#include \"singletons\/thememanager.hpp\"\n#include \"singletons\/windowmanager.hpp\"\n#include \"widgets\/helper\/notebookbutton.hpp\"\n#include \"widgets\/helper\/notebooktab.hpp\"\n#include \"widgets\/settingsdialog.hpp\"\n#include \"widgets\/splitcontainer.hpp\"\n#include \"widgets\/window.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace chatterino {\nnamespace widgets {\n\nNotebook::Notebook(Window *parent, bool _showButtons, const std::string &settingPrefix)\n : BaseWidget(parent)\n , parentWindow(parent)\n , settingRoot(fS(\"{}\/notebook\", settingPrefix))\n , addButton(this)\n , settingsButton(this)\n , userButton(this)\n , showButtons(_showButtons)\n , tabs(fS(\"{}\/tabs\", this->settingRoot))\n , closeConfirmDialog(this)\n{\n this->connect(&this->settingsButton, SIGNAL(clicked()), this, SLOT(settingsButtonClicked()));\n this->connect(&this->userButton, SIGNAL(clicked()), this, SLOT(usersButtonClicked()));\n this->connect(&this->addButton, SIGNAL(clicked()), this, SLOT(addPageButtonClicked()));\n\n this->settingsButton.icon = NotebookButton::IconSettings;\n\n this->userButton.move(24, 0);\n this->userButton.icon = NotebookButton::IconUser;\n\n auto &settingsManager = singletons::SettingManager::getInstance();\n\n settingsManager.hidePreferencesButton.connectSimple([this](auto) { this->performLayout(); });\n settingsManager.hideUserButton.connectSimple([this](auto) { this->performLayout(); });\n\n this->loadTabs();\n\n closeConfirmDialog.setText(\"Are you sure you want to close this tab?\");\n closeConfirmDialog.setIcon(QMessageBox::Icon::Question);\n closeConfirmDialog.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);\n closeConfirmDialog.setDefaultButton(QMessageBox::Yes);\n\n \/\/ this->scaleChangedEvent(this->getScale());\n}\n\nSplitContainer *Notebook::addNewPage()\n{\n return this->addPage(CreateUUID().toStdString(), true);\n}\n\nSplitContainer *Notebook::addPage(const std::string &uuid, bool select)\n{\n auto tab = new NotebookTab(this, uuid);\n auto page = new SplitContainer(this, tab, uuid);\n\n tab->show();\n\n if (select || this->pages.count() == 0) {\n this->select(page);\n }\n\n this->pages.append(page);\n\n this->performLayout();\n\n return page;\n}\n\nvoid Notebook::removePage(SplitContainer *page)\n{\n if (page->splitCount() > 0 && closeConfirmDialog.exec() != QMessageBox::Yes) {\n return;\n }\n\n int index = this->pages.indexOf(page);\n\n if (this->pages.size() == 1) {\n select(nullptr);\n } else if (index == this->pages.count() - 1) {\n select(this->pages[index - 1]);\n } else {\n select(this->pages[index + 1]);\n }\n\n page->getTab()->deleteLater();\n page->deleteLater();\n\n this->pages.removeOne(page);\n\n if (this->pages.size() == 0) {\n this->addNewPage();\n }\n\n this->performLayout();\n}\n\nvoid Notebook::removeCurrentPage()\n{\n if (this->selectedPage == nullptr) {\n return;\n }\n\n this->removePage(this->selectedPage);\n}\n\nvoid Notebook::select(SplitContainer *page)\n{\n if (page == this->selectedPage) {\n return;\n }\n\n if (page != nullptr) {\n page->setHidden(false);\n page->getTab()->setSelected(true);\n page->getTab()->raise();\n }\n\n if (this->selectedPage != nullptr) {\n this->selectedPage->setHidden(true);\n this->selectedPage->getTab()->setSelected(false);\n for (auto split : this->selectedPage->getSplits()) {\n split->updateLastReadMessage();\n }\n }\n\n this->selectedPage = page;\n\n this->performLayout();\n}\n\nvoid Notebook::selectIndex(int index)\n{\n if (index < 0 || index >= this->pages.size()) {\n return;\n }\n\n this->select(this->pages.at(index));\n}\n\nint Notebook::tabCount()\n{\n return this->pages.size();\n}\n\nSplitContainer *Notebook::tabAt(QPoint point, int &index, int maxWidth)\n{\n int i = 0;\n\n for (auto *page : this->pages) {\n QRect rect = page->getTab()->getDesiredRect();\n rect.setWidth(std::min(maxWidth, rect.width()));\n\n if (rect.contains(point)) {\n index = i;\n return page;\n }\n\n i++;\n }\n\n index = -1;\n return nullptr;\n}\n\nvoid Notebook::rearrangePage(SplitContainer *page, int index)\n{\n this->pages.move(this->pages.indexOf(page), index);\n\n this->performLayout();\n}\n\nvoid Notebook::nextTab()\n{\n if (this->pages.size() <= 1) {\n return;\n }\n\n int index = (this->pages.indexOf(this->selectedPage) + 1) % this->pages.size();\n\n this->select(this->pages[index]);\n}\n\nvoid Notebook::previousTab()\n{\n if (this->pages.size() <= 1) {\n return;\n }\n\n int index = (this->pages.indexOf(this->selectedPage) - 1);\n\n if (index < 0) {\n index += this->pages.size();\n }\n\n this->select(this->pages[index]);\n}\n\nvoid Notebook::performLayout(bool animated)\n{\n singletons::SettingManager &settings = singletons::SettingManager::getInstance();\n\n int x = 0, y = 0;\n float scale = this->getScale();\n bool customFrame = this->parentWindow->hasCustomWindowFrame();\n\n if (!this->showButtons || settings.hidePreferencesButton || customFrame) {\n this->settingsButton.hide();\n } else {\n this->settingsButton.show();\n x += settingsButton.width();\n }\n if (!this->showButtons || settings.hideUserButton || customFrame) {\n this->userButton.hide();\n } else {\n this->userButton.move(x, 0);\n this->userButton.show();\n x += userButton.width();\n }\n\n if (customFrame || !this->showButtons ||\n (settings.hideUserButton && settings.hidePreferencesButton)) {\n x += (int)(scale * 2);\n }\n\n int tabHeight = static_cast(24 * scale);\n bool first = true;\n\n for (auto &i : this->pages) {\n if (!first &&\n (i == this->pages.last() ? tabHeight : 0) + x + i->getTab()->width() > width()) {\n y += i->getTab()->height();\n i->getTab()->moveAnimated(QPoint(0, y), animated);\n x = i->getTab()->width();\n } else {\n i->getTab()->moveAnimated(QPoint(x, y), animated);\n x += i->getTab()->width();\n }\n\n first = false;\n }\n\n this->addButton.move(x, y);\n\n if (this->selectedPage != nullptr) {\n this->selectedPage->move(0, y + tabHeight);\n this->selectedPage->resize(width(), height() - y - tabHeight);\n this->selectedPage->raise();\n }\n}\n\nvoid Notebook::resizeEvent(QResizeEvent *)\n{\n this->performLayout(false);\n}\n\nvoid Notebook::scaleChangedEvent(float)\n{\n float h = 24 * this->getScale();\n\n this->settingsButton.setFixedSize(h, h);\n this->userButton.setFixedSize(h, h);\n this->addButton.setFixedSize(h, h);\n\n for (auto &i : this->pages) {\n i->getTab()->updateSize();\n }\n}\n\nvoid Notebook::settingsButtonClicked()\n{\n singletons::WindowManager::getInstance().showSettingsDialog();\n}\n\nvoid Notebook::usersButtonClicked()\n{\n singletons::WindowManager::getInstance().showAccountSelectPopup(\n this->mapToGlobal(this->userButton.rect().bottomRight()));\n}\n\nvoid Notebook::addPageButtonClicked()\n{\n QTimer::singleShot(80, [this] { this->addNewPage(); });\n}\n\nvoid Notebook::loadTabs()\n{\n const std::vector tabArray = this->tabs.getValue();\n\n if (tabArray.size() == 0) {\n this->addNewPage();\n return;\n }\n\n for (const std::string &tabUUID : tabArray) {\n this->addPage(tabUUID);\n }\n}\n\nvoid Notebook::save()\n{\n std::vector tabArray;\n\n for (const auto &page : this->pages) {\n tabArray.push_back(page->getUUID());\n page->save();\n }\n\n this->tabs = tabArray;\n}\n\n} \/\/ namespace widgets\n} \/\/ namespace chatterino\nfixed + button size#include \"widgets\/notebook.hpp\"\n#include \"debug\/log.hpp\"\n#include \"singletons\/thememanager.hpp\"\n#include \"singletons\/windowmanager.hpp\"\n#include \"widgets\/helper\/notebookbutton.hpp\"\n#include \"widgets\/helper\/notebooktab.hpp\"\n#include \"widgets\/settingsdialog.hpp\"\n#include \"widgets\/splitcontainer.hpp\"\n#include \"widgets\/window.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace chatterino {\nnamespace widgets {\n\nNotebook::Notebook(Window *parent, bool _showButtons, const std::string &settingPrefix)\n : BaseWidget(parent)\n , parentWindow(parent)\n , settingRoot(fS(\"{}\/notebook\", settingPrefix))\n , addButton(this)\n , settingsButton(this)\n , userButton(this)\n , showButtons(_showButtons)\n , tabs(fS(\"{}\/tabs\", this->settingRoot))\n , closeConfirmDialog(this)\n{\n this->connect(&this->settingsButton, SIGNAL(clicked()), this, SLOT(settingsButtonClicked()));\n this->connect(&this->userButton, SIGNAL(clicked()), this, SLOT(usersButtonClicked()));\n this->connect(&this->addButton, SIGNAL(clicked()), this, SLOT(addPageButtonClicked()));\n\n this->settingsButton.icon = NotebookButton::IconSettings;\n\n this->userButton.move(24, 0);\n this->userButton.icon = NotebookButton::IconUser;\n\n auto &settingsManager = singletons::SettingManager::getInstance();\n\n settingsManager.hidePreferencesButton.connectSimple([this](auto) { this->performLayout(); });\n settingsManager.hideUserButton.connectSimple([this](auto) { this->performLayout(); });\n\n this->loadTabs();\n\n closeConfirmDialog.setText(\"Are you sure you want to close this tab?\");\n closeConfirmDialog.setIcon(QMessageBox::Icon::Question);\n closeConfirmDialog.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);\n closeConfirmDialog.setDefaultButton(QMessageBox::Yes);\n\n this->scaleChangedEvent(this->getScale());\n}\n\nSplitContainer *Notebook::addNewPage()\n{\n return this->addPage(CreateUUID().toStdString(), true);\n}\n\nSplitContainer *Notebook::addPage(const std::string &uuid, bool select)\n{\n auto tab = new NotebookTab(this, uuid);\n auto page = new SplitContainer(this, tab, uuid);\n\n tab->show();\n\n if (select || this->pages.count() == 0) {\n this->select(page);\n }\n\n this->pages.append(page);\n\n this->performLayout();\n\n return page;\n}\n\nvoid Notebook::removePage(SplitContainer *page)\n{\n if (page->splitCount() > 0 && closeConfirmDialog.exec() != QMessageBox::Yes) {\n return;\n }\n\n int index = this->pages.indexOf(page);\n\n if (this->pages.size() == 1) {\n select(nullptr);\n } else if (index == this->pages.count() - 1) {\n select(this->pages[index - 1]);\n } else {\n select(this->pages[index + 1]);\n }\n\n page->getTab()->deleteLater();\n page->deleteLater();\n\n this->pages.removeOne(page);\n\n if (this->pages.size() == 0) {\n this->addNewPage();\n }\n\n this->performLayout();\n}\n\nvoid Notebook::removeCurrentPage()\n{\n if (this->selectedPage == nullptr) {\n return;\n }\n\n this->removePage(this->selectedPage);\n}\n\nvoid Notebook::select(SplitContainer *page)\n{\n if (page == this->selectedPage) {\n return;\n }\n\n if (page != nullptr) {\n page->setHidden(false);\n page->getTab()->setSelected(true);\n page->getTab()->raise();\n }\n\n if (this->selectedPage != nullptr) {\n this->selectedPage->setHidden(true);\n this->selectedPage->getTab()->setSelected(false);\n for (auto split : this->selectedPage->getSplits()) {\n split->updateLastReadMessage();\n }\n }\n\n this->selectedPage = page;\n\n this->performLayout();\n}\n\nvoid Notebook::selectIndex(int index)\n{\n if (index < 0 || index >= this->pages.size()) {\n return;\n }\n\n this->select(this->pages.at(index));\n}\n\nint Notebook::tabCount()\n{\n return this->pages.size();\n}\n\nSplitContainer *Notebook::tabAt(QPoint point, int &index, int maxWidth)\n{\n int i = 0;\n\n for (auto *page : this->pages) {\n QRect rect = page->getTab()->getDesiredRect();\n rect.setWidth(std::min(maxWidth, rect.width()));\n\n if (rect.contains(point)) {\n index = i;\n return page;\n }\n\n i++;\n }\n\n index = -1;\n return nullptr;\n}\n\nvoid Notebook::rearrangePage(SplitContainer *page, int index)\n{\n this->pages.move(this->pages.indexOf(page), index);\n\n this->performLayout();\n}\n\nvoid Notebook::nextTab()\n{\n if (this->pages.size() <= 1) {\n return;\n }\n\n int index = (this->pages.indexOf(this->selectedPage) + 1) % this->pages.size();\n\n this->select(this->pages[index]);\n}\n\nvoid Notebook::previousTab()\n{\n if (this->pages.size() <= 1) {\n return;\n }\n\n int index = (this->pages.indexOf(this->selectedPage) - 1);\n\n if (index < 0) {\n index += this->pages.size();\n }\n\n this->select(this->pages[index]);\n}\n\nvoid Notebook::performLayout(bool animated)\n{\n singletons::SettingManager &settings = singletons::SettingManager::getInstance();\n\n int x = 0, y = 0;\n float scale = this->getScale();\n bool customFrame = this->parentWindow->hasCustomWindowFrame();\n\n if (!this->showButtons || settings.hidePreferencesButton || customFrame) {\n this->settingsButton.hide();\n } else {\n this->settingsButton.show();\n x += settingsButton.width();\n }\n if (!this->showButtons || settings.hideUserButton || customFrame) {\n this->userButton.hide();\n } else {\n this->userButton.move(x, 0);\n this->userButton.show();\n x += userButton.width();\n }\n\n if (customFrame || !this->showButtons ||\n (settings.hideUserButton && settings.hidePreferencesButton)) {\n x += (int)(scale * 2);\n }\n\n int tabHeight = static_cast(24 * scale);\n bool first = true;\n\n for (auto &i : this->pages) {\n if (!first &&\n (i == this->pages.last() ? tabHeight : 0) + x + i->getTab()->width() > width()) {\n y += i->getTab()->height();\n i->getTab()->moveAnimated(QPoint(0, y), animated);\n x = i->getTab()->width();\n } else {\n i->getTab()->moveAnimated(QPoint(x, y), animated);\n x += i->getTab()->width();\n }\n\n first = false;\n }\n\n this->addButton.move(x, y);\n\n if (this->selectedPage != nullptr) {\n this->selectedPage->move(0, y + tabHeight);\n this->selectedPage->resize(width(), height() - y - tabHeight);\n this->selectedPage->raise();\n }\n}\n\nvoid Notebook::resizeEvent(QResizeEvent *)\n{\n this->performLayout(false);\n}\n\nvoid Notebook::scaleChangedEvent(float)\n{\n float h = 24 * this->getScale();\n\n this->settingsButton.setFixedSize(h, h);\n this->userButton.setFixedSize(h, h);\n this->addButton.setFixedSize(h, h);\n\n for (auto &i : this->pages) {\n i->getTab()->updateSize();\n }\n}\n\nvoid Notebook::settingsButtonClicked()\n{\n singletons::WindowManager::getInstance().showSettingsDialog();\n}\n\nvoid Notebook::usersButtonClicked()\n{\n singletons::WindowManager::getInstance().showAccountSelectPopup(\n this->mapToGlobal(this->userButton.rect().bottomRight()));\n}\n\nvoid Notebook::addPageButtonClicked()\n{\n QTimer::singleShot(80, [this] { this->addNewPage(); });\n}\n\nvoid Notebook::loadTabs()\n{\n const std::vector tabArray = this->tabs.getValue();\n\n if (tabArray.size() == 0) {\n this->addNewPage();\n return;\n }\n\n for (const std::string &tabUUID : tabArray) {\n this->addPage(tabUUID);\n }\n}\n\nvoid Notebook::save()\n{\n std::vector tabArray;\n\n for (const auto &page : this->pages) {\n tabArray.push_back(page->getUUID());\n page->save();\n }\n\n this->tabs = tabArray;\n}\n\n} \/\/ namespace widgets\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"#include \"taginput.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst int defaultMargins = 6;\n\n\/\/---------------------------------------------------------\n\/\/ TagItem\n\/\/---------------------------------------------------------\n\nTagItem::TagItem(QObject *parent)\n : QObject(parent)\n , m_unique(true)\n{\n}\n\nTagItem::TagItem(const QString &tagName, QObject *parent)\n : QObject(parent)\n , m_tagName(tagName)\n , m_unique(true)\n{\n}\n\nTagItem::TagItem(const QString &tagName, const QString &tagId, QObject *parent)\n : QObject(parent)\n , m_tagName(tagName)\n , m_id(tagId)\n , m_unique(true)\n{\n}\n\nTagItem *TagItem::clone()\n{\n TagItem *item = new TagItem(parent());\n item->setTagName(m_tagName);\n item->setId(m_id);\n item->setDescriptionText(m_descriptionText);\n return item;\n}\n\nQString TagItem::tagName() const\n{\n return m_tagName;\n}\n\nvoid TagItem::setTagName(const QString &tagName)\n{\n m_tagName = tagName;\n}\n\nQString TagItem::id() const\n{\n return !m_id.isEmpty() ? m_id : m_tagName;\n}\n\nvoid TagItem::setId(const QString &id)\n{\n m_id = id;\n}\n\nQString TagItem::descriptionText() const\n{\n return !m_descriptionText.isEmpty() ? m_descriptionText : m_tagName;\n}\n\nvoid TagItem::setDescriptionText(const QString &descriptionText)\n{\n m_descriptionText = descriptionText;\n}\n\nbool TagItem::unique() const\n{\n return m_unique;\n}\n\nvoid TagItem::setUnique(bool unique)\n{\n m_unique = unique;\n}\n\n\/\/---------------------------------------------------------\n\/\/ TagInput\n\/\/---------------------------------------------------------\n\nTagInput::TagInput(QWidget *parent)\n : QScrollArea(parent)\n , m_dragStartOffset(0)\n{\n initWidget();\n\n#if 0\n append(\"test\");\n append(\"hoge\");\n append(\"a\");\n append(\"ほげふが\");\n append(\"ふふぉjのの\");\n append(\"っっz\");\n append(\"test5\");\n append(\"hoge6\");\n append(\"test7\");\n append(\"hoge8\");\n#endif\n}\n\nvoid TagInput::initWidget()\n{\n \/\/connect(this, &QTextEdit::textChanged, this, &TagInput::updateTags);\n\n QFontMetrics fm = fontMetrics();\n setSizePolicy(sizePolicy().horizontalPolicy(), QSizePolicy::Fixed);\n QMargins margin(contentsMargins().left() ? contentsMargins().left() : defaultMargins,\n contentsMargins().top() ? contentsMargins().top() : defaultMargins,\n contentsMargins().right() ? contentsMargins().right() : defaultMargins,\n contentsMargins().bottom() ? contentsMargins().bottom() : defaultMargins\n );\n setContentsMargins(0, 0, 0, 0);\n\n setMaximumHeight(fm.height() + margin.top() + margin.bottom() + 4 * 2);\n\n setBackgroundRole(QPalette::Base);\n setFrameShadow(QFrame::Plain);\n setFrameShape(QFrame::StyledPanel);\n setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n setWidgetResizable(true);\n\n QWidget* base = new QWidget(this);\n base->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);\n base->setLayout(m_layout = new QHBoxLayout(base));\n setWidget(base);\n\n m_layout->setSpacing(defaultMargins);\n m_layout->setContentsMargins(margin.left() ? margin.left() : defaultMargins,\n margin.top() ? margin.top() : defaultMargins,\n margin.right() ? margin.right() : defaultMargins,\n margin.bottom() ? margin.bottom() : defaultMargins\n );\n\n \/\/ list and editor\n m_tagListWidget = new QComboBox(this);\n \/\/m_tagListWidget->setEditable(true);\n m_tagListWidget->setFrame(false);\n m_layout->addWidget(m_tagListWidget);\n connect(m_tagListWidget, QOverload::of(&QComboBox::currentIndexChanged),\n this, &TagInput::onTagListSelected);\n\n \/\/ spacer\n QWidget* spacer = new QWidget();\n spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);\n m_layout->addWidget(spacer);\n}\n\nQFrame *TagInput::createTagItem(TagItem *item)\n{\n \/\/ add widget\n QFrame *tagItem = new QFrame(this);\n tagItem->setObjectName(QStringLiteral(\"tag:%1\").arg(item->id()));\n tagItem->setStyleSheet(QStringLiteral(\n \"QFrame { border-radius: 5px; padding: 2px; border: none;\"\n \"background: #19BC9C; color: #FFF; }\"\n ));\n tagItem->setFrameShape(QFrame::StyledPanel);\n tagItem->setFrameShadow(QFrame::Raised);\n\n QLabel *tagLabel = new QLabel(tagItem);\n tagLabel->setObjectName(QStringLiteral(\"label\"));\n QFontMetrics tagLabelFm = tagLabel->fontMetrics();\n QSizePolicy sizePolicyLabel(QSizePolicy::Preferred, QSizePolicy::Fixed);\n sizePolicyLabel.setHorizontalStretch(0);\n sizePolicyLabel.setVerticalStretch(0);\n tagLabel->setMaximumHeight(tagLabelFm.height());\n tagLabel->setSizePolicy(sizePolicyLabel);\n tagLabel->setContentsMargins(0, 0, 0, 0);\n tagLabel->setText(item->tagName());\n tagLabel->setStyleSheet(QStringLiteral(\"QFrame { border-radius: 0; border: none; background: #FFEEEE; color: #000; padding: 0; height: 1em; line-height: 1em; }\"));\n tagLabel->setStyleSheet(QStringLiteral(\"QFrame { border-radius: 0; border: none; padding: 0; height: 1em; line-height: 1em; }\"));\n\n QPushButton *tagRemoveButton = new QPushButton(tagItem);\n tagRemoveButton->setObjectName(QStringLiteral(\"removeButton\"));\n QFontMetrics tagRemoveButtonFm = tagRemoveButton->fontMetrics();\n QSizePolicy sizePolicyRemoveButton(QSizePolicy::Fixed, QSizePolicy::Fixed);\n sizePolicyRemoveButton.setHorizontalStretch(0);\n sizePolicyRemoveButton.setVerticalStretch(0);\n \/\/sizePolicy5.setHeightForWidth(tagRemove->sizePolicy().hasHeightForWidth());\n QFont fontRemoveButton = tagRemoveButton->font();\n fontRemoveButton.setBold(true);\n fontRemoveButton.setWeight(75);\n tagRemoveButton->setFont(fontRemoveButton);\n tagRemoveButton->setText(\"x\");\n tagRemoveButton->setSizePolicy(sizePolicyRemoveButton);\n tagRemoveButton->setMouseTracking(true);\n tagRemoveButton->setFocusPolicy(Qt::NoFocus);\n tagRemoveButton->setContentsMargins(0, 0, 0, 0);\n tagRemoveButton->setMaximumWidth(tagRemoveButtonFm.width(tagRemoveButton->text()) + 6);\n tagRemoveButton->setMaximumHeight(tagRemoveButtonFm.height());\n tagRemoveButton->setStyleSheet(QStringLiteral(\n \"QPushButton { margin: 0; padding: 0; border: none; color: #FFF; }\"\n \"QPushButton:pressed { border: none; background: #19BC9C; color: #F66;}\"\n ));\n tagRemoveButton->setAttribute(Qt::WA_TransparentForMouseEvents, false);\n\n QRect rc = tagRemoveButtonFm.boundingRect(\"x\");\n \/\/qDebug() << \"tagRemoveFm.w\" << tagRemoveButtonFm.width(\"x\") << tagRemoveButtonFm.height() << rc;\n\n QHBoxLayout *tagItemLayout = new QHBoxLayout(tagItem);\n tagItemLayout->setObjectName(QStringLiteral(\"layout\"));\n tagItemLayout->setSpacing(3);\n tagItemLayout->setMargin(0);\n tagItemLayout->setContentsMargins(3, 0, 3, 0);\n tagItemLayout->addWidget(tagLabel);\n tagItemLayout->addWidget(tagRemoveButton);\n\n connect(tagRemoveButton, &QAbstractButton::clicked, this, &TagInput::onTagRemoveClick);\n\n return tagItem;\n}\n\nvoid TagInput::append(const QString &tag, const QString &tagId)\n{\n append(new TagItem(tag, tagId, this));\n}\n\nvoid TagInput::append(TagItem *item)\n{\n \/\/ check unique tag\n foreach (TagItem* ite, m_tags) {\n if (ite->id() == item->id() &&\n (ite->unique() || item->unique())) {\n return;\n }\n }\n\n \/\/ add tag list\n m_tags.append(item);\n\n \/\/ add tag widget\n QFrame *tagItem = createTagItem(item);\n m_layout->insertWidget(m_layout->count() - 2, tagItem);\n}\n\nvoid TagInput::removeById(const QString &tagId)\n{\n foreach (TagItem* ite, m_tags) {\n if (tagId == ite->id()) {\n m_tagList.removeOne(ite);\n break;\n }\n }\n}\n\nvoid TagInput::appendList(const QString &tag, const QString &tagId)\n{\n appendList(new TagItem(tag, tagId, this));\n}\n\nvoid TagInput::appendList(TagItem *item)\n{\n \/\/ check unique tag\n foreach (TagItem* ite, m_tagList) {\n if (ite->id() == item->id()) {\n return;\n }\n }\n\n m_tagList.append(item);\n\n m_tagListWidget->blockSignals(true);\n m_tagListWidget->addItem(item->tagName(), item->id());\n m_tagListWidget->setCurrentIndex(-1);\n m_tagListWidget->blockSignals(false);\n}\n\nvoid TagInput::removeListById(const QString &tagId)\n{\n foreach (TagItem* ite, m_tagList) {\n if (tagId == ite->id()) {\n m_tagList.removeOne(ite);\n break;\n }\n }\n\n int index = m_tagListWidget->findData(tagId);\n if (0 <= index) {\n m_tagListWidget->removeItem(index);\n }\n}\n\nvoid TagInput::mousePressEvent(QMouseEvent *event)\n{\n m_dragStartPos = event->pos();\n m_dragStartOffset = horizontalScrollBar()->value();\n setCursor(Qt::SizeHorCursor);\n\/\/ qDebug() << \"mousePressEvent\" << m_dragStartPos;\n}\n\nvoid TagInput::mouseMoveEvent(QMouseEvent *event)\n{\n if (m_dragStartOffset < 0) {\n return;\n }\n\n QPoint topLeft = viewport()->rect().topLeft();\n\n int offset = m_dragStartOffset - (event->pos().x() - m_dragStartPos.x());\n if (offset < 0) { offset = 0; }\n if (horizontalScrollBar()->maximum() <= offset) { offset = horizontalScrollBar()->maximum(); }\n\n horizontalScrollBar()->setValue(offset);\n widget()->move(topLeft.x() - offset, topLeft.y());\n\n\/\/ qDebug() << \"mouseMoveEvent\" << m_dragStartPos << event->pos() << (m_dragStartPos - event->pos());\n}\n\nvoid TagInput::mouseReleaseEvent(QMouseEvent *event)\n{\n if (m_dragStartOffset < 0) {\n return;\n }\n\n QPoint topLeft = viewport()->rect().topLeft();\n\n int offset = m_dragStartOffset - (event->pos().x() - m_dragStartPos.x());\n if (offset < 0) { offset = 0; }\n if (horizontalScrollBar()->maximum() <= offset) { offset = horizontalScrollBar()->maximum(); }\n\n horizontalScrollBar()->setValue(offset);\n widget()->move(topLeft.x() - offset, topLeft.y());\n\n unsetCursor();\n\n m_dragStartOffset = -1;\n\/\/ qDebug() << \"mouseReleaseEvent\" << m_dragStartPos << event->pos() << (m_dragStartPos - event->pos());\n\n}\n\nvoid TagInput::onTagRemoveClick(bool checked)\n{\n QPushButton *button = qobject_cast( sender() );\n QLabel *label = button->parentWidget()->findChild();\n\n if (label) {\n qDebug() << label->text();\n }\n}\n\nvoid TagInput::onTagClick()\n{\n\n}\n\nvoid TagInput::onTagListSelected(int index)\n{\n if (index < 0 ||\n m_tagList.size() <= index) {\n return;\n }\n\n TagItem *item = m_tagList.at(index);\n TagItem *itemClone = item->clone();\n\n append(itemClone);\n\n m_tagListWidget->setCurrentIndex(-1);\n}\n削除処理を実装#include \"taginput.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst int defaultMargins = 6;\n\n\/\/---------------------------------------------------------\n\/\/ TagItem\n\/\/---------------------------------------------------------\n\nTagItem::TagItem(QObject *parent)\n : QObject(parent)\n , m_unique(true)\n{\n}\n\nTagItem::TagItem(const QString &tagName, QObject *parent)\n : QObject(parent)\n , m_tagName(tagName)\n , m_unique(true)\n{\n}\n\nTagItem::TagItem(const QString &tagName, const QString &tagId, QObject *parent)\n : QObject(parent)\n , m_tagName(tagName)\n , m_id(tagId)\n , m_unique(true)\n{\n}\n\nTagItem *TagItem::clone()\n{\n TagItem *item = new TagItem(parent());\n item->setTagName(m_tagName);\n item->setId(m_id);\n item->setDescriptionText(m_descriptionText);\n return item;\n}\n\nQString TagItem::tagName() const\n{\n return m_tagName;\n}\n\nvoid TagItem::setTagName(const QString &tagName)\n{\n m_tagName = tagName;\n}\n\nQString TagItem::id() const\n{\n return !m_id.isEmpty() ? m_id : m_tagName;\n}\n\nvoid TagItem::setId(const QString &id)\n{\n m_id = id;\n}\n\nQString TagItem::descriptionText() const\n{\n return !m_descriptionText.isEmpty() ? m_descriptionText : m_tagName;\n}\n\nvoid TagItem::setDescriptionText(const QString &descriptionText)\n{\n m_descriptionText = descriptionText;\n}\n\nbool TagItem::unique() const\n{\n return m_unique;\n}\n\nvoid TagItem::setUnique(bool unique)\n{\n m_unique = unique;\n}\n\n\/\/---------------------------------------------------------\n\/\/ TagInput\n\/\/---------------------------------------------------------\n\nTagInput::TagInput(QWidget *parent)\n : QScrollArea(parent)\n , m_dragStartOffset(0)\n{\n initWidget();\n\n#if 0\n append(\"test\");\n append(\"hoge\");\n append(\"a\");\n append(\"ほげふが\");\n append(\"ふふぉjのの\");\n append(\"っっz\");\n append(\"test5\");\n append(\"hoge6\");\n append(\"test7\");\n append(\"hoge8\");\n#endif\n}\n\nvoid TagInput::initWidget()\n{\n \/\/connect(this, &QTextEdit::textChanged, this, &TagInput::updateTags);\n\n QFontMetrics fm = fontMetrics();\n setSizePolicy(sizePolicy().horizontalPolicy(), QSizePolicy::Fixed);\n QMargins margin(contentsMargins().left() ? contentsMargins().left() : defaultMargins,\n contentsMargins().top() ? contentsMargins().top() : defaultMargins,\n contentsMargins().right() ? contentsMargins().right() : defaultMargins,\n contentsMargins().bottom() ? contentsMargins().bottom() : defaultMargins\n );\n setContentsMargins(0, 0, 0, 0);\n\n setMaximumHeight(fm.height() + margin.top() + margin.bottom() + 4 * 2);\n\n setBackgroundRole(QPalette::Base);\n setFrameShadow(QFrame::Plain);\n setFrameShape(QFrame::StyledPanel);\n setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n setWidgetResizable(true);\n\n QWidget* base = new QWidget(this);\n base->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);\n base->setLayout(m_layout = new QHBoxLayout(base));\n setWidget(base);\n\n m_layout->setSpacing(defaultMargins);\n m_layout->setContentsMargins(margin.left() ? margin.left() : defaultMargins,\n margin.top() ? margin.top() : defaultMargins,\n margin.right() ? margin.right() : defaultMargins,\n margin.bottom() ? margin.bottom() : defaultMargins\n );\n\n \/\/ list and editor\n m_tagListWidget = new QComboBox(this);\n \/\/m_tagListWidget->setEditable(true);\n m_tagListWidget->setFrame(false);\n m_layout->addWidget(m_tagListWidget);\n connect(m_tagListWidget, QOverload::of(&QComboBox::currentIndexChanged),\n this, &TagInput::onTagListSelected);\n\n \/\/ spacer\n QWidget* spacer = new QWidget();\n spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);\n m_layout->addWidget(spacer);\n}\n\nQFrame *TagInput::createTagItem(TagItem *item)\n{\n \/\/ add widget\n QFrame *tagItem = new QFrame(this);\n tagItem->setObjectName(QStringLiteral(\"tag:%1\").arg(item->id()));\n tagItem->setProperty(\"tagItem\", QVariant::fromValue(static_cast( item )));\n tagItem->setStyleSheet(QStringLiteral(\n \"QFrame { border-radius: 5px; padding: 2px; border: none;\"\n \"background: #19BC9C; color: #FFF; }\"\n ));\n tagItem->setFrameShape(QFrame::StyledPanel);\n tagItem->setFrameShadow(QFrame::Raised);\n\n QLabel *tagLabel = new QLabel(tagItem);\n tagLabel->setObjectName(QStringLiteral(\"label\"));\n QFontMetrics tagLabelFm = tagLabel->fontMetrics();\n QSizePolicy sizePolicyLabel(QSizePolicy::Preferred, QSizePolicy::Fixed);\n sizePolicyLabel.setHorizontalStretch(0);\n sizePolicyLabel.setVerticalStretch(0);\n tagLabel->setMaximumHeight(tagLabelFm.height());\n tagLabel->setSizePolicy(sizePolicyLabel);\n tagLabel->setContentsMargins(0, 0, 0, 0);\n tagLabel->setText(item->tagName());\n tagLabel->setStyleSheet(QStringLiteral(\"QFrame { border-radius: 0; border: none; background: #FFEEEE; color: #000; padding: 0; height: 1em; line-height: 1em; }\"));\n tagLabel->setStyleSheet(QStringLiteral(\"QFrame { border-radius: 0; border: none; padding: 0; height: 1em; line-height: 1em; }\"));\n\n QPushButton *tagRemoveButton = new QPushButton(tagItem);\n tagRemoveButton->setObjectName(QStringLiteral(\"removeButton\"));\n QFontMetrics tagRemoveButtonFm = tagRemoveButton->fontMetrics();\n QSizePolicy sizePolicyRemoveButton(QSizePolicy::Fixed, QSizePolicy::Fixed);\n sizePolicyRemoveButton.setHorizontalStretch(0);\n sizePolicyRemoveButton.setVerticalStretch(0);\n \/\/sizePolicy5.setHeightForWidth(tagRemove->sizePolicy().hasHeightForWidth());\n QFont fontRemoveButton = tagRemoveButton->font();\n fontRemoveButton.setBold(true);\n fontRemoveButton.setWeight(75);\n tagRemoveButton->setFont(fontRemoveButton);\n tagRemoveButton->setText(\"x\");\n tagRemoveButton->setSizePolicy(sizePolicyRemoveButton);\n tagRemoveButton->setMouseTracking(true);\n tagRemoveButton->setFocusPolicy(Qt::NoFocus);\n tagRemoveButton->setContentsMargins(0, 0, 0, 0);\n tagRemoveButton->setMaximumWidth(tagRemoveButtonFm.width(tagRemoveButton->text()) + 6);\n tagRemoveButton->setMaximumHeight(tagRemoveButtonFm.height());\n tagRemoveButton->setStyleSheet(QStringLiteral(\n \"QPushButton { margin: 0; padding: 0; border: none; color: #FFF; }\"\n \"QPushButton:pressed { border: none; background: #19BC9C; color: #F66;}\"\n ));\n tagRemoveButton->setAttribute(Qt::WA_TransparentForMouseEvents, false);\n\n QRect rc = tagRemoveButtonFm.boundingRect(\"x\");\n \/\/qDebug() << \"tagRemoveFm.w\" << tagRemoveButtonFm.width(\"x\") << tagRemoveButtonFm.height() << rc;\n\n QHBoxLayout *tagItemLayout = new QHBoxLayout(tagItem);\n tagItemLayout->setObjectName(QStringLiteral(\"layout\"));\n tagItemLayout->setSpacing(3);\n tagItemLayout->setMargin(0);\n tagItemLayout->setContentsMargins(3, 0, 3, 0);\n tagItemLayout->addWidget(tagLabel);\n tagItemLayout->addWidget(tagRemoveButton);\n\n connect(tagRemoveButton, &QAbstractButton::clicked, this, &TagInput::onTagRemoveClick);\n\n return tagItem;\n}\n\nvoid TagInput::append(const QString &tag, const QString &tagId)\n{\n append(new TagItem(tag, tagId, this));\n}\n\nvoid TagInput::append(TagItem *item)\n{\n \/\/ check unique tag\n foreach (TagItem* ite, m_tags) {\n if (ite->id() == item->id() &&\n (ite->unique() || item->unique())) {\n return;\n }\n }\n\n \/\/ add tag list\n m_tags.append(item);\n\n \/\/ add tag widget\n QFrame *tagItem = createTagItem(item);\n m_layout->insertWidget(m_layout->count() - 2, tagItem);\n}\n\nvoid TagInput::removeById(const QString &tagId)\n{\n int tabOrder = -1;\n\n int index = 0;\n foreach (TagItem* ite, m_tags) {\n if (tagId == ite->id()) {\n m_tags.removeOne(ite);\n tabOrder = index;\n break;\n }\n ++index;\n }\n\n if (tabOrder < 0) {\n return;\n }\n\n if (QLayoutItem *item = m_layout->itemAt(tabOrder)) {\n QWidget *w = item->widget();\n m_layout->removeItem(item);\n delete w;\n }\n}\n\nvoid TagInput::appendList(const QString &tag, const QString &tagId)\n{\n appendList(new TagItem(tag, tagId, this));\n}\n\nvoid TagInput::appendList(TagItem *item)\n{\n \/\/ check unique tag\n foreach (TagItem* ite, m_tagList) {\n if (ite->id() == item->id()) {\n return;\n }\n }\n\n m_tagList.append(item);\n\n m_tagListWidget->blockSignals(true);\n m_tagListWidget->addItem(item->tagName(), item->id());\n m_tagListWidget->setCurrentIndex(-1);\n m_tagListWidget->blockSignals(false);\n}\n\nvoid TagInput::removeListById(const QString &tagId)\n{\n foreach (TagItem* ite, m_tagList) {\n if (tagId == ite->id()) {\n m_tagList.removeOne(ite);\n break;\n }\n }\n\n int index = m_tagListWidget->findData(tagId);\n if (0 <= index) {\n m_tagListWidget->removeItem(index);\n }\n}\n\nvoid TagInput::mousePressEvent(QMouseEvent *event)\n{\n m_dragStartPos = event->pos();\n m_dragStartOffset = horizontalScrollBar()->value();\n setCursor(Qt::SizeHorCursor);\n\/\/ qDebug() << \"mousePressEvent\" << m_dragStartPos;\n}\n\nvoid TagInput::mouseMoveEvent(QMouseEvent *event)\n{\n if (m_dragStartOffset < 0) {\n return;\n }\n\n QPoint topLeft = viewport()->rect().topLeft();\n\n int offset = m_dragStartOffset - (event->pos().x() - m_dragStartPos.x());\n if (offset < 0) { offset = 0; }\n if (horizontalScrollBar()->maximum() <= offset) { offset = horizontalScrollBar()->maximum(); }\n\n horizontalScrollBar()->setValue(offset);\n widget()->move(topLeft.x() - offset, topLeft.y());\n\n\/\/ qDebug() << \"mouseMoveEvent\" << m_dragStartPos << event->pos() << (m_dragStartPos - event->pos());\n}\n\nvoid TagInput::mouseReleaseEvent(QMouseEvent *event)\n{\n if (m_dragStartOffset < 0) {\n return;\n }\n\n QPoint topLeft = viewport()->rect().topLeft();\n\n int offset = m_dragStartOffset - (event->pos().x() - m_dragStartPos.x());\n if (offset < 0) { offset = 0; }\n if (horizontalScrollBar()->maximum() <= offset) { offset = horizontalScrollBar()->maximum(); }\n\n horizontalScrollBar()->setValue(offset);\n widget()->move(topLeft.x() - offset, topLeft.y());\n\n unsetCursor();\n\n m_dragStartOffset = -1;\n\/\/ qDebug() << \"mouseReleaseEvent\" << m_dragStartPos << event->pos() << (m_dragStartPos - event->pos());\n\n}\n\nvoid TagInput::onTagRemoveClick(bool checked)\n{\n if (QPushButton *button = qobject_cast( sender() )) {\n if (QLabel *label = button->parentWidget()->findChild()) {\n if (QFrame *tagItem = qobject_cast(label->parentWidget())) {\n if (TagItem *item = static_cast( tagItem->property(\"tagItem\").value() )) {\n qDebug() << label->text();\n removeById(item->id());\n }\n }\n }\n }\n\n#if 0\n int tagOrder = -1;\n for (int index = 0; index < m_layout->count(); ++index) {\n if (QLayoutItem *item = m_layout->itemAt(index)) {\n if (QFrame *tagItem_ = qobject_cast(item->widget())) {\n if (tagItem_ == tagItem) {\n tabOrder = index;\n break;\n }\n }\n }\n }\n#endif\n}\n\nvoid TagInput::onTagClick()\n{\n\n}\n\nvoid TagInput::onTagListSelected(int index)\n{\n if (index < 0 ||\n m_tagList.size() <= index) {\n return;\n }\n\n TagItem *item = m_tagList.at(index);\n TagItem *itemClone = item->clone();\n\n append(itemClone);\n\n m_tagListWidget->setCurrentIndex(-1);\n}\n<|endoftext|>"} {"text":"\/\/ @file AesopDemo.cpp\r\n\/\/ @brief A small test application for the Aesop library.\r\n\r\n#include \r\n#include \r\n\r\n#include \"AesopDemo.h\"\r\n#include \"AesopObjects.h\"\r\n#include \"AesopPredicates.h\"\r\n#include \"AesopActionSet.h\"\r\n#include \"AesopWorldState.h\"\r\n#include \"AesopReverseAstar.h\"\r\n\r\nnamespace ae = Aesop;\r\n\r\nvoid printPlan(const ae::Plan &plan, const ae::ActionSet &actions)\r\n{\r\n printf(\"The plan:\\n\");\r\n ae::Plan::const_iterator it;\r\n for(it = plan.begin(); it != plan.end(); it++)\r\n {\r\n printf(\" %s\", actions.repr(it->action).c_str());\r\n if(it->parameters.size())\r\n {\r\n ae::WorldState::paramlist::const_iterator pl;\r\n for(pl = it->parameters.begin(); pl != it->parameters.end(); pl++)\r\n printf(\" %d\", *pl);\r\n }\r\n putchar('\\n');\r\n }\r\n}\r\n\r\nvoid complexTest()\r\n{\r\n}\r\n\r\nvoid STRIPSTest()\r\n{\r\n}\r\n\r\nvoid subSTRIPSTest()\r\n{\r\n \/\/ --------------------\r\n \/\/ STEP 1. The Domain.\r\n\/*\r\n \/\/ 1.1. Define the types of objects that can exist.\r\n ae::NamedTypes types;\r\n types.add(\"object\");\r\n ae::Types::typeID place = types.add(\"place\");\r\n\r\n \/\/ 1.2. Create predicates that describe the physics of our problem.\r\n ae::AesopPredicates preds;\r\n\r\n \/\/ A physical object can be at a place\r\n preds.create(\"at\");\r\n preds.parameter(\"place\");\r\n preds.add();\r\n\r\n preds.create(\"box-at\");\r\n preds.parameter(\"place\");\r\n preds.add();\r\n\r\n preds.create(\"high\");\r\n ae::Predicates::predicateID high = preds.add();\r\n\r\n \/\/ 1.3. Define actions we can use to modify the world state.\r\n ae::SingleParamActionSet actions;\r\n\r\n actions.create(\"move\");\r\n actions.parameter(place);\r\n actions.add();\r\n\r\n actions.create(\"move-box\");\r\n actions.parameter(place);\r\n actions.add();\r\n\r\n actions.create(\"climb-box\");\r\n preds.effect(high);\r\n actions.add();\r\n\r\n \/\/ --------------------\r\n \/\/ STEP 2. The Problem.\r\n\r\n \/\/ 2.1. Create some objects.\r\n ae::Objects objects(types);\r\n objects.add(\"roomA\", place);\r\n objects.add(\"roomB\", place);\r\n objects.add(\"roomC\", place);\r\n*\/\r\n \/\/ 2.2. Create initial and goal world states.\r\n}\r\n\r\nvoid simpleTest()\r\n{\r\n \/\/ --------------------\r\n \/\/ STEP 1. The Domain.\r\n\r\n \/\/ 1.1. Create predicates that describe the physics of our problem.\r\n ae::SimplePredicates preds;\r\n\r\n enum {\r\n gunLoaded,\r\n gunEquipped,\r\n haveGun,\r\n haveMelee,\r\n meleeEquipped,\r\n inTurret,\r\n haveTarget,\r\n targetDead,\r\n NUMPREDS\r\n };\r\n\r\n \/\/ Define all predicates.\r\n preds.define(NUMPREDS);\r\n\r\n \/\/ 1.2. Create actions to modify the world state.\r\n ae::SimpleActionSet actions(preds);\r\n\r\n actions.create(\"attackRanged\");\r\n actions.condition(haveTarget, true);\r\n actions.condition(gunLoaded, true);\r\n actions.condition(targetDead, false);\r\n actions.effect(targetDead, true);\r\n actions.effect(gunLoaded, false);\r\n actions.add();\r\n\r\n actions.create(\"attackMelee\");\r\n actions.condition(haveTarget, true);\r\n actions.condition(targetDead, false);\r\n actions.condition(meleeEquipped, true);\r\n \/\/actions.condition();\r\n actions.effect(targetDead, true);\r\n actions.add();\r\n\r\n actions.create(\"attackTurret\");\r\n actions.condition(haveTarget, true);\r\n actions.condition(inTurret, true);\r\n actions.condition(targetDead, false);\r\n \/\/actions.condition();\r\n actions.effect(targetDead, true);\r\n actions.add();\r\n\r\n actions.create(\"loadGun\");\r\n actions.condition(gunEquipped, true);\r\n actions.condition(gunLoaded, false);\r\n actions.effect(gunLoaded, true);\r\n actions.add();\r\n\r\n actions.create(\"drawGun\");\r\n actions.condition(haveGun, true);\r\n actions.condition(gunEquipped, false);\r\n actions.effect(gunEquipped, true);\r\n actions.add();\r\n\r\n actions.create(\"findGun\");\r\n actions.condition(haveGun, false);\r\n actions.effect(haveGun, true);\r\n actions.add();\r\n\r\n actions.create(\"drawMelee\");\r\n actions.condition(haveMelee, true);\r\n actions.condition(meleeEquipped, false);\r\n actions.effect(meleeEquipped, true);\r\n actions.add();\r\n\r\n actions.create(\"findMelee\");\r\n actions.condition(haveMelee, false);\r\n actions.effect(haveMelee, true);\r\n actions.add();\r\n\r\n actions.create(\"findTurret\");\r\n actions.condition(inTurret, false);\r\n actions.effect(inTurret, true);\r\n \/\/actions.add();\r\n\r\n \/\/ --------------------\r\n \/\/ STEP 2. The Problem.\r\n\r\n \/\/ 2.1. Create initial and goal world states.\r\n ae::SimpleWorldState init(preds), goal(preds);\r\n\r\n init.set(haveTarget);\r\n\r\n goal.set(targetDead);\r\n\r\n \/\/ --------------------\r\n \/\/ STEP 3. The Solution.\r\n ae::Plan plan;\r\n ae::FileWriterContext context(*stdout);\r\n if(ae::ReverseAstarSolve(init, goal, actions, ae::NoObjects, plan, context))\r\n printPlan(plan, actions);\r\n else\r\n printf(\"No valid plan was found.\\n\");\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n simpleTest();\r\n return 0;\r\n}\r\nAdded a 'using namespace' to demo code.\/\/ @file AesopDemo.cpp\r\n\/\/ @brief A small test application for the Aesop library.\r\n\r\n#include \r\n#include \r\n\r\n#include \"AesopDemo.h\"\r\n#include \"AesopObjects.h\"\r\n#include \"AesopPredicates.h\"\r\n#include \"AesopActionSet.h\"\r\n#include \"AesopWorldState.h\"\r\n#include \"AesopReverseAstar.h\"\r\n\r\nusing namespace Aesop;\r\n\r\nvoid printPlan(const Plan &plan, const ActionSet &actions)\r\n{\r\n printf(\"The plan:\\n\");\r\n Plan::const_iterator it;\r\n for(it = plan.begin(); it != plan.end(); it++)\r\n {\r\n printf(\" %s\", actions.repr(it->action).c_str());\r\n if(it->parameters.size())\r\n {\r\n WorldState::paramlist::const_iterator pl;\r\n for(pl = it->parameters.begin(); pl != it->parameters.end(); pl++)\r\n printf(\" %d\", *pl);\r\n }\r\n putchar('\\n');\r\n }\r\n}\r\n\r\nvoid complexTest()\r\n{\r\n}\r\n\r\nvoid STRIPSTest()\r\n{\r\n}\r\n\r\nvoid subSTRIPSTest()\r\n{\r\n \/\/ --------------------\r\n \/\/ STEP 1. The Domain.\r\n\/*\r\n \/\/ 1.1. Define the types of objects that can exist.\r\n NamedTypes types;\r\n types.add(\"object\");\r\n Types::typeID place = types.add(\"place\");\r\n\r\n \/\/ 1.2. Create predicates that describe the physics of our problem.\r\n AesopPredicates preds;\r\n\r\n \/\/ A physical object can be at a place\r\n preds.create(\"at\");\r\n preds.parameter(\"place\");\r\n preds.add();\r\n\r\n preds.create(\"box-at\");\r\n preds.parameter(\"place\");\r\n preds.add();\r\n\r\n preds.create(\"high\");\r\n Predicates::predicateID high = preds.add();\r\n\r\n \/\/ 1.3. Define actions we can use to modify the world state.\r\n SingleParamActionSet actions;\r\n\r\n actions.create(\"move\");\r\n actions.parameter(place);\r\n actions.add();\r\n\r\n actions.create(\"move-box\");\r\n actions.parameter(place);\r\n actions.add();\r\n\r\n actions.create(\"climb-box\");\r\n preds.effect(high);\r\n actions.add();\r\n\r\n \/\/ --------------------\r\n \/\/ STEP 2. The Problem.\r\n\r\n \/\/ 2.1. Create some objects.\r\n Objects objects(types);\r\n objects.add(\"roomA\", place);\r\n objects.add(\"roomB\", place);\r\n objects.add(\"roomC\", place);\r\n*\/\r\n \/\/ 2.2. Create initial and goal world states.\r\n}\r\n\r\nvoid simpleTest()\r\n{\r\n \/\/ --------------------\r\n \/\/ STEP 1. The Domain.\r\n\r\n \/\/ 1.1. Create predicates that describe the physics of our problem.\r\n SimplePredicates preds;\r\n\r\n enum {\r\n gunLoaded,\r\n gunEquipped,\r\n haveGun,\r\n haveMelee,\r\n meleeEquipped,\r\n inTurret,\r\n haveTarget,\r\n targetDead,\r\n NUMPREDS\r\n };\r\n\r\n \/\/ Define all predicates.\r\n preds.define(NUMPREDS);\r\n\r\n \/\/ 1.2. Create actions to modify the world state.\r\n SimpleActionSet actions(preds);\r\n\r\n actions.create(\"attackRanged\");\r\n actions.condition(haveTarget, true);\r\n actions.condition(gunLoaded, true);\r\n actions.condition(targetDead, false);\r\n actions.effect(targetDead, true);\r\n actions.effect(gunLoaded, false);\r\n actions.add();\r\n\r\n actions.create(\"attackMelee\");\r\n actions.condition(haveTarget, true);\r\n actions.condition(targetDead, false);\r\n actions.condition(meleeEquipped, true);\r\n \/\/actions.condition();\r\n actions.effect(targetDead, true);\r\n actions.add();\r\n\r\n actions.create(\"attackTurret\");\r\n actions.condition(haveTarget, true);\r\n actions.condition(inTurret, true);\r\n actions.condition(targetDead, false);\r\n \/\/actions.condition();\r\n actions.effect(targetDead, true);\r\n actions.add();\r\n\r\n actions.create(\"loadGun\");\r\n actions.condition(gunEquipped, true);\r\n actions.condition(gunLoaded, false);\r\n actions.effect(gunLoaded, true);\r\n actions.add();\r\n\r\n actions.create(\"drawGun\");\r\n actions.condition(haveGun, true);\r\n actions.condition(gunEquipped, false);\r\n actions.effect(gunEquipped, true);\r\n actions.add();\r\n\r\n actions.create(\"findGun\");\r\n actions.condition(haveGun, false);\r\n actions.effect(haveGun, true);\r\n actions.add();\r\n\r\n actions.create(\"drawMelee\");\r\n actions.condition(haveMelee, true);\r\n actions.condition(meleeEquipped, false);\r\n actions.effect(meleeEquipped, true);\r\n actions.add();\r\n\r\n actions.create(\"findMelee\");\r\n actions.condition(haveMelee, false);\r\n actions.effect(haveMelee, true);\r\n actions.add();\r\n\r\n actions.create(\"findTurret\");\r\n actions.condition(inTurret, false);\r\n actions.effect(inTurret, true);\r\n \/\/actions.add();\r\n\r\n \/\/ --------------------\r\n \/\/ STEP 2. The Problem.\r\n\r\n \/\/ 2.1. Create initial and goal world states.\r\n SimpleWorldState init(preds), goal(preds);\r\n\r\n init.set(haveTarget);\r\n\r\n goal.set(targetDead);\r\n\r\n \/\/ --------------------\r\n \/\/ STEP 3. The Solution.\r\n Plan plan;\r\n FileWriterContext context(*stdout);\r\n if(ReverseAstarSolve(init, goal, actions, NoObjects, plan, context))\r\n printPlan(plan, actions);\r\n else\r\n printf(\"No valid plan was found.\\n\");\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n simpleTest();\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2004 Michael Stevens\n * See accompanying Bayes++.html for terms and conditions of use.\n *\n * $Header$\n *\/\n\n\/*\n * Good random numbers from Boost\n * Provides a common class for all random number requirements to test Bayes++\n *\/\n\n#include \n\n\nnamespace Bayesian_filter_test\n{\n\n\/*\n * Random numbers from Boost Random\n *\/\n\nnamespace\n{\n\t\/\/ ISSUE variate_generator cannot be used without Partial template specialistion\n\ttemplate\n\tclass simple_generator\n\t{\n\tpublic:\n\t\ttypedef typename Distribution::result_type result_type;\n\t\tsimple_generator(Engine& e, Distribution& d)\n\t\t\t: _eng(e), _dist(d)\n\t\t{}\n\t\tresult_type operator()()\n\t\t{\treturn _dist(_eng); }\n\tprivate:\n\t\tEngine& _eng;\n\t\tDistribution& _dist;\n\t};\n}\/\/namespace\n\nclass Boost_random\n{\npublic:\n\t\/\/ ISSUE mt19937 is failing on x86_64\n\t\/\/\ttypedef boost::mt19937 Boost_gen;\n\ttypedef boost::ranlux3 Boost_gen;\t\n\n\ttypedef Bayesian_filter_matrix::Float Float;\n\ttypedef boost::uniform_01 UGen;\n\tBoost_random() : gen01(Boost_gen()), dist_normal()\n\t{}\n\tBayesian_filter_matrix::Float normal(const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution dist(mean, sigma);\n\t\tsimple_generator > gen(gen01, dist);\n\t\treturn gen();\n\t}\n\tvoid normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution dist(mean, sigma);\n\t\tsimple_generator > gen(gen01, dist);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n\tvoid normal(Bayesian_filter_matrix::DenseVec& v)\n\t{\n\t\tsimple_generator > gen(gen01, dist_normal);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n\tvoid uniform_01(Bayesian_filter_matrix::DenseVec& v)\n\t{\n\t\tstd::generate (v.begin(), v.end(), gen01);\n\t}\n#ifdef BAYES_FILTER_GAPPY\n\tvoid normal(Bayesian_filter_matrix::Vec& v, const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution dist(mean, sigma);\n\t\tsimple_generator > gen(gen01, dist);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n\tvoid normal(Bayesian_filter_matrix::Vec& v)\n\t{\n\t\tsimple_generator > gen(gen01, dist_normal);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n\tvoid uniform_01(Bayesian_filter_matrix::Vec& v)\n\t{\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen01();\n\t}\n#endif\n\tvoid seed()\n\t{\n\t\tgen01.base().seed();\n\t}\nprivate:\n\tUGen gen01;\n\tboost::normal_distribution dist_normal;\n};\n\n\n}\/\/namespace\nmt19937 problem is GCC 3.3.3 specfic (may SuSE specific)\/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2004 Michael Stevens\n * See accompanying Bayes++.html for terms and conditions of use.\n *\n * $Header$\n *\/\n\n\/*\n * Good random numbers from Boost\n * Provides a common class for all random number requirements to test Bayes++\n *\/\n\n#include \n\n\nnamespace Bayesian_filter_test\n{\n\n\/*\n * Random numbers from Boost Random\n *\/\n\nnamespace\n{\n\t\/\/ ISSUE variate_generator cannot be used without Partial template specialistion\n\ttemplate\n\tclass simple_generator\n\t{\n\tpublic:\n\t\ttypedef typename Distribution::result_type result_type;\n\t\tsimple_generator(Engine& e, Distribution& d)\n\t\t\t: _eng(e), _dist(d)\n\t\t{}\n\t\tresult_type operator()()\n\t\t{\treturn _dist(_eng); }\n\tprivate:\n\t\tEngine& _eng;\n\t\tDistribution& _dist;\n\t};\n}\/\/namespace\n\nclass Boost_random\n{\npublic:\n\t\/\/ ISSUE mt19937 results incorrect on x86_64 GCC version 3.3.3 (SuSE Linux)\n\ttypedef boost::mt19937 Boost_gen;\n\n\ttypedef Bayesian_filter_matrix::Float Float;\n\ttypedef boost::uniform_01 UGen;\n\tBoost_random() : gen01(Boost_gen()), dist_normal()\n\t{}\n\tBayesian_filter_matrix::Float normal(const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution dist(mean, sigma);\n\t\tsimple_generator > gen(gen01, dist);\n\t\treturn gen();\n\t}\n\tvoid normal(Bayesian_filter_matrix::DenseVec& v, const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution dist(mean, sigma);\n\t\tsimple_generator > gen(gen01, dist);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n\tvoid normal(Bayesian_filter_matrix::DenseVec& v)\n\t{\n\t\tsimple_generator > gen(gen01, dist_normal);\n\t\tstd::generate (v.begin(), v.end(), gen);\n\t}\n\tvoid uniform_01(Bayesian_filter_matrix::DenseVec& v)\n\t{\n\t\tstd::generate (v.begin(), v.end(), gen01);\n\t}\n#ifdef BAYES_FILTER_GAPPY\n\tvoid normal(Bayesian_filter_matrix::Vec& v, const Float mean, const Float sigma)\n\t{\n\t\tboost::normal_distribution dist(mean, sigma);\n\t\tsimple_generator > gen(gen01, dist);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n\tvoid normal(Bayesian_filter_matrix::Vec& v)\n\t{\n\t\tsimple_generator > gen(gen01, dist_normal);\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen();\n\t}\n\tvoid uniform_01(Bayesian_filter_matrix::Vec& v)\n\t{\n\t\tfor (std::size_t i = 0, iend=v.size(); i < iend; ++i)\n\t\t\tv[i] = gen01();\n\t}\n#endif\n\tvoid seed()\n\t{\n\t\tgen01.base().seed();\n\t}\nprivate:\n\tUGen gen01;\n\tboost::normal_distribution dist_normal;\n};\n\n\n}\/\/namespace\n<|endoftext|>"} {"text":"#include \"NumbersGame.h\"\n#include \"SimpleAudioEngine.h\"\n\nUSING_NS_CC;\nNumbersGame::NumbersGame() : _fishPool(20)\n{\n}\nScene* NumbersGame::createScene()\n{\n auto scene = Scene::create();\n auto layer = NumbersGame::create();\n scene->addChild(layer);\n return scene;\n}\n\n\/\/ on \"init\" you need to initialize your instance\nbool NumbersGame::init()\n{\n if ( !Layer::init() )\n {\n return false;\n }\n \n _screenSize = Director::getInstance()->getVisibleSize();\n Vec2 origin = Director::getInstance()->getVisibleOrigin();\n\n _score = 0;\n _hook_has_fish = false;\n \/\/create game screen elements\n createGameScreen();\n \/\/create object pools\n createPools();\n \/\/create CCActions\n createActions();\n \n auto listener = EventListenerTouchOneByOne::create();\n listener->onTouchBegan = CC_CALLBACK_2(NumbersGame::onTouchBegan, this);\n listener->onTouchEnded = CC_CALLBACK_2(NumbersGame::onTouchEnded, this);\n this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);\n \n this->schedule(schedule_selector(NumbersGame::update));\n return true;\n}\n\nvoid NumbersGame::createGameScreen () {\n Sprite * bg = Sprite::create(\"bg.png\");\n bg->setPosition(Vec2(_screenSize.width * 0.5f, _screenSize.height * 0.5f));\n this->addChild(bg, kBackground);\n \n SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(\"sprites.plist\");\n _gameBatchNode = SpriteBatchNode::create(\"sprites.png\", 100);\n\n this->addChild(_gameBatchNode, kForeground);\n \n _hook = Sprite::create(\"hook.png\");\n _hook->setScale(0.1);\n _hook->setPosition(Vec2(_screenSize.width * 0.5f, _hook->getBoundingBox().size.height * 0.5));\n this->addChild(_hook, kMiddleground);\n \n _scoreDisplay = LabelTTF::create();\n _scoreDisplay->setFontName(\"fonts\/font.ttf\");\n _scoreDisplay->setAnchorPoint(Vec2(1,0.5));\n _scoreDisplay->setFontSize(20);\n _scoreDisplay->setPosition(Vec2(_screenSize.width * 0.9f, _screenSize.height * 0.94f));\n _scoreDisplay->setString(\"0\");\n this->addChild(_scoreDisplay,kForeground);\n \n \n _scoreDisplayLarge = LabelTTF::create();\n _scoreDisplayLarge->setFontSize(300);\n _scoreDisplayLarge->setFontName(\"fonts\/font.ttf\");\n _scoreDisplayLarge->setPosition(Vec2(_screenSize.width * 0.5f, _screenSize.height * 0.5f));\n _scoreDisplayLarge->setScale(0.2);\n _scoreDisplayLarge->setString(\"0\");\n _scoreDisplayLarge->setVisible(false);\n this->addChild(_scoreDisplayLarge,kForeground);\n \n ParticleSystemQuad* p = ParticleSystemQuad::create(\"bubbles.plist\");\n p->setScale(0.);\n this->addChild(p,kForeground);\n}\nvoid NumbersGame::createPools () {\n Sprite * sprite;\n int i,output;\n \n _fishPoolIndex = 0;\n for (i = 0; i < _fishPool.capacity(); i++) {\n output = 1 + (rand() % (int)(6 - 2));\n auto name = CCString::createWithFormat(\"fish_%i.png\", output);\n sprite = Sprite::createWithSpriteFrameName(name->_string);\n sprite->setVisible(false);\n sprite->setScale(0.2);\n _gameBatchNode->addChild(sprite, kMiddleground);\n _fishPool.pushBack(sprite);\n }\n}\nvoid NumbersGame::createActions () {\n \n}\nvoid NumbersGame::update (float dt) {\n if (!_running) return;\n \n _fishTimer += dt;\n if (_fishTimer > _fishInterval) {\n _fishTimer = 0;\n this->resetFish();\n }\n \n if(_hook_has_fish) return;\n \n if (_hook_pull){\n _hook->setPosition(_hook->getPositionX(),_hook->getPositionY() + 5);\n if(_hook->getPositionY() > _screenSize.height - _hook->getBoundingBox().size.height \/2)\n _hook->setPositionY( _screenSize.height - _hook->getBoundingBox().size.height \/2);\n \n for (auto fish: this->_fishPool)\n {\n if(fish->getBoundingBox().intersectsRect(_hook->getBoundingBox()))\n {\n fish->stopAllActions();\n _hook_has_fish = true;\n _hook_pull = false;\n \n auto fishing = MoveTo::create(\n ( (_screenSize.height - _hook->getPositionY()) * 0.002)\n , Vec2(_hook->getPositionX(),_screenSize.height));\n auto rotate = RotateTo::create(0.2,90);\n fish->runAction(\n CCSequence::create(\n fishing->clone(),\n CCCallFuncN::create(this, callfuncN_selector(NumbersGame::fishingDone)),\n NULL)\n );\n fish->runAction(rotate);\n _hook->runAction(fishing);\n _hook->setVisible(false);\n }\n }\n }else{\n _hook->setPosition(_hook->getPositionX(),_hook->getPositionY() - 3);\n if(_hook->getPositionY() < _hook->getBoundingBox().size.height \/2)\n _hook->setPositionY( _hook->getBoundingBox().size.height \/2);\n }\n}\nbool NumbersGame::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event * event){\n if (!_running) _running = true;\n _hook_pull = true;\n return true;\n}\nvoid NumbersGame::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event * event){\n _hook_pull = false;\n}\n\nvoid NumbersGame::resetFish(){\n Sprite * fish = (Sprite *) _fishPool.at(_fishPoolIndex);\n _fishPoolIndex++;\n if (_fishPoolIndex == _fishPool.size()) _fishPoolIndex = 0;\n\n int meteor_y = rand() % (int) (_screenSize.height * 0.8f) + _screenSize.height * 0.1f;\n\n fish->stopAllActions();\n \n fish->setPosition(Vec2(_screenSize.width + fish->getBoundingBox().size.width * 0.5,meteor_y));\n auto swim = MoveTo::create(_fishSpeed, Vec2(0-fish->getBoundingBox().size.width * 0.5,meteor_y));\n\n fish->setVisible ( true );\n fish->runAction(swim);\n}\n\nvoid NumbersGame::fishingDone (Node* pSender) {\n pSender->setVisible(false);\n pSender->setRotation(0);\n pSender->setPosition(0,0);\n _score++;\n auto name = CCString::createWithFormat(\"%i\", _score);\n _scoreDisplay->setString(name->_string);\n _scoreDisplayLarge->setString(name->_string);\n _scoreDisplayLarge->setVisible(true);\n\n char numstr[21]; \/\/ enough to hold all numbers up to 64-bits\n std::sprintf(numstr, \"%i\", _score);\n std::string result__ = numstr + std::string(\"_.wav\");\n const char * audio_file = result__.c_str();\n if(_score < 11)\n CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(audio_file);\n\n _scoreDisplayLarge->runAction(CCSequence::create(\n EaseBackOut::create(ScaleTo::create(4,1)),\n CCCallFuncN::create(this, callfuncN_selector(NumbersGame::bigScoreDone)),\n NULL)\n );\n}\nvoid NumbersGame::bigScoreDone (Node* pSender) {\n pSender->setScale(0.2);\n pSender->setVisible(false);\n _hook_has_fish = false;\n _hook->setVisible(true);\n}position particles#include \"NumbersGame.h\"\n#include \"SimpleAudioEngine.h\"\n\nUSING_NS_CC;\nNumbersGame::NumbersGame() : _fishPool(20)\n{\n}\nScene* NumbersGame::createScene()\n{\n auto scene = Scene::create();\n auto layer = NumbersGame::create();\n scene->addChild(layer);\n return scene;\n}\n\n\/\/ on \"init\" you need to initialize your instance\nbool NumbersGame::init()\n{\n if ( !Layer::init() )\n {\n return false;\n }\n \n _screenSize = Director::getInstance()->getVisibleSize();\n Vec2 origin = Director::getInstance()->getVisibleOrigin();\n\n _score = 0;\n _hook_has_fish = false;\n \/\/create game screen elements\n createGameScreen();\n \/\/create object pools\n createPools();\n \/\/create CCActions\n createActions();\n \n auto listener = EventListenerTouchOneByOne::create();\n listener->onTouchBegan = CC_CALLBACK_2(NumbersGame::onTouchBegan, this);\n listener->onTouchEnded = CC_CALLBACK_2(NumbersGame::onTouchEnded, this);\n this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);\n \n this->schedule(schedule_selector(NumbersGame::update));\n return true;\n}\n\nvoid NumbersGame::createGameScreen () {\n Sprite * bg = Sprite::create(\"bg.png\");\n bg->setPosition(Vec2(_screenSize.width * 0.5f, _screenSize.height * 0.5f));\n this->addChild(bg, kBackground);\n \n SpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(\"sprites.plist\");\n _gameBatchNode = SpriteBatchNode::create(\"sprites.png\", 100);\n\n this->addChild(_gameBatchNode, kForeground);\n \n _hook = Sprite::create(\"hook.png\");\n _hook->setScale(0.1);\n _hook->setPosition(Vec2(_screenSize.width * 0.5f, _hook->getBoundingBox().size.height * 0.5));\n this->addChild(_hook, kMiddleground);\n \n _scoreDisplay = LabelTTF::create();\n _scoreDisplay->setFontName(\"fonts\/font.ttf\");\n _scoreDisplay->setAnchorPoint(Vec2(1,0.5));\n _scoreDisplay->setFontSize(20);\n _scoreDisplay->setPosition(Vec2(_screenSize.width * 0.9f, _screenSize.height * 0.94f));\n _scoreDisplay->setString(\"0\");\n this->addChild(_scoreDisplay,kForeground);\n \n \n _scoreDisplayLarge = LabelTTF::create();\n _scoreDisplayLarge->setFontSize(300);\n _scoreDisplayLarge->setFontName(\"fonts\/font.ttf\");\n _scoreDisplayLarge->setPosition(Vec2(_screenSize.width * 0.5f, _screenSize.height * 0.5f));\n _scoreDisplayLarge->setScale(0.2);\n _scoreDisplayLarge->setString(\"0\");\n _scoreDisplayLarge->setVisible(false);\n this->addChild(_scoreDisplayLarge,kForeground);\n \n ParticleSystemQuad* p1 = ParticleSystemQuad::create(\"bubbles.plist\");\n p1->setPosition(Vec2(_screenSize.width * 0.86f, _screenSize.height * 0.1f));\n p1->setScale(0.1);\n p1->setLife(0.6);\n this->addChild(p1,kForeground);\n \n ParticleSystemQuad* p2 = ParticleSystemQuad::create(\"bubbles.plist\");\n p2->setPosition(Vec2(_screenSize.width * 0.9f, _screenSize.height * 0.125f));\n p2->setScale(0.1);\n p2->setLife(0.6);\n this->addChild(p2,kMiddleground);\n}\nvoid NumbersGame::createPools () {\n Sprite * sprite;\n int i,output;\n \n _fishPoolIndex = 0;\n for (i = 0; i < _fishPool.capacity(); i++) {\n output = 1 + (rand() % (int)(6 - 2));\n auto name = CCString::createWithFormat(\"fish_%i.png\", output);\n sprite = Sprite::createWithSpriteFrameName(name->_string);\n sprite->setVisible(false);\n sprite->setScale(0.2);\n _gameBatchNode->addChild(sprite, kMiddleground);\n _fishPool.pushBack(sprite);\n }\n}\nvoid NumbersGame::createActions () {\n \n}\nvoid NumbersGame::update (float dt) {\n if (!_running) return;\n \n _fishTimer += dt;\n if (_fishTimer > _fishInterval) {\n _fishTimer = 0;\n this->resetFish();\n }\n \n if(_hook_has_fish) return;\n \n if (_hook_pull){\n _hook->setPosition(_hook->getPositionX(),_hook->getPositionY() + 5);\n if(_hook->getPositionY() > _screenSize.height - _hook->getBoundingBox().size.height \/2)\n _hook->setPositionY( _screenSize.height - _hook->getBoundingBox().size.height \/2);\n \n for (auto fish: this->_fishPool)\n {\n if(fish->getBoundingBox().intersectsRect(_hook->getBoundingBox()))\n {\n fish->stopAllActions();\n _hook_has_fish = true;\n _hook_pull = false;\n \n auto fishing = MoveTo::create(\n ( (_screenSize.height - _hook->getPositionY()) * 0.002)\n , Vec2(_hook->getPositionX(),_screenSize.height));\n auto rotate = RotateTo::create(0.2,90);\n fish->runAction(\n CCSequence::create(\n fishing->clone(),\n CCCallFuncN::create(this, callfuncN_selector(NumbersGame::fishingDone)),\n NULL)\n );\n fish->runAction(rotate);\n _hook->runAction(fishing);\n _hook->setVisible(false);\n }\n }\n }else{\n _hook->setPosition(_hook->getPositionX(),_hook->getPositionY() - 3);\n if(_hook->getPositionY() < _hook->getBoundingBox().size.height \/2)\n _hook->setPositionY( _hook->getBoundingBox().size.height \/2);\n }\n}\nbool NumbersGame::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event * event){\n if (!_running) _running = true;\n _hook_pull = true;\n return true;\n}\nvoid NumbersGame::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event * event){\n _hook_pull = false;\n}\n\nvoid NumbersGame::resetFish(){\n Sprite * fish = (Sprite *) _fishPool.at(_fishPoolIndex);\n _fishPoolIndex++;\n if (_fishPoolIndex == _fishPool.size()) _fishPoolIndex = 0;\n\n int meteor_y = rand() % (int) (_screenSize.height * 0.8f) + _screenSize.height * 0.1f;\n\n fish->stopAllActions();\n \n fish->setPosition(Vec2(_screenSize.width + fish->getBoundingBox().size.width * 0.5,meteor_y));\n auto swim = MoveTo::create(_fishSpeed, Vec2(0-fish->getBoundingBox().size.width * 0.5,meteor_y));\n\n fish->setVisible ( true );\n fish->runAction(swim);\n}\n\nvoid NumbersGame::fishingDone (Node* pSender) {\n pSender->setVisible(false);\n pSender->setRotation(0);\n pSender->setPosition(0,0);\n _score++;\n auto name = CCString::createWithFormat(\"%i\", _score);\n _scoreDisplay->setString(name->_string);\n _scoreDisplayLarge->setString(name->_string);\n _scoreDisplayLarge->setVisible(true);\n\n char numstr[21]; \/\/ enough to hold all numbers up to 64-bits\n std::sprintf(numstr, \"%i\", _score);\n std::string result__ = numstr + std::string(\"_.wav\");\n const char * audio_file = result__.c_str();\n if(_score < 11)\n CocosDenshion::SimpleAudioEngine::getInstance()->playEffect(audio_file);\n\n _scoreDisplayLarge->runAction(CCSequence::create(\n EaseBackOut::create(ScaleTo::create(4,1)),\n CCCallFuncN::create(this, callfuncN_selector(NumbersGame::bigScoreDone)),\n NULL)\n );\n}\nvoid NumbersGame::bigScoreDone (Node* pSender) {\n pSender->setScale(0.2);\n pSender->setVisible(false);\n _hook_has_fish = false;\n _hook->setVisible(true);\n}<|endoftext|>"} {"text":"\n\/*\n Copyright 1995 The University of Rhode Island and The Massachusetts\n Institute of Technology\n\n Portions of this software were developed by the Graduate School of\n Oceanography (GSO) at the University of Rhode Island (URI) in collaboration\n with The Massachusetts Institute of Technology (MIT).\n\n Access and use of this software shall impose the following obligations and\n understandings on the user. The user is granted the right, without any fee\n or cost, to use, copy, modify, alter, enhance and distribute this software,\n and any derivative works thereof, and its supporting documentation for any\n purpose whatsoever, provided that this entire notice appears in all copies\n of the software, derivative works and supporting documentation. Further,\n the user agrees to credit URI\/MIT in any publications that result from the\n use of this software or in any product that includes this software. The\n names URI, MIT and\/or GSO, however, may not be used in any advertising or\n publicity to endorse or promote any products or commercial entity unless\n specific written permission is obtained from URI\/MIT. The user also\n understands that URI\/MIT is not obligated to provide the user with any\n support, consulting, training or assistance of any kind with regard to the\n use, operation and performance of this software nor to provide the user\n with any updates, revisions, new versions or \"bug fixes\".\n\n THIS SOFTWARE IS PROVIDED BY URI\/MIT \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n EVENT SHALL URI\/MIT BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS\n ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE\n OF THIS SOFTWARE.\n*\/\n\n\/\/ Implementation for the class Structure\n\/\/\n\/\/ jhrg 9\/14\/94\n\n\/\/ $Log: Structure.cc,v $\n\/\/ Revision 1.19 1996\/02\/02 00:31:13 jimg\n\/\/ Merge changes for DODS-1.1.0 into DODS-2.x\n\/\/\n\/\/ Revision 1.18 1995\/12\/09 01:07:00 jimg\n\/\/ Added changes so that relational operators will work properly for all the\n\/\/ datatypes (including Sequences). The relational ops are evaluated in\n\/\/ DDS::eval_constraint() after being parsed by DDS::parse_constraint().\n\/\/\n\/\/ Revision 1.17 1995\/12\/06 21:56:32 jimg\n\/\/ Added `constrained' flag to print_decl.\n\/\/ Removed third parameter of read.\n\/\/ Modified print_decl() to print only those parts of a dataset that are\n\/\/ selected when `constrained' is true.\n\/\/\n\/\/ Revision 1.16 1995\/10\/23 23:21:04 jimg\n\/\/ Added _send_p and _read_p fields (and their accessors) along with the\n\/\/ virtual mfuncs set_send_p() and set_read_p().\n\/\/\n\/\/ Revision 1.15 1995\/08\/26 00:31:49 jimg\n\/\/ Removed code enclosed in #ifdef NEVER #endif.\n\/\/\n\/\/ Revision 1.14 1995\/08\/23 00:11:08 jimg\n\/\/ Changed old, deprecated member functions to new ones.\n\/\/ Switched from String representation of type to enum.\n\/\/\n\/\/ Revision 1.13.2.1 1995\/09\/14 20:58:13 jimg\n\/\/ Moved some loop index variables out of the loop statement.\n\/\/\n\/\/ Revision 1.13 1995\/07\/09 21:29:06 jimg\n\/\/ Added copyright notice.\n\/\/\n\/\/ Revision 1.12 1995\/05\/10 15:34:06 jimg\n\/\/ Failed to change `config.h' to `config_dap.h' in these files.\n\/\/\n\/\/ Revision 1.11 1995\/05\/10 13:45:31 jimg\n\/\/ Changed the name of the configuration header file from `config.h' to\n\/\/ `config_dap.h' so that other libraries could have header files which were\n\/\/ installed in the DODS include directory without overwriting this one. Each\n\/\/ config header should follow the convention config_.h.\n\/\/\n\/\/ Revision 1.10 1995\/03\/16 17:29:12 jimg\n\/\/ Added include config_dap.h to top of include list.\n\/\/ Added TRACE_NEW switched dbnew includes.\n\/\/ Fixed bug in read_val() where **val was passed incorrectly to\n\/\/ subordinate read_val() calls.\n\/\/\n\/\/ Revision 1.9 1995\/03\/04 14:34:51 jimg\n\/\/ Major modifications to the transmission and representation of values:\n\/\/ Added card() virtual function which is true for classes that\n\/\/ contain cardinal types (byte, int float, string).\n\/\/ Changed the representation of Str from the C rep to a C++\n\/\/ class represenation.\n\/\/ Chnaged read_val and store_val so that they take and return\n\/\/ types that are stored by the object (e.g., inthe case of Str\n\/\/ an URL, read_val returns a C++ String object).\n\/\/ Modified Array representations so that arrays of card()\n\/\/ objects are just that - no more storing strings, ... as\n\/\/ C would store them.\n\/\/ Arrays of non cardinal types are arrays of the DODS objects (e.g.,\n\/\/ an array of a structure is represented as an array of Structure\n\/\/ objects).\n\/\/\n\/\/ Revision 1.8 1995\/02\/10 02:22:59 jimg\n\/\/ Added DBMALLOC includes and switch to code which uses malloc\/free.\n\/\/ Private and protected symbols now start with `_'.\n\/\/ Added new accessors for name and type fields of BaseType; the old ones\n\/\/ will be removed in a future release.\n\/\/ Added the store_val() mfunc. It stores the given value in the object's\n\/\/ internal buffer.\n\/\/ Made both List and Str handle their values via pointers to memory.\n\/\/ Fixed read_val().\n\/\/ Made serialize\/deserialize handle all malloc\/free calls (even in those\n\/\/ cases where xdr initiates the allocation).\n\/\/ Fixed print_val().\n\/\/\n\/\/ Revision 1.7 1995\/01\/19 20:05:24 jimg\n\/\/ ptr_duplicate() mfunc is now abstract virtual.\n\/\/ Array, ... Grid duplicate mfuncs were modified to take pointers, not\n\/\/ referenves.\n\/\/\n\/\/ Revision 1.6 1995\/01\/11 15:54:49 jimg\n\/\/ Added modifications necessary for BaseType's static XDR pointers. This\n\/\/ was mostly a name change from xdrin\/out to _xdrin\/out.\n\/\/ Removed the two FILE pointers from ctors, since those are now set with\n\/\/ functions which are friends of BaseType.\n\/\/\n\/\/ Revision 1.5 1994\/12\/16 15:16:39 dan\n\/\/ Modified Structure class removing inheritance from class CtorType\n\/\/ and directly inheriting from class BaseType to alloc calling\n\/\/ BaseType's constructor directly.\n\/\/\n\/\/ Revision 1.4 1994\/11\/22 14:06:10 jimg\n\/\/ Added code for data transmission to parts of the type hierarchy. Not\n\/\/ complete yet.\n\/\/ Fixed erros in type hierarchy headers (typos, incorrect comments, ...).\n\/\/\n\/\/ Revision 1.3 1994\/10\/17 23:34:47 jimg\n\/\/ Added code to print_decl so that variable declarations are pretty\n\/\/ printed.\n\/\/ Added private mfunc duplicate().\n\/\/ Added ptr_duplicate().\n\/\/ Added Copy ctor, dtor and operator=.\n\/\/\n\/\/ Revision 1.2 1994\/09\/23 14:45:26 jimg\n\/\/ Added mfunc check_semantics().\n\/\/ Added sanity checking on the variable list (is it empty?).\n\/\/\n\n#ifdef _GNUG_\n#pragma implementation\n#endif\n\n#include \"config_dap.h\"\n\n#include \n#include \n#include \n\n#include \"Structure.h\"\n#include \"DDS.h\"\n#include \"util.h\"\n\n#ifdef TRACE_NEW\n#include \"trace_new.h\"\n#endif\n\nvoid\nStructure::_duplicate(const Structure &s)\n{\n#ifdef NEVER\n set_name(s.name());\n set_type(s.type());\n\n Structure &cs = (Structure &)s; \/\/ cast away const\n#endif\n \n BaseType::_duplicate(s);\n\n Structure &cs = (Structure &)s; \/\/ cast away const\n\n for (Pix p = cs._vars.first(); p; cs._vars.next(p))\n\t_vars.append(cs._vars(p)->ptr_duplicate());\n}\n\nStructure::Structure(const String &n) : BaseType(n, structure_t)\n{\n}\n\nStructure::Structure(const Structure &rhs)\n{\n _duplicate(rhs);\n}\n\nStructure::~Structure()\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\tdelete _vars(p);\n}\n\nconst Structure &\nStructure::operator=(const Structure &rhs)\n{\n if (this == &rhs)\n\treturn *this;\n\n _duplicate(rhs);\n\n return *this;\n}\n\nvoid\nStructure::set_send_p(bool state)\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\t_vars(p)->set_send_p(state);\n\n BaseType::set_send_p(state);\n}\n\nvoid\nStructure::set_read_p(bool state)\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\t_vars(p)->set_read_p(state);\n\n BaseType::set_read_p(state);\n}\n\n\/\/ NB: Part p defaults to nil for this class\n\nvoid \nStructure::add_var(BaseType *bt, Part p)\n{\n _vars.append(bt);\n}\n\nunsigned int\nStructure::width()\n{\n return sizeof(Structure);\n}\n\nbool\nStructure::serialize(const String &dataset, DDS &dds, bool flush)\n{\n bool status = true;\n\n if (!read_p())\t\t\/\/ only read if not read already\n\tstatus = read(dataset);\n\n if (status && !dds.eval_constraint()) \/\/ if the constraint is false, return\n\treturn status;\n\n if (!status)\n\treturn false;\n\n for (Pix p = first_var(); p; next_var(p)) \n\tif (var(p)->send_p() \n\t && !(status = var(p)->serialize(dataset, dds, false))) \n\t break;\n\n if (status && flush)\n\tstatus = expunge();\n\n return status;\n}\n\nbool\nStructure::deserialize(bool reuse)\n{\n bool status;\n\n for (Pix p = first_var(); p; next_var(p)) {\n\tstatus = var(p)->deserialize(reuse);\n\tif (!status) \n\t break;\n }\n\n return status;\n}\n\n\/\/ This mfunc assumes that val contains values for all the elements of the\n\/\/ strucuture in the order those elements are declared.\n\nunsigned int\nStructure::val2buf(void *val, bool reuse)\n{\n return sizeof(Structure);\n}\n\nunsigned int\nStructure::buf2val(void **val)\n{\n return sizeof(Structure);\n}\n\nBaseType *\nStructure::var(const String &name)\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\tif (_vars(p)->name() == name)\n\t return _vars(p);\n\n return 0;\n}\n\nPix\nStructure::first_var()\n{\n return _vars.first();\n}\n\nvoid\nStructure::next_var(Pix &p)\n{\n if (!_vars.empty() && p)\n\t_vars.next(p);\n}\n\nBaseType *\nStructure::var(Pix p)\n{\n if (!_vars.empty() && p)\n\treturn _vars(p);\n else \n return NULL;\n}\n\nvoid\nStructure::print_decl(ostream &os, String space, bool print_semi,\n\t\t bool constraint_info, bool constrained)\n{\n if (constrained && !send_p())\n\treturn;\n\n os << space << type_name() << \" {\" << endl;\n for (Pix p = _vars.first(); p; _vars.next(p))\n\t_vars(p)->print_decl(os, space + \" \", true, constraint_info,\n\t\t\t constrained);\n os << space << \"} \" << name();\n\n if (constraint_info) {\n\tif (send_p())\n\t cout << \": Send True\";\n\telse\n\t cout << \": Send False\";\n }\n\n if (print_semi)\n\tos << \";\" << endl;\n}\n\n\/\/ print the values of the contained variables\n\nvoid \nStructure::print_val(ostream &os, String space, bool print_decl_p)\n{\n if (print_decl_p) {\n\tprint_decl(os, space, false);\n\tos << \" = \";\n }\n\n os << \"{ \";\n for (Pix p = _vars.first(); p; _vars.next(p), p && os << \", \") {\n\t_vars(p)->print_val(os, \"\", false);\n }\n os << \" }\";\n\n if (print_decl_p)\n\tos << \";\" << endl;\n}\n\nbool\nStructure::check_semantics(bool all)\n{\n if (!BaseType::check_semantics())\n\treturn false;\n\n if (!unique(_vars, (const char *)name(), (const char *)type_name()))\n\treturn false;\n\n if (all) \n\tfor (Pix p = _vars.first(); p; _vars.next(p))\n\t if (!_vars(p)->check_semantics(true))\n\t\treturn false;\n\n return true;\n}\n\nAdded ce_eval to serailize member function. Added debugging information to _duplicate member function.\n\/*\n Copyright 1995 The University of Rhode Island and The Massachusetts\n Institute of Technology\n\n Portions of this software were developed by the Graduate School of\n Oceanography (GSO) at the University of Rhode Island (URI) in collaboration\n with The Massachusetts Institute of Technology (MIT).\n\n Access and use of this software shall impose the following obligations and\n understandings on the user. The user is granted the right, without any fee\n or cost, to use, copy, modify, alter, enhance and distribute this software,\n and any derivative works thereof, and its supporting documentation for any\n purpose whatsoever, provided that this entire notice appears in all copies\n of the software, derivative works and supporting documentation. Further,\n the user agrees to credit URI\/MIT in any publications that result from the\n use of this software or in any product that includes this software. The\n names URI, MIT and\/or GSO, however, may not be used in any advertising or\n publicity to endorse or promote any products or commercial entity unless\n specific written permission is obtained from URI\/MIT. The user also\n understands that URI\/MIT is not obligated to provide the user with any\n support, consulting, training or assistance of any kind with regard to the\n use, operation and performance of this software nor to provide the user\n with any updates, revisions, new versions or \"bug fixes\".\n\n THIS SOFTWARE IS PROVIDED BY URI\/MIT \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n EVENT SHALL URI\/MIT BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS\n ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE\n OF THIS SOFTWARE.\n*\/\n\n\/\/ Implementation for the class Structure\n\/\/\n\/\/ jhrg 9\/14\/94\n\n\/\/ $Log: Structure.cc,v $\n\/\/ Revision 1.20 1996\/03\/05 17:36:12 jimg\n\/\/ Added ce_eval to serailize member function.\n\/\/ Added debugging information to _duplicate member function.\n\/\/\n\/\/ Revision 1.19 1996\/02\/02 00:31:13 jimg\n\/\/ Merge changes for DODS-1.1.0 into DODS-2.x\n\/\/\n\/\/ Revision 1.18 1995\/12\/09 01:07:00 jimg\n\/\/ Added changes so that relational operators will work properly for all the\n\/\/ datatypes (including Sequences). The relational ops are evaluated in\n\/\/ DDS::eval_constraint() after being parsed by DDS::parse_constraint().\n\/\/\n\/\/ Revision 1.17 1995\/12\/06 21:56:32 jimg\n\/\/ Added `constrained' flag to print_decl.\n\/\/ Removed third parameter of read.\n\/\/ Modified print_decl() to print only those parts of a dataset that are\n\/\/ selected when `constrained' is true.\n\/\/\n\/\/ Revision 1.16 1995\/10\/23 23:21:04 jimg\n\/\/ Added _send_p and _read_p fields (and their accessors) along with the\n\/\/ virtual mfuncs set_send_p() and set_read_p().\n\/\/\n\/\/ Revision 1.15 1995\/08\/26 00:31:49 jimg\n\/\/ Removed code enclosed in #ifdef NEVER #endif.\n\/\/\n\/\/ Revision 1.14 1995\/08\/23 00:11:08 jimg\n\/\/ Changed old, deprecated member functions to new ones.\n\/\/ Switched from String representation of type to enum.\n\/\/\n\/\/ Revision 1.13.2.1 1995\/09\/14 20:58:13 jimg\n\/\/ Moved some loop index variables out of the loop statement.\n\/\/\n\/\/ Revision 1.13 1995\/07\/09 21:29:06 jimg\n\/\/ Added copyright notice.\n\/\/\n\/\/ Revision 1.12 1995\/05\/10 15:34:06 jimg\n\/\/ Failed to change `config.h' to `config_dap.h' in these files.\n\/\/\n\/\/ Revision 1.11 1995\/05\/10 13:45:31 jimg\n\/\/ Changed the name of the configuration header file from `config.h' to\n\/\/ `config_dap.h' so that other libraries could have header files which were\n\/\/ installed in the DODS include directory without overwriting this one. Each\n\/\/ config header should follow the convention config_.h.\n\/\/\n\/\/ Revision 1.10 1995\/03\/16 17:29:12 jimg\n\/\/ Added include config_dap.h to top of include list.\n\/\/ Added TRACE_NEW switched dbnew includes.\n\/\/ Fixed bug in read_val() where **val was passed incorrectly to\n\/\/ subordinate read_val() calls.\n\/\/\n\/\/ Revision 1.9 1995\/03\/04 14:34:51 jimg\n\/\/ Major modifications to the transmission and representation of values:\n\/\/ Added card() virtual function which is true for classes that\n\/\/ contain cardinal types (byte, int float, string).\n\/\/ Changed the representation of Str from the C rep to a C++\n\/\/ class represenation.\n\/\/ Chnaged read_val and store_val so that they take and return\n\/\/ types that are stored by the object (e.g., inthe case of Str\n\/\/ an URL, read_val returns a C++ String object).\n\/\/ Modified Array representations so that arrays of card()\n\/\/ objects are just that - no more storing strings, ... as\n\/\/ C would store them.\n\/\/ Arrays of non cardinal types are arrays of the DODS objects (e.g.,\n\/\/ an array of a structure is represented as an array of Structure\n\/\/ objects).\n\/\/\n\/\/ Revision 1.8 1995\/02\/10 02:22:59 jimg\n\/\/ Added DBMALLOC includes and switch to code which uses malloc\/free.\n\/\/ Private and protected symbols now start with `_'.\n\/\/ Added new accessors for name and type fields of BaseType; the old ones\n\/\/ will be removed in a future release.\n\/\/ Added the store_val() mfunc. It stores the given value in the object's\n\/\/ internal buffer.\n\/\/ Made both List and Str handle their values via pointers to memory.\n\/\/ Fixed read_val().\n\/\/ Made serialize\/deserialize handle all malloc\/free calls (even in those\n\/\/ cases where xdr initiates the allocation).\n\/\/ Fixed print_val().\n\/\/\n\/\/ Revision 1.7 1995\/01\/19 20:05:24 jimg\n\/\/ ptr_duplicate() mfunc is now abstract virtual.\n\/\/ Array, ... Grid duplicate mfuncs were modified to take pointers, not\n\/\/ referenves.\n\/\/\n\/\/ Revision 1.6 1995\/01\/11 15:54:49 jimg\n\/\/ Added modifications necessary for BaseType's static XDR pointers. This\n\/\/ was mostly a name change from xdrin\/out to _xdrin\/out.\n\/\/ Removed the two FILE pointers from ctors, since those are now set with\n\/\/ functions which are friends of BaseType.\n\/\/\n\/\/ Revision 1.5 1994\/12\/16 15:16:39 dan\n\/\/ Modified Structure class removing inheritance from class CtorType\n\/\/ and directly inheriting from class BaseType to alloc calling\n\/\/ BaseType's constructor directly.\n\/\/\n\/\/ Revision 1.4 1994\/11\/22 14:06:10 jimg\n\/\/ Added code for data transmission to parts of the type hierarchy. Not\n\/\/ complete yet.\n\/\/ Fixed erros in type hierarchy headers (typos, incorrect comments, ...).\n\/\/\n\/\/ Revision 1.3 1994\/10\/17 23:34:47 jimg\n\/\/ Added code to print_decl so that variable declarations are pretty\n\/\/ printed.\n\/\/ Added private mfunc duplicate().\n\/\/ Added ptr_duplicate().\n\/\/ Added Copy ctor, dtor and operator=.\n\/\/\n\/\/ Revision 1.2 1994\/09\/23 14:45:26 jimg\n\/\/ Added mfunc check_semantics().\n\/\/ Added sanity checking on the variable list (is it empty?).\n\/\/\n\n#ifdef _GNUG_\n#pragma implementation\n#endif\n\n#include \"config_dap.h\"\n\n#include \n#include \n#include \n\n#include \"Structure.h\"\n#include \"DDS.h\"\n#include \"util.h\"\n#include \"debug.h\"\n\n#ifdef TRACE_NEW\n#include \"trace_new.h\"\n#endif\n\nvoid\nStructure::_duplicate(const Structure &s)\n{\n BaseType::_duplicate(s);\n\n Structure &cs = (Structure &)s; \/\/ cast away const\n\n DBG(cerr << \"Copying strucutre: \" << name() << endl);\n\n for (Pix p = cs._vars.first(); p; cs._vars.next(p)) {\n\tDBG(cerr << \"Copying field: \" << cs.name() << endl);\n\t_vars.append(cs._vars(p)->ptr_duplicate());\n }\n}\n\nStructure::Structure(const String &n) : BaseType(n, structure_t)\n{\n}\n\nStructure::Structure(const Structure &rhs)\n{\n _duplicate(rhs);\n}\n\nStructure::~Structure()\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\tdelete _vars(p);\n}\n\nconst Structure &\nStructure::operator=(const Structure &rhs)\n{\n if (this == &rhs)\n\treturn *this;\n\n _duplicate(rhs);\n\n return *this;\n}\n\nvoid\nStructure::set_send_p(bool state)\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\t_vars(p)->set_send_p(state);\n\n BaseType::set_send_p(state);\n}\n\nvoid\nStructure::set_read_p(bool state)\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\t_vars(p)->set_read_p(state);\n\n BaseType::set_read_p(state);\n}\n\n\/\/ NB: Part p defaults to nil for this class\n\nvoid \nStructure::add_var(BaseType *bt, Part p)\n{\n _vars.append(bt);\n}\n\nunsigned int\nStructure::width()\n{\n return sizeof(Structure);\n}\n\n\/\/ Returns: false if an error was detected, true otherwise. \n\/\/ NB: this means that serialize() returns true when the CE evaluates to\n\/\/ false. This bug might be fixed using exceptions.\n\nbool\nStructure::serialize(const String &dataset, DDS &dds, bool ce_eval, bool flush)\n{\n bool status = true;\n\n if (!read_p() && !read(dataset))\n\treturn false;\n\n if (ce_eval && !dds.eval_selection(dataset))\n\treturn true;\n\n for (Pix p = first_var(); p; next_var(p)) \n\tif (var(p)->send_p() \n\t && !(status = var(p)->serialize(dataset, dds, false, false))) \n\t break;\n\n \/\/ flush the stream *even* if status is false, but preserve the value of\n \/\/ status if it's false.\n if (flush)\n\tstatus = status && expunge();\n\n return status;\n}\n\nbool\nStructure::deserialize(bool reuse)\n{\n bool status;\n\n for (Pix p = first_var(); p; next_var(p)) {\n\tstatus = var(p)->deserialize(reuse);\n\tif (!status) \n\t break;\n }\n\n return status;\n}\n\n\/\/ This mfunc assumes that val contains values for all the elements of the\n\/\/ strucuture in the order those elements are declared.\n\nunsigned int\nStructure::val2buf(void *val, bool reuse)\n{\n return sizeof(Structure);\n}\n\nunsigned int\nStructure::buf2val(void **val)\n{\n return sizeof(Structure);\n}\n\nBaseType *\nStructure::var(const String &name)\n{\n for (Pix p = _vars.first(); p; _vars.next(p))\n\tif (_vars(p)->name() == name)\n\t return _vars(p);\n\n return 0;\n}\n\nPix\nStructure::first_var()\n{\n return _vars.first();\n}\n\nvoid\nStructure::next_var(Pix &p)\n{\n if (!_vars.empty() && p)\n\t_vars.next(p);\n}\n\nBaseType *\nStructure::var(Pix p)\n{\n if (!_vars.empty() && p)\n\treturn _vars(p);\n else \n return NULL;\n}\n\nvoid\nStructure::print_decl(ostream &os, String space, bool print_semi,\n\t\t bool constraint_info, bool constrained)\n{\n if (constrained && !send_p())\n\treturn;\n\n os << space << type_name() << \" {\" << endl;\n for (Pix p = _vars.first(); p; _vars.next(p))\n\t_vars(p)->print_decl(os, space + \" \", true, constraint_info,\n\t\t\t constrained);\n os << space << \"} \" << name();\n\n if (constraint_info) {\n\tif (send_p())\n\t cout << \": Send True\";\n\telse\n\t cout << \": Send False\";\n }\n\n if (print_semi)\n\tos << \";\" << endl;\n}\n\n\/\/ print the values of the contained variables\n\nvoid \nStructure::print_val(ostream &os, String space, bool print_decl_p)\n{\n if (print_decl_p) {\n\tprint_decl(os, space, false);\n\tos << \" = \";\n }\n\n os << \"{ \";\n for (Pix p = _vars.first(); p; _vars.next(p), p && os << \", \") {\n\t_vars(p)->print_val(os, \"\", false);\n }\n os << \" }\";\n\n if (print_decl_p)\n\tos << \";\" << endl;\n}\n\nbool\nStructure::check_semantics(bool all)\n{\n if (!BaseType::check_semantics())\n\treturn false;\n\n if (!unique(_vars, (const char *)name(), (const char *)type_name()))\n\treturn false;\n\n if (all) \n\tfor (Pix p = _vars.first(); p; _vars.next(p))\n\t if (!_vars(p)->check_semantics(true))\n\t\treturn false;\n\n return true;\n}\n\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Guido Tack \n *\n * Copyright:\n * Guido Tack, 2007\n *\n * Last modified:\n * $Date: 2010-07-02 19:18:43 +1000 (Fri, 02 Jul 2010) $ by $Author: tack $\n * $Revision: 11149 $\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"base\/stringprintf.h\"\n#include \"flatzinc\/flatzinc.h\"\n\n#include \n#include \nusing namespace std;\n\nnamespace operations_research {\n\nFlatZincModel::FlatZincModel(void)\n : int_var_count(-1),\n bool_var_count(-1),\n set_var_count(-1),\n objective_variable_(-1),\n solve_annotations_(NULL),\n solver_(\"FlatZincSolver\"),\n objective_(NULL),\n output_(NULL) {}\n\nvoid FlatZincModel::Init(int intVars, int boolVars, int setVars) {\n int_var_count = 0;\n integer_variables_.resize(intVars);\n integer_variables_introduced.resize(intVars);\n integer_variables_boolalias.resize(intVars);\n bool_var_count = 0;\n boolean_variables_.resize(boolVars);\n boolean_variables_introduced.resize(boolVars);\n set_var_count = 0;\n \/\/ sv = std::vector(setVars);\n \/\/ sv_introduced = std::vector(setVars);\n}\n\nvoid FlatZincModel::NewIntVar(const std::string& name, IntVarSpec* const vs) {\n if (vs->alias) {\n integer_variables_[int_var_count++] = integer_variables_[vs->i];\n } else {\n AST::SetLit* domain = vs->domain.some();\n if (domain == NULL) {\n integer_variables_[int_var_count++] =\n solver_.MakeIntVar(kint32min, kint32max, name);\n } else if (domain->interval) {\n integer_variables_[int_var_count++] =\n solver_.MakeIntVar(domain->min, domain->max, name);\n } else {\n integer_variables_[int_var_count++] = solver_.MakeIntVar(domain->s, name);\n }\n VLOG(1) << \"Create IntVar: \"\n << integer_variables_[int_var_count - 1]->DebugString();\n }\n integer_variables_introduced[int_var_count - 1] = vs->introduced;\n integer_variables_boolalias[int_var_count - 1] = -1;\n}\n\nvoid FlatZincModel::AliasBool2Int(int iv, int bv) {\n integer_variables_boolalias[iv] = bv;\n}\n\nint FlatZincModel::AliasBool2Int(int iv) {\n return integer_variables_boolalias[iv];\n}\n\nvoid FlatZincModel::NewBoolVar(const std::string& name, BoolVarSpec* const vs) {\n if (vs->alias) {\n boolean_variables_[bool_var_count++] = boolean_variables_[vs->i];\n } else {\n boolean_variables_[bool_var_count++] = solver_.MakeBoolVar(name);\n VLOG(1) << \"Create BoolVar: \"\n << boolean_variables_[bool_var_count - 1]->DebugString();\n }\n boolean_variables_introduced[bool_var_count-1] = vs->introduced;\n}\n\n\/\/ void FlatZincModel::newSetVar(SetVarSpec* vs) {\n\/\/ if (vs->alias) {\n\/\/ sv[set_var_count++] = sv[vs->i];\n\/\/ } else {\n\/\/ LOG(FATAL) << \"SetVar not supported\";\n\/\/ sv[set_var_count++] = SetVar();\n\/\/ }\n\/\/ sv_introduced[set_var_count-1] = vs->introduced;\n\/\/ }\n\nvoid FlattenAnnotations(AST::Array* const annotations,\n std::vector& out) {\n for (unsigned int i=0; i < annotations->a.size(); i++) {\n if (annotations->a[i]->isCall(\"seq_search\")) {\n AST::Call* c = annotations->a[i]->getCall();\n if (c->args->isArray()) {\n FlattenAnnotations(c->args->getArray(), out);\n } else {\n out.push_back(c->args);\n }\n } else {\n out.push_back(annotations->a[i]);\n }\n }\n}\n\nvoid FlatZincModel::CreateDecisionBuilders(bool ignore_unknown,\n bool ignore_annotations) {\n AST::Node* annotations = solve_annotations_;\n if (annotations && !ignore_annotations) {\n std::vector flat_annotations;\n if (annotations->isArray()) {\n FlattenAnnotations(annotations->getArray(), flat_annotations);\n } else {\n flat_annotations.push_back(annotations);\n }\n\n for (unsigned int i=0; i < flat_annotations.size(); i++) {\n try {\n AST::Call *call = flat_annotations[i]->getCall(\"int_search\");\n AST::Array *args = call->getArgs(4);\n AST::Array *vars = args->a[0]->getArray();\n std::vector int_vars;\n for (int i = 0; i < vars->a.size(); ++i) {\n int_vars.push_back(integer_variables_[vars->a[i]->getIntVar()]);\n }\n builders_.push_back(solver_.MakePhase(int_vars,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MIN_VALUE));\n } catch (AST::TypeError& e) {\n (void) e;\n try {\n AST::Call *call = flat_annotations[i]->getCall(\"bool_search\");\n AST::Array *args = call->getArgs(4);\n AST::Array *vars = args->a[0]->getArray();\n std::vector int_vars;\n for (int i = 0; i < vars->a.size(); ++i) {\n int_vars.push_back(boolean_variables_[vars->a[i]->getBoolVar()]);\n }\n builders_.push_back(solver_.MakePhase(int_vars,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MAX_VALUE));\n } catch (AST::TypeError& e) {\n (void) e;\n try {\n AST::Call *call = flat_annotations[i]->getCall(\"set_search\");\n AST::Array *args = call->getArgs(4);\n AST::Array *vars = args->a[0]->getArray();\n LOG(FATAL) << \"Search on set variables not supported\";\n } catch (AST::TypeError& e) {\n (void) e;\n if (!ignore_unknown) {\n LOG(WARNING) << \"Warning, ignored search annotation: \"\n << flat_annotations[i]->DebugString();\n }\n }\n }\n }\n VLOG(1) << \"Adding decision builder = \"\n << builders_.back()->DebugString();\n }\n } else {\n std::vector primary_integer_variables;\n std::vector secondary_integer_variables;\n std::vector sequence_variables;\n std::vector interval_variables;\n solver_.CollectDecisionVariables(&primary_integer_variables,\n &secondary_integer_variables,\n &sequence_variables,\n &interval_variables);\n builders_.push_back(solver_.MakePhase(primary_integer_variables,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MIN_VALUE));\n VLOG(1) << \"Decision builder = \" << builders_.back()->DebugString();\n }\n}\n\nvoid FlatZincModel::Satisfy(AST::Array* const annotations) {\n method_ = SAT;\n solve_annotations_ = annotations;\n}\n\nvoid FlatZincModel::Minimize(int var, AST::Array* const annotations) {\n method_ = MIN;\n objective_variable_ = var;\n solve_annotations_ = annotations;\n \/\/ Branch on optimization variable to ensure that it is given a value.\n AST::Array* args = new AST::Array(4);\n args->a[0] = new AST::Array(new AST::IntVar(objective_variable_));\n args->a[1] = new AST::Atom(\"input_order\");\n args->a[2] = new AST::Atom(\"indomain_min\");\n args->a[3] = new AST::Atom(\"complete\");\n AST::Call* c = new AST::Call(\"int_search\", args);\n if (!solve_annotations_) {\n solve_annotations_ = new AST::Array(c);\n } else {\n solve_annotations_->a.push_back(c);\n }\n objective_ = solver_.MakeMinimize(integer_variables_[objective_variable_], 1);\n}\n\nvoid FlatZincModel::Maximize(int var, AST::Array* const annotations) {\n method_ = MAX;\n objective_variable_ = var;\n solve_annotations_ = annotations;\n \/\/ Branch on optimization variable to ensure that it is given a value.\n AST::Array* args = new AST::Array(4);\n args->a[0] = new AST::Array(new AST::IntVar(objective_variable_));\n args->a[1] = new AST::Atom(\"input_order\");\n args->a[2] = new AST::Atom(\"indomain_min\");\n args->a[3] = new AST::Atom(\"complete\");\n AST::Call* c = new AST::Call(\"int_search\", args);\n if (!solve_annotations_) {\n solve_annotations_ = new AST::Array(c);\n } else {\n solve_annotations_->a.push_back(c);\n }\n objective_ = solver_.MakeMaximize(integer_variables_[objective_variable_], 1);\n}\n\nFlatZincModel::~FlatZincModel(void) {\n delete solve_annotations_;\n delete output_;\n}\n\nvoid FlatZincModel::Solve(int solve_frequency,\n bool use_log,\n bool all_solutions,\n bool ignore_annotations,\n int num_solutions) {\n CreateDecisionBuilders(false, ignore_annotations);\n if (all_solutions && num_solutions == 0) {\n num_solutions = kint32max;\n }\n std::vector monitors;\n switch (method_) {\n case MIN:\n case MAX: {\n SearchMonitor* const log = use_log ?\n solver_.MakeSearchLog(solve_frequency, objective_) :\n NULL;\n monitors.push_back(log);\n monitors.push_back(objective_);\n break;\n }\n case SAT: {\n SearchMonitor* const log = use_log ?\n solver_.MakeSearchLog(solve_frequency) :\n NULL;\n monitors.push_back(log);\n break;\n }\n }\n\n int count = 0;\n solver_.NewSearch(solver_.Compose(builders_), monitors);\n while (solver_.NextSolution()) {\n if (output_ != NULL) {\n for (unsigned int i = 0; i < output_->a.size(); i++) {\n std::cout << DebugString(output_->a[i]);\n }\n std::cout << \"----------\" << std::endl;\n }\n count++;\n if (num_solutions > 0 && count >= num_solutions) {\n break;\n }\n }\n solver_.EndSearch();\n}\n\nvoid FlatZincModel::InitOutput(AST::Array* const output) {\n output_ = output;\n}\n\nstring FlatZincModel::DebugString(AST::Node* const ai) const {\n string output;\n int k;\n if (ai->isArray()) {\n AST::Array* aia = ai->getArray();\n int size = aia->a.size();\n output += \"[\";\n for (int j = 0; j < size; j++) {\n output += DebugString(aia->a[j]);\n if (j < size - 1) {\n output += \", \";\n }\n }\n output += \"]\";\n } else if (ai->isInt(k)) {\n output += StringPrintf(\"%d\", k);\n } else if (ai->isIntVar()) {\n IntVar* const var = integer_variables_[ai->getIntVar()];\n output += StringPrintf(\"%d\", var->Value());\n } else if (ai->isBoolVar()) {\n IntVar* const var = boolean_variables_[ai->getBoolVar()];\n output += var->Value() ? \"true\" : \"false\";\n } else if (ai->isSetVar()) {\n LOG(FATAL) << \"Set variables not implemented\";\n } else if (ai->isBool()) {\n output += (ai->getBool() ? \"true\" : \"false\");\n } else if (ai->isSet()) {\n AST::SetLit* s = ai->getSet();\n if (s->interval) {\n output += StringPrintf(\"%d..%d\", s->min, s->max);\n } else {\n output += \"{\";\n for (unsigned int i=0; is.size(); i++) {\n output += StringPrintf(\"%d%s\",\n s->s[i],\n (i < s->s.size()-1 ? \", \" : \"}\"));\n }\n }\n } else if (ai->isString()) {\n string s = ai->getString();\n for (unsigned int i = 0; i < s.size(); i++) {\n if (s[i] == '\\\\' && i < s.size() - 1) {\n switch (s[i+1]) {\n case 'n': output += \"\\n\"; break;\n case '\\\\': output += \"\\\\\"; break;\n case 't': output += \"\\t\"; break;\n default: {\n output += \"\\\\\";\n output += s[i+1];\n }\n }\n i++;\n } else {\n output += s[i];\n }\n }\n }\n return output;\n}\n}\n\n\/\/ STATISTICS: flatzinc-any\nrevamp parsing...\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Guido Tack \n *\n * Copyright:\n * Guido Tack, 2007\n *\n * Last modified:\n * $Date: 2010-07-02 19:18:43 +1000 (Fri, 02 Jul 2010) $ by $Author: tack $\n * $Revision: 11149 $\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \"base\/stringprintf.h\"\n#include \"flatzinc\/flatzinc.h\"\n\n#include \n#include \nusing namespace std;\n\nnamespace operations_research {\n\nFlatZincModel::FlatZincModel(void)\n : int_var_count(-1),\n bool_var_count(-1),\n set_var_count(-1),\n objective_variable_(-1),\n solve_annotations_(NULL),\n solver_(\"FlatZincSolver\"),\n objective_(NULL),\n output_(NULL) {}\n\nvoid FlatZincModel::Init(int intVars, int boolVars, int setVars) {\n int_var_count = 0;\n integer_variables_.resize(intVars);\n integer_variables_introduced.resize(intVars);\n integer_variables_boolalias.resize(intVars);\n bool_var_count = 0;\n boolean_variables_.resize(boolVars);\n boolean_variables_introduced.resize(boolVars);\n set_var_count = 0;\n \/\/ sv = std::vector(setVars);\n \/\/ sv_introduced = std::vector(setVars);\n}\n\nvoid FlatZincModel::NewIntVar(const std::string& name, IntVarSpec* const vs) {\n if (vs->alias) {\n integer_variables_[int_var_count++] = integer_variables_[vs->i];\n } else {\n AST::SetLit* domain = vs->domain.some();\n if (domain == NULL) {\n integer_variables_[int_var_count++] =\n solver_.MakeIntVar(kint32min, kint32max, name);\n } else if (domain->interval) {\n integer_variables_[int_var_count++] =\n solver_.MakeIntVar(domain->min, domain->max, name);\n } else {\n integer_variables_[int_var_count++] = solver_.MakeIntVar(domain->s, name);\n }\n VLOG(1) << \"Create IntVar: \"\n << integer_variables_[int_var_count - 1]->DebugString();\n }\n integer_variables_introduced[int_var_count - 1] = vs->introduced;\n integer_variables_boolalias[int_var_count - 1] = -1;\n}\n\nvoid FlatZincModel::AliasBool2Int(int iv, int bv) {\n integer_variables_boolalias[iv] = bv;\n}\n\nint FlatZincModel::AliasBool2Int(int iv) {\n return integer_variables_boolalias[iv];\n}\n\nvoid FlatZincModel::NewBoolVar(const std::string& name, BoolVarSpec* const vs) {\n if (vs->alias) {\n boolean_variables_[bool_var_count++] = boolean_variables_[vs->i];\n } else {\n boolean_variables_[bool_var_count++] = solver_.MakeBoolVar(name);\n VLOG(1) << \"Create BoolVar: \"\n << boolean_variables_[bool_var_count - 1]->DebugString();\n }\n boolean_variables_introduced[bool_var_count-1] = vs->introduced;\n}\n\n\/\/ void FlatZincModel::newSetVar(SetVarSpec* vs) {\n\/\/ if (vs->alias) {\n\/\/ sv[set_var_count++] = sv[vs->i];\n\/\/ } else {\n\/\/ LOG(FATAL) << \"SetVar not supported\";\n\/\/ sv[set_var_count++] = SetVar();\n\/\/ }\n\/\/ sv_introduced[set_var_count-1] = vs->introduced;\n\/\/ }\n\nvoid FlattenAnnotations(AST::Array* const annotations,\n std::vector& out) {\n for (unsigned int i=0; i < annotations->a.size(); i++) {\n if (annotations->a[i]->isCall(\"seq_search\")) {\n AST::Call* c = annotations->a[i]->getCall();\n if (c->args->isArray()) {\n FlattenAnnotations(c->args->getArray(), out);\n } else {\n out.push_back(c->args);\n }\n } else {\n out.push_back(annotations->a[i]);\n }\n }\n}\n\nvoid FlatZincModel::CreateDecisionBuilders(bool ignore_unknown,\n bool ignore_annotations) {\n AST::Node* annotations = solve_annotations_;\n if (annotations && !ignore_annotations) {\n std::vector flat_annotations;\n if (annotations->isArray()) {\n FlattenAnnotations(annotations->getArray(), flat_annotations);\n } else {\n flat_annotations.push_back(annotations);\n }\n\n for (unsigned int i=0; i < flat_annotations.size(); i++) {\n try {\n AST::Call *call = flat_annotations[i]->getCall(\"int_search\");\n AST::Array *args = call->getArgs(4);\n AST::Array *vars = args->a[0]->getArray();\n std::vector int_vars;\n for (int i = 0; i < vars->a.size(); ++i) {\n int_vars.push_back(integer_variables_[vars->a[i]->getIntVar()]);\n }\n builders_.push_back(solver_.MakePhase(int_vars,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MIN_VALUE));\n } catch (AST::TypeError& e) {\n (void) e;\n try {\n AST::Call *call = flat_annotations[i]->getCall(\"bool_search\");\n AST::Array *args = call->getArgs(4);\n AST::Array *vars = args->a[0]->getArray();\n std::vector int_vars;\n for (int i = 0; i < vars->a.size(); ++i) {\n int_vars.push_back(boolean_variables_[vars->a[i]->getBoolVar()]);\n }\n builders_.push_back(solver_.MakePhase(int_vars,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MAX_VALUE));\n } catch (AST::TypeError& e) {\n (void) e;\n try {\n AST::Call *call = flat_annotations[i]->getCall(\"set_search\");\n AST::Array *args = call->getArgs(4);\n AST::Array *vars = args->a[0]->getArray();\n LOG(FATAL) << \"Search on set variables not supported\";\n } catch (AST::TypeError& e) {\n (void) e;\n if (!ignore_unknown) {\n LOG(WARNING) << \"Warning, ignored search annotation: \"\n << flat_annotations[i]->DebugString();\n }\n }\n }\n }\n VLOG(1) << \"Adding decision builder = \"\n << builders_.back()->DebugString();\n }\n } else {\n std::vector primary_integer_variables;\n std::vector secondary_integer_variables;\n std::vector sequence_variables;\n std::vector interval_variables;\n solver_.CollectDecisionVariables(&primary_integer_variables,\n &secondary_integer_variables,\n &sequence_variables,\n &interval_variables);\n builders_.push_back(solver_.MakePhase(primary_integer_variables,\n Solver::CHOOSE_FIRST_UNBOUND,\n Solver::ASSIGN_MIN_VALUE));\n VLOG(1) << \"Decision builder = \" << builders_.back()->DebugString();\n }\n}\n\nvoid FlatZincModel::Satisfy(AST::Array* const annotations) {\n method_ = SAT;\n solve_annotations_ = annotations;\n}\n\nvoid FlatZincModel::Minimize(int var, AST::Array* const annotations) {\n method_ = MIN;\n objective_variable_ = var;\n solve_annotations_ = annotations;\n \/\/ Branch on optimization variable to ensure that it is given a value.\n AST::Array* args = new AST::Array(4);\n args->a[0] = new AST::Array(new AST::IntVar(objective_variable_));\n args->a[1] = new AST::Atom(\"input_order\");\n args->a[2] = new AST::Atom(\"indomain_min\");\n args->a[3] = new AST::Atom(\"complete\");\n AST::Call* c = new AST::Call(\"int_search\", args);\n if (!solve_annotations_) {\n solve_annotations_ = new AST::Array(c);\n } else {\n solve_annotations_->a.push_back(c);\n }\n objective_ = solver_.MakeMinimize(integer_variables_[objective_variable_], 1);\n}\n\nvoid FlatZincModel::Maximize(int var, AST::Array* const annotations) {\n method_ = MAX;\n objective_variable_ = var;\n solve_annotations_ = annotations;\n \/\/ Branch on optimization variable to ensure that it is given a value.\n AST::Array* args = new AST::Array(4);\n args->a[0] = new AST::Array(new AST::IntVar(objective_variable_));\n args->a[1] = new AST::Atom(\"input_order\");\n args->a[2] = new AST::Atom(\"indomain_min\");\n args->a[3] = new AST::Atom(\"complete\");\n AST::Call* c = new AST::Call(\"int_search\", args);\n if (!solve_annotations_) {\n solve_annotations_ = new AST::Array(c);\n } else {\n solve_annotations_->a.push_back(c);\n }\n objective_ = solver_.MakeMaximize(integer_variables_[objective_variable_], 1);\n}\n\nFlatZincModel::~FlatZincModel(void) {\n delete solve_annotations_;\n delete output_;\n}\n\nvoid FlatZincModel::Solve(int solve_frequency,\n bool use_log,\n bool all_solutions,\n bool ignore_annotations,\n int num_solutions) {\n CreateDecisionBuilders(false, ignore_annotations);\n if (all_solutions && num_solutions == 0) {\n num_solutions = kint32max;\n } else if (objective_ == NULL) {\n num_solutions = 1;\n }\n std::vector monitors;\n switch (method_) {\n case MIN:\n case MAX: {\n SearchMonitor* const log = use_log ?\n solver_.MakeSearchLog(solve_frequency, objective_) :\n NULL;\n monitors.push_back(log);\n monitors.push_back(objective_);\n break;\n }\n case SAT: {\n SearchMonitor* const log = use_log ?\n solver_.MakeSearchLog(solve_frequency) :\n NULL;\n monitors.push_back(log);\n break;\n }\n }\n\n int count = 0;\n solver_.NewSearch(solver_.Compose(builders_), monitors);\n while (solver_.NextSolution()) {\n if (output_ != NULL) {\n for (unsigned int i = 0; i < output_->a.size(); i++) {\n std::cout << DebugString(output_->a[i]);\n }\n std::cout << \"----------\" << std::endl;\n }\n count++;\n if (num_solutions > 0 && count >= num_solutions) {\n break;\n }\n }\n solver_.EndSearch();\n}\n\nvoid FlatZincModel::InitOutput(AST::Array* const output) {\n output_ = output;\n}\n\nstring FlatZincModel::DebugString(AST::Node* const ai) const {\n string output;\n int k;\n if (ai->isArray()) {\n AST::Array* aia = ai->getArray();\n int size = aia->a.size();\n output += \"[\";\n for (int j = 0; j < size; j++) {\n output += DebugString(aia->a[j]);\n if (j < size - 1) {\n output += \", \";\n }\n }\n output += \"]\";\n } else if (ai->isInt(k)) {\n output += StringPrintf(\"%d\", k);\n } else if (ai->isIntVar()) {\n IntVar* const var = integer_variables_[ai->getIntVar()];\n output += StringPrintf(\"%d\", var->Value());\n } else if (ai->isBoolVar()) {\n IntVar* const var = boolean_variables_[ai->getBoolVar()];\n output += var->Value() ? \"true\" : \"false\";\n } else if (ai->isSetVar()) {\n LOG(FATAL) << \"Set variables not implemented\";\n } else if (ai->isBool()) {\n output += (ai->getBool() ? \"true\" : \"false\");\n } else if (ai->isSet()) {\n AST::SetLit* s = ai->getSet();\n if (s->interval) {\n output += StringPrintf(\"%d..%d\", s->min, s->max);\n } else {\n output += \"{\";\n for (unsigned int i=0; is.size(); i++) {\n output += StringPrintf(\"%d%s\",\n s->s[i],\n (i < s->s.size()-1 ? \", \" : \"}\"));\n }\n }\n } else if (ai->isString()) {\n string s = ai->getString();\n for (unsigned int i = 0; i < s.size(); i++) {\n if (s[i] == '\\\\' && i < s.size() - 1) {\n switch (s[i+1]) {\n case 'n': output += \"\\n\"; break;\n case '\\\\': output += \"\\\\\"; break;\n case 't': output += \"\\t\"; break;\n default: {\n output += \"\\\\\";\n output += s[i+1];\n }\n }\n i++;\n } else {\n output += s[i];\n }\n }\n }\n return output;\n}\n}\n\n\/\/ STATISTICS: flatzinc-any\n<|endoftext|>"} {"text":"#include \"gorgone.h\"\nusing namespace cv;\nusing namespace ofxCv;\nint accum = 0;\n\nvoid gorgone::setup()\n{\n masterIp = \"Mac-Pro-de-10-52.local\";\n appName = \"gorgone-1\";\n parseCmdLineOptions();\n vidGrabber.setup(filename);\n svgInterp.setup();\n jamoma.setup((void*) this, appName, masterIp);\n motionDetector.setup(&jamoma);\n}\n\nvoid gorgone::exit(){\n setPwm(0);\n#ifdef TARGET_RASPBERRY_PI\n vidGrabber.led.switchOffIR();\n#endif\n}\n\nvoid gorgone::update()\n{\n \/\/ cout << ofGetFrameRate() << \" fps\" << endl;\n\n vidGrabber.update();\n\n if ( vidGrabber.isFrameNew() ){\n frame = vidGrabber.getFrame();\n\n if ( bMotion ){\n motionDetector.update(frame);\n }\n\n if( bTracking ){\n\n if ( frame.cols == 0 ) return;\n\n cv::Mat gray;\n if ( frame.channels() == 1 ){\n gray = frame.clone();\n } else {\n cv::cvtColor(frame, gray, CV_RGB2GRAY);\n }\n\n cout << \"new frame to process : \" << gray.cols << \"x\" << gray.rows << endl;\n\n irisDetector.update(gray);\n }\n }\n\n if (bComputeCode) {\n irisDetector.computeCode();\n bComputeCode=false;\n jamoma.mComputeIrisCodeParameter.set(\"value\", bComputeCode);\n\n\/*\n\/\/ desactivated because Max doesn't handle list longer than 256 item, yes this still happens in 2015...\n TTValue v;\n Mat code = irisDetector.getIrisCode();\n v.push_back(code.cols);\n v.push_back(code.rows);\n uchar* p;\n for (int i = 0; i < code.rows; i++ ){\n p=code.ptr(i);\n for (int j = 0; j < code.cols; j++ ){\n v.push_back((int) p[j]);\n }\n }\n cout << \"v size : \" << v.size() << endl;\n jamoma.mTrackingIrisCodeReturn.set(\"value\",v);\n*\/\n }\n\n Mat img = irisDetector.getIrisCode();\n if( bDisplaying && irisDetector.newCode && img.total() > 0 ) {\n\n if ( irisDetector.newCode ){\n svgInterp.coeff.clear();\n cout << \"code image resolution : \" << img.cols << \"x\" << img.rows << endl;\n uchar* p;\n for (int i = 0; i < img.rows; i++ ){\n float avg=0;\n p=img.ptr(i);\n for (int j = 0; j < img.cols; j++ ){\n avg+=p[j] \/ 255.;\n }\n avg\/=img.cols;\n svgInterp.coeff.push_back(avg);\n }\n irisDetector.newCode = false;\n }\n\n TTValue v,x,y;\n for (int i = 0; i line = svgInterp.interpolatedLine;\n\n for (int i=0; i keys = ofxArgParser::allKeys();\n for (int i = 0; i < keys.size(); i++) {\n if ( keys[i] == \"f\" ) filename = ofxArgParser::getValue(keys[i]);\n if ( keys[i] == \"name\" ) appName = ofxArgParser::getValue(keys[i]);\n if ( keys[i] == \"masterIp\" ) masterIp = ofxArgParser::getValue(keys[i]);\n cout << \"key: \" << keys[i] << \", value: \" << ofxArgParser::getValue(keys[i]) << endl;\n }\n}\n\n\nvoid gorgone::setPwm(float pc){\n#ifdef TARGET_RASPBERRY_PI\n ofstream file;\n file.open(\"\/dev\/servoblaster\", ios::in);\n file << \"0=\" << pc << \"%\" << endl;\n file.close();\n#endif\n}\nrestore preview#include \"gorgone.h\"\nusing namespace cv;\nusing namespace ofxCv;\nint accum = 0;\n\nvoid gorgone::setup()\n{\n masterIp = \"Mac-Pro-de-10-52.local\";\n appName = \"gorgone-1\";\n parseCmdLineOptions();\n vidGrabber.setup(filename);\n svgInterp.setup();\n jamoma.setup((void*) this, appName, masterIp);\n motionDetector.setup(&jamoma);\n}\n\nvoid gorgone::exit(){\n setPwm(0);\n#ifdef TARGET_RASPBERRY_PI\n vidGrabber.led.switchOffIR();\n#endif\n}\n\nvoid gorgone::update()\n{\n \/\/ cout << ofGetFrameRate() << \" fps\" << endl;\n\n vidGrabber.update();\n\n if ( vidGrabber.isFrameNew() ){\n frame = vidGrabber.getFrame();\n\n if ( bMotion ){\n motionDetector.update(frame);\n }\n\n if( bTracking ){\n\n if ( frame.cols == 0 ) return;\n\n cv::Mat gray;\n if ( frame.channels() == 1 ){\n gray = frame.clone();\n } else {\n cv::cvtColor(frame, gray, CV_RGB2GRAY);\n }\n\n cout << \"new frame to process : \" << gray.cols << \"x\" << gray.rows << endl;\n\n irisDetector.update(gray);\n }\n }\n\n if (bComputeCode) {\n irisDetector.computeCode();\n bComputeCode=false;\n jamoma.mComputeIrisCodeParameter.set(\"value\", bComputeCode);\n\n\/*\n\/\/ desactivated because Max doesn't handle list longer than 256 item, yes this still happens in 2015...\n TTValue v;\n Mat code = irisDetector.getIrisCode();\n v.push_back(code.cols);\n v.push_back(code.rows);\n uchar* p;\n for (int i = 0; i < code.rows; i++ ){\n p=code.ptr(i);\n for (int j = 0; j < code.cols; j++ ){\n v.push_back((int) p[j]);\n }\n }\n cout << \"v size : \" << v.size() << endl;\n jamoma.mTrackingIrisCodeReturn.set(\"value\",v);\n*\/\n }\n\n Mat img = irisDetector.getIrisCode();\n if( bDisplaying && irisDetector.newCode && img.total() > 0 ) {\n\n if ( irisDetector.newCode ){\n svgInterp.coeff.clear();\n cout << \"code image resolution : \" << img.cols << \"x\" << img.rows << endl;\n uchar* p;\n for (int i = 0; i < img.rows; i++ ){\n float avg=0;\n p=img.ptr(i);\n for (int j = 0; j < img.cols; j++ ){\n avg+=p[j] \/ 255.;\n }\n avg\/=img.cols;\n svgInterp.coeff.push_back(avg);\n }\n irisDetector.newCode = false;\n }\n\n TTValue v,x,y;\n for (int i = 0; i line = svgInterp.interpolatedLine;\n\n for (int i=0; i keys = ofxArgParser::allKeys();\n for (int i = 0; i < keys.size(); i++) {\n if ( keys[i] == \"f\" ) filename = ofxArgParser::getValue(keys[i]);\n if ( keys[i] == \"name\" ) appName = ofxArgParser::getValue(keys[i]);\n if ( keys[i] == \"masterIp\" ) masterIp = ofxArgParser::getValue(keys[i]);\n cout << \"key: \" << keys[i] << \", value: \" << ofxArgParser::getValue(keys[i]) << endl;\n }\n}\n\n\nvoid gorgone::setPwm(float pc){\n#ifdef TARGET_RASPBERRY_PI\n ofstream file;\n file.open(\"\/dev\/servoblaster\", ios::in);\n file << \"0=\" << pc << \"%\" << endl;\n file.close();\n#endif\n}\n<|endoftext|>"} {"text":"#include \"gorgone.h\"\nusing namespace cv;\nusing namespace ofxCv;\nint accum = 0;\n\nvoid gorgone::setup()\n{\n ofSetLogLevel(OF_LOG_NOTICE);\n masterIp = \"Mac-Pro-de-10-52.local\";\n appName = \"gorgone-1\";\n parseCmdLineOptions();\n vidGrabber.setup(filename);\n svgInterp.setup();\n jamoma.setup((void*) this, appName, masterIp);\n motionDetector.setup(&jamoma);\n irisDetector.setJamomaRef(&jamoma);\n counter = 0;\n}\n\nvoid gorgone::exit(){\n setPwm(0);\n#ifdef TARGET_RASPBERRY_PI\n vidGrabber.led.switchOffIR();\n#endif\n}\n\nvoid gorgone::update()\n{\n ofLogVerbose(\"gorgone\") << ofGetFrameRate() << \" fps\" << endl;\n\n vidGrabber.update();\n\n if ( vidGrabber.isFrameNew() ){\n frame = vidGrabber.getFrame();\n\n if ( bMotion ){\n motionDetector.update(frame);\n }\n\n if( bTracking ){\n\n if ( frame.cols == 0 ) return;\n\n cv::Mat gray;\n if ( frame.channels() == 1 ){\n gray = frame.clone();\n } else {\n cv::cvtColor(frame, gray, CV_RGB2GRAY);\n }\n\n ofLogVerbose(\"gorgone\") << \"new frame to process : \" << gray.cols << \"x\" << gray.rows << endl;\n\n irisDetector.updateBool(gray);\n }\n }\n\n if (bComputeCode) {\n irisDetector.computeCode();\n bComputeCode=false;\n jamoma.mComputeIrisCodeParameter.set(\"value\", bComputeCode);\n\n\/*\n\/\/ desactivated because Max doesn't handle list longer than 256 item, yes this still happens in 2015...\n TTValue v;\n Mat code = irisDetector.getIrisCode();\n v.push_back(code.cols);\n v.push_back(code.rows);\n uchar* p;\n for (int i = 0; i < code.rows; i++ ){\n p=code.ptr(i);\n for (int j = 0; j < code.cols; j++ ){\n v.push_back((int) p[j]);\n }\n }\n cout << \"v size : \" << v.size() << endl;\n jamoma.mTrackingIrisCodeReturn.set(\"value\",v);\n*\/\n }\n\n Mat img = irisDetector.getIrisCode();\n if( bDisplaying && irisDetector.newCode && img.total() > 0 ) {\n\n if ( irisDetector.newCode ){\n svgInterp.coeff.clear();\n ofLogVerbose(\"gorgone\") << \"code image resolution : \" << img.cols << \"x\" << img.rows << endl;\n uchar* p;\n for (int i = 0; i < img.rows; i++ ){\n float avg=0;\n p=img.ptr(i);\n for (int j = 0; j < img.cols; j++ ){\n avg+=p[j] \/ 255.;\n }\n avg\/=img.cols;\n svgInterp.coeff.push_back(avg);\n }\n irisDetector.newCode = false;\n\n TTValue v;\n for (int i = 0; i keys = ofxArgParser::allKeys();\n for (int i = 0; i < keys.size(); i++) {\n if ( keys[i] == \"f\" ) filename = ofxArgParser::getValue(keys[i]);\n else if ( keys[i] == \"name\" ) appName = ofxArgParser::getValue(keys[i]);\n else if ( keys[i] == \"masterIp\" ) masterIp = ofxArgParser::getValue(keys[i]);\n else if ( keys[i] == \"verbose\" ) { \/\/ vebose level, value : 0..5, default 1 (OF_LOG_NOTICE)\n int logLevel;\n istringstream( ofxArgParser::getValue(keys[i]) ) >> logLevel;\n ofSetLogLevel((ofLogLevel) logLevel);\n }\n\n ofLogNotice(\"gorgone\") << \"key: \" << keys[i] << \", value: \" << ofxArgParser::getValue(keys[i]) << endl;\n }\n}\n\n\nvoid gorgone::setPwm(float pc){\n#ifdef TARGET_RASPBERRY_PI\n ofstream file;\n file.open(\"\/dev\/servoblaster\", ios::in);\n file << \"0=\" << pc << \"%\" << endl;\n file.close();\n#endif\n}\nuse \/tracking\/iriscode to return computed coefficient from iriscode#include \"gorgone.h\"\nusing namespace cv;\nusing namespace ofxCv;\nint accum = 0;\n\nvoid gorgone::setup()\n{\n ofSetLogLevel(OF_LOG_NOTICE);\n masterIp = \"Mac-Pro-de-10-52.local\";\n appName = \"gorgone-1\";\n parseCmdLineOptions();\n vidGrabber.setup(filename);\n svgInterp.setup();\n jamoma.setup((void*) this, appName, masterIp);\n motionDetector.setup(&jamoma);\n irisDetector.setJamomaRef(&jamoma);\n counter = 0;\n}\n\nvoid gorgone::exit(){\n setPwm(0);\n#ifdef TARGET_RASPBERRY_PI\n vidGrabber.led.switchOffIR();\n#endif\n}\n\nvoid gorgone::update()\n{\n ofLogVerbose(\"gorgone\") << ofGetFrameRate() << \" fps\" << endl;\n\n vidGrabber.update();\n\n if ( vidGrabber.isFrameNew() ){\n frame = vidGrabber.getFrame();\n\n if ( bMotion ){\n motionDetector.update(frame);\n }\n\n if( bTracking ){\n\n if ( frame.cols == 0 ) return;\n\n cv::Mat gray;\n if ( frame.channels() == 1 ){\n gray = frame.clone();\n } else {\n cv::cvtColor(frame, gray, CV_RGB2GRAY);\n }\n\n ofLogVerbose(\"gorgone\") << \"new frame to process : \" << gray.cols << \"x\" << gray.rows << endl;\n\n irisDetector.updateBool(gray);\n }\n }\n\n if (bComputeCode) {\n irisDetector.computeCode();\n bComputeCode=false;\n jamoma.mComputeIrisCodeParameter.set(\"value\", bComputeCode);\n\n\/*\n\/\/ desactivated because Max doesn't handle list longer than 256 item, yes this still happens in 2015...\n TTValue v;\n Mat code = irisDetector.getIrisCode();\n v.push_back(code.cols);\n v.push_back(code.rows);\n uchar* p;\n for (int i = 0; i < code.rows; i++ ){\n p=code.ptr(i);\n for (int j = 0; j < code.cols; j++ ){\n v.push_back((int) p[j]);\n }\n }\n cout << \"v size : \" << v.size() << endl;\n jamoma.mTrackingIrisCodeReturn.set(\"value\",v);\n*\/\n }\n\n Mat img = irisDetector.getIrisCode();\n if( bDisplaying && irisDetector.newCode && img.total() > 0 ) {\n\n if ( irisDetector.newCode ){\n svgInterp.coeff.clear();\n ofLogVerbose(\"gorgone\") << \"code image resolution : \" << img.cols << \"x\" << img.rows << endl;\n uchar* p;\n for (int i = 0; i < img.rows; i++ ){\n float avg=0;\n p=img.ptr(i);\n for (int j = 0; j < img.cols; j++ ){\n avg+=p[j] \/ 255.;\n }\n avg\/=img.cols;\n svgInterp.coeff.push_back(avg);\n }\n irisDetector.newCode = false;\n\n TTValue v;\n for (int i = 0; i keys = ofxArgParser::allKeys();\n for (int i = 0; i < keys.size(); i++) {\n if ( keys[i] == \"f\" ) filename = ofxArgParser::getValue(keys[i]);\n else if ( keys[i] == \"name\" ) appName = ofxArgParser::getValue(keys[i]);\n else if ( keys[i] == \"masterIp\" ) masterIp = ofxArgParser::getValue(keys[i]);\n else if ( keys[i] == \"verbose\" ) { \/\/ vebose level, value : 0..5, default 1 (OF_LOG_NOTICE)\n int logLevel;\n istringstream( ofxArgParser::getValue(keys[i]) ) >> logLevel;\n ofSetLogLevel((ofLogLevel) logLevel);\n }\n\n ofLogNotice(\"gorgone\") << \"key: \" << keys[i] << \", value: \" << ofxArgParser::getValue(keys[i]) << endl;\n }\n}\n\n\nvoid gorgone::setPwm(float pc){\n#ifdef TARGET_RASPBERRY_PI\n ofstream file;\n file.open(\"\/dev\/servoblaster\", ios::in);\n file << \"0=\" << pc << \"%\" << endl;\n file.close();\n#endif\n}\n<|endoftext|>"} {"text":"#include \"redis_cli.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"pink_define.h\"\n#include \"pink_cli_socket.h\"\n#include \"xdebug.h\"\n\n\nnamespace pink {\n\nenum REDIS_STATUS {\n REDIS_ERR = -1,\n REDIS_OK = 0,\n REDIS_HALF,\n REDIS_REPLY_STRING,\n REDIS_REPLY_ARRAY,\n REDIS_REPLY_INTEGER,\n REDIS_REPLY_NIL,\n REDIS_REPLY_STATUS,\n REDIS_REPLY_ERROR\n};\n\nRedisCli::RedisCli()\n : rbuf_size_(REDIS_MAX_MESSAGE),\n rbuf_pos_(0),\n rbuf_offset_(0),\n err_(REDIS_OK) {\n rbuf_ = (char *)malloc(sizeof(char) * rbuf_size_);\n }\n\nRedisCli::~RedisCli() {\n free(rbuf_);\n}\n\n#if 0\nvoid RedisCli::Init(int send_timeout, int recv_timeout, int connect_timeout) {\n if (send_timeout > 0) {\n cli_socket_->set_send_timeout(send_timeout);\n }\n if (recv_timeout > 0) {\n cli_socket_->set_recv_timeout(recv_timeout);\n }\n if (connect_timeout > 0) {\n cli_socket_->set_connect_timeout(connect_timeout);\n }\n}\n#endif\n\n\/\/ We use passed-in send buffer here\nStatus RedisCli::Send(void *msg) {\n log_info(\"The Send function\");\n Status s;\n\n std::string* storage = reinterpret_cast(msg);\n const char *wbuf = storage->data();\n size_t nleft = storage->size();\n int wbuf_pos = 0;\n\n ssize_t nwritten;\n\n while (nleft > 0) {\n if ((nwritten = write(fd(), wbuf + wbuf_pos, nleft)) <= 0) {\n if (errno == EINTR) {\n nwritten = 0;\n continue;\n \/\/ block will EAGAIN ?\n } else {\n s = Status::IOError(wbuf, \"write context error\");\n return s;\n }\n }\n\n nleft -= nwritten;\n wbuf_pos += nwritten;\n }\n\n return s;\n}\n\n\/\/ The result is useless\nStatus RedisCli::Recv(void *result) {\n log_info(\"The Recv function\");\n\n if (GetReply() == REDIS_ERR) {\n return Status::IOError(std::string(strerror(errno)));\n }\n\n return Status::OK();\n}\n\nssize_t RedisCli::BufferRead() {\n \/\/ memmove the remain chars to rbuf begin\n if (rbuf_pos_ > 0) {\n memmove(rbuf_, rbuf_ + rbuf_pos_, rbuf_offset_);\n rbuf_pos_ = 0;\n }\n\n ssize_t nread;\n\n while (true) {\n nread = read(fd(), rbuf_ + rbuf_offset_, rbuf_size_ - rbuf_offset_);\n\n if (nread == -1) {\n if (errno == EINTR) {\n continue;\n } else {\n log_info(\"read error, %s\", strerror(errno));\n return -1;\n }\n } else if (nread == 0) { \/\/ we consider read null an error \n err = REDIS_ERR;\n return -1;\n }\n\n rbuf_offset_ += nread;\n return nread;\n }\n}\n\n\/* Find pointer to \\r\\n. *\/\nstatic char *seekNewline(char *s, size_t len) {\n int pos = 0;\n int _len = len-1;\n\n \/* Position should be < len-1 because the character at \"pos\" should be\n * followed by a \\n. Note that strchr cannot be used because it doesn't\n * allow to search a limited length and the buffer that is being searched\n * might not have a trailing NULL character. *\/\n while (pos < _len) {\n while (pos < _len && s[pos] != '\\r') pos++;\n if (s[pos] != '\\r') {\n \/* Not found. *\/\n return NULL;\n } else {\n if (s[pos+1] == '\\n') {\n \/* Found. *\/\n return s+pos;\n } else {\n \/* Continue searching. *\/\n pos++;\n }\n }\n }\n return NULL;\n}\n\nint RedisCli::ProcessLineItem() {\n char *p;\n int len;\n\n if ((p = ReadLine(&len)) == NULL) {\n return REDIS_HALF;\n }\n\n std::string arg(p, len);\n argv_.push_back(arg);\n\n return REDIS_OK;\n}\n\nint RedisCli::GetReply() {\n int result = REDIS_OK;\n\n while (true) {\n \/\/ Should read again\n if (rbuf_offset_ == 0 || result == REDIS_HALF) {\n if ((result = BufferRead()) < 0) {\n return REDIS_ERR;\n }\n }\n\n \/\/ REDIS_HALF will read and parse again\n if ((result = GetReplyFromReader()) != REDIS_HALF)\n return result;\n }\n}\n\nchar* RedisCli::ReadBytes(unsigned int bytes) {\n char *p = NULL;\n if (rbuf_offset_ >= bytes) {\n p = rbuf_ + rbuf_pos_;\n rbuf_pos_ += bytes;\n rbuf_offset_ -= bytes;\n }\n return p;\n}\n\nchar *RedisCli::ReadLine(int *_len) {\n char *p, *s;\n int len;\n\n p = rbuf_ + rbuf_pos_;\n s = seekNewline(rbuf_ + rbuf_pos_, rbuf_offset_);\n if (s != NULL) {\n len = s - (rbuf_ + rbuf_pos_); \n rbuf_pos_ += len + 2; \/* skip \\r\\n *\/\n rbuf_offset_ -= len + 2;\n if (_len) *_len = len;\n return p;\n }\n return NULL;\n}\n\nint RedisCli::GetReplyFromReader() {\n if (err_) {\n return REDIS_ERR;\n }\n\n if (rbuf_offset_ == 0) {\n return REDIS_HALF;\n }\n\n char *p;\n if ((p = ReadBytes(1)) == NULL) {\n return REDIS_HALF;\n }\n\n int type;\n \/\/ Check reply type \n switch (*p) {\n case '-':\n type = REDIS_REPLY_ERROR;\n break;\n case '+':\n type = REDIS_REPLY_STATUS;\n break;\n case ':':\n type = REDIS_REPLY_INTEGER;\n break;\n case '$':\n type = REDIS_REPLY_STRING;\n break;\n case '*':\n type = REDIS_REPLY_ARRAY;\n break;\n default:\n return REDIS_ERR;\n }\n\n switch(type) {\n case REDIS_REPLY_ERROR:\n case REDIS_REPLY_STATUS:\n case REDIS_REPLY_INTEGER:\n return ProcessLineItem();\n case REDIS_REPLY_STRING:\n \/\/ need processBulkItem();\n case REDIS_REPLY_ARRAY:\n \/\/ need processMultiBulkItem();\n default:\n return REDIS_ERR; \/\/ Avoid warning.\n }\n}\n\n\/\/ Calculate the number of bytes needed to represent an integer as string.\nstatic int intlen(int i) {\n int len = 0;\n if (i < 0) {\n len++;\n i = -i;\n }\n do {\n len++;\n i \/= 10;\n } while(i);\n return len;\n}\n\n\/\/ Helper that calculates the bulk length given a certain string length.\nstatic size_t bulklen(size_t len) {\n return 1 + intlen(len) + 2 + len + 2;\n}\n\nint redisvFormatCommand(std::string *cmd, const char *format, va_list ap) {\n const char *c = format;\n std::string curarg;\n char buf[REDIS_MAX_MESSAGE];\n std::vector args;\n int touched = 0; \/* was the current argument touched? *\/\n size_t totlen = 0;\n\n while (*c != '\\0') {\n if (*c != '%' || c[1] == '\\0') {\n if (*c == ' ') {\n if (touched) {\n args.push_back(curarg);\n totlen += bulklen(curarg.size());\n curarg.clear();\n touched = 0;\n }\n } else {\n curarg.append(c, 1);\n touched = 1;\n }\n } else {\n char *arg;\n size_t size;\n\n switch (c[1]) {\n case 's':\n arg = va_arg(ap, char*);\n size = strlen(arg);\n if (size > 0) {\n curarg.append(arg, size);\n }\n break;\n case 'b':\n arg = va_arg(ap, char*);\n size = va_arg(ap, size_t);\n if (size > 0) {\n curarg.append(arg, size);\n }\n break;\n case '%':\n curarg.append(arg, size);\n break;\n default:\n \/* Try to detect printf format *\/\n {\n static const char intfmts[] = \"diouxX\";\n char _format[16];\n const char *_p = c+1;\n size_t _l = 0;\n va_list _cpy;\n bool fmt_valid = false;\n\n \/* Flags *\/\n if (*_p != '\\0' && *_p == '#') _p++;\n if (*_p != '\\0' && *_p == '0') _p++;\n if (*_p != '\\0' && *_p == '-') _p++;\n if (*_p != '\\0' && *_p == ' ') _p++;\n if (*_p != '\\0' && *_p == '+') _p++;\n\n \/* Field width *\/\n while (*_p != '\\0' && isdigit(*_p)) _p++;\n\n \/* Precision *\/\n if (*_p == '.') {\n _p++;\n while (*_p != '\\0' && isdigit(*_p)) _p++;\n }\n\n \/* Copy va_list before consuming with va_arg *\/\n va_copy(_cpy, ap);\n\n if (strchr(intfmts, *_p) != NULL) { \/* Integer conversion (without modifiers) *\/\n va_arg(ap,int);\n fmt_valid = true;\n } else if (strchr(\"eEfFgGaA\",*_p) != NULL) { \/* Double conversion (without modifiers) *\/\n va_arg(ap, double);\n fmt_valid = true;\n } else if (_p[0] == 'h' && _p[1] == 'h') { \/* Size: char *\/\n _p += 2;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap,int); \/* char gets promoted to int *\/\n fmt_valid = true;\n }\n } else if (_p[0] == 'h') { \/* Size: short *\/\n _p += 1;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap,int); \/* short gets promoted to int *\/\n fmt_valid = true;\n }\n } else if (_p[0] == 'l' && _p[1] == 'l') { \/* Size: long long *\/\n _p += 2;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap, long long);\n fmt_valid = true;\n }\n } else if (_p[0] == 'l') { \/* Size: long *\/\n _p += 1;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap,long);\n fmt_valid = true;\n }\n }\n\n if (!fmt_valid) {\n va_end(_cpy);\n return REDIS_ERR;\n }\n\n _l = (_p + 1) - c;\n if (_l < sizeof(_format) - 2) {\n memcpy(_format, c, _l);\n _format[_l] = '\\0';\n\n int n = vsnprintf (buf, REDIS_MAX_MESSAGE, _format, _cpy);\n curarg.append(buf, n);\n\n \/* Update current position (note: outer blocks\n * increment c twice so compensate here) *\/\n c = _p - 1;\n }\n\n va_end(_cpy);\n break;\n }\n }\n\n if (curarg.empty()) {\n return REDIS_ERR;\n }\n\n touched = 1;\n c++;\n }\n c++;\n }\n\n \/* Add the last argument if needed *\/\n if (touched) {\n args.push_back(curarg);\n totlen += bulklen(curarg.size());\n }\n\n \/* Add bytes needed to hold multi bulk count *\/\n totlen += 1 + intlen(args.size()) + 2;\n\n \/* Build the command at protocol level *\/\n cmd->clear();\n cmd->reserve(totlen);\n\n cmd->append(1, '*');\n cmd->append(std::to_string(args.size()));\n cmd->append(\"\\r\\n\");\n for (size_t i = 0; i < args.size(); i++) {\n cmd->append(1, '$');\n cmd->append(std::to_string(args[i].size()));\n cmd->append(\"\\r\\n\");\n cmd->append(args[i]);\n cmd->append(\"\\r\\n\");\n }\n assert(cmd->size() == totlen);\n\n return totlen;\n}\n\nint redisvAppendCommand(std::string *cmd, const char *format, va_list ap) {\n int len = redisvFormatCommand(cmd, format, ap);\n if (len == -1) {\n return REDIS_ERR;\n }\n\n return REDIS_OK;\n}\n\nint RedisCli::SerializeCommand(std::string *cmd, const char *format, ...) {\n va_list ap;\n va_start(ap, format);\n int result = redisvAppendCommand(cmd, format, ap);\n va_end(ap);\n return result;\n}\n\n}; \/\/ namespace pink\nfix wrong commit#include \"redis_cli.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"pink_define.h\"\n#include \"pink_cli_socket.h\"\n#include \"xdebug.h\"\n\n\nnamespace pink {\n\nenum REDIS_STATUS {\n REDIS_ERR = -1,\n REDIS_OK = 0,\n REDIS_HALF,\n REDIS_REPLY_STRING,\n REDIS_REPLY_ARRAY,\n REDIS_REPLY_INTEGER,\n REDIS_REPLY_NIL,\n REDIS_REPLY_STATUS,\n REDIS_REPLY_ERROR\n};\n\nRedisCli::RedisCli()\n : rbuf_size_(REDIS_MAX_MESSAGE),\n rbuf_pos_(0),\n rbuf_offset_(0),\n err_(REDIS_OK) {\n rbuf_ = (char *)malloc(sizeof(char) * rbuf_size_);\n }\n\nRedisCli::~RedisCli() {\n free(rbuf_);\n}\n\n#if 0\nvoid RedisCli::Init(int send_timeout, int recv_timeout, int connect_timeout) {\n if (send_timeout > 0) {\n cli_socket_->set_send_timeout(send_timeout);\n }\n if (recv_timeout > 0) {\n cli_socket_->set_recv_timeout(recv_timeout);\n }\n if (connect_timeout > 0) {\n cli_socket_->set_connect_timeout(connect_timeout);\n }\n}\n#endif\n\n\/\/ We use passed-in send buffer here\nStatus RedisCli::Send(void *msg) {\n log_info(\"The Send function\");\n Status s;\n\n std::string* storage = reinterpret_cast(msg);\n const char *wbuf = storage->data();\n size_t nleft = storage->size();\n int wbuf_pos = 0;\n\n ssize_t nwritten;\n\n while (nleft > 0) {\n if ((nwritten = write(fd(), wbuf + wbuf_pos, nleft)) <= 0) {\n if (errno == EINTR) {\n nwritten = 0;\n continue;\n \/\/ block will EAGAIN ?\n } else {\n s = Status::IOError(wbuf, \"write context error\");\n return s;\n }\n }\n\n nleft -= nwritten;\n wbuf_pos += nwritten;\n }\n\n return s;\n}\n\n\/\/ The result is useless\nStatus RedisCli::Recv(void *result) {\n log_info(\"The Recv function\");\n\n if (GetReply() == REDIS_ERR) {\n return Status::IOError(std::string(strerror(errno)));\n }\n\n return Status::OK();\n}\n\nssize_t RedisCli::BufferRead() {\n \/\/ memmove the remain chars to rbuf begin\n if (rbuf_pos_ > 0) {\n memmove(rbuf_, rbuf_ + rbuf_pos_, rbuf_offset_);\n rbuf_pos_ = 0;\n }\n\n ssize_t nread;\n\n while (true) {\n nread = read(fd(), rbuf_ + rbuf_offset_, rbuf_size_ - rbuf_offset_);\n\n if (nread == -1) {\n if (errno == EINTR) {\n continue;\n } else {\n log_info(\"read error, %s\", strerror(errno));\n return -1;\n }\n } else if (nread == 0) { \/\/ we consider read null an error \n err_ = REDIS_ERR;\n return -1;\n }\n\n rbuf_offset_ += nread;\n return nread;\n }\n}\n\n\/* Find pointer to \\r\\n. *\/\nstatic char *seekNewline(char *s, size_t len) {\n int pos = 0;\n int _len = len-1;\n\n \/* Position should be < len-1 because the character at \"pos\" should be\n * followed by a \\n. Note that strchr cannot be used because it doesn't\n * allow to search a limited length and the buffer that is being searched\n * might not have a trailing NULL character. *\/\n while (pos < _len) {\n while (pos < _len && s[pos] != '\\r') pos++;\n if (s[pos] != '\\r') {\n \/* Not found. *\/\n return NULL;\n } else {\n if (s[pos+1] == '\\n') {\n \/* Found. *\/\n return s+pos;\n } else {\n \/* Continue searching. *\/\n pos++;\n }\n }\n }\n return NULL;\n}\n\nint RedisCli::ProcessLineItem() {\n char *p;\n int len;\n\n if ((p = ReadLine(&len)) == NULL) {\n return REDIS_HALF;\n }\n\n std::string arg(p, len);\n argv_.push_back(arg);\n\n return REDIS_OK;\n}\n\nint RedisCli::GetReply() {\n int result = REDIS_OK;\n\n while (true) {\n \/\/ Should read again\n if (rbuf_offset_ == 0 || result == REDIS_HALF) {\n if ((result = BufferRead()) < 0) {\n return REDIS_ERR;\n }\n }\n\n \/\/ REDIS_HALF will read and parse again\n if ((result = GetReplyFromReader()) != REDIS_HALF)\n return result;\n }\n}\n\nchar* RedisCli::ReadBytes(unsigned int bytes) {\n char *p = NULL;\n if (rbuf_offset_ >= bytes) {\n p = rbuf_ + rbuf_pos_;\n rbuf_pos_ += bytes;\n rbuf_offset_ -= bytes;\n }\n return p;\n}\n\nchar *RedisCli::ReadLine(int *_len) {\n char *p, *s;\n int len;\n\n p = rbuf_ + rbuf_pos_;\n s = seekNewline(rbuf_ + rbuf_pos_, rbuf_offset_);\n if (s != NULL) {\n len = s - (rbuf_ + rbuf_pos_); \n rbuf_pos_ += len + 2; \/* skip \\r\\n *\/\n rbuf_offset_ -= len + 2;\n if (_len) *_len = len;\n return p;\n }\n return NULL;\n}\n\nint RedisCli::GetReplyFromReader() {\n if (err_) {\n return REDIS_ERR;\n }\n\n if (rbuf_offset_ == 0) {\n return REDIS_HALF;\n }\n\n char *p;\n if ((p = ReadBytes(1)) == NULL) {\n return REDIS_HALF;\n }\n\n int type;\n \/\/ Check reply type \n switch (*p) {\n case '-':\n type = REDIS_REPLY_ERROR;\n break;\n case '+':\n type = REDIS_REPLY_STATUS;\n break;\n case ':':\n type = REDIS_REPLY_INTEGER;\n break;\n case '$':\n type = REDIS_REPLY_STRING;\n break;\n case '*':\n type = REDIS_REPLY_ARRAY;\n break;\n default:\n return REDIS_ERR;\n }\n\n switch(type) {\n case REDIS_REPLY_ERROR:\n case REDIS_REPLY_STATUS:\n case REDIS_REPLY_INTEGER:\n return ProcessLineItem();\n case REDIS_REPLY_STRING:\n \/\/ need processBulkItem();\n case REDIS_REPLY_ARRAY:\n \/\/ need processMultiBulkItem();\n default:\n return REDIS_ERR; \/\/ Avoid warning.\n }\n}\n\n\/\/ Calculate the number of bytes needed to represent an integer as string.\nstatic int intlen(int i) {\n int len = 0;\n if (i < 0) {\n len++;\n i = -i;\n }\n do {\n len++;\n i \/= 10;\n } while(i);\n return len;\n}\n\n\/\/ Helper that calculates the bulk length given a certain string length.\nstatic size_t bulklen(size_t len) {\n return 1 + intlen(len) + 2 + len + 2;\n}\n\nint redisvFormatCommand(std::string *cmd, const char *format, va_list ap) {\n const char *c = format;\n std::string curarg;\n char buf[REDIS_MAX_MESSAGE];\n std::vector args;\n int touched = 0; \/* was the current argument touched? *\/\n size_t totlen = 0;\n\n while (*c != '\\0') {\n if (*c != '%' || c[1] == '\\0') {\n if (*c == ' ') {\n if (touched) {\n args.push_back(curarg);\n totlen += bulklen(curarg.size());\n curarg.clear();\n touched = 0;\n }\n } else {\n curarg.append(c, 1);\n touched = 1;\n }\n } else {\n char *arg;\n size_t size;\n\n switch (c[1]) {\n case 's':\n arg = va_arg(ap, char*);\n size = strlen(arg);\n if (size > 0) {\n curarg.append(arg, size);\n }\n break;\n case 'b':\n arg = va_arg(ap, char*);\n size = va_arg(ap, size_t);\n if (size > 0) {\n curarg.append(arg, size);\n }\n break;\n case '%':\n curarg.append(arg, size);\n break;\n default:\n \/* Try to detect printf format *\/\n {\n static const char intfmts[] = \"diouxX\";\n char _format[16];\n const char *_p = c+1;\n size_t _l = 0;\n va_list _cpy;\n bool fmt_valid = false;\n\n \/* Flags *\/\n if (*_p != '\\0' && *_p == '#') _p++;\n if (*_p != '\\0' && *_p == '0') _p++;\n if (*_p != '\\0' && *_p == '-') _p++;\n if (*_p != '\\0' && *_p == ' ') _p++;\n if (*_p != '\\0' && *_p == '+') _p++;\n\n \/* Field width *\/\n while (*_p != '\\0' && isdigit(*_p)) _p++;\n\n \/* Precision *\/\n if (*_p == '.') {\n _p++;\n while (*_p != '\\0' && isdigit(*_p)) _p++;\n }\n\n \/* Copy va_list before consuming with va_arg *\/\n va_copy(_cpy, ap);\n\n if (strchr(intfmts, *_p) != NULL) { \/* Integer conversion (without modifiers) *\/\n va_arg(ap,int);\n fmt_valid = true;\n } else if (strchr(\"eEfFgGaA\",*_p) != NULL) { \/* Double conversion (without modifiers) *\/\n va_arg(ap, double);\n fmt_valid = true;\n } else if (_p[0] == 'h' && _p[1] == 'h') { \/* Size: char *\/\n _p += 2;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap,int); \/* char gets promoted to int *\/\n fmt_valid = true;\n }\n } else if (_p[0] == 'h') { \/* Size: short *\/\n _p += 1;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap,int); \/* short gets promoted to int *\/\n fmt_valid = true;\n }\n } else if (_p[0] == 'l' && _p[1] == 'l') { \/* Size: long long *\/\n _p += 2;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap, long long);\n fmt_valid = true;\n }\n } else if (_p[0] == 'l') { \/* Size: long *\/\n _p += 1;\n if (*_p != '\\0' && strchr(intfmts,*_p) != NULL) {\n va_arg(ap,long);\n fmt_valid = true;\n }\n }\n\n if (!fmt_valid) {\n va_end(_cpy);\n return REDIS_ERR;\n }\n\n _l = (_p + 1) - c;\n if (_l < sizeof(_format) - 2) {\n memcpy(_format, c, _l);\n _format[_l] = '\\0';\n\n int n = vsnprintf (buf, REDIS_MAX_MESSAGE, _format, _cpy);\n curarg.append(buf, n);\n\n \/* Update current position (note: outer blocks\n * increment c twice so compensate here) *\/\n c = _p - 1;\n }\n\n va_end(_cpy);\n break;\n }\n }\n\n if (curarg.empty()) {\n return REDIS_ERR;\n }\n\n touched = 1;\n c++;\n }\n c++;\n }\n\n \/* Add the last argument if needed *\/\n if (touched) {\n args.push_back(curarg);\n totlen += bulklen(curarg.size());\n }\n\n \/* Add bytes needed to hold multi bulk count *\/\n totlen += 1 + intlen(args.size()) + 2;\n\n \/* Build the command at protocol level *\/\n cmd->clear();\n cmd->reserve(totlen);\n\n cmd->append(1, '*');\n cmd->append(std::to_string(args.size()));\n cmd->append(\"\\r\\n\");\n for (size_t i = 0; i < args.size(); i++) {\n cmd->append(1, '$');\n cmd->append(std::to_string(args[i].size()));\n cmd->append(\"\\r\\n\");\n cmd->append(args[i]);\n cmd->append(\"\\r\\n\");\n }\n assert(cmd->size() == totlen);\n\n return totlen;\n}\n\nint redisvAppendCommand(std::string *cmd, const char *format, va_list ap) {\n int len = redisvFormatCommand(cmd, format, ap);\n if (len == -1) {\n return REDIS_ERR;\n }\n\n return REDIS_OK;\n}\n\nint RedisCli::SerializeCommand(std::string *cmd, const char *format, ...) {\n va_list ap;\n va_start(ap, format);\n int result = redisvAppendCommand(cmd, format, ap);\n va_end(ap);\n return result;\n}\n\n}; \/\/ namespace pink\n<|endoftext|>"} {"text":"#include \"grammar.h\"\n\n#include \"ast.h\"\n#include \"token.h\"\n#include \"parser.h\"\n#include \"grammar.h\"\n#include \"exceptions.h\"\n\n#include \n#include \n#include \n\nnamespace sota {\n\n \/\/ scanners\n size_t RegexScanner(Symbol *symbol, const std::string &source, size_t index) {\n auto pattern = symbol->pattern;\n boost::smatch matches;\n boost::regex re(\"^\" + pattern);\n if (boost::regex_search(source, matches, re)) {\n auto match = matches[0];\n \/\/std::cout << \"re pattern: \" << pattern << \" matched: \" << match << std::endl;\n return index + match.length();\n }\n return index;\n }\n\n size_t LiteralScanner(Symbol *symbol, const std::string &source, size_t index) {\n auto pattern = symbol->pattern;\n auto patternSize = pattern.size();\n if (source.size() >= patternSize && source.compare(0, patternSize, pattern) == 0) {\n \/\/std::cout << \"lit pattern: \" << pattern << \" matched: \" << pattern << std::endl;\n return index + patternSize;\n }\n return index;\n }\n\n \/\/ nud parsing functions\n Ast * NotImplementedNud(Parser *parser, Token *token) {\n throw SotaNotImplemented(\"nud: NotImplemented; this shouldn't be called!\");\n }\n Ast * EndOfFileNud(Parser *parser, Token *token) {\n std::cout << \"EndOfFileNud\" << std::endl;\n return nullptr;\n }\n Ast * WhiteSpaceNud(Parser *parser, Token *token) {\n std::cout << \"WhiteSpaceNud\" << std::endl;\n return nullptr;\n }\n Ast * NumberNud(Parser *parser, Token *token) {\n std::cout << \"NumberNud\" << std::endl;\n return nullptr;\n }\n Ast * IdentifierNud(Parser *parser, Token *token) {\n std::cout << \"IdentifierNud\" << std::endl;\n Ast *ast = new IdentifierAst(token->Value());\n return ast;\n }\n Ast * PrefixOperatorNud(Parser *parser, Token *token) {\n std::cout << \"PrefixOperatorNud\" << std::endl;\n return nullptr;\n }\n\n \/\/ led parsing functions\n Ast * NotImplementedLed(Parser *parser, Ast *left, Token *token) {\n throw SotaNotImplemented(\"led: NotImplemented; this shouldn't be called!\");\n }\n Ast * InfixOperatorLed(Parser *parser, Ast *left, Token *token) {\n std::cout << \"InfixOperatorLed\" << std::endl;\n Ast *right = parser->Parse(token->symbol.lbp);\n return new InfixOperatorAst(token, left, right);\n }\n Ast * PostfixOperatorNud(Parser *parser, Ast *left, Token *token) {\n std::cout << \"PostfixOperatorLed\" << std::endl;\n return nullptr;\n }\n\n #define T(k,p,s,n,l,b) std::make_pair(SymbolType::k, new Symbol(SymbolType::k,p,s,n,l,b) ),\n std::map Type2Symbol {\n SYMBOLS\n };\n #undef T\n\n #define T(k,p,s,n,l,b) std::make_pair(#k, Type2Symbol[SymbolType::k]),\n std::map Name2Symbol {\n SYMBOLS\n };\n #undef T\n\n #define T(k,p,s,n,l,b) std::make_pair(SymbolType::k, #k),\n std::map Type2Name {\n SYMBOLS\n };\n #undef T\n\n #define T(k,p,s,n,l,b) std::make_pair(#k, SymbolType::k),\n std::map Name2Type {\n SYMBOLS\n };\n #undef T\n\n}\nAdded identifier and number ast implementations... -sai#include \"grammar.h\"\n\n#include \"ast.h\"\n#include \"token.h\"\n#include \"parser.h\"\n#include \"grammar.h\"\n#include \"exceptions.h\"\n\n#include \n#include \n#include \n\nnamespace sota {\n\n \/\/ scanners\n size_t RegexScanner(Symbol *symbol, const std::string &source, size_t index) {\n auto pattern = symbol->pattern;\n boost::smatch matches;\n boost::regex re(\"^\" + pattern);\n if (boost::regex_search(source, matches, re)) {\n auto match = matches[0];\n \/\/std::cout << \"re pattern: \" << pattern << \" matched: \" << match << std::endl;\n return index + match.length();\n }\n return index;\n }\n\n size_t LiteralScanner(Symbol *symbol, const std::string &source, size_t index) {\n auto pattern = symbol->pattern;\n auto patternSize = pattern.size();\n if (source.size() >= patternSize && source.compare(0, patternSize, pattern) == 0) {\n \/\/std::cout << \"lit pattern: \" << pattern << \" matched: \" << pattern << std::endl;\n return index + patternSize;\n }\n return index;\n }\n\n \/\/ nud parsing functions\n Ast * NotImplementedNud(Parser *parser, Token *token) {\n throw SotaNotImplemented(\"nud: NotImplemented; this shouldn't be called!\");\n }\n Ast * EndOfFileNud(Parser *parser, Token *token) {\n std::cout << \"EndOfFileNud\" << std::endl;\n return nullptr;\n }\n Ast * WhiteSpaceNud(Parser *parser, Token *token) {\n std::cout << \"WhiteSpaceNud\" << std::endl;\n return nullptr;\n }\n Ast * NumberNud(Parser *parser, Token *token) {\n std::cout << \"NumberNud\" << std::endl;\n return new NumberAst(token->Value());\n }\n Ast * IdentifierNud(Parser *parser, Token *token) {\n std::cout << \"IdentifierNud\" << std::endl;\n return new IdentifierAst(token->Value());\n }\n Ast * PrefixOperatorNud(Parser *parser, Token *token) {\n std::cout << \"PrefixOperatorNud\" << std::endl;\n return nullptr;\n }\n\n \/\/ led parsing functions\n Ast * NotImplementedLed(Parser *parser, Ast *left, Token *token) {\n throw SotaNotImplemented(\"led: NotImplemented; this shouldn't be called!\");\n }\n Ast * InfixOperatorLed(Parser *parser, Ast *left, Token *token) {\n std::cout << \"InfixOperatorLed\" << std::endl;\n Ast *right = parser->Parse(token->symbol.lbp);\n return new InfixOperatorAst(token, left, right);\n }\n Ast * PostfixOperatorNud(Parser *parser, Ast *left, Token *token) {\n std::cout << \"PostfixOperatorLed\" << std::endl;\n return nullptr;\n }\n\n #define T(k,p,s,n,l,b) std::make_pair(SymbolType::k, new Symbol(SymbolType::k,p,s,n,l,b) ),\n std::map Type2Symbol {\n SYMBOLS\n };\n #undef T\n\n #define T(k,p,s,n,l,b) std::make_pair(#k, Type2Symbol[SymbolType::k]),\n std::map Name2Symbol {\n SYMBOLS\n };\n #undef T\n\n #define T(k,p,s,n,l,b) std::make_pair(SymbolType::k, #k),\n std::map Type2Name {\n SYMBOLS\n };\n #undef T\n\n #define T(k,p,s,n,l,b) std::make_pair(#k, SymbolType::k),\n std::map Name2Type {\n SYMBOLS\n };\n #undef T\n\n}\n<|endoftext|>"} {"text":"#include \"renderer.h\"\n\nRenderer::Renderer() {\n \/\/ Set color and depth clear value\n glClearDepth(1.f);\n glClearColor(0.f, 0.f, 0.f, 0.f);\n\n \/\/ Enable Z-buffer read and write\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_TRUE);\n\n \/\/ Setup a perspective projection\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(90.f, 1.f, 1.f, 500.f);\n \n \/\/ Lighting test junk\n GLfloat LightAmbient[]= { 0.5f, 0.5f, 0.5f, 1.0f }; \t\t\t\t\/\/ Ambient Light Values ( NEW )\n GLfloat LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f };\t\t\t\t \/\/ Diffuse Light Values ( NEW )\n GLfloat LightPosition[]= { 0.0f, 0.0f, 2.0f, 1.0f };\t\t\t\t \/\/ Light Position ( NEW )\n glShadeModel(GL_SMOOTH);\t\t\t\t\t\t\/\/ Enable Smooth Shading\n glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);\t\t\t\t\/\/ Setup The Ambient Light\n glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);\t\t\t\t\/\/ Setup The Diffuse Light\n glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);\t\t\t\/\/ Position The Light\n glEnable(GL_LIGHT1);\t\t\t\t\t\t\t\/\/ Enable Light One\n glEnable(GL_LIGHTING);\n}\n\nvoid drawCube() {\n glBegin(GL_QUADS);\n\n\t\t\/\/ Front Face\n\t\tglNormal3f( 0.0f, 0.0f, 1.0f);\t\t\t\t\t\/\/ Normal Pointing Towards Viewer\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);\t\/\/ Point 1 (Front)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);\t\/\/ Point 2 (Front)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Front)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);\t\/\/ Point 4 (Front)\n\t\t\/\/ Back Face\n\t\tglNormal3f( 0.0f, 0.0f,-1.0f);\t\t\t\t\t\/\/ Normal Pointing Away From Viewer\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Back)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);\t\/\/ Point 2 (Back)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);\t\/\/ Point 3 (Back)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);\t\/\/ Point 4 (Back)\n\t\t\/\/ Top Face\n\t\tglNormal3f( 0.0f, 1.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Up\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);\t\/\/ Point 1 (Top)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);\t\/\/ Point 2 (Top)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Top)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);\t\/\/ Point 4 (Top)\n\t\t\/\/ Bottom Face\n\t\tglNormal3f( 0.0f,-1.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Down\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Bottom)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);\t\/\/ Point 2 (Bottom)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);\t\/\/ Point 3 (Bottom)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);\t\/\/ Point 4 (Bottom)\n\t\t\/\/ Right face\n\t\tglNormal3f( 1.0f, 0.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Right\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Right)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);\t\/\/ Point 2 (Right)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Right)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);\t\/\/ Point 4 (Right)\n\t\t\/\/ Left Face\n\t\tglNormal3f(-1.0f, 0.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Left\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Left)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);\t\/\/ Point 2 (Left)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Left)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);\t\/\/ Point 4 (Left)\n\tglEnd();\t\t\t\t\t\t\t\t\/\/ Done Drawing Quads\n}\n\nvoid Renderer::render(float Left, float Top, float Up) {\n\n \/\/ Clear color and depth buffer\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_MODELVIEW);\n \n \/\/ Apply some transformations\n glLoadIdentity();\n\t glTranslatef(-Left, -Up, -Top);\t\t\t\t\/\/ Translate The Scene Based On Player Position\n glTranslatef(0.f, 0.f, -5.f);\n \n drawCube();\n \n \/\/ Apply some transformations\n glLoadIdentity();\n\t glTranslatef(-Left, -Up, -Top);\t\t\t\t\/\/ Translate The Scene Based On Player Position\n glTranslatef(2.f, 0.f, -5.f);\n \n drawCube();\n}\nRender four test cubes#include \"renderer.h\"\n\nRenderer::Renderer() {\n \/\/ Set color and depth clear value\n glClearDepth(1.f);\n glClearColor(0.f, 0.f, 0.f, 0.f);\n\n \/\/ Enable Z-buffer read and write\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_TRUE);\n\n \/\/ Setup a perspective projection\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(90.f, 1.f, 1.f, 500.f);\n \n \/\/ Lighting test junk\n GLfloat LightAmbient[]= { 0.5f, 0.5f, 0.5f, 1.0f }; \t\t\t\t\/\/ Ambient Light Values ( NEW )\n GLfloat LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f };\t\t\t\t \/\/ Diffuse Light Values ( NEW )\n GLfloat LightPosition[]= { 0.0f, 0.0f, 2.0f, 1.0f };\t\t\t\t \/\/ Light Position ( NEW )\n glShadeModel(GL_SMOOTH);\t\t\t\t\t\t\/\/ Enable Smooth Shading\n glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);\t\t\t\t\/\/ Setup The Ambient Light\n glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);\t\t\t\t\/\/ Setup The Diffuse Light\n glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);\t\t\t\/\/ Position The Light\n glEnable(GL_LIGHT1);\t\t\t\t\t\t\t\/\/ Enable Light One\n glEnable(GL_LIGHTING);\n}\n\nvoid drawCube(float x, float y, float z, float length) {\n\n \/\/ Apply some transformations\n\t glPushMatrix();\n glTranslatef(x, y, z);\n glScalef(length, length, length);\n\n glBegin(GL_QUADS);\n\n\t\t\/\/ Front Face\n\t\tglNormal3f( 0.0f, 0.0f, 1.0f);\t\t\t\t\t\/\/ Normal Pointing Towards Viewer\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);\t\/\/ Point 1 (Front)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);\t\/\/ Point 2 (Front)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Front)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);\t\/\/ Point 4 (Front)\n\t\t\/\/ Back Face\n\t\tglNormal3f( 0.0f, 0.0f,-1.0f);\t\t\t\t\t\/\/ Normal Pointing Away From Viewer\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Back)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);\t\/\/ Point 2 (Back)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);\t\/\/ Point 3 (Back)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);\t\/\/ Point 4 (Back)\n\t\t\/\/ Top Face\n\t\tglNormal3f( 0.0f, 1.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Up\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);\t\/\/ Point 1 (Top)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);\t\/\/ Point 2 (Top)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Top)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);\t\/\/ Point 4 (Top)\n\t\t\/\/ Bottom Face\n\t\tglNormal3f( 0.0f,-1.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Down\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Bottom)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);\t\/\/ Point 2 (Bottom)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);\t\/\/ Point 3 (Bottom)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);\t\/\/ Point 4 (Bottom)\n\t\t\/\/ Right face\n\t\tglNormal3f( 1.0f, 0.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Right\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Right)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);\t\/\/ Point 2 (Right)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Right)\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);\t\/\/ Point 4 (Right)\n\t\t\/\/ Left Face\n\t\tglNormal3f(-1.0f, 0.0f, 0.0f);\t\t\t\t\t\/\/ Normal Pointing Left\n\t\tglTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);\t\/\/ Point 1 (Left)\n\t\tglTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);\t\/\/ Point 2 (Left)\n\t\tglTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);\t\/\/ Point 3 (Left)\n\t\tglTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);\t\/\/ Point 4 (Left)\n\tglEnd();\t\t\t\t\t\t\t\t\/\/ Done Drawing Quads\n\t\n\t glPopMatrix();\n}\n\nvoid Renderer::render(float Left, float Top, float Up) {\n\n \/\/ Clear color and depth buffer\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_MODELVIEW);\n \n \/\/ Apply some transformations\n glLoadIdentity();\n\t glTranslatef(-Left, -Up, -Top);\t\t\t\t\/\/ Translate The Scene Based On Player Position\n\t \n drawCube(0.f, 0.f, -5.f, 1.f);\n drawCube(3.f, 0.f, -5.f, 1.f);\n drawCube(-2.f, 1.f, -4.f, 0.5f);\n drawCube(10.f, -10.f, -10.f, 5.f);\n}\n<|endoftext|>"} {"text":"\/\/ $Id: TGHtmlImage.cxx,v 1.2 2007\/05\/07 15:28:48 brun Exp $\n\/\/ Author: Valeriy Onuchin 03\/05\/2007\n\n\/*************************************************************************\n * Copyright (C) 1995-2001, Rene Brun, Fons Rademakers and Reiner Rohlfs *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/**************************************************************************\n\n HTML widget for xclass. Based on tkhtml 1.28\n Copyright (C) 1997-2000 D. Richard Hipp \n Copyright (C) 2002-2003 Hector Peraza.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n**************************************************************************\/\n\n\/\/ Routines used for processing markup\n\n#include \n#include \n\n#include \"TGHtml.h\"\n\/\/#include \n#include \"TImage.h\"\n#include \"TUrl.h\"\n#include \"TSocket.h\"\n#include \"TSystem.h\"\n\n\/\/______________________________________________________________________________\nTGHtmlImage::TGHtmlImage(TGHtml *htm, const char *url, const char *width,\n const char *height)\n{\n \/\/ ctor.\n\n fHtml = htm;\n fZUrl = StrDup(url);\n fZWidth = StrDup(width);\n fZHeight = StrDup(height);\n fImage = NULL;\n fPNext = NULL;\n fPList = NULL;\n fW = 0;\n fH = 0;\n fTimer = NULL;\n}\n\n\/\/______________________________________________________________________________\nTGHtmlImage::~TGHtmlImage()\n{\n \/\/ dtor.\n\n delete [] fZUrl;\n delete [] fZWidth;\n delete [] fZHeight;\n\n if (fImage) delete fImage;\n if (fTimer) delete fTimer;\n}\n\n\/\/______________________________________________________________________________\nint TGHtml::GetImageAlignment(TGHtmlElement *p)\n{\n \/\/ Find the alignment for an image\n\n const char *z;\n int i;\n int result;\n\n static struct {\n const char *zName;\n int iValue;\n } aligns[] = {\n { \"bottom\", IMAGE_ALIGN_Bottom },\n { \"baseline\", IMAGE_ALIGN_Bottom },\n { \"middle\", IMAGE_ALIGN_Middle },\n { \"top\", IMAGE_ALIGN_Top },\n { \"absbottom\", IMAGE_ALIGN_AbsBottom },\n { \"absmiddle\", IMAGE_ALIGN_AbsMiddle },\n { \"texttop\", IMAGE_ALIGN_TextTop },\n { \"left\", IMAGE_ALIGN_Left },\n { \"right\", IMAGE_ALIGN_Right },\n };\n\n z = p->MarkupArg(\"align\", 0);\n result = IMAGE_ALIGN_Bottom;\n if (z) {\n for (i = 0; i < int(sizeof(aligns) \/ sizeof(aligns[0])); i++) {\n if (strcasecmp(aligns[i].zName, z) == 0) {\n result = aligns[i].iValue;\n break;\n }\n }\n }\n return result;\n}\n\n\/\/______________________________________________________________________________\nvoid TGHtml::ImageChanged(TGHtmlImage *pImage, int newWidth, int newHeight)\n{\n \/\/ This routine is called when an image changes. If the size of the\n \/\/ images changes, then we need to completely redo the layout. If\n \/\/ only the appearance changes, then this works like an expose event.\n \/\/\n \/\/ pImage - Pointer to an TGHtmlImage object\n \/\/ newWidth - New width of the image\n \/\/ newHeight - New height of the image\n\n TGHtmlImageMarkup *pElem;\n\n if (pImage->fW != newWidth || pImage->fH != newHeight) {\n \/\/ We have to completely redo the layout after adjusting the size\n \/\/ of the images\n for (pElem = pImage->fPList; pElem; pElem = pElem->fINext) {\n pElem->fW = newWidth;\n pElem->fH = newHeight;\n }\n fFlags |= RELAYOUT;\n pImage->fW = newWidth;\n pImage->fH = newHeight;\n RedrawEverything();\n } else {\n#if 0\n for (pElem = pImage->fPList; pElem; pElem = pElem->fINext) {\n pElem->fRedrawNeeded = 1;\n }\n fFlags |= REDRAW_IMAGES;\n ScheduleRedraw();\n#else\n for (pElem = pImage->fPList; pElem; pElem = pElem->fINext) {\n pElem->fRedrawNeeded = 1;\n DrawRegion(pElem->fX, pElem->fY - pElem->fAscent, pElem->fW, pElem->fH);\n }\n#endif\n }\n}\n\n\/\/______________________________________________________________________________\nTGHtmlImage *TGHtml::GetImage(TGHtmlImageMarkup *p)\n{\n \/\/ Given an markup, find or create an appropriate TGHtmlImage\n \/\/ object and return a pointer to that object. NULL might be returned.\n\n const char *zWidth;\n const char *zHeight;\n const char *zSrc;\n TGHtmlImage *pImage;\n\n if (p->fType != Html_IMG) { CANT_HAPPEN; return 0; }\n\n zSrc = p->MarkupArg(\"src\", 0);\n if (zSrc == 0) return 0;\n\n zSrc = ResolveUri(zSrc);\n if (zSrc == 0) return 0;\n\n zWidth = p->MarkupArg(\"width\", \"\");\n zHeight = p->MarkupArg(\"height\", \"\");\n\n \/\/p->w = atoi(fZWidth);\n \/\/p->h = atoi(zHeight);\n\n for (pImage = fImageList; pImage; pImage = pImage->fPNext) {\n if (strcmp(pImage->fZUrl, zSrc) == 0\n && strcmp(pImage->fZWidth, zWidth) == 0\n && strcmp(pImage->fZHeight, zHeight) == 0) {\n delete [] zSrc;\n return pImage;\n }\n }\n\n TImage *img = LoadImage(zSrc, atoi(zWidth), atoi(zHeight));\n\n if (img) {\n pImage = new TGHtmlImage(this, zSrc, zWidth, zHeight);\n pImage->fImage = img;\n \/\/if (img->IsAnimated()) {\n \/\/ pImage->timer = new TTimer(this, img->GetAnimDelay());\n \/\/}\n ImageChanged(pImage, img->GetWidth(), img->GetHeight());\n pImage->fPNext = fImageList;\n fImageList = pImage;\n } else {\n pImage = 0;\n }\n\n delete [] zSrc;\n\n return pImage;\n}\n\n\/\/______________________________________________________________________________\nstatic TImage *ReadRemoteImage(const char *url)\n{\n \/\/ Temporary function to read remote pictures\n\n TImage *image = 0;\n FILE *tmp;\n char *buf;\n TUrl fUrl(url);\n\n TString msg = \"GET \";\n msg += fUrl.GetProtocol();\n msg += \":\/\/\";\n msg += fUrl.GetHost();\n msg += \":\";\n msg += fUrl.GetPort();\n msg += \"\/\";\n msg += fUrl.GetFile();\n msg += \"\\r\\n\";\n\n TString uri(url);\n if (!uri.BeginsWith(\"http:\/\/\") || uri.EndsWith(\".html\"))\n return 0;\n TSocket s(fUrl.GetHost(), fUrl.GetPort());\n if (!s.IsValid())\n return 0;\n if (s.SendRaw(msg.Data(), msg.Length()) == -1)\n return 0;\n Int_t size = 1024*1024;\n buf = (char *)calloc(size, sizeof(char));\n if (!buf) return 0;\n if (s.RecvRaw(buf, size) == -1) {\n free(buf);\n return 0;\n }\n TString pathtmp = TString::Format(\"%s\/%s\", gSystem->TempDirectory(), \n gSystem->BaseName(url));\n tmp = fopen(pathtmp.Data(), \"wb\");\n if (!tmp) {\n free(buf);\n return 0;\n }\n fwrite(buf, sizeof(char), size, tmp);\n fclose(tmp);\n free(buf);\n image = TImage::Open(pathtmp.Data());\n if (image && !image->IsValid()) {\n delete image;\n image = 0;\n }\n gSystem->Unlink(pathtmp.Data());\n return image;\n}\n\n\/\/______________________________________________________________________________\nTImage *TGHtml::LoadImage(const char *url, int w, int h)\n{\n \/\/ This is the default LoadImage() procedure. It just tries to load the\n \/\/ image from a file in the local filesystem.\n\n TImage *image = 0;\n\n \/\/TGHtmlUri uri(url);\n\n TString uri(url);\n if (uri.BeginsWith(\"http:\/\/\") && !uri.EndsWith(\".html\"))\n image = ReadRemoteImage(url);\n else\n image = TImage::Open(url);\n if (image) {\n if (!image->IsValid()) {\n delete image;\n image = 0;\n return 0;\n }\n if ((w > 0 && h > 0) && ((w != (int)image->GetWidth()) ||\n (h != (int)image->GetHeight()))) {\n image->Scale(w, h);\n }\n }\n return image;\n}\n\n\/\/______________________________________________________________________________\nconst char *TGHtml::GetPctWidth(TGHtmlElement *p, char *opt, char *ret)\n{\n \/\/ Return the height and width, converting to percent if required\n \/\/ ret must be at least 16 characters long\n\n int n, m, val;\n const char *tz, *z;\n TGHtmlElement *pElem = p;\n\n z = pElem->MarkupArg(opt, \"\");\n if (!strchr(z, '%')) return z;\n \/\/ coverity[secure_coding]\n if (!sscanf(z, \"%d\", &n)) return z;\n if (n < 0 || n > 100) return z;\n if (opt[0] == 'h') {\n val = fCanvas->GetHeight() * 100;\n } else {\n val = fCanvas->GetWidth() * 100;\n }\n if (!fInTd) {\n snprintf(ret, 15, \"%d\", val \/ n);\n } else {\n while (pElem && pElem->fType != Html_TD) pElem = pElem->fPPrev;\n if (!pElem) return z;\n tz = pElem->MarkupArg(opt, 0);\n \/\/ coverity[secure_coding]\n if (tz && !strchr(tz, '%') && sscanf(tz, \"%d\", &m)) {\n snprintf(ret, 15, \"%d\", m * 100 \/ n);\n return ret;\n }\n pElem = ((TGHtmlCell *)pElem)->fPTable;\n if (!pElem) return z;\n tz = pElem->MarkupArg(opt, 0);\n \/\/ coverity[secure_coding]\n if (tz && !strchr(tz, '%') && sscanf(tz, \"%d\", &m)) {\n snprintf(ret, 15, \"%d\", m * 100 \/ n);\n return ret;\n }\n return z;\n }\n return ret;\n}\n\n\/\/______________________________________________________________________________\nint TGHtml::GetImageAt(int x, int y)\n{\n \/\/ This routine searchs for an image beneath the coordinates x,y\n \/\/ and returns the token number of the the image, or -1 if no\n \/\/ image found.\n\n TGHtmlBlock *pBlock;\n TGHtmlElement *pElem;\n \/\/int n;\n\n for (pBlock = fFirstBlock; pBlock; pBlock = pBlock->fBNext) {\n if (pBlock->fTop > y || pBlock->fBottom < y ||\n pBlock->fLeft > x || pBlock->fRight < x) {\n continue;\n }\n for (pElem = pBlock->fPNext; pElem; pElem = pElem->fPNext) {\n if (pBlock->fBNext && pElem == pBlock->fBNext->fPNext) break;\n if (pElem->fType == Html_IMG) {\n return TokenNumber(pElem);\n }\n }\n }\n\n return -1;\n}\nFix coverity #36020 Dereference null return\/\/ $Id: TGHtmlImage.cxx,v 1.2 2007\/05\/07 15:28:48 brun Exp $\n\/\/ Author: Valeriy Onuchin 03\/05\/2007\n\n\/*************************************************************************\n * Copyright (C) 1995-2001, Rene Brun, Fons Rademakers and Reiner Rohlfs *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/**************************************************************************\n\n HTML widget for xclass. Based on tkhtml 1.28\n Copyright (C) 1997-2000 D. Richard Hipp \n Copyright (C) 2002-2003 Hector Peraza.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n**************************************************************************\/\n\n\/\/ Routines used for processing markup\n\n#include \n#include \n\n#include \"TGHtml.h\"\n\/\/#include \n#include \"TImage.h\"\n#include \"TUrl.h\"\n#include \"TSocket.h\"\n#include \"TSystem.h\"\n\n\/\/______________________________________________________________________________\nTGHtmlImage::TGHtmlImage(TGHtml *htm, const char *url, const char *width,\n const char *height)\n{\n \/\/ ctor.\n\n fHtml = htm;\n fZUrl = StrDup(url);\n fZWidth = StrDup(width);\n fZHeight = StrDup(height);\n fImage = NULL;\n fPNext = NULL;\n fPList = NULL;\n fW = 0;\n fH = 0;\n fTimer = NULL;\n}\n\n\/\/______________________________________________________________________________\nTGHtmlImage::~TGHtmlImage()\n{\n \/\/ dtor.\n\n delete [] fZUrl;\n delete [] fZWidth;\n delete [] fZHeight;\n\n if (fImage) delete fImage;\n if (fTimer) delete fTimer;\n}\n\n\/\/______________________________________________________________________________\nint TGHtml::GetImageAlignment(TGHtmlElement *p)\n{\n \/\/ Find the alignment for an image\n\n const char *z;\n int i;\n int result;\n\n static struct {\n const char *zName;\n int iValue;\n } aligns[] = {\n { \"bottom\", IMAGE_ALIGN_Bottom },\n { \"baseline\", IMAGE_ALIGN_Bottom },\n { \"middle\", IMAGE_ALIGN_Middle },\n { \"top\", IMAGE_ALIGN_Top },\n { \"absbottom\", IMAGE_ALIGN_AbsBottom },\n { \"absmiddle\", IMAGE_ALIGN_AbsMiddle },\n { \"texttop\", IMAGE_ALIGN_TextTop },\n { \"left\", IMAGE_ALIGN_Left },\n { \"right\", IMAGE_ALIGN_Right },\n };\n\n z = p->MarkupArg(\"align\", 0);\n result = IMAGE_ALIGN_Bottom;\n if (z) {\n for (i = 0; i < int(sizeof(aligns) \/ sizeof(aligns[0])); i++) {\n if (strcasecmp(aligns[i].zName, z) == 0) {\n result = aligns[i].iValue;\n break;\n }\n }\n }\n return result;\n}\n\n\/\/______________________________________________________________________________\nvoid TGHtml::ImageChanged(TGHtmlImage *pImage, int newWidth, int newHeight)\n{\n \/\/ This routine is called when an image changes. If the size of the\n \/\/ images changes, then we need to completely redo the layout. If\n \/\/ only the appearance changes, then this works like an expose event.\n \/\/\n \/\/ pImage - Pointer to an TGHtmlImage object\n \/\/ newWidth - New width of the image\n \/\/ newHeight - New height of the image\n\n TGHtmlImageMarkup *pElem;\n\n if (pImage->fW != newWidth || pImage->fH != newHeight) {\n \/\/ We have to completely redo the layout after adjusting the size\n \/\/ of the images\n for (pElem = pImage->fPList; pElem; pElem = pElem->fINext) {\n pElem->fW = newWidth;\n pElem->fH = newHeight;\n }\n fFlags |= RELAYOUT;\n pImage->fW = newWidth;\n pImage->fH = newHeight;\n RedrawEverything();\n } else {\n#if 0\n for (pElem = pImage->fPList; pElem; pElem = pElem->fINext) {\n pElem->fRedrawNeeded = 1;\n }\n fFlags |= REDRAW_IMAGES;\n ScheduleRedraw();\n#else\n for (pElem = pImage->fPList; pElem; pElem = pElem->fINext) {\n pElem->fRedrawNeeded = 1;\n DrawRegion(pElem->fX, pElem->fY - pElem->fAscent, pElem->fW, pElem->fH);\n }\n#endif\n }\n}\n\n\/\/______________________________________________________________________________\nTGHtmlImage *TGHtml::GetImage(TGHtmlImageMarkup *p)\n{\n \/\/ Given an markup, find or create an appropriate TGHtmlImage\n \/\/ object and return a pointer to that object. NULL might be returned.\n\n const char *zWidth;\n const char *zHeight;\n const char *zSrc;\n TGHtmlImage *pImage;\n\n if (p->fType != Html_IMG) { CANT_HAPPEN; return 0; }\n\n zSrc = p->MarkupArg(\"src\", 0);\n if (zSrc == 0) return 0;\n\n zSrc = ResolveUri(zSrc);\n if (zSrc == 0) return 0;\n\n zWidth = p->MarkupArg(\"width\", \"\");\n zHeight = p->MarkupArg(\"height\", \"\");\n\n \/\/p->w = atoi(fZWidth);\n \/\/p->h = atoi(zHeight);\n\n for (pImage = fImageList; pImage; pImage = pImage->fPNext) {\n if (strcmp(pImage->fZUrl, zSrc) == 0\n && strcmp(pImage->fZWidth, zWidth) == 0\n && strcmp(pImage->fZHeight, zHeight) == 0) {\n delete [] zSrc;\n return pImage;\n }\n }\n\n TImage *img = LoadImage(zSrc, atoi(zWidth), atoi(zHeight));\n\n if (img) {\n pImage = new TGHtmlImage(this, zSrc, zWidth, zHeight);\n pImage->fImage = img;\n \/\/if (img->IsAnimated()) {\n \/\/ pImage->timer = new TTimer(this, img->GetAnimDelay());\n \/\/}\n ImageChanged(pImage, img->GetWidth(), img->GetHeight());\n pImage->fPNext = fImageList;\n fImageList = pImage;\n } else {\n pImage = 0;\n }\n\n delete [] zSrc;\n\n return pImage;\n}\n\n\/\/______________________________________________________________________________\nstatic TImage *ReadRemoteImage(const char *url)\n{\n \/\/ Temporary function to read remote pictures\n\n TImage *image = 0;\n FILE *tmp;\n char *buf;\n TUrl fUrl(url);\n\n TString msg = \"GET \";\n msg += fUrl.GetProtocol();\n msg += \":\/\/\";\n msg += fUrl.GetHost();\n msg += \":\";\n msg += fUrl.GetPort();\n msg += \"\/\";\n msg += fUrl.GetFile();\n msg += \"\\r\\n\";\n\n TString uri(url);\n if (!uri.BeginsWith(\"http:\/\/\") || uri.EndsWith(\".html\"))\n return 0;\n TSocket s(fUrl.GetHost(), fUrl.GetPort());\n if (!s.IsValid())\n return 0;\n if (s.SendRaw(msg.Data(), msg.Length()) == -1)\n return 0;\n Int_t size = 1024*1024;\n buf = (char *)calloc(size, sizeof(char));\n if (!buf) return 0;\n if (s.RecvRaw(buf, size) == -1) {\n free(buf);\n return 0;\n }\n TString pathtmp = TString::Format(\"%s\/%s\", gSystem->TempDirectory(), \n gSystem->BaseName(url));\n tmp = fopen(pathtmp.Data(), \"wb\");\n if (!tmp) {\n free(buf);\n return 0;\n }\n fwrite(buf, sizeof(char), size, tmp);\n fclose(tmp);\n free(buf);\n image = TImage::Open(pathtmp.Data());\n if (image && !image->IsValid()) {\n delete image;\n image = 0;\n }\n gSystem->Unlink(pathtmp.Data());\n return image;\n}\n\n\/\/______________________________________________________________________________\nTImage *TGHtml::LoadImage(const char *url, int w, int h)\n{\n \/\/ This is the default LoadImage() procedure. It just tries to load the\n \/\/ image from a file in the local filesystem.\n\n TImage *image = 0;\n\n \/\/TGHtmlUri uri(url);\n\n TString uri(url);\n if (uri.BeginsWith(\"http:\/\/\") && !uri.EndsWith(\".html\"))\n image = ReadRemoteImage(url);\n else\n image = TImage::Open(url);\n if (image) {\n if (!image->IsValid()) {\n delete image;\n image = 0;\n return 0;\n }\n if ((w > 0 && h > 0) && ((w != (int)image->GetWidth()) ||\n (h != (int)image->GetHeight()))) {\n image->Scale(w, h);\n }\n }\n return image;\n}\n\n\/\/______________________________________________________________________________\nconst char *TGHtml::GetPctWidth(TGHtmlElement *p, char *opt, char *ret)\n{\n \/\/ Return the height and width, converting to percent if required\n \/\/ ret must be at least 16 characters long\n\n int n, m, val;\n const char *tz, *z;\n TGHtmlElement *pElem = p;\n\n z = pElem->MarkupArg(opt, \"\");\n if (!z) return z;\n if (!strchr(z, '%')) return z;\n \/\/ coverity[secure_coding]\n if (!sscanf(z, \"%d\", &n)) return z;\n if (n < 0 || n > 100) return z;\n if (opt[0] == 'h') {\n val = fCanvas->GetHeight() * 100;\n } else {\n val = fCanvas->GetWidth() * 100;\n }\n if (!fInTd) {\n snprintf(ret, 15, \"%d\", val \/ n);\n } else {\n while (pElem && pElem->fType != Html_TD) pElem = pElem->fPPrev;\n if (!pElem) return z;\n tz = pElem->MarkupArg(opt, 0);\n \/\/ coverity[secure_coding]\n if (tz && !strchr(tz, '%') && sscanf(tz, \"%d\", &m)) {\n snprintf(ret, 15, \"%d\", m * 100 \/ n);\n return ret;\n }\n pElem = ((TGHtmlCell *)pElem)->fPTable;\n if (!pElem) return z;\n tz = pElem->MarkupArg(opt, 0);\n \/\/ coverity[secure_coding]\n if (tz && !strchr(tz, '%') && sscanf(tz, \"%d\", &m)) {\n snprintf(ret, 15, \"%d\", m * 100 \/ n);\n return ret;\n }\n return z;\n }\n return ret;\n}\n\n\/\/______________________________________________________________________________\nint TGHtml::GetImageAt(int x, int y)\n{\n \/\/ This routine searchs for an image beneath the coordinates x,y\n \/\/ and returns the token number of the the image, or -1 if no\n \/\/ image found.\n\n TGHtmlBlock *pBlock;\n TGHtmlElement *pElem;\n \/\/int n;\n\n for (pBlock = fFirstBlock; pBlock; pBlock = pBlock->fBNext) {\n if (pBlock->fTop > y || pBlock->fBottom < y ||\n pBlock->fLeft > x || pBlock->fRight < x) {\n continue;\n }\n for (pElem = pBlock->fPNext; pElem; pElem = pElem->fPNext) {\n if (pBlock->fBNext && pElem == pBlock->fBNext->fPNext) break;\n if (pElem->fType == Html_IMG) {\n return TokenNumber(pElem);\n }\n }\n }\n\n return -1;\n}\n<|endoftext|>"} {"text":"#include \"selection.hh\"\n\n#include \"utf8.hh\"\n\nnamespace Kakoune\n{\n\nvoid Range::merge_with(const Range& range)\n{\n m_last = range.m_last;\n if (m_first < m_last)\n m_first = std::min(m_first, range.m_first);\n if (m_first > m_last)\n m_first = std::max(m_first, range.m_first);\n}\n\nnamespace\n{\n\ntemplate