text
stringlengths
54
60.6k
<commit_before>#include "Version.h" #include "SourceControl.h" #include "System/Config.h" #include "System/Events/EventLoop.h" #include "System/IO/IOProcessor.h" #include "System/Service.h" #include "System/FileSystem.h" #include "System/CrashReporter.h" #include "Framework/Storage/BloomFilter.h" #include "Application/Common/ContextTransport.h" #include "Application/ConfigServer/ConfigServerApp.h" #include "Application/ShardServer/ShardServerApp.h" #define IDENT "ScalienDB" const char PRODUCT_STRING[] = IDENT " v" VERSION_STRING " " PLATFORM_STRING; const char BUILD_DATE[] = "Build date: " __DATE__ " " __TIME__; static void InitLog(); static void ParseArgs(int argc, char** argv); static void SetupServiceIdentity(ServiceIdentity& ident); static void RunMain(int argc, char** argv); static void RunApplication(); static void ConfigureSystemSettings(); static bool IsController(); static void InitContextTransport(); static void LogPrintVersion(bool isController); static void CrashReporterCallback(); // the application object is global for debugging purposes static Application* app; static bool restoreMode = false; int main(int argc, char** argv) { try { // crash reporter messes up the debugging on Windows #ifndef DEBUG CrashReporter::SetCallback(CFunc(CrashReporterCallback)); #endif RunMain(argc, argv); } catch (std::bad_alloc& e) { UNUSED(e); STOP_FAIL(1, "Out of memory error"); } catch (std::exception& e) { STOP_FAIL(1, "Unexpected exception happened (%s)", e.what()); } catch (...) { STOP_FAIL(1, "Unexpected exception happened"); } return 0; } static void RunMain(int argc, char** argv) { ServiceIdentity identity; ParseArgs(argc, argv); if (argc < 2) STOP_FAIL(1, "Config file argument not given"); if (!configFile.Init(argv[1])) STOP_FAIL(1, "Invalid config file (%s)", argv[1]); InitLog(); // HACK: this is called twice, because command line arguments may override log settings ParseArgs(argc, argv); SetupServiceIdentity(identity); Service::Main(argc, argv, RunApplication, identity); } static void RunApplication() { bool isController; StartClock(); ConfigureSystemSettings(); IOProcessor::Init(configFile.GetIntValue("io.maxfd", 32768)); InitContextTransport(); BloomFilter::StaticInit(); isController = IsController(); LogPrintVersion(isController); if (isController) app = new ConfigServerApp; else app = new ShardServerApp(restoreMode); Service::SetStatus(SERVICE_STATUS_RUNNING); app->Init(); IOProcessor::BlockSignals(IOPROCESSOR_BLOCK_ALL); EventLoop::Init(); EventLoop::Run(); Service::SetStatus(SERVICE_STATUS_STOP_PENDING); Log_Message("Shutting down..."); EventLoop::Shutdown(); app->Shutdown(); delete app; IOProcessor::Shutdown(); StopClock(); configFile.Shutdown(); Log_Shutdown(); } static void SetupServiceIdentity(ServiceIdentity& identity) { // set up service identity based on role if (IsController()) { identity.name = "ScalienController"; identity.displayName = "Scalien Database Controller"; identity.description = "Provides and stores metadata for Scalien Database cluster"; } else { identity.name = "ScalienShardServer"; identity.displayName = "Scalien Database Shard Server"; identity.description = "Provides reliable and replicated data storage for Scalien Database cluster"; } } static void InitLog() { int logTargets; bool debug; #ifdef DEBUG debug = true; #else debug = false; #endif logTargets = 0; if (configFile.GetListNum("log.targets") == 0) logTargets = LOG_TARGET_STDOUT; for (int i = 0; i < configFile.GetListNum("log.targets"); i++) { if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0) { logTargets |= LOG_TARGET_FILE; Log_SetOutputFile(configFile.GetValue("log.file", NULL), configFile.GetBoolValue("log.truncate", false)); } if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0) logTargets |= LOG_TARGET_STDOUT; if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0) logTargets |= LOG_TARGET_STDERR; } Log_SetTarget(logTargets); Log_SetTrace(configFile.GetBoolValue("log.trace", false)); Log_SetDebug(configFile.GetBoolValue("log.debug", debug)); Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false)); Log_SetAutoFlush(configFile.GetBoolValue("log.autoFlush", true)); Log_SetMaxSize(configFile.GetIntValue("log.maxSize", 100*1000*1000) / (1000 * 1000)); Log_SetTraceBufferSize(configFile.GetIntValue("log.traceBufferSize", 0)); Log_SetFlushInterval(configFile.GetIntValue("log.flushInterval", 0) * 1000); } static void ParseArgs(int argc, char** argv) { for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 't': Log_SetTrace(true); break; case 'X': SetExitOnError(false); SetAssertCritical(false); break; case 'v': STOP("%s", PRODUCT_STRING); break; case 'r': restoreMode = true; break; case 'h': STOP("Usage:\n" "\n" " %s config-file [options]\n" "\n" "Options:\n" "\n" " -v: print version number and exit\n" " -r: start server in restore mode\n" " -t: turn trace mode on\n" " -h: print this help\n" , argv[0]); break; } } } } static void ConfigureSystemSettings() { int memLimitPerc; uint64_t memLimit; const char* dir; // percentage of physical memory can be used by the program memLimitPerc = configFile.GetIntValue("system.memoryLimitPercentage", 90); if (memLimitPerc < 0) memLimitPerc = 90; // memoryLimit overrides memoryLimitPercentage memLimit = configFile.GetInt64Value("system.memoryLimit", 0); if (memLimit == 0) memLimit = (uint64_t) (GetTotalPhysicalMemory() * memLimit / 100.0 + 0.5); if (memLimit != 0) SetMemoryLimit(memLimit); // set the base directory dir = configFile.GetValue("dir", NULL); if (dir) { if (!FS_ChangeDir(dir)) STOP_FAIL(1, "Cannot change to dir: %s", dir); // setting the base dir may affect the location of the log file InitLog(); } // set exit on error: this is how ASSERTs are handled in release build SetExitOnError(true); SeedRandom(); } static bool IsController() { const char* role; role = configFile.GetValue("role", ""); if (role == NULL) STOP_FAIL(1, "Missing \"role\" in config file!"); if (strcmp(role, "controller") == 0) return true; else return false; } static void InitContextTransport() { const char* str; Endpoint endpoint; // set my endpoint str = configFile.GetValue("endpoint", ""); if (str == NULL) STOP_FAIL(1, "Missing \"endpoint\" in config file!"); if (!endpoint.Set(str, true)) STOP_FAIL(1, "Bad endpoint format in config file!"); CONTEXT_TRANSPORT->Init(endpoint); } static void LogPrintVersion(bool isController) { Log_Message("%s started as %s", PRODUCT_STRING, isController ? "CONTROLLER" : "SHARD SERVER"); Log_Debug("Pid: %U", GetProcessID()); Log_Debug("%s", BUILD_DATE); Log_Debug("Branch: %s", SOURCE_CONTROL_BRANCH); Log_Debug("Source control version: %s", SOURCE_CONTROL_VERSION); Log_Debug("================================================================"); } static void CrashReporterCallback() { const char* msg; // We need to be careful here, because by the time the control gets here the stack and the heap // may already be corrupted. Therefore there must not be any heap allocations here, but unfortunately // stack allocations cannot be avoided. // When rotating the log there is heap allocation. To prevent it, we turn off log rotation ASAP. Log_SetMaxSize(0); CrashReporter::ReportSystemEvent(IDENT); // Generate report and send it to log and standard error msg = CrashReporter::GetReport(); Log_SetTarget(Log_GetTarget() | LOG_TARGET_STDERR | LOG_TARGET_FILE); Log_Message("%s", msg); IFDEBUG(ASSERT_FAIL()); _exit(1); } <commit_msg>Added better help for command line options.<commit_after>#include "Version.h" #include "SourceControl.h" #include "System/Config.h" #include "System/Events/EventLoop.h" #include "System/IO/IOProcessor.h" #include "System/Service.h" #include "System/FileSystem.h" #include "System/CrashReporter.h" #include "Framework/Storage/BloomFilter.h" #include "Application/Common/ContextTransport.h" #include "Application/ConfigServer/ConfigServerApp.h" #include "Application/ShardServer/ShardServerApp.h" #define IDENT "ScalienDB" const char PRODUCT_STRING[] = IDENT " v" VERSION_STRING " " PLATFORM_STRING; const char BUILD_DATE[] = "Build date: " __DATE__ " " __TIME__; static void InitLog(); static void ParseArgs(int argc, char** argv); static void SetupServiceIdentity(ServiceIdentity& ident); static void RunMain(int argc, char** argv); static void RunApplication(); static void ConfigureSystemSettings(); static bool IsController(); static void InitContextTransport(); static void LogPrintVersion(bool isController); static void CrashReporterCallback(); // the application object is global for debugging purposes static Application* app; static bool restoreMode = false; int main(int argc, char** argv) { try { // crash reporter messes up the debugging on Windows #ifndef DEBUG CrashReporter::SetCallback(CFunc(CrashReporterCallback)); #endif RunMain(argc, argv); } catch (std::bad_alloc& e) { UNUSED(e); STOP_FAIL(1, "Out of memory error"); } catch (std::exception& e) { STOP_FAIL(1, "Unexpected exception happened (%s)", e.what()); } catch (...) { STOP_FAIL(1, "Unexpected exception happened"); } return 0; } static void RunMain(int argc, char** argv) { ServiceIdentity identity; ParseArgs(argc, argv); if (argc < 2) STOP_FAIL(1, "Config file argument not given"); if (!configFile.Init(argv[1])) STOP_FAIL(1, "Invalid config file (%s)", argv[1]); InitLog(); // HACK: this is called twice, because command line arguments may override log settings ParseArgs(argc, argv); SetupServiceIdentity(identity); Service::Main(argc, argv, RunApplication, identity); } static void RunApplication() { bool isController; StartClock(); ConfigureSystemSettings(); IOProcessor::Init(configFile.GetIntValue("io.maxfd", 32768)); InitContextTransport(); BloomFilter::StaticInit(); isController = IsController(); LogPrintVersion(isController); if (isController) app = new ConfigServerApp; else app = new ShardServerApp(restoreMode); Service::SetStatus(SERVICE_STATUS_RUNNING); app->Init(); IOProcessor::BlockSignals(IOPROCESSOR_BLOCK_ALL); EventLoop::Init(); EventLoop::Run(); Service::SetStatus(SERVICE_STATUS_STOP_PENDING); Log_Message("Shutting down..."); EventLoop::Shutdown(); app->Shutdown(); delete app; IOProcessor::Shutdown(); StopClock(); configFile.Shutdown(); Log_Shutdown(); } static void SetupServiceIdentity(ServiceIdentity& identity) { // set up service identity based on role if (IsController()) { identity.name = "ScalienController"; identity.displayName = "Scalien Database Controller"; identity.description = "Provides and stores metadata for Scalien Database cluster"; } else { identity.name = "ScalienShardServer"; identity.displayName = "Scalien Database Shard Server"; identity.description = "Provides reliable and replicated data storage for Scalien Database cluster"; } } static void InitLog() { int logTargets; bool debug; #ifdef DEBUG debug = true; #else debug = false; #endif logTargets = 0; if (configFile.GetListNum("log.targets") == 0) logTargets = LOG_TARGET_STDOUT; for (int i = 0; i < configFile.GetListNum("log.targets"); i++) { if (strcmp(configFile.GetListValue("log.targets", i, ""), "file") == 0) { logTargets |= LOG_TARGET_FILE; Log_SetOutputFile(configFile.GetValue("log.file", NULL), configFile.GetBoolValue("log.truncate", false)); } if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stdout") == 0) logTargets |= LOG_TARGET_STDOUT; if (strcmp(configFile.GetListValue("log.targets", i, NULL), "stderr") == 0) logTargets |= LOG_TARGET_STDERR; } Log_SetTarget(logTargets); Log_SetTrace(configFile.GetBoolValue("log.trace", false)); Log_SetDebug(configFile.GetBoolValue("log.debug", debug)); Log_SetTimestamping(configFile.GetBoolValue("log.timestamping", false)); Log_SetAutoFlush(configFile.GetBoolValue("log.autoFlush", true)); Log_SetMaxSize(configFile.GetIntValue("log.maxSize", 100*1000*1000) / (1000 * 1000)); Log_SetTraceBufferSize(configFile.GetIntValue("log.traceBufferSize", 0)); Log_SetFlushInterval(configFile.GetIntValue("log.flushInterval", 0) * 1000); } static void ParseArgs(int argc, char** argv) { for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 't': Log_SetTrace(true); break; case 'X': SetExitOnError(false); SetAssertCritical(false); break; case 'v': STOP("%s", PRODUCT_STRING); break; case 'r': restoreMode = true; break; case 'h': STOP("Usage:\n" "\n" " %s config-file [options] [service-options]\n" "\n" "Options:\n" "\n" " -v: print version number and exit\n" " -r: start server in restore mode\n" " -t: turn trace mode on\n" " -h: print this help\n" "\n" "Service options (mutually exclusive):\n" "\n" " --install: install service\n" " --reinstall: reinstall service\n" " --uninstall: uninstall server\n" , argv[0]); break; } } } } static void ConfigureSystemSettings() { int memLimitPerc; uint64_t memLimit; const char* dir; // percentage of physical memory can be used by the program memLimitPerc = configFile.GetIntValue("system.memoryLimitPercentage", 90); if (memLimitPerc < 0) memLimitPerc = 90; // memoryLimit overrides memoryLimitPercentage memLimit = configFile.GetInt64Value("system.memoryLimit", 0); if (memLimit == 0) memLimit = (uint64_t) (GetTotalPhysicalMemory() * memLimit / 100.0 + 0.5); if (memLimit != 0) SetMemoryLimit(memLimit); // set the base directory dir = configFile.GetValue("dir", NULL); if (dir) { if (!FS_ChangeDir(dir)) STOP_FAIL(1, "Cannot change to dir: %s", dir); // setting the base dir may affect the location of the log file InitLog(); } // set exit on error: this is how ASSERTs are handled in release build SetExitOnError(true); SeedRandom(); } static bool IsController() { const char* role; role = configFile.GetValue("role", ""); if (role == NULL) STOP_FAIL(1, "Missing \"role\" in config file!"); if (strcmp(role, "controller") == 0) return true; else return false; } static void InitContextTransport() { const char* str; Endpoint endpoint; // set my endpoint str = configFile.GetValue("endpoint", ""); if (str == NULL) STOP_FAIL(1, "Missing \"endpoint\" in config file!"); if (!endpoint.Set(str, true)) STOP_FAIL(1, "Bad endpoint format in config file!"); CONTEXT_TRANSPORT->Init(endpoint); } static void LogPrintVersion(bool isController) { Log_Message("%s started as %s", PRODUCT_STRING, isController ? "CONTROLLER" : "SHARD SERVER"); Log_Debug("Pid: %U", GetProcessID()); Log_Debug("%s", BUILD_DATE); Log_Debug("Branch: %s", SOURCE_CONTROL_BRANCH); Log_Debug("Source control version: %s", SOURCE_CONTROL_VERSION); Log_Debug("================================================================"); } static void CrashReporterCallback() { const char* msg; // We need to be careful here, because by the time the control gets here the stack and the heap // may already be corrupted. Therefore there must not be any heap allocations here, but unfortunately // stack allocations cannot be avoided. // When rotating the log there is heap allocation. To prevent it, we turn off log rotation ASAP. Log_SetMaxSize(0); CrashReporter::ReportSystemEvent(IDENT); // Generate report and send it to log and standard error msg = CrashReporter::GetReport(); Log_SetTarget(Log_GetTarget() | LOG_TARGET_STDERR | LOG_TARGET_FILE); Log_Message("%s", msg); IFDEBUG(ASSERT_FAIL()); _exit(1); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh4_builder_instancing.h" #include "bvh4_statistics.h" #include "../builders/bvh_builder_sah.h" #include "../geometry/triangle4.h" namespace embree { namespace isa { BVH4BuilderInstancing::BVH4BuilderInstancing (BVH4* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel) : bvh(bvh), objects(bvh->objects), scene(scene), createTriangleMeshAccel(createTriangleMeshAccel), refs(scene->device), prims(scene->device), nextRef(0), numInstancedPrimitives(0) {} BVH4BuilderInstancing::~BVH4BuilderInstancing () { for (size_t i=0; i<builders.size(); i++) delete builders[i]; } void BVH4BuilderInstancing::build(size_t threadIndex, size_t threadCount) { /* delete some objects */ size_t N = scene->size(); if (N < objects.size()) { parallel_for(N, objects.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { delete builders[i]; builders[i] = nullptr; delete objects[i]; objects[i] = nullptr; } }); } /* reset memory allocator */ bvh->alloc.reset(); /* skip build for empty scene */ const size_t numPrimitives = scene->getNumPrimitives<TriangleMesh,1>(); if (numPrimitives == 0) { prims.resize(0); bvh->set(BVH4::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH4BuilderInstancing"); /* resize object array if scene got larger */ if (objects.size() < N) objects.resize(N); if (builders.size() < N) builders.resize(N); if (refs.size() < N) refs.resize(N); nextRef = 0; /* creation of acceleration structures */ parallel_for(size_t(0), N, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID); /* verify meshes got deleted properly */ if (mesh == nullptr || mesh->numTimeSteps != 1) { assert(objectID < objects.size () && objects[objectID] == nullptr); assert(objectID < builders.size() && builders[objectID] == nullptr); continue; } /* delete BVH and builder for meshes that are scheduled for deletion */ if (mesh->isErasing()) { delete builders[objectID]; builders[objectID] = nullptr; delete objects [objectID]; objects [objectID] = nullptr; continue; } /* create BVH and builder for new meshes */ if (objects[objectID] == nullptr) createTriangleMeshAccel(mesh,(AccelData*&)objects[objectID],builders[objectID]); } }); numInstancedPrimitives = 0; /* parallel build of acceleration structures */ parallel_for(size_t(0), N, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { /* ignore if no triangle mesh or not enabled */ TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID); if (mesh == nullptr || mesh->numTimeSteps != 1) continue; BVH4* object = objects [objectID]; assert(object); Builder* builder = builders[objectID]; assert(builder); /* build object if it got modified */ if (mesh->isModified() && mesh->isUsed()) builder->build(0,0); /* create build primitive */ if (!object->bounds.empty() && mesh->isEnabled()) { refs[nextRef++] = BVH4BuilderInstancing::BuildRef(one,object->bounds,object->root); numInstancedPrimitives += mesh->size(); } } }); /* creates all instances */ parallel_for(size_t(0), N, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { /* ignore if no triangle mesh or not enabled */ Geometry* geom = scene->get(objectID); if (geom->getType() != (Geometry::TRIANGLE_MESH | Geometry::INSTANCE)) continue; GeometryInstance* instance = (GeometryInstance*) geom; if (!instance->isEnabled() || instance->numTimeSteps != 1) continue; BVH4* object = objects [objectID]; assert(object); /* create build primitive */ if (!object->bounds.empty()) { refs[nextRef++] = BVH4BuilderInstancing::BuildRef(instance->local2world,object->bounds,object->root); numInstancedPrimitives += instance->geom->size(); } } }); /* fast path for single geometry scenes */ /*if (nextRef == 1) { bvh->set(refs[0].node,refs[0].bounds(),numPrimitives); return; }*/ /* open all large nodes */ refs.resize(nextRef); open(numPrimitives); /* fast path for small geometries */ /*if (refs.size() == 1) { bvh->set(refs[0].node,refs[0].bounds(),numPrimitives); return; }*/ /* compute PrimRefs */ prims.resize(refs.size()); const PrimInfo pinfo = parallel_reduce(size_t(0), refs.size(), size_t(1024), PrimInfo(empty), [&] (const range<size_t>& r) -> PrimInfo { PrimInfo pinfo(empty); for (size_t i=r.begin(); i<r.end(); i++) { const BBox3fa bounds = refs[i].worldBounds(); pinfo.add(bounds); prims[i] = PrimRef(bounds,(size_t)&refs[i]); } return pinfo; }, [] (const PrimInfo& a, const PrimInfo& b) { return PrimInfo::merge(a,b); }); /* skip if all objects where empty */ if (pinfo.size() == 0) bvh->set(BVH4::emptyNode,empty,0); /* otherwise build toplevel hierarchy */ else { BVH4::NodeRef root; BVHBuilderBinnedSAH::build<BVH4::NodeRef> (root, [&] { return bvh->alloc.threadLocal2(); }, [&] (const isa::BVHBuilderBinnedSAH::BuildRecord& current, BVHBuilderBinnedSAH::BuildRecord* children, const size_t N, FastAllocator::ThreadLocal2* alloc) -> int { BVH4::Node* node = (BVH4::Node*) alloc->alloc0.malloc(sizeof(BVH4::Node)); node->clear(); for (size_t i=0; i<N; i++) { node->set(i,children[i].pinfo.geomBounds); children[i].parent = (size_t*)&node->child(i); } *current.parent = bvh->encodeNode(node); return 0; }, [&] (const BVHBuilderBinnedSAH::BuildRecord& current, FastAllocator::ThreadLocal2* alloc) -> int { assert(current.prims.size() == 1); BuildRef* ref = (BuildRef*) prims[current.prims.begin()].ID(); BVH4::TransformNode* node = (BVH4::TransformNode*) alloc->alloc0.malloc(sizeof(BVH4::TransformNode)); new (node) BVH4::TransformNode(ref->local2world,ref->localBounds,ref->node); // FIXME: rcp should be precalculated somewhere *current.parent = BVH4::encodeNode(node); //*current.parent = ref->node; ((BVH4::NodeRef*)current.parent)->setBarrier(); return 1; }, [&] (size_t dn) { bvh->scene->progressMonitor(0); }, prims.data(),pinfo,BVH4::N,BVH4::maxBuildDepthLeaf,4,1,1,1.0f,1.0f); bvh->set(root,pinfo.geomBounds,numPrimitives); } bvh->root = collapse(bvh->root); bvh->alloc.cleanup(); bvh->postBuild(t0); } void BVH4BuilderInstancing::clear() { for (size_t i=0; i<objects.size(); i++) if (objects[i]) objects[i]->clear(); for (size_t i=0; i<builders.size(); i++) if (builders[i]) builders[i]->clear(); refs.clear(); } void set_primID(BVH4::NodeRef node, unsigned primID) { if (node.isLeaf()) { size_t num; Triangle4* prims = (Triangle4*) node.leaf(num); for (size_t i=0; i<num; i++) for (size_t j=0; j<4; j++) if (prims[i].geomIDs[j] != -1) prims[i].primIDs[j] = primID; } else { BVH4::Node* n = node.node(); for (size_t c=0; c<BVH4::N; c++) set_primID(n->child(c),primID); } } void BVH4BuilderInstancing::open(size_t numPrimitives) { if (refs.size() == 0) return; //size_t N = 0; //size_t N = numInstancedPrimitives/2000; size_t N = numInstancedPrimitives/200; //size_t N = numInstancedPrimitives; refs.reserve(N); std::make_heap(refs.begin(),refs.end()); while (refs.size()+3 <= N) { std::pop_heap (refs.begin(),refs.end()); BVH4::NodeRef ref = refs.back().node; const AffineSpace3fa local2world = refs.back().local2world; if (ref.isLeaf()) break; refs.pop_back(); BVH4::Node* node = ref.node(); for (size_t i=0; i<BVH4::N; i++) { if (node->child(i) == BVH4::emptyNode) continue; refs.push_back(BuildRef(local2world,node->bounds(i),node->child(i))); std::push_heap (refs.begin(),refs.end()); } } //for (size_t i=0; i<refs.size(); i++) // set_primID((BVH4::NodeRef) refs[i].node, i); } BVH4::NodeRef BVH4BuilderInstancing::collapse(BVH4::NodeRef& node) { if (node.isBarrier()) { node.clearBarrier(); return node; } assert(node.isNode()); BVH4::Node* n = node.node(); BVH4::TransformNode* first = nullptr; for (size_t c=0; c<BVH4::N; c++) { if (n->child(c) == BVH4::emptyNode) continue; BVH4::NodeRef child = n->child(c) = collapse(n->child(c)); if (child.isTransformNode()) first = child.transformNode(); } bool allEqual = true; for (size_t c=0; c<BVH4::N; c++) { BVH4::NodeRef child = n->child(c); if (child == BVH4::emptyNode) continue; if (!child.isTransformNode()) { allEqual = false; break; } if (child.transformNode()->world2local != first->world2local) { allEqual = false; break; } } if (!allEqual) return node; BBox3fa bounds = empty; for (size_t c=0; c<BVH4::N; c++) { if (n->child(c) == BVH4::emptyNode) continue; BVH4::TransformNode* child = n->child(c).transformNode(); const BBox3fa cbounds = child->localBounds; n->set(c,cbounds,child->child); bounds.extend(cbounds); } first->localBounds = bounds; first->child = node; return BVH4::encodeNode(first); } Builder* BVH4BuilderInstancingSAH (void* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel) { return new BVH4BuilderInstancing((BVH4*)bvh,scene,createTriangleMeshAccel); } } } <commit_msg>bugfix in bvh4_builder_instancing<commit_after>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh4_builder_instancing.h" #include "bvh4_statistics.h" #include "../builders/bvh_builder_sah.h" #include "../geometry/triangle4.h" namespace embree { namespace isa { BVH4BuilderInstancing::BVH4BuilderInstancing (BVH4* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel) : bvh(bvh), objects(bvh->objects), scene(scene), createTriangleMeshAccel(createTriangleMeshAccel), refs(scene->device), prims(scene->device), nextRef(0), numInstancedPrimitives(0) {} BVH4BuilderInstancing::~BVH4BuilderInstancing () { for (size_t i=0; i<builders.size(); i++) delete builders[i]; } void BVH4BuilderInstancing::build(size_t threadIndex, size_t threadCount) { /* delete some objects */ size_t N = scene->size(); if (N < objects.size()) { parallel_for(N, objects.size(), [&] (const range<size_t>& r) { for (size_t i=r.begin(); i<r.end(); i++) { delete builders[i]; builders[i] = nullptr; delete objects[i]; objects[i] = nullptr; } }); } /* reset memory allocator */ bvh->alloc.reset(); /* skip build for empty scene */ const size_t numPrimitives = scene->getNumPrimitives<TriangleMesh,1>(); if (numPrimitives == 0) { prims.resize(0); bvh->set(BVH4::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH4BuilderInstancing"); /* resize object array if scene got larger */ if (objects.size() < N) objects.resize(N); if (builders.size() < N) builders.resize(N); if (refs.size() < N) refs.resize(N); nextRef = 0; /* creation of acceleration structures */ parallel_for(size_t(0), N, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID); /* verify meshes got deleted properly */ if (mesh == nullptr || mesh->numTimeSteps != 1) { assert(objectID < objects.size () && objects[objectID] == nullptr); assert(objectID < builders.size() && builders[objectID] == nullptr); continue; } /* delete BVH and builder for meshes that are scheduled for deletion */ if (mesh->isErasing()) { delete builders[objectID]; builders[objectID] = nullptr; delete objects [objectID]; objects [objectID] = nullptr; continue; } /* create BVH and builder for new meshes */ if (objects[objectID] == nullptr) createTriangleMeshAccel(mesh,(AccelData*&)objects[objectID],builders[objectID]); } }); numInstancedPrimitives = 0; /* parallel build of acceleration structures */ parallel_for(size_t(0), N, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { /* ignore if no triangle mesh or not enabled */ TriangleMesh* mesh = scene->getTriangleMeshSafe(objectID); if (mesh == nullptr || mesh->numTimeSteps != 1) continue; BVH4* object = objects [objectID]; assert(object); Builder* builder = builders[objectID]; assert(builder); /* build object if it got modified */ if (mesh->isModified() && mesh->isUsed()) builder->build(0,0); /* create build primitive */ if (!object->bounds.empty() && mesh->isEnabled()) { refs[nextRef++] = BVH4BuilderInstancing::BuildRef(one,object->bounds,object->root); numInstancedPrimitives += mesh->size(); } } }); /* creates all instances */ parallel_for(size_t(0), N, [&] (const range<size_t>& r) { for (size_t objectID=r.begin(); objectID<r.end(); objectID++) { /* ignore if no triangle mesh or not enabled */ Geometry* geom = scene->get(objectID); if (geom->getType() != (Geometry::TRIANGLE_MESH | Geometry::INSTANCE)) continue; GeometryInstance* instance = (GeometryInstance*) geom; if (!instance->isEnabled() || instance->numTimeSteps != 1) continue; BVH4* object = objects [instance->geom->id]; assert(object); /* create build primitive */ if (!object->bounds.empty()) { refs[nextRef++] = BVH4BuilderInstancing::BuildRef(instance->local2world,object->bounds,object->root); numInstancedPrimitives += instance->geom->size(); } } }); /* fast path for single geometry scenes */ /*if (nextRef == 1) { bvh->set(refs[0].node,refs[0].bounds(),numPrimitives); return; }*/ /* open all large nodes */ refs.resize(nextRef); open(numPrimitives); /* fast path for small geometries */ /*if (refs.size() == 1) { bvh->set(refs[0].node,refs[0].bounds(),numPrimitives); return; }*/ /* compute PrimRefs */ prims.resize(refs.size()); const PrimInfo pinfo = parallel_reduce(size_t(0), refs.size(), size_t(1024), PrimInfo(empty), [&] (const range<size_t>& r) -> PrimInfo { PrimInfo pinfo(empty); for (size_t i=r.begin(); i<r.end(); i++) { const BBox3fa bounds = refs[i].worldBounds(); pinfo.add(bounds); prims[i] = PrimRef(bounds,(size_t)&refs[i]); } return pinfo; }, [] (const PrimInfo& a, const PrimInfo& b) { return PrimInfo::merge(a,b); }); /* skip if all objects where empty */ if (pinfo.size() == 0) bvh->set(BVH4::emptyNode,empty,0); /* otherwise build toplevel hierarchy */ else { BVH4::NodeRef root; BVHBuilderBinnedSAH::build<BVH4::NodeRef> (root, [&] { return bvh->alloc.threadLocal2(); }, [&] (const isa::BVHBuilderBinnedSAH::BuildRecord& current, BVHBuilderBinnedSAH::BuildRecord* children, const size_t N, FastAllocator::ThreadLocal2* alloc) -> int { BVH4::Node* node = (BVH4::Node*) alloc->alloc0.malloc(sizeof(BVH4::Node)); node->clear(); for (size_t i=0; i<N; i++) { node->set(i,children[i].pinfo.geomBounds); children[i].parent = (size_t*)&node->child(i); } *current.parent = bvh->encodeNode(node); return 0; }, [&] (const BVHBuilderBinnedSAH::BuildRecord& current, FastAllocator::ThreadLocal2* alloc) -> int { assert(current.prims.size() == 1); BuildRef* ref = (BuildRef*) prims[current.prims.begin()].ID(); BVH4::TransformNode* node = (BVH4::TransformNode*) alloc->alloc0.malloc(sizeof(BVH4::TransformNode)); new (node) BVH4::TransformNode(ref->local2world,ref->localBounds,ref->node); // FIXME: rcp should be precalculated somewhere *current.parent = BVH4::encodeNode(node); //*current.parent = ref->node; ((BVH4::NodeRef*)current.parent)->setBarrier(); return 1; }, [&] (size_t dn) { bvh->scene->progressMonitor(0); }, prims.data(),pinfo,BVH4::N,BVH4::maxBuildDepthLeaf,4,1,1,1.0f,1.0f); bvh->set(root,pinfo.geomBounds,numPrimitives); } bvh->root = collapse(bvh->root); bvh->alloc.cleanup(); bvh->postBuild(t0); } void BVH4BuilderInstancing::clear() { for (size_t i=0; i<objects.size(); i++) if (objects[i]) objects[i]->clear(); for (size_t i=0; i<builders.size(); i++) if (builders[i]) builders[i]->clear(); refs.clear(); } void set_primID(BVH4::NodeRef node, unsigned primID) { if (node.isLeaf()) { size_t num; Triangle4* prims = (Triangle4*) node.leaf(num); for (size_t i=0; i<num; i++) for (size_t j=0; j<4; j++) if (prims[i].geomIDs[j] != -1) prims[i].primIDs[j] = primID; } else { BVH4::Node* n = node.node(); for (size_t c=0; c<BVH4::N; c++) set_primID(n->child(c),primID); } } void BVH4BuilderInstancing::open(size_t numPrimitives) { if (refs.size() == 0) return; //size_t N = 0; //size_t N = numInstancedPrimitives/2000; size_t N = numInstancedPrimitives/200; //size_t N = numInstancedPrimitives; refs.reserve(N); std::make_heap(refs.begin(),refs.end()); while (refs.size()+3 <= N) { std::pop_heap (refs.begin(),refs.end()); BVH4::NodeRef ref = refs.back().node; const AffineSpace3fa local2world = refs.back().local2world; if (ref.isLeaf()) break; refs.pop_back(); BVH4::Node* node = ref.node(); for (size_t i=0; i<BVH4::N; i++) { if (node->child(i) == BVH4::emptyNode) continue; refs.push_back(BuildRef(local2world,node->bounds(i),node->child(i))); std::push_heap (refs.begin(),refs.end()); } } //for (size_t i=0; i<refs.size(); i++) // set_primID((BVH4::NodeRef) refs[i].node, i); } BVH4::NodeRef BVH4BuilderInstancing::collapse(BVH4::NodeRef& node) { if (node.isBarrier()) { node.clearBarrier(); return node; } assert(node.isNode()); BVH4::Node* n = node.node(); BVH4::TransformNode* first = nullptr; for (size_t c=0; c<BVH4::N; c++) { if (n->child(c) == BVH4::emptyNode) continue; BVH4::NodeRef child = n->child(c) = collapse(n->child(c)); if (child.isTransformNode()) first = child.transformNode(); } bool allEqual = true; for (size_t c=0; c<BVH4::N; c++) { BVH4::NodeRef child = n->child(c); if (child == BVH4::emptyNode) continue; if (!child.isTransformNode()) { allEqual = false; break; } if (child.transformNode()->world2local != first->world2local) { allEqual = false; break; } } if (!allEqual) return node; BBox3fa bounds = empty; for (size_t c=0; c<BVH4::N; c++) { if (n->child(c) == BVH4::emptyNode) continue; BVH4::TransformNode* child = n->child(c).transformNode(); const BBox3fa cbounds = child->localBounds; n->set(c,cbounds,child->child); bounds.extend(cbounds); } first->localBounds = bounds; first->child = node; return BVH4::encodeNode(first); } Builder* BVH4BuilderInstancingSAH (void* bvh, Scene* scene, const createTriangleMeshAccelTy createTriangleMeshAccel) { return new BVH4BuilderInstancing((BVH4*)bvh,scene,createTriangleMeshAccel); } } } <|endoftext|>
<commit_before>/* * exiv2-xmpdatum.cpp * * Author(s): * Stephane Delcroix (stephane@delcroix.org) * * Copyright (c) 2008 Novell * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "exiv2-xmpdatum.h" #include "exiv2-xmpdatum-private.h" #include <exiv2/xmp.hpp> G_BEGIN_DECLS G_DEFINE_TYPE (Exiv2XmpDatum, exiv2_xmpdatum, G_TYPE_OBJECT); //const char* exiv2_xmpdatum_real_get_key (Exiv2XmpDatum *self); //guint16 exiv2_xmpdatum_real_get_tag (Exiv2XmpDatum *self); //const char* exiv2_xmpdatum_real_get_typename (Exiv2XmpDatum *self); //glong exiv2_xmpdatum_real_get_count (Exiv2XmpDatum *self); const char* exiv2_xmpdatum_real_toString (Exiv2XmpDatum *self); //void exiv2_xmpdatum_real_setValueUShort (Exiv2XmpDatum *self, const guint16 value); //void exiv2_xmpdatum_real_setValueULong (Exiv2XmpDatum *self, const guint32 value); //void exiv2_xmpdatum_real_setValueURational (Exiv2XmpDatum *self, const guint32 numerator, const guint32 denominator); //void exiv2_xmpdatum_real_setValueSShort (Exiv2XmpDatum *self, const gint16 value); //void exiv2_xmpdatum_real_setValueSLong (Exiv2XmpDatum *self, const gint32 value); //void exiv2_xmpdatum_real_setValueRational (Exiv2XmpDatum *self, const gint32 numerator, const gint32 denominator); //void exiv2_xmpdatum_real_setValueString (Exiv2XmpDatum *self, const char* value); static void exiv2_xmpdatum_init (Exiv2XmpDatum *self) { Exiv2XmpDatumPrivate *priv; self->priv = priv = EXIV2_XMPDATUM_GET_PRIVATE (self); } static void exiv2_xmpdatum_class_init (Exiv2XmpDatumClass *klass) { // klass->get_key = exiv2_xmpdatum_real_get_key; // klass->get_tag = exiv2_xmpdatum_real_get_tag; // klass->get_typename = exiv2_xmpdatum_real_get_typename; // klass->get_count = exiv2_xmpdatum_real_get_count; klass->toString = exiv2_xmpdatum_real_toString; // klass->set_value_ushort = exiv2_xmpdatum_real_setValueUShort; // klass->set_value_ulong = exiv2_xmpdatum_real_setValueULong; // klass->set_value_urational = exiv2_xmpdatum_real_setValueURational; // klass->set_value_sshort = exiv2_xmpdatum_real_setValueSShort; // klass->set_value_slong = exiv2_xmpdatum_real_setValueSLong; // klass->set_value_rational = exiv2_xmpdatum_real_setValueRational; // klass->set_value_string = exiv2_xmpdatum_real_setValueString; // g_type_class_add_private (klass, sizeof (Exiv2XmpDatumPrivate)); } //const char* //exiv2_xmpdatum_get_key (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_key (self); //} // //guint16 //exiv2_xmpdatum_get_tag (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_tag (self); //} // //const char* //exiv2_xmpdatum_get_typename (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_typename (self); //} // //glong //exiv2_xmpdatum_get_count (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_count (self); //} const char* exiv2_xmpdatum_toString (Exiv2XmpDatum *self) { return EXIV2_XMPDATUM_GET_CLASS (self)->toString (self); } //void exiv2_xmpdatum_setValueUShort (Exiv2XmpDatum *self, const guint16 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_ushort (self, value); //} // //void exiv2_xmpdatum_setValueULong (Exiv2XmpDatum *self, const guint32 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_ulong (self, value); //} //void exiv2_xmpdatum_setValueURational (Exiv2XmpDatum *self, const guint32 numerator, const guint32 denominator) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_urational (self, numerator, denominator); //} // //void exiv2_xmpdatum_setValueSShort (Exiv2XmpDatum *self, const gint16 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_sshort (self, value); //} // //void exiv2_xmpdatum_setValueSLong (Exiv2XmpDatum *self, const gint32 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_slong (self, value); //} // //void exiv2_xmpdatum_setValueRational (Exiv2XmpDatum *self, const gint32 numerator, const gint32 denominator) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_rational (self, numerator, denominator); //} // //void exiv2_xmpdatum_setValueString (Exiv2XmpDatum *self, const char* value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_string (self, value); //} // //const char* //exiv2_xmpdatum_real_get_key (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), NULL); // return self->priv->datum->key ().c_str (); //} // //guint16 //exiv2_xmpdatum_real_get_tag (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), -1); // return self->priv->datum->tag (); //} // // //const char* //exiv2_xmpdatum_real_get_typename (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), NULL); // return self->priv->datum->typeName (); //} // //glong //exiv2_xmpdatum_real_get_count (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), -1); // return self->priv->datum->count (); //} // //const char* //exiv2_xmpdatum_real_toString (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), NULL); // return self->priv->datum->toString ().c_str (); //} // //void exiv2_xmpdatum_real_setValueUShort (Exiv2XmpDatum *self, const uint16_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueULong (Exiv2XmpDatum *self, const uint32_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueURational (Exiv2XmpDatum *self, const uint32_t numerator, const uint32_t denominator) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = Exiv2::URational (numerator, denominator); //} // //void exiv2_xmpdatum_real_setValueSShort (Exiv2XmpDatum *self, const int16_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueSLong (Exiv2XmpDatum *self, const int32_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueRational (Exiv2XmpDatum *self, const int32_t numerator, const int32_t denominator) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = Exiv2::Rational (numerator, denominator); //} // //void exiv2_xmpdatum_real_setValueString (Exiv2XmpDatum *self, const char* value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} G_END_DECLS <commit_msg>missing method<commit_after>/* * exiv2-xmpdatum.cpp * * Author(s): * Stephane Delcroix (stephane@delcroix.org) * * Copyright (c) 2008 Novell * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "exiv2-xmpdatum.h" #include "exiv2-xmpdatum-private.h" #include <exiv2/xmp.hpp> G_BEGIN_DECLS G_DEFINE_TYPE (Exiv2XmpDatum, exiv2_xmpdatum, G_TYPE_OBJECT); //const char* exiv2_xmpdatum_real_get_key (Exiv2XmpDatum *self); //guint16 exiv2_xmpdatum_real_get_tag (Exiv2XmpDatum *self); //const char* exiv2_xmpdatum_real_get_typename (Exiv2XmpDatum *self); //glong exiv2_xmpdatum_real_get_count (Exiv2XmpDatum *self); const char* exiv2_xmpdatum_real_toString (Exiv2XmpDatum *self); //void exiv2_xmpdatum_real_setValueUShort (Exiv2XmpDatum *self, const guint16 value); //void exiv2_xmpdatum_real_setValueULong (Exiv2XmpDatum *self, const guint32 value); //void exiv2_xmpdatum_real_setValueURational (Exiv2XmpDatum *self, const guint32 numerator, const guint32 denominator); //void exiv2_xmpdatum_real_setValueSShort (Exiv2XmpDatum *self, const gint16 value); //void exiv2_xmpdatum_real_setValueSLong (Exiv2XmpDatum *self, const gint32 value); //void exiv2_xmpdatum_real_setValueRational (Exiv2XmpDatum *self, const gint32 numerator, const gint32 denominator); //void exiv2_xmpdatum_real_setValueString (Exiv2XmpDatum *self, const char* value); static void exiv2_xmpdatum_init (Exiv2XmpDatum *self) { Exiv2XmpDatumPrivate *priv; self->priv = priv = EXIV2_XMPDATUM_GET_PRIVATE (self); } static void exiv2_xmpdatum_class_init (Exiv2XmpDatumClass *klass) { // klass->get_key = exiv2_xmpdatum_real_get_key; // klass->get_tag = exiv2_xmpdatum_real_get_tag; // klass->get_typename = exiv2_xmpdatum_real_get_typename; // klass->get_count = exiv2_xmpdatum_real_get_count; klass->toString = exiv2_xmpdatum_real_toString; // klass->set_value_ushort = exiv2_xmpdatum_real_setValueUShort; // klass->set_value_ulong = exiv2_xmpdatum_real_setValueULong; // klass->set_value_urational = exiv2_xmpdatum_real_setValueURational; // klass->set_value_sshort = exiv2_xmpdatum_real_setValueSShort; // klass->set_value_slong = exiv2_xmpdatum_real_setValueSLong; // klass->set_value_rational = exiv2_xmpdatum_real_setValueRational; // klass->set_value_string = exiv2_xmpdatum_real_setValueString; // g_type_class_add_private (klass, sizeof (Exiv2XmpDatumPrivate)); } //const char* //exiv2_xmpdatum_get_key (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_key (self); //} // //guint16 //exiv2_xmpdatum_get_tag (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_tag (self); //} // //const char* //exiv2_xmpdatum_get_typename (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_typename (self); //} // //glong //exiv2_xmpdatum_get_count (Exiv2XmpDatum *self) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->get_count (self); //} const char* exiv2_xmpdatum_toString (Exiv2XmpDatum *self) { return EXIV2_XMPDATUM_GET_CLASS (self)->toString (self); } //void exiv2_xmpdatum_setValueUShort (Exiv2XmpDatum *self, const guint16 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_ushort (self, value); //} // //void exiv2_xmpdatum_setValueULong (Exiv2XmpDatum *self, const guint32 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_ulong (self, value); //} //void exiv2_xmpdatum_setValueURational (Exiv2XmpDatum *self, const guint32 numerator, const guint32 denominator) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_urational (self, numerator, denominator); //} // //void exiv2_xmpdatum_setValueSShort (Exiv2XmpDatum *self, const gint16 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_sshort (self, value); //} // //void exiv2_xmpdatum_setValueSLong (Exiv2XmpDatum *self, const gint32 value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_slong (self, value); //} // //void exiv2_xmpdatum_setValueRational (Exiv2XmpDatum *self, const gint32 numerator, const gint32 denominator) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_rational (self, numerator, denominator); //} // //void exiv2_xmpdatum_setValueString (Exiv2XmpDatum *self, const char* value) //{ // return EXIV2_XMPDATUM_GET_CLASS (self)->set_value_string (self, value); //} // //const char* //exiv2_xmpdatum_real_get_key (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), NULL); // return self->priv->datum->key ().c_str (); //} // //guint16 //exiv2_xmpdatum_real_get_tag (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), -1); // return self->priv->datum->tag (); //} // // //const char* //exiv2_xmpdatum_real_get_typename (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), NULL); // return self->priv->datum->typeName (); //} // //glong //exiv2_xmpdatum_real_get_count (Exiv2XmpDatum *self) //{ // g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), -1); // return self->priv->datum->count (); //} // const char* exiv2_xmpdatum_real_toString (Exiv2XmpDatum *self) { g_return_val_if_fail (EXIV2_IS_XMPDATUM (self), NULL); return self->priv->datum->toString ().c_str (); } // //void exiv2_xmpdatum_real_setValueUShort (Exiv2XmpDatum *self, const uint16_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueULong (Exiv2XmpDatum *self, const uint32_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueURational (Exiv2XmpDatum *self, const uint32_t numerator, const uint32_t denominator) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = Exiv2::URational (numerator, denominator); //} // //void exiv2_xmpdatum_real_setValueSShort (Exiv2XmpDatum *self, const int16_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueSLong (Exiv2XmpDatum *self, const int32_t value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} // //void exiv2_xmpdatum_real_setValueRational (Exiv2XmpDatum *self, const int32_t numerator, const int32_t denominator) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = Exiv2::Rational (numerator, denominator); //} // //void exiv2_xmpdatum_real_setValueString (Exiv2XmpDatum *self, const char* value) //{ // g_return_if_fail (EXIV2_IS_XMPDATUM (self)); // Exiv2::Exifdatum* datum = self->priv->datum; // (*datum) = value; //} G_END_DECLS <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "XalanEXSLTDateTime.hpp" #include "XalanEXSLTDateTimeImpl.hpp" #include <ctime> #include <cstdio> #include <xalanc/PlatformSupport/XalanMessageLoader.hpp> #include <xalanc/XPath/XObjectFactory.hpp> XALAN_CPP_NAMESPACE_BEGIN #define MAX_DATE_TIME_LEN 100 static const XalanEXSLTFunctionDateTime s_dateTimeFunction; static const XalanDOMChar s_dateTimeFunctionName[] = { XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, XalanUnicode::charHyphenMinus, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, 0 }; static const XalanEXSLTDateTimeFunctionsInstaller::FunctionTableEntry theFunctionTable[] = { { s_dateTimeFunctionName, &s_dateTimeFunction }, { 0, 0 } }; static const XalanDOMChar s_dateTimeNamespace[] = { XalanUnicode::charLetter_h, XalanUnicode::charLetter_t, XalanUnicode::charLetter_t, XalanUnicode::charLetter_p, XalanUnicode::charColon, XalanUnicode::charSolidus, XalanUnicode::charSolidus, XalanUnicode::charLetter_e, XalanUnicode::charLetter_x, XalanUnicode::charLetter_s, XalanUnicode::charLetter_l, XalanUnicode::charLetter_t, XalanUnicode::charFullStop, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_g, XalanUnicode::charSolidus, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, XalanUnicode::charHyphenMinus, XalanUnicode::charLetter_a, XalanUnicode::charLetter_n, XalanUnicode::charLetter_d, XalanUnicode::charHyphenMinus, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, 0 }; XObjectPtr XalanEXSLTFunctionDateTime::execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const LocatorType* locator) const { if (args.size() != 0) { executionContext.error(getError(), context, locator); } XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext); XalanDOMString& theResult = theGuard.get(); time_t long_time; time( &long_time ); const struct tm* strctTime = localtime(&long_time); assert (strctTime != 0 ); //save hours - the struct going to be overrided const int iHours = strctTime->tm_hour; char stringTime[MAX_DATE_TIME_LEN + 1]; const size_t result = strftime(stringTime, MAX_DATE_TIME_LEN, "%Y-%m-%dT%H:%M:%S", strctTime); if (result == 0) { theResult.clear(); } else { // Microsoft doesn't fully support the strftime definition. Let's complete the job manually strctTime = gmtime(&long_time); assert (strctTime != 0 ); char timeZone[MAX_DATE_TIME_LEN+1]; sprintf(timeZone , "%2.2d:00", iHours - strctTime->tm_hour); theResult.assign(stringTime); theResult.append(timeZone); } return executionContext.getXObjectFactory().createString(theResult); } const XalanDOMString XalanEXSLTFunctionDateTime::getError() const { return XalanMessageLoader::getMessage(XalanMessages::EXSLTFunctionAcceptsOneArgument_1Param, s_dateTimeFunctionName); } void XalanEXSLTDateTimeFunctionsInstaller::installLocal(XPathEnvSupportDefault& theSupport) { doInstallLocal(s_dateTimeNamespace, theFunctionTable, theSupport); } void XalanEXSLTDateTimeFunctionsInstaller::installGlobal() { doInstallGlobal(s_dateTimeNamespace, theFunctionTable); } void XalanEXSLTDateTimeFunctionsInstaller::uninstallLocal(XPathEnvSupportDefault& theSupport) { doUninstallLocal(s_dateTimeNamespace, theFunctionTable, theSupport); } void XalanEXSLTDateTimeFunctionsInstaller::uninstallGlobal() { doUninstallGlobal(s_dateTimeNamespace, theFunctionTable); } XALAN_CPP_NAMESPACE_END <commit_msg>Fixes for picky platforms.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "XalanEXSLTDateTime.hpp" #include "XalanEXSLTDateTimeImpl.hpp" #include <ctime> #include <cstdio> #include <xalanc/PlatformSupport/XalanMessageLoader.hpp> #include <xalanc/XPath/XObjectFactory.hpp> XALAN_CPP_NAMESPACE_BEGIN static const XalanEXSLTFunctionDateTime s_dateTimeFunction; static const XalanDOMChar s_dateTimeFunctionName[] = { XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, XalanUnicode::charHyphenMinus, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, 0 }; static const XalanEXSLTDateTimeFunctionsInstaller::FunctionTableEntry theFunctionTable[] = { { s_dateTimeFunctionName, &s_dateTimeFunction }, { 0, 0 } }; static const XalanDOMChar s_dateTimeNamespace[] = { XalanUnicode::charLetter_h, XalanUnicode::charLetter_t, XalanUnicode::charLetter_t, XalanUnicode::charLetter_p, XalanUnicode::charColon, XalanUnicode::charSolidus, XalanUnicode::charSolidus, XalanUnicode::charLetter_e, XalanUnicode::charLetter_x, XalanUnicode::charLetter_s, XalanUnicode::charLetter_l, XalanUnicode::charLetter_t, XalanUnicode::charFullStop, XalanUnicode::charLetter_o, XalanUnicode::charLetter_r, XalanUnicode::charLetter_g, XalanUnicode::charSolidus, XalanUnicode::charLetter_d, XalanUnicode::charLetter_a, XalanUnicode::charLetter_t, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, XalanUnicode::charHyphenMinus, XalanUnicode::charLetter_a, XalanUnicode::charLetter_n, XalanUnicode::charLetter_d, XalanUnicode::charHyphenMinus, XalanUnicode::charLetter_t, XalanUnicode::charLetter_i, XalanUnicode::charLetter_m, XalanUnicode::charLetter_e, XalanUnicode::charLetter_s, 0 }; XObjectPtr XalanEXSLTFunctionDateTime::execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const LocatorType* locator) const { if (args.size() != 0) { executionContext.error(getError(), context, locator); } XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext); XalanDOMString& theResult = theGuard.get(); #if defined(XALAN_STRICT_ANSI_HEADERS) using std::localtime; using std::tm; using std::time_t; using std::time; using std::size_t; using std::strftime; using std::gmtime; #endif time_t long_time; time( &long_time ); const struct tm* strctTime = localtime(&long_time); assert (strctTime != 0 ); //save hours - the struct going to be overrided const int iHours = strctTime->tm_hour; const size_t MAX_DATE_TIME_LEN = 1000; char stringTime[MAX_DATE_TIME_LEN + 1]; const size_t result = strftime(stringTime, MAX_DATE_TIME_LEN, "%Y-%m-%dT%H:%M:%S", strctTime); if (result == 0) { theResult.clear(); } else { // Microsoft doesn't fully support the strftime definition. Let's complete the job manually strctTime = gmtime(&long_time); assert (strctTime != 0 ); char timeZone[MAX_DATE_TIME_LEN+1]; sprintf(timeZone , "%2.2d:00", iHours - strctTime->tm_hour); theResult.assign(stringTime); theResult.append(timeZone); } return executionContext.getXObjectFactory().createString(theResult); } const XalanDOMString XalanEXSLTFunctionDateTime::getError() const { return XalanMessageLoader::getMessage(XalanMessages::EXSLTFunctionAcceptsOneArgument_1Param, s_dateTimeFunctionName); } void XalanEXSLTDateTimeFunctionsInstaller::installLocal(XPathEnvSupportDefault& theSupport) { doInstallLocal(s_dateTimeNamespace, theFunctionTable, theSupport); } void XalanEXSLTDateTimeFunctionsInstaller::installGlobal() { doInstallGlobal(s_dateTimeNamespace, theFunctionTable); } void XalanEXSLTDateTimeFunctionsInstaller::uninstallLocal(XPathEnvSupportDefault& theSupport) { doUninstallLocal(s_dateTimeNamespace, theFunctionTable, theSupport); } void XalanEXSLTDateTimeFunctionsInstaller::uninstallGlobal() { doUninstallGlobal(s_dateTimeNamespace, theFunctionTable); } XALAN_CPP_NAMESPACE_END <|endoftext|>
<commit_before>// // Created by monty on 06/12/16. // #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #ifdef __APPLE__ #if TARGET_IOS #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> #else #import <OpenGL/OpenGL.h> #import <OpenGL/gl3.h> #endif #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <EGL/egl.h> #endif #include <functional> #include <memory> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <unordered_set> #include <map> #include <cstdint> #include <string> #include <tuple> #include <utility> #include <array> #include <stdio.h> #include <cmath> #include "NativeBitmap.h" #include "Texture.h" #include "Material.h" #include "Trig.h" #include "TrigBatch.h" #include "MeshObject.h" #include "MaterialList.h" #include "Scene.h" #include "WavefrontOBJReader.h" #include "Logger.h" #include "AudioSink.h" #include "SoundClip.h" #include "SoundUtils.h" #include "SoundListener.h" #include "SoundEmitter.h" #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "VBORenderingJob.h" #include "DungeonGLES2Renderer.h" #include "LightningStrategy.h" #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" #include "GameNativeAPI.h" #include "IRenderer.h" #include "NativeBitmap.h" #include "CKnight.h" #include "CGame.h" #include "Common.h" #include "NoudarGLES2Bridge.h" #include "SplatAnimation.h" #include "NoudarDungeonSnapshot.h"<commit_msg>Remove unecessary headers<commit_after>// // Created by monty on 06/12/16. // #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include <functional> #include <memory> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <unordered_set> #include <map> #include <cstdint> #include <string> #include <tuple> #include <utility> #include <array> #include <stdio.h> #include <cmath> #include "NativeBitmap.h" #include "Texture.h" #include "Material.h" #include "Trig.h" #include "TrigBatch.h" #include "MeshObject.h" #include "MaterialList.h" #include "Scene.h" #include "WavefrontOBJReader.h" #include "Logger.h" #include "AudioSink.h" #include "SoundClip.h" #include "SoundUtils.h" #include "SoundListener.h" #include "SoundEmitter.h" #include "Vec2i.h" #include "IMapElement.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "VBORenderingJob.h" #include "DungeonGLES2Renderer.h" #include "LightningStrategy.h" #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" #include "GameNativeAPI.h" #include "IRenderer.h" #include "NativeBitmap.h" #include "CKnight.h" #include "CGame.h" #include "Common.h" #include "NoudarGLES2Bridge.h" #include "SplatAnimation.h" #include "NoudarDungeonSnapshot.h"<|endoftext|>
<commit_before>#include "Grid.h" #include "Server.h" #include "Object.h" #include "Player.h" #include "Tools.h" #include "ServerConfig.h" #include "Log.h" #include "debugging.h" Poco::UInt8 Grid::losRange; /** * Initializes a Grid object * */ Grid::Grid(Poco::UInt16 x, Poco::UInt16 y): _x(x), _y(y) { _lastTick = clock(); } /** * Updates the Grid and its objects * * @return false if the grid must be deleted, true otherwise */ bool Grid::update() { // Update only if it's more than 1ms since last tick if (clock() - _lastTick > 0) { for (ObjectMap::const_iterator itr = _players.begin(); itr != _players.end(); ) { SharedPtr<Object> object = itr->second; ++itr; // Find near grids // Must be done before moving, other we may run into LoS problems GridsList nearGrids = findNearGrids(object); // Update AI, movement, everything if there is any or we have to // If update returns false, that means the object is no longer in this grid! if (!object->update(clock() - _lastTick)) _players.erase(object->GetGUID()); // Update near mobs GuidsSet objects; visit(object, objects); // Update other grids near mobs for (GridsList::iterator nGrid = nearGrids.begin(); nGrid != nearGrids.end(); nGrid++) (*nGrid)->visit(object, objects); // Update players LoS // Players will update mobs LoS in its method object->ToPlayer()->UpdateLoS(objects); } _lastTick = clock(); } return true; } /** * Returns all near grids to the object * * @param object Object which we must find near grids * @return the list of near grids */ Grid::GridsList Grid::findNearGrids(SharedPtr<Object> object) { Vector2D position = object->GetPosition(); Poco::UInt16 gridX = Tools::GetPositionInXCell(GetPositionX(), position.x); Poco::UInt16 gridY = Tools::GetPositionInYCell(GetPositionY(), position.z); std::list<Grid*> nearGrids; // Near at left if (gridX < losRange && GetPositionX() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() - 1, GetPositionY()); grid->forceLoad(); nearGrids.push_back(grid); // Near at left top corner if (gridY < losRange && GetPositionY() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() - 1, GetPositionY() - 1); grid->forceLoad(); nearGrids.push_back(grid); } // Near at left bottom corner if (gridY > UNITS_PER_CELL - losRange && GetPositionY() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() - 1, GetPositionY() + 1); grid->forceLoad(); nearGrids.push_back(grid); } } // Near at top if (gridY < losRange && GetPositionY() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX(), GetPositionY() - 1); grid->forceLoad(); nearGrids.push_back(grid); } // Near at right if (gridX > UNITS_PER_CELL - losRange && GetPositionX() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() + 1, GetPositionY()); grid->forceLoad(); nearGrids.push_back(grid); // Near at right top corner if (gridY < losRange && GetPositionY() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() + 1, GetPositionY() - 1); grid->forceLoad(); nearGrids.push_back(grid); } // Near at right bottom corner if (gridY > UNITS_PER_CELL - losRange && GetPositionY() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() + 1, GetPositionY() + 1); grid->forceLoad(); nearGrids.push_back(grid); } } // Near at bottom if (gridY > UNITS_PER_CELL - losRange && GetPositionY() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX(), GetPositionY() + 1); grid->forceLoad(); nearGrids.push_back(grid); } return nearGrids; } /** * Finds an object in radius in a Grid given a centre * * @param it dense_hash_map element * @param c Position taken as centre * @return true if it's the searched object */ static bool findObjectsIf(rde::pair<Poco::UInt64, SharedPtr<Object> > it, Vector2D c) { Poco::UInt32 x = it.second->GetPosition().x; Poco::UInt32 z = it.second->GetPosition().z; return (_max(x, Grid::losRange) - Grid::losRange <= c.x && c.x <= x + Grid::losRange && _max(z, Grid::losRange) - Grid::losRange <= c.z && c.z <= z + Grid::losRange); } /** * Enables a player to visit a grid, be it its grid or a nearby grid * * @param object Visiting object * @param objets List where near objects are included */ void Grid::visit(SharedPtr<Object> object, GuidsSet& objects) { Vector2D c(object->GetPosition().x, object->GetPosition().z); ObjectMap::iterator it = rde::find_if(_objects.begin(), _objects.end(), c, findObjectsIf); while (it != _objects.end()) { // Update the object, if it fails, it means it is in a new grid SharedPtr<Object> obj = it->second; // Find next near object now, avoid issues it = rde::find_if(++it, _objects.end(), c, findObjectsIf); // Find out the update time for the object Poco::UInt32 diff = clock() - obj->getLastUpdate(clock()); Poco::UInt32 loopDiff = clock() - _lastTick; // The smaller, the better if (diff > loopDiff) diff = loopDiff; // Update the object and erase it from the grid if we have to if (!obj->update(diff)) _objects.erase(obj->GetGUID()); else objects.insert(obj->GetGUID()); } it = rde::find_if(_players.begin(), _players.end(), c, findObjectsIf); while (it != _players.end()) { if (it->first != object->GetGUID()) objects.insert(it->first); it = rde::find_if(++it, _players.end(), c, findObjectsIf); // We don't update players, as that is done by the grid itself!! } } /** * Returns a list of GUIDs * * @param highGUID object type to gather * @return the objects list */ GuidsSet Grid::getObjects(Poco::UInt32 highGUID) { GuidsSet objects; if (highGUID & HIGH_GUID_PLAYER) { for (ObjectMap::const_iterator itr = _players.begin(); itr != _players.end(); ) { Poco::UInt64 GUID = itr->first; itr++; objects.insert(GUID); } } if (highGUID & ~HIGH_GUID_PLAYER) { for (ObjectMap::const_iterator itr = _objects.begin(); itr != _objects.end(); ) { Poco::UInt64 GUID = itr->first; itr++; if (GUID & highGUID) objects.insert(GUID); } } return objects; } /** * Returns the object specified by its complete GUID * * @param GUID object's GUID * @return NULL SharedPtr if not found, the object otherwise */ SharedPtr<Object> Grid::getObject(Poco::UInt64 GUID) { SharedPtr<Object> object = NULL; if (HIGUID(GUID) & HIGH_GUID_PLAYER) { ObjectMap::iterator itr = _players.find(GUID); if (itr != _players.end()) object = itr->second; } else { ObjectMap::iterator itr = _objects.find(GUID); if (itr != _objects.end()) object = itr->second; } return object; } /** * Adds an object to the grid * * @param object Object to be added * @return true if the object has been added */ bool Grid::addObject(SharedPtr<Object> object) { bool inserted = false; if (object->GetHighGUID() & HIGH_GUID_PLAYER) inserted = _players.insert(rde::make_pair(object->GetGUID(), object)).second; else inserted = _objects.insert(rde::make_pair(object->GetGUID(), object)).second; if (inserted) object->SetGrid(this); return inserted; } /** * Removes an object from the Grid * */ void Grid::removeObject(Poco::UInt64 GUID) { if (HIGUID(GUID) & HIGH_GUID_PLAYER) _players.erase(GUID); else _objects.erase(GUID); } /** * Forces a Grid to remain loaded (this happens when a players gets near to a grid!) * */ void Grid::forceLoad() { _forceLoad = clock(); } /** * Checks whether a grid has been force loaded or not * * @return true if it's force loaded */ bool Grid::isForceLoaded() { return (clock() - _forceLoad) < 5000; } /** * Initializes the grid loader, which manages and handles all grids * */ GridLoader::GridLoader(): _server(NULL) { //@todo: We should be able to have more than one grid handler // and they should all balance themselves, in order to keep // update rate really low (in ms) _gridsPool = new Poco::ThreadPool(1, 1); for (Poco::UInt16 x = 0; x < MAX_X; x++) for (Poco::UInt16 y = 0; y < MAX_Y; y++) _isGridLoaded[x][y] = false; // Set LoS range Grid::losRange = sConfig.getIntConfig("LoSRange"); sLog.out(Message::PRIO_TRACE, "\t[OK] LoS Range set to: %d", Grid::losRange); // Check for correct grid size ASSERT((MAP_MAX_X - MAP_MIN_X) / UNITS_PER_CELL < MAX_X) ASSERT((MAP_MAX_Z - MAP_MIN_Z) / UNITS_PER_CELL < MAX_Y) } /** * Class destructor, frees memory * */ GridLoader::~GridLoader() { delete _gridsPool; } /** * Initializes the grid loader, called uppon server start * * @param server Server reference, to keep this alive */ void GridLoader::initialize(Server* server) { _server = server; _gridsPool->start(*this); } /** * Checks if a grid is loaded, and if it's not, it loads it * * @param x X position of the grid * @param y Y position of the grid * @return True if the grid is successfully added */ bool GridLoader::checkAndLoad(Poco::UInt16 x, Poco::UInt16 y) { ASSERT(x >= 0 && x <= MAX_X) ASSERT(y >= 0 && y <= MAX_Y) if (_isGridLoaded[x][y]) return true; Grid* grid = new Grid(x, y); bool inserted = _grids.insert(rde::make_pair(grid->hashCode(), grid)).second; _isGridLoaded[x][y] = true; sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been created (%d)", x, y, inserted); return inserted; } /** * Gets a Grid. Should be safe as std::set iterators are safe, but we should keep and eye to this. * * @param x Cell Position x * @param y Cell Position y */ Grid* GridLoader::GetGrid(Poco::UInt16 x, Poco::UInt16 y) { Grid* grid = NULL; if (!_isGridLoaded[x][y]) return grid; GridsMap::const_iterator itr = _grids.find((x << 16) | y); if (itr != _grids.end()) grid = itr->second; return grid; } /** * Checks if a Grid is loaded, if not it loads it. Finally, returns the Grid * * @param x X position of the Grid * @param y Y position of the Grid * @return The grid itself */ Grid* GridLoader::GetGridOrLoad(Poco::UInt16 x, Poco::UInt16 y) { if (checkAndLoad(x, y)) return GetGrid(x, y); return NULL; } /** * Given an object, it adds it to a Grid * * @param x X position of the Grid * @param y Y position of the Grid * @param object Object to be added * @return Grid where the object has been added */ Grid* GridLoader::addObjectTo(Poco::UInt16 x, Poco::UInt16 y, SharedPtr<Object> object) { if (!checkAndLoad(x, y)) return NULL; Grid* grid = NULL; if (grid = GetGrid(x, y)) if (!grid->addObject(object)) grid = NULL; return grid; } /** * Adds an object to the Grid where it should be * * @param object Object to be added * @return Grid where it has been added */ Grid* GridLoader::addObject(SharedPtr<Object> object) { Vector2D pos = object->GetPosition(); return addObjectTo(Tools::GetXCellFromPos(pos.x), Tools::GetYCellFromPos(pos.z), object); } /** * Removes an object from the Grid where it is * * @param object Object to be removed * @return True if the object has been removed */ bool GridLoader::removeObject(Object* object) { Poco::UInt16 x = Tools::GetXCellFromPos(object->GetPosition().x); Poco::UInt16 y = Tools::GetYCellFromPos(object->GetPosition().z); if (!_isGridLoaded[x][y]) return false; if (Grid* grid = GetGrid(x, y)) { grid->removeObject(object->GetGUID()); object->SetGrid(NULL); return true; } return false; } /** * Thread where the Grids are updating * */ void GridLoader::run_impl() { while (sServer->isRunning()) { // Update all Grids for (GridsMap::const_iterator itr = _grids.begin(); itr != _grids.end(); ) { Grid* grid = itr->second; itr++; // If update fails, something went really wrong, delete this grid // If the grid has no players in it, check for nearby grids, if they are not loaded or have no players, remove it if (!grid->update() || (!grid->hasPlayers() && !grid->isForceLoaded())) { sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been deleted (%d %d)", grid->GetPositionX(), grid->GetPositionY(), grid->hasPlayers(), grid->isForceLoaded()); _isGridLoaded[grid->GetPositionX()][grid->GetPositionY()] = false; _grids.erase(grid->hashCode()); delete grid; } } Poco::Thread::sleep(1); } } <commit_msg>Core/Grid: Fix a doubtably usefull type conversion and warning<commit_after>#include "Grid.h" #include "Server.h" #include "Object.h" #include "Player.h" #include "Tools.h" #include "ServerConfig.h" #include "Log.h" #include "debugging.h" Poco::UInt8 Grid::losRange; /** * Initializes a Grid object * */ Grid::Grid(Poco::UInt16 x, Poco::UInt16 y): _x(x), _y(y) { _lastTick = clock(); } /** * Updates the Grid and its objects * * @return false if the grid must be deleted, true otherwise */ bool Grid::update() { // Update only if it's more than 1ms since last tick if (clock() - _lastTick > 0) { for (ObjectMap::const_iterator itr = _players.begin(); itr != _players.end(); ) { SharedPtr<Object> object = itr->second; ++itr; // Find near grids // Must be done before moving, other we may run into LoS problems GridsList nearGrids = findNearGrids(object); // Update AI, movement, everything if there is any or we have to // If update returns false, that means the object is no longer in this grid! if (!object->update(clock() - _lastTick)) _players.erase(object->GetGUID()); // Update near mobs GuidsSet objects; visit(object, objects); // Update other grids near mobs for (GridsList::iterator nGrid = nearGrids.begin(); nGrid != nearGrids.end(); nGrid++) (*nGrid)->visit(object, objects); // Update players LoS // Players will update mobs LoS in its method object->ToPlayer()->UpdateLoS(objects); } _lastTick = clock(); } return true; } /** * Returns all near grids to the object * * @param object Object which we must find near grids * @return the list of near grids */ Grid::GridsList Grid::findNearGrids(SharedPtr<Object> object) { Vector2D position = object->GetPosition(); Poco::UInt16 gridX = Tools::GetPositionInXCell(GetPositionX(), position.x); Poco::UInt16 gridY = Tools::GetPositionInYCell(GetPositionY(), position.z); std::list<Grid*> nearGrids; // Near at left if (gridX < losRange && GetPositionX() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() - 1, GetPositionY()); grid->forceLoad(); nearGrids.push_back(grid); // Near at left top corner if (gridY < losRange && GetPositionY() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() - 1, GetPositionY() - 1); grid->forceLoad(); nearGrids.push_back(grid); } // Near at left bottom corner if (gridY > UNITS_PER_CELL - losRange && GetPositionY() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() - 1, GetPositionY() + 1); grid->forceLoad(); nearGrids.push_back(grid); } } // Near at top if (gridY < losRange && GetPositionY() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX(), GetPositionY() - 1); grid->forceLoad(); nearGrids.push_back(grid); } // Near at right if (gridX > UNITS_PER_CELL - losRange && GetPositionX() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() + 1, GetPositionY()); grid->forceLoad(); nearGrids.push_back(grid); // Near at right top corner if (gridY < losRange && GetPositionY() > 1) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() + 1, GetPositionY() - 1); grid->forceLoad(); nearGrids.push_back(grid); } // Near at right bottom corner if (gridY > UNITS_PER_CELL - losRange && GetPositionY() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX() + 1, GetPositionY() + 1); grid->forceLoad(); nearGrids.push_back(grid); } } // Near at bottom if (gridY > UNITS_PER_CELL - losRange && GetPositionY() < 0xFF) { Grid* grid = sGridLoader.GetGridOrLoad(GetPositionX(), GetPositionY() + 1); grid->forceLoad(); nearGrids.push_back(grid); } return nearGrids; } /** * Finds an object in radius in a Grid given a centre * * @param it dense_hash_map element * @param c Position taken as centre * @return true if it's the searched object */ static bool findObjectsIf(rde::pair<Poco::UInt64, SharedPtr<Object> > it, Vector2D c) { float x = it.second->GetPosition().x; float z = it.second->GetPosition().z; return (_max(x, Grid::losRange) - Grid::losRange <= c.x && c.x <= x + Grid::losRange && _max(z, Grid::losRange) - Grid::losRange <= c.z && c.z <= z + Grid::losRange); } /** * Enables a player to visit a grid, be it its grid or a nearby grid * * @param object Visiting object * @param objets List where near objects are included */ void Grid::visit(SharedPtr<Object> object, GuidsSet& objects) { Vector2D c(object->GetPosition().x, object->GetPosition().z); ObjectMap::iterator it = rde::find_if(_objects.begin(), _objects.end(), c, findObjectsIf); while (it != _objects.end()) { // Update the object, if it fails, it means it is in a new grid SharedPtr<Object> obj = it->second; // Find next near object now, avoid issues it = rde::find_if(++it, _objects.end(), c, findObjectsIf); // Find out the update time for the object Poco::UInt32 diff = clock() - obj->getLastUpdate(clock()); Poco::UInt32 loopDiff = clock() - _lastTick; // The smaller, the better if (diff > loopDiff) diff = loopDiff; // Update the object and erase it from the grid if we have to if (!obj->update(diff)) _objects.erase(obj->GetGUID()); else objects.insert(obj->GetGUID()); } it = rde::find_if(_players.begin(), _players.end(), c, findObjectsIf); while (it != _players.end()) { if (it->first != object->GetGUID()) objects.insert(it->first); it = rde::find_if(++it, _players.end(), c, findObjectsIf); // We don't update players, as that is done by the grid itself!! } } /** * Returns a list of GUIDs * * @param highGUID object type to gather * @return the objects list */ GuidsSet Grid::getObjects(Poco::UInt32 highGUID) { GuidsSet objects; if (highGUID & HIGH_GUID_PLAYER) { for (ObjectMap::const_iterator itr = _players.begin(); itr != _players.end(); ) { Poco::UInt64 GUID = itr->first; itr++; objects.insert(GUID); } } if (highGUID & ~HIGH_GUID_PLAYER) { for (ObjectMap::const_iterator itr = _objects.begin(); itr != _objects.end(); ) { Poco::UInt64 GUID = itr->first; itr++; if (GUID & highGUID) objects.insert(GUID); } } return objects; } /** * Returns the object specified by its complete GUID * * @param GUID object's GUID * @return NULL SharedPtr if not found, the object otherwise */ SharedPtr<Object> Grid::getObject(Poco::UInt64 GUID) { SharedPtr<Object> object = NULL; if (HIGUID(GUID) & HIGH_GUID_PLAYER) { ObjectMap::iterator itr = _players.find(GUID); if (itr != _players.end()) object = itr->second; } else { ObjectMap::iterator itr = _objects.find(GUID); if (itr != _objects.end()) object = itr->second; } return object; } /** * Adds an object to the grid * * @param object Object to be added * @return true if the object has been added */ bool Grid::addObject(SharedPtr<Object> object) { bool inserted = false; if (object->GetHighGUID() & HIGH_GUID_PLAYER) inserted = _players.insert(rde::make_pair(object->GetGUID(), object)).second; else inserted = _objects.insert(rde::make_pair(object->GetGUID(), object)).second; if (inserted) object->SetGrid(this); return inserted; } /** * Removes an object from the Grid * */ void Grid::removeObject(Poco::UInt64 GUID) { if (HIGUID(GUID) & HIGH_GUID_PLAYER) _players.erase(GUID); else _objects.erase(GUID); } /** * Forces a Grid to remain loaded (this happens when a players gets near to a grid!) * */ void Grid::forceLoad() { _forceLoad = clock(); } /** * Checks whether a grid has been force loaded or not * * @return true if it's force loaded */ bool Grid::isForceLoaded() { return (clock() - _forceLoad) < 5000; } /** * Initializes the grid loader, which manages and handles all grids * */ GridLoader::GridLoader(): _server(NULL) { //@todo: We should be able to have more than one grid handler // and they should all balance themselves, in order to keep // update rate really low (in ms) _gridsPool = new Poco::ThreadPool(1, 1); for (Poco::UInt16 x = 0; x < MAX_X; x++) for (Poco::UInt16 y = 0; y < MAX_Y; y++) _isGridLoaded[x][y] = false; // Set LoS range Grid::losRange = sConfig.getIntConfig("LoSRange"); sLog.out(Message::PRIO_TRACE, "\t[OK] LoS Range set to: %d", Grid::losRange); // Check for correct grid size ASSERT((MAP_MAX_X - MAP_MIN_X) / UNITS_PER_CELL < MAX_X) ASSERT((MAP_MAX_Z - MAP_MIN_Z) / UNITS_PER_CELL < MAX_Y) } /** * Class destructor, frees memory * */ GridLoader::~GridLoader() { delete _gridsPool; } /** * Initializes the grid loader, called uppon server start * * @param server Server reference, to keep this alive */ void GridLoader::initialize(Server* server) { _server = server; _gridsPool->start(*this); } /** * Checks if a grid is loaded, and if it's not, it loads it * * @param x X position of the grid * @param y Y position of the grid * @return True if the grid is successfully added */ bool GridLoader::checkAndLoad(Poco::UInt16 x, Poco::UInt16 y) { ASSERT(x >= 0 && x <= MAX_X) ASSERT(y >= 0 && y <= MAX_Y) if (_isGridLoaded[x][y]) return true; Grid* grid = new Grid(x, y); bool inserted = _grids.insert(rde::make_pair(grid->hashCode(), grid)).second; _isGridLoaded[x][y] = true; sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been created (%d)", x, y, inserted); return inserted; } /** * Gets a Grid. Should be safe as std::set iterators are safe, but we should keep and eye to this. * * @param x Cell Position x * @param y Cell Position y */ Grid* GridLoader::GetGrid(Poco::UInt16 x, Poco::UInt16 y) { Grid* grid = NULL; if (!_isGridLoaded[x][y]) return grid; GridsMap::const_iterator itr = _grids.find((x << 16) | y); if (itr != _grids.end()) grid = itr->second; return grid; } /** * Checks if a Grid is loaded, if not it loads it. Finally, returns the Grid * * @param x X position of the Grid * @param y Y position of the Grid * @return The grid itself */ Grid* GridLoader::GetGridOrLoad(Poco::UInt16 x, Poco::UInt16 y) { if (checkAndLoad(x, y)) return GetGrid(x, y); return NULL; } /** * Given an object, it adds it to a Grid * * @param x X position of the Grid * @param y Y position of the Grid * @param object Object to be added * @return Grid where the object has been added */ Grid* GridLoader::addObjectTo(Poco::UInt16 x, Poco::UInt16 y, SharedPtr<Object> object) { if (!checkAndLoad(x, y)) return NULL; Grid* grid = NULL; if (grid = GetGrid(x, y)) if (!grid->addObject(object)) grid = NULL; return grid; } /** * Adds an object to the Grid where it should be * * @param object Object to be added * @return Grid where it has been added */ Grid* GridLoader::addObject(SharedPtr<Object> object) { Vector2D pos = object->GetPosition(); return addObjectTo(Tools::GetXCellFromPos(pos.x), Tools::GetYCellFromPos(pos.z), object); } /** * Removes an object from the Grid where it is * * @param object Object to be removed * @return True if the object has been removed */ bool GridLoader::removeObject(Object* object) { Poco::UInt16 x = Tools::GetXCellFromPos(object->GetPosition().x); Poco::UInt16 y = Tools::GetYCellFromPos(object->GetPosition().z); if (!_isGridLoaded[x][y]) return false; if (Grid* grid = GetGrid(x, y)) { grid->removeObject(object->GetGUID()); object->SetGrid(NULL); return true; } return false; } /** * Thread where the Grids are updating * */ void GridLoader::run_impl() { while (sServer->isRunning()) { // Update all Grids for (GridsMap::const_iterator itr = _grids.begin(); itr != _grids.end(); ) { Grid* grid = itr->second; itr++; // If update fails, something went really wrong, delete this grid // If the grid has no players in it, check for nearby grids, if they are not loaded or have no players, remove it if (!grid->update() || (!grid->hasPlayers() && !grid->isForceLoaded())) { sLog.out(Message::PRIO_DEBUG, "Grid (%d, %d) has been deleted (%d %d)", grid->GetPositionX(), grid->GetPositionY(), grid->hasPlayers(), grid->isForceLoaded()); _isGridLoaded[grid->GetPositionX()][grid->GetPositionY()] = false; _grids.erase(grid->hashCode()); delete grid; } } Poco::Thread::sleep(1); } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "cdbstacktracecontext.h" #include "cdbstackframecontext.h" #include "cdbbreakpoint.h" #include "cdbsymbolgroupcontext.h" #include "cdbdebugengine_p.h" #include "cdbdumperhelper.h" #include <QtCore/QDir> #include <QtCore/QTextStream> namespace Debugger { namespace Internal { CdbStackTraceContext::CdbStackTraceContext(const QSharedPointer<CdbDumperHelper> &dumper) : m_dumper(dumper), m_cif(dumper->comInterfaces()), m_instructionOffset(0) { } CdbStackTraceContext *CdbStackTraceContext::create(const QSharedPointer<CdbDumperHelper> &dumper, unsigned long threadId, QString *errorMessage) { if (debugCDB) qDebug() << Q_FUNC_INFO << threadId; // fill the DEBUG_STACK_FRAME array ULONG frameCount; CdbStackTraceContext *ctx = new CdbStackTraceContext(dumper); const HRESULT hr = dumper->comInterfaces()->debugControl->GetStackTrace(0, 0, 0, ctx->m_cdbFrames, CdbStackTraceContext::maxFrames, &frameCount); if (FAILED(hr)) { delete ctx; *errorMessage = msgComFailed("GetStackTrace", hr); return 0; } if (!ctx->init(frameCount, errorMessage)) { delete ctx; return 0; } return ctx; } CdbStackTraceContext::~CdbStackTraceContext() { qDeleteAll(m_frameContexts); } bool CdbStackTraceContext::init(unsigned long frameCount, QString * /*errorMessage*/) { if (debugCDB) qDebug() << Q_FUNC_INFO << frameCount; m_frameContexts.resize(frameCount); qFill(m_frameContexts, static_cast<CdbStackFrameContext*>(0)); // Convert the DEBUG_STACK_FRAMEs to our StackFrame structure and populate the frames WCHAR wszBuf[MAX_PATH]; for (ULONG i=0; i < frameCount; ++i) { StackFrame frame; frame.level = i; const ULONG64 instructionOffset = m_cdbFrames[i].InstructionOffset; if (i == 0) m_instructionOffset = instructionOffset; frame.address = QString::fromLatin1("0x%1").arg(instructionOffset, 0, 16); m_cif->debugSymbols->GetNameByOffsetWide(instructionOffset, wszBuf, MAX_PATH, 0, 0); frame.function = QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf)); ULONG ulLine; ULONG64 ul64Displacement; const HRESULT hr = m_cif->debugSymbols->GetLineByOffsetWide(instructionOffset, &ulLine, wszBuf, MAX_PATH, 0, &ul64Displacement); if (SUCCEEDED(hr)) { frame.line = ulLine; // Vitally important to use canonical file that matches editormanager, // else the marker will not show. frame.file = CDBBreakPoint::canonicalSourceFile(QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf))); } m_frames.push_back(frame); } return true; } int CdbStackTraceContext::indexOf(const QString &function) const { const QChar exclamationMark = QLatin1Char('!'); const int count = m_frames.size(); // Module contained ('module!foo'). Exact match if (function.contains(exclamationMark)) { for (int i = 0; i < count; i++) if (m_frames.at(i).function == function) return i; return -1; } // No module, fuzzy match QString pattern = exclamationMark + function; for (int i = 0; i < count; i++) if (m_frames.at(i).function.endsWith(pattern)) return i; return -1; } static inline QString msgFrameContextFailed(int index, const StackFrame &f, const QString &why) { return QString::fromLatin1("Unable to create stack frame context #%1, %2:%3 (%4): %5"). arg(index).arg(f.function).arg(f.line).arg(f.file, why); } CdbStackFrameContext *CdbStackTraceContext::frameContextAt(int index, QString *errorMessage) { // Create a frame on demand if (debugCDB) qDebug() << Q_FUNC_INFO << index; if (index < 0 || index >= m_frameContexts.size()) { *errorMessage = QString::fromLatin1("%1: Index %2 out of range %3."). arg(QLatin1String(Q_FUNC_INFO)).arg(index).arg(m_frameContexts.size()); return 0; } if (m_frameContexts.at(index)) return m_frameContexts.at(index); CIDebugSymbolGroup *sg = createSymbolGroup(index, errorMessage); if (!sg) { *errorMessage = msgFrameContextFailed(index, m_frames.at(index), *errorMessage); return 0; } CdbSymbolGroupContext *sc = CdbSymbolGroupContext::create(QLatin1String("local"), sg, errorMessage); if (!sc) { *errorMessage = msgFrameContextFailed(index, m_frames.at(index), *errorMessage); return 0; } CdbStackFrameContext *fr = new CdbStackFrameContext(m_dumper, sc); m_frameContexts[index] = fr; return fr; } CIDebugSymbolGroup *CdbStackTraceContext::createSymbolGroup(int index, QString *errorMessage) { CIDebugSymbolGroup *sg = 0; HRESULT hr = m_cif->debugSymbols->GetScopeSymbolGroup2(DEBUG_SCOPE_GROUP_LOCALS, NULL, &sg); if (FAILED(hr)) { *errorMessage = msgComFailed("GetScopeSymbolGroup", hr); return 0; } hr = m_cif->debugSymbols->SetScope(0, m_cdbFrames + index, NULL, 0); if (FAILED(hr)) { *errorMessage = msgComFailed("SetScope", hr); sg->Release(); return 0; } // refresh with current frame hr = m_cif->debugSymbols->GetScopeSymbolGroup2(DEBUG_SCOPE_GROUP_LOCALS, sg, &sg); if (FAILED(hr)) { *errorMessage = msgComFailed("GetScopeSymbolGroup", hr); sg->Release(); return 0; } return sg; } QString CdbStackTraceContext::toString() const { QString rc; QTextStream str(&rc); format(str); return rc; } void CdbStackTraceContext::format(QTextStream &str) const { const int count = m_frames.count(); const int defaultFieldWidth = str.fieldWidth(); const QTextStream::FieldAlignment defaultAlignment = str.fieldAlignment(); for (int f = 0; f < count; f++) { const StackFrame &frame = m_frames.at(f); const bool hasFile = !frame.file.isEmpty(); // left-pad level str << qSetFieldWidth(6) << left << f; str.setFieldWidth(defaultFieldWidth); str.setFieldAlignment(defaultAlignment); if (hasFile) str << QDir::toNativeSeparators(frame.file) << ':' << frame.line << " ("; str << frame.function; if (hasFile) str << ')'; str << '\n'; } } // Thread state helper static inline QString msgGetThreadStateFailed(unsigned long threadId, const QString &why) { return QString::fromLatin1("Unable to determine the state of thread %1: %2").arg(threadId).arg(why); } static inline bool getStoppedThreadState(const CdbComInterfaces &cif, ThreadData *t, QString *errorMessage) { ULONG currentThread; HRESULT hr = cif.debugSystemObjects->GetCurrentThreadId(&currentThread); if (FAILED(hr)) { *errorMessage = msgGetThreadStateFailed(t->id, msgComFailed("GetCurrentThreadId", hr)); return false; } if (currentThread != t->id) { hr = cif.debugSystemObjects->SetCurrentThreadId(t->id); if (FAILED(hr)) { *errorMessage = msgGetThreadStateFailed(t->id, msgComFailed("SetCurrentThreadId", hr)); return false; } } ULONG frameCount; DEBUG_STACK_FRAME topFrame[1]; hr = cif.debugControl->GetStackTrace(0, 0, 0, topFrame, 1, &frameCount); if (FAILED(hr)) { *errorMessage = msgGetThreadStateFailed(t->id, msgComFailed("GetStackTrace", hr)); return false; } t->address = topFrame[0].InstructionOffset; WCHAR wszBuf[MAX_PATH]; cif.debugSymbols->GetNameByOffsetWide(topFrame[0].InstructionOffset, wszBuf, MAX_PATH, 0, 0); t->function = QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf)); ULONG ulLine; hr = cif.debugSymbols->GetLineByOffsetWide(topFrame[0].InstructionOffset, &ulLine, wszBuf, MAX_PATH, 0, 0); if (SUCCEEDED(hr)) { t->line = ulLine; // Just display base name t->file = QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf)); if (!t->file.isEmpty()) { const int slashPos = t->file.lastIndexOf(QLatin1Char('\\')); if (slashPos != -1) t->file.remove(0, slashPos + 1); } } return true; } static inline QString msgGetThreadsFailed(const QString &why) { return QString::fromLatin1("Unable to determine the thread information: %1").arg(why); } bool CdbStackTraceContext::getThreads(const CdbComInterfaces &cif, bool isStopped, QList<ThreadData> *threads, ULONG *currentThreadId, QString *errorMessage) { threads->clear(); ULONG threadCount; *currentThreadId = 0; HRESULT hr= cif.debugSystemObjects->GetNumberThreads(&threadCount); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("GetNumberThreads", hr)); return false; } // Get ids and index of current if (!threadCount) return true; hr = cif.debugSystemObjects->GetCurrentThreadId(currentThreadId); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("GetCurrentThreadId", hr)); return false; } QVector<ULONG> threadIds(threadCount); hr = cif.debugSystemObjects->GetThreadIdsByIndex(0, threadCount, &(*threadIds.begin()), 0); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("GetThreadIdsByIndex", hr)); return false; } for (ULONG i = 0; i < threadCount; i++) { ThreadData threadData(threadIds.at(i)); if (isStopped) { if (!getStoppedThreadState(cif, &threadData, errorMessage)) { qWarning("%s\n", qPrintable(*errorMessage)); errorMessage->clear(); } } threads->push_back(threadData); } return true; } } // namespace Internal } // namespace Debugger <commit_msg>CDB: Restore current thread.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "cdbstacktracecontext.h" #include "cdbstackframecontext.h" #include "cdbbreakpoint.h" #include "cdbsymbolgroupcontext.h" #include "cdbdebugengine_p.h" #include "cdbdumperhelper.h" #include <QtCore/QDir> #include <QtCore/QTextStream> namespace Debugger { namespace Internal { CdbStackTraceContext::CdbStackTraceContext(const QSharedPointer<CdbDumperHelper> &dumper) : m_dumper(dumper), m_cif(dumper->comInterfaces()), m_instructionOffset(0) { } CdbStackTraceContext *CdbStackTraceContext::create(const QSharedPointer<CdbDumperHelper> &dumper, unsigned long threadId, QString *errorMessage) { if (debugCDB) qDebug() << Q_FUNC_INFO << threadId; // fill the DEBUG_STACK_FRAME array ULONG frameCount; CdbStackTraceContext *ctx = new CdbStackTraceContext(dumper); const HRESULT hr = dumper->comInterfaces()->debugControl->GetStackTrace(0, 0, 0, ctx->m_cdbFrames, CdbStackTraceContext::maxFrames, &frameCount); if (FAILED(hr)) { delete ctx; *errorMessage = msgComFailed("GetStackTrace", hr); return 0; } if (!ctx->init(frameCount, errorMessage)) { delete ctx; return 0; } return ctx; } CdbStackTraceContext::~CdbStackTraceContext() { qDeleteAll(m_frameContexts); } bool CdbStackTraceContext::init(unsigned long frameCount, QString * /*errorMessage*/) { if (debugCDB) qDebug() << Q_FUNC_INFO << frameCount; m_frameContexts.resize(frameCount); qFill(m_frameContexts, static_cast<CdbStackFrameContext*>(0)); // Convert the DEBUG_STACK_FRAMEs to our StackFrame structure and populate the frames WCHAR wszBuf[MAX_PATH]; for (ULONG i=0; i < frameCount; ++i) { StackFrame frame; frame.level = i; const ULONG64 instructionOffset = m_cdbFrames[i].InstructionOffset; if (i == 0) m_instructionOffset = instructionOffset; frame.address = QString::fromLatin1("0x%1").arg(instructionOffset, 0, 16); m_cif->debugSymbols->GetNameByOffsetWide(instructionOffset, wszBuf, MAX_PATH, 0, 0); frame.function = QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf)); ULONG ulLine; ULONG64 ul64Displacement; const HRESULT hr = m_cif->debugSymbols->GetLineByOffsetWide(instructionOffset, &ulLine, wszBuf, MAX_PATH, 0, &ul64Displacement); if (SUCCEEDED(hr)) { frame.line = ulLine; // Vitally important to use canonical file that matches editormanager, // else the marker will not show. frame.file = CDBBreakPoint::canonicalSourceFile(QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf))); } m_frames.push_back(frame); } return true; } int CdbStackTraceContext::indexOf(const QString &function) const { const QChar exclamationMark = QLatin1Char('!'); const int count = m_frames.size(); // Module contained ('module!foo'). Exact match if (function.contains(exclamationMark)) { for (int i = 0; i < count; i++) if (m_frames.at(i).function == function) return i; return -1; } // No module, fuzzy match QString pattern = exclamationMark + function; for (int i = 0; i < count; i++) if (m_frames.at(i).function.endsWith(pattern)) return i; return -1; } static inline QString msgFrameContextFailed(int index, const StackFrame &f, const QString &why) { return QString::fromLatin1("Unable to create stack frame context #%1, %2:%3 (%4): %5"). arg(index).arg(f.function).arg(f.line).arg(f.file, why); } CdbStackFrameContext *CdbStackTraceContext::frameContextAt(int index, QString *errorMessage) { // Create a frame on demand if (debugCDB) qDebug() << Q_FUNC_INFO << index; if (index < 0 || index >= m_frameContexts.size()) { *errorMessage = QString::fromLatin1("%1: Index %2 out of range %3."). arg(QLatin1String(Q_FUNC_INFO)).arg(index).arg(m_frameContexts.size()); return 0; } if (m_frameContexts.at(index)) return m_frameContexts.at(index); CIDebugSymbolGroup *sg = createSymbolGroup(index, errorMessage); if (!sg) { *errorMessage = msgFrameContextFailed(index, m_frames.at(index), *errorMessage); return 0; } CdbSymbolGroupContext *sc = CdbSymbolGroupContext::create(QLatin1String("local"), sg, errorMessage); if (!sc) { *errorMessage = msgFrameContextFailed(index, m_frames.at(index), *errorMessage); return 0; } CdbStackFrameContext *fr = new CdbStackFrameContext(m_dumper, sc); m_frameContexts[index] = fr; return fr; } CIDebugSymbolGroup *CdbStackTraceContext::createSymbolGroup(int index, QString *errorMessage) { CIDebugSymbolGroup *sg = 0; HRESULT hr = m_cif->debugSymbols->GetScopeSymbolGroup2(DEBUG_SCOPE_GROUP_LOCALS, NULL, &sg); if (FAILED(hr)) { *errorMessage = msgComFailed("GetScopeSymbolGroup", hr); return 0; } hr = m_cif->debugSymbols->SetScope(0, m_cdbFrames + index, NULL, 0); if (FAILED(hr)) { *errorMessage = msgComFailed("SetScope", hr); sg->Release(); return 0; } // refresh with current frame hr = m_cif->debugSymbols->GetScopeSymbolGroup2(DEBUG_SCOPE_GROUP_LOCALS, sg, &sg); if (FAILED(hr)) { *errorMessage = msgComFailed("GetScopeSymbolGroup", hr); sg->Release(); return 0; } return sg; } QString CdbStackTraceContext::toString() const { QString rc; QTextStream str(&rc); format(str); return rc; } void CdbStackTraceContext::format(QTextStream &str) const { const int count = m_frames.count(); const int defaultFieldWidth = str.fieldWidth(); const QTextStream::FieldAlignment defaultAlignment = str.fieldAlignment(); for (int f = 0; f < count; f++) { const StackFrame &frame = m_frames.at(f); const bool hasFile = !frame.file.isEmpty(); // left-pad level str << qSetFieldWidth(6) << left << f; str.setFieldWidth(defaultFieldWidth); str.setFieldAlignment(defaultAlignment); if (hasFile) str << QDir::toNativeSeparators(frame.file) << ':' << frame.line << " ("; str << frame.function; if (hasFile) str << ')'; str << '\n'; } } // Thread state helper static inline QString msgGetThreadStateFailed(unsigned long threadId, const QString &why) { return QString::fromLatin1("Unable to determine the state of thread %1: %2").arg(threadId).arg(why); } // Determine information about thread. This changes the // current thread to thread->id. static inline bool getStoppedThreadState(const CdbComInterfaces &cif, ThreadData *t, QString *errorMessage) { ULONG currentThread; HRESULT hr = cif.debugSystemObjects->GetCurrentThreadId(&currentThread); if (FAILED(hr)) { *errorMessage = msgGetThreadStateFailed(t->id, msgComFailed("GetCurrentThreadId", hr)); return false; } if (currentThread != t->id) { hr = cif.debugSystemObjects->SetCurrentThreadId(t->id); if (FAILED(hr)) { *errorMessage = msgGetThreadStateFailed(t->id, msgComFailed("SetCurrentThreadId", hr)); return false; } } ULONG frameCount; DEBUG_STACK_FRAME topFrame[1]; hr = cif.debugControl->GetStackTrace(0, 0, 0, topFrame, 1, &frameCount); if (FAILED(hr)) { *errorMessage = msgGetThreadStateFailed(t->id, msgComFailed("GetStackTrace", hr)); return false; } t->address = topFrame[0].InstructionOffset; WCHAR wszBuf[MAX_PATH]; cif.debugSymbols->GetNameByOffsetWide(topFrame[0].InstructionOffset, wszBuf, MAX_PATH, 0, 0); t->function = QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf)); ULONG ulLine; hr = cif.debugSymbols->GetLineByOffsetWide(topFrame[0].InstructionOffset, &ulLine, wszBuf, MAX_PATH, 0, 0); if (SUCCEEDED(hr)) { t->line = ulLine; // Just display base name t->file = QString::fromUtf16(reinterpret_cast<const ushort *>(wszBuf)); if (!t->file.isEmpty()) { const int slashPos = t->file.lastIndexOf(QLatin1Char('\\')); if (slashPos != -1) t->file.remove(0, slashPos + 1); } } return true; } static inline QString msgGetThreadsFailed(const QString &why) { return QString::fromLatin1("Unable to determine the thread information: %1").arg(why); } bool CdbStackTraceContext::getThreads(const CdbComInterfaces &cif, bool isStopped, QList<ThreadData> *threads, ULONG *currentThreadId, QString *errorMessage) { threads->clear(); ULONG threadCount; *currentThreadId = 0; HRESULT hr= cif.debugSystemObjects->GetNumberThreads(&threadCount); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("GetNumberThreads", hr)); return false; } // Get ids and index of current if (!threadCount) return true; hr = cif.debugSystemObjects->GetCurrentThreadId(currentThreadId); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("GetCurrentThreadId", hr)); return false; } QVector<ULONG> threadIds(threadCount); hr = cif.debugSystemObjects->GetThreadIdsByIndex(0, threadCount, &(*threadIds.begin()), 0); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("GetThreadIdsByIndex", hr)); return false; } for (ULONG i = 0; i < threadCount; i++) { ThreadData threadData(threadIds.at(i)); if (isStopped) { if (!getStoppedThreadState(cif, &threadData, errorMessage)) { qWarning("%s\n", qPrintable(*errorMessage)); errorMessage->clear(); } } threads->push_back(threadData); } // Restore thread id if (isStopped && threads->back().id != *currentThreadId) { hr = cif.debugSystemObjects->SetCurrentThreadId(*currentThreadId); if (FAILED(hr)) { *errorMessage= msgGetThreadsFailed(msgComFailed("SetCurrentThreadId", hr)); return false; } } return true; } } // namespace Internal } // namespace Debugger <|endoftext|>
<commit_before>#include "terminalpp/attribute.hpp" #include <iostream> namespace terminalpp { // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, low_colour const &col) { switch (col.value_) { default : // Fall-through case terminalpp::ansi::graphics::colour::default_ : out << "default"; break; case terminalpp::ansi::graphics::colour::black : out << "black"; break; case terminalpp::ansi::graphics::colour::red : out << "red"; break; case terminalpp::ansi::graphics::colour::green : out << "green"; break; case terminalpp::ansi::graphics::colour::yellow : out << "yellow"; break; case terminalpp::ansi::graphics::colour::blue : out << "blue"; break; case terminalpp::ansi::graphics::colour::magenta : out << "magenta"; break; case terminalpp::ansi::graphics::colour::cyan : out << "cyan"; break; case terminalpp::ansi::graphics::colour::white : out << "white"; break; } return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, high_colour const &col) { // Offset for normal ANSI colours. int const colour_value = col.value_ - 16; int const red_value = (colour_value / 36) % 6; int const green_value = (colour_value / 6) % 6; int const blue_value = colour_value % 6; out << "R:" << red_value << "," << "G:" << green_value << "," << "B:" << blue_value; return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, greyscale_colour const &col) { out << "grey:" << col.shade_ - 232; return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, colour const &col) { out << "colour["; switch (col.type_) { case colour::type::low : out << col.low_colour_; break; case colour::type::high : out << col.high_colour_; break; case colour::type::greyscale : out << col.greyscale_colour_; break; default : break; } out << "]"; return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, attribute const &attr) { out << "attr["; // TODO: add attributes. out << "]"; return out; } } <commit_msg>Completed debug output of attributes.<commit_after>#include "terminalpp/attribute.hpp" #include <iostream> namespace terminalpp { static const auto default_colour = low_colour(terminalpp::ansi::graphics::colour::default_); // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, low_colour const &col) { switch (col.value_) { default : // Fall-through case terminalpp::ansi::graphics::colour::default_ : out << "default"; break; case terminalpp::ansi::graphics::colour::black : out << "black"; break; case terminalpp::ansi::graphics::colour::red : out << "red"; break; case terminalpp::ansi::graphics::colour::green : out << "green"; break; case terminalpp::ansi::graphics::colour::yellow : out << "yellow"; break; case terminalpp::ansi::graphics::colour::blue : out << "blue"; break; case terminalpp::ansi::graphics::colour::magenta : out << "magenta"; break; case terminalpp::ansi::graphics::colour::cyan : out << "cyan"; break; case terminalpp::ansi::graphics::colour::white : out << "white"; break; } return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, high_colour const &col) { // Offset for normal ANSI colours. int const colour_value = col.value_ - 16; int const red_value = (colour_value / 36) % 6; int const green_value = (colour_value / 6) % 6; int const blue_value = colour_value % 6; out << "R:" << red_value << "," << "G:" << green_value << "," << "B:" << blue_value; return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, greyscale_colour const &col) { out << "grey:" << col.shade_ - 232; return out; } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, colour const &col) { out << "colour["; switch (col.type_) { case colour::type::low : out << col.low_colour_; break; case colour::type::high : out << col.high_colour_; break; case colour::type::greyscale : out << col.greyscale_colour_; break; default : break; } out << "]"; return out; } // ========================================================================== // APPEND_COMMA_IF_NECESSARY // ========================================================================== static void append_comma_if_necessary(std::ostream &out, bool necessary) { if (necessary) { out << ","; } } // ========================================================================== // APPEND_FOREGROUND_COLOUR // ========================================================================== static void append_foreground_colour( std::ostream &out, attribute const &attr, bool &comma) { if (attr.foreground_colour_ != default_colour) { append_comma_if_necessary(out, comma); out << "fg:" << attr.foreground_colour_; comma = true; } } // ========================================================================== // APPEND_BACKGROUND_COLOUR // ========================================================================== static void append_background_colour( std::ostream &out, attribute const &attr, bool &comma) { if (attr.background_colour_ != default_colour) { append_comma_if_necessary(out, comma); out << "fg:" << attr.background_colour_; comma = true; } } // ========================================================================== // APPEND_INTENSITY // ========================================================================== static void append_intensity( std::ostream &out, attribute const &attr, bool &comma) { static const auto default_intensity = terminalpp::ansi::graphics::intensity::normal; if (attr.intensity_ != default_intensity) { append_comma_if_necessary(out, comma); if (attr.intensity_ == ansi::graphics::intensity::bold) { out << "bold"; } else if (attr.intensity_ == ansi::graphics::intensity::faint) { out << "faint"; } comma = true; } } // ========================================================================== // APPEND_UNDERLINING // ========================================================================== static void append_underlining( std::ostream &out, attribute const &attr, bool &comma) { static const auto default_underlining = terminalpp::ansi::graphics::underlining::not_underlined; if (attr.underlining_ != default_underlining) { append_comma_if_necessary(out, comma); if (attr.underlining_ == ansi::graphics::underlining::underlined) { out << "underlined"; } comma = true; } } // ========================================================================== // APPEND_POLARITY // ========================================================================== static void append_polarity( std::ostream &out, attribute const &attr, bool &comma) { static const auto default_polarity = terminalpp::ansi::graphics::polarity::positive; if (attr.polarity_ != default_polarity) { append_comma_if_necessary(out, comma); if (attr.polarity_ == ansi::graphics::polarity::negative) { out << "inverse"; } comma = true; } } // ========================================================================== // APPEND_BLINKING // ========================================================================== static void append_blinking( std::ostream &out, attribute const &attr, bool &comma) { static const auto default_blinking = terminalpp::ansi::graphics::blinking::steady; if (attr.blinking_ != default_blinking) { append_comma_if_necessary(out, comma); if (attr.blinking_ == ansi::graphics::blinking::blink) { out << "blinking"; } comma = true; } } // ========================================================================== // STREAM OPERATOR // ========================================================================== std::ostream &operator<<(std::ostream &out, attribute const &attr) { bool comma = false; out << "attr["; append_foreground_colour(out, attr, comma); append_background_colour(out, attr, comma); append_intensity(out, attr, comma); append_underlining(out, attr, comma); append_polarity(out, attr, comma); append_blinking(out, attr, comma); out << "]"; return out; } } <|endoftext|>
<commit_before>/******************************************************************************* Copyright The University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellML support tests //============================================================================== #include "../../../../tests/src/testsutils.h" //============================================================================== #include "cellmlfile.h" #include "corecliutils.h" #include "tests.h" //============================================================================== #include <QtTest/QtTest> //============================================================================== void Tests::doRuntimeTest(const QString &pFileName, const QString &pCellmlVersion, const QStringList &pModelParameters) { // Get a CellML file object for the given CellML file and make sure that it // is considered of the expected CellML version OpenCOR::CellMLSupport::CellmlFile cellmlFile(pFileName); QCOMPARE(QString::fromStdWString(cellmlFile.model()->cellmlVersion()), pCellmlVersion); // Retrieve a runtime for our model and make sure that it is valid OpenCOR::CellMLSupport::CellmlFileRuntime *runtime = cellmlFile.runtime(); QVERIFY(runtime); QVERIFY(runtime->isValid()); // Retrieve the model parameters (i.e. the ones that would be shown in, say, // the Single Cell view) for our model and check that they contain the // information we would expect QStringList modelParameters = QStringList(); OpenCOR::CellMLSupport::CellmlFileRuntimeParameters parameters = runtime->parameters(); foreach (OpenCOR::CellMLSupport::CellmlFileRuntimeParameter *parameter, parameters) { modelParameters << QString("%1 (%2)").arg(parameter->fullyFormattedName()) .arg(parameter->formattedUnit(runtime->variableOfIntegration()->unit())); } QCOMPARE(modelParameters << QString(), pModelParameters); } //============================================================================== void Tests::runtimeTests() { // Run some runtime-related tests on the Noble 1962 model QStringList modelParameters = OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/noble_model_1962.out")); doRuntimeTest(OpenCOR::fileName("models/noble_model_1962.cellml"), "1.0", modelParameters); // Do the same as above but using the CellML 1.1 namespace // Note: the idea is to check that we are doing to retrieve the parameters // of a model is not dependent on the version of a CellML file... QString fileName = OpenCOR::Core::temporaryFileName(); QByteArray fileContents = OpenCOR::rawFileContents(OpenCOR::fileName("models/noble_model_1962.cellml")); fileContents.replace("cellml/1.0#", "cellml/1.1#"); QVERIFY(OpenCOR::Core::writeFileContentsToFile(fileName, fileContents)); doRuntimeTest(fileName, "1.1", modelParameters); // Finally, we do the same for some proper CellML 1.1 models: // - Hodgking-Huxley model, which is somewhat 'complex' in terms of // imports, etc.; // - An 'old' version of a bond graph model implementation where the // variable of integration is not visible in the main CellML file (so the // idea is to ensure that the model is still considered valid even though // the variable of integration is not directly visible); // - A 'new' version of a bond graph model implementation where the // variable of integration is now visible in the main CellML file (as // well as some other model parameters); and // - A model (Noble 1962) that imports its units (and no components) from a // child model. doRuntimeTest(OpenCOR::fileName("doc/developer/functionalTests/res/cellml/cellml_1_1/experiments/periodic-stimulus.xml"), "1.1", OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/periodic-stimulus.out"))); doRuntimeTest(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_old.cellml"), "1.1", OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_old.out"))); doRuntimeTest(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_new.cellml"), "1.1", OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_new.out"))); doRuntimeTest(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/units_import_only_parent_model.cellml"), "1.1", modelParameters); // Clean up after ourselves QFile::remove(fileName); } //============================================================================== QTEST_GUILESS_MAIN(Tests) //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Copyright The University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellML support tests //============================================================================== #include "../../../../tests/src/testsutils.h" //============================================================================== #include "cellmlfile.h" #include "corecliutils.h" #include "tests.h" //============================================================================== #include <QtTest/QtTest> //============================================================================== void Tests::doRuntimeTest(const QString &pFileName, const QString &pCellmlVersion, const QStringList &pModelParameters) { // Get a CellML file object for the given CellML file and make sure that it // is considered of the expected CellML version OpenCOR::CellMLSupport::CellmlFile cellmlFile(pFileName); QCOMPARE(QString::fromStdWString(cellmlFile.model()->cellmlVersion()), pCellmlVersion); // Retrieve a runtime for our model and make sure that it is valid OpenCOR::CellMLSupport::CellmlFileRuntime *runtime = cellmlFile.runtime(); QVERIFY(runtime); QVERIFY(runtime->isValid()); // Retrieve the model parameters (i.e. the ones that would be shown in, say, // the Single Cell view) for our model and check that they contain the // information we would expect QStringList modelParameters = QStringList(); OpenCOR::CellMLSupport::CellmlFileRuntimeParameters parameters = runtime->parameters(); foreach (OpenCOR::CellMLSupport::CellmlFileRuntimeParameter *parameter, parameters) { modelParameters << QString("%1 (%2)").arg(parameter->fullyFormattedName()) .arg(parameter->formattedUnit(runtime->variableOfIntegration()->unit())); } QCOMPARE(modelParameters << QString(), pModelParameters); } //============================================================================== void Tests::runtimeTests() { // Run some runtime-related tests on the Noble 1962 model QStringList modelParameters = OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/noble_model_1962.out")); doRuntimeTest(OpenCOR::fileName("models/noble_model_1962.cellml"), "1.0", modelParameters); // Do the same as above but using the CellML 1.1 namespace // Note: the idea is to check that we are doing to retrieve the parameters // of a model is not dependent on the version of a CellML file... QString fileName = OpenCOR::Core::temporaryFileName(); QByteArray fileContents = OpenCOR::rawFileContents(OpenCOR::fileName("models/noble_model_1962.cellml")); fileContents.replace("cellml/1.0#", "cellml/1.1#"); QVERIFY(OpenCOR::Core::writeFileContentsToFile(fileName, fileContents)); doRuntimeTest(fileName, "1.1", modelParameters); // Finally, we do the same for some proper CellML 1.1 models: // - Hodgking-Huxley model, which is somewhat 'complex' in terms of // imports, etc.; // - An 'old' version of a bond graph model implementation where the // variable of integration is not visible in the main CellML file (so the // idea is to ensure that the model is still considered valid even though // the variable of integration is not directly visible); // - A 'new' version of a bond graph model implementation where the // variable of integration is now visible in the main CellML file (as // well as some other model parameters); and // - A model (Noble 1962) that imports its units (and no components) from a // child model. doRuntimeTest(OpenCOR::fileName("doc/developer/functionalTests/res/cellml/cellml_1_1/experiments/periodic-stimulus.xml"), "1.1", OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/periodic-stimulus.out"))); doRuntimeTest(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_old.cellml"), "1.1", OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_old.out"))); doRuntimeTest(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_new.cellml"), "1.1", OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/bond_graph_model_new.out"))); doRuntimeTest(OpenCOR::fileName("src/plugins/support/CellMLSupport/tests/data/units_import_only_parent_model.cellml"), "1.1", modelParameters); // Clean up after ourselves QFile::remove(fileName); } //============================================================================== QTEST_GUILESS_MAIN(Tests) //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP #ifdef STAN_OPENCL #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation_cl.hpp> #include <stan/math/opencl/kernel_generator/as_operation_cl.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <stan/math/opencl/kernel_generator/common_return_scalar.hpp> #include <set> #include <string> #include <type_traits> #include <utility> namespace stan { namespace math { /** * Represents a selection operation in kernel generator expressions. This is * element wise ternary operator <code>condition ? then : els</code>, also * equivalent to Eigen's \c .select(). * @tparam Derived derived type * @tparam T_condition type of condition * @tparam T_then type of then expression * @tparam T_else type of else expression */ template <typename T_condition, typename T_then, typename T_else> class select_ : public operation_cl<select_<T_condition, T_then, T_else>, common_scalar_t<T_then, T_else>, T_condition, T_then, T_else> { public: using Scalar = common_scalar_t<T_then, T_else>; using base = operation_cl<select_<T_condition, T_then, T_else>, Scalar, T_condition, T_then, T_else>; using base::var_name; protected: using base::arguments_; public: /** * Constructor * @param condition condition expression * @param then then expression * @param els else expression */ select_(T_condition&& condition, T_then&& then, T_else&& els) // NOLINT : base(std::forward<T_condition>(condition), std::forward<T_then>(then), std::forward<T_else>(els)) { if (condition.rows() != base::dynamic && then.rows() != base::dynamic) { check_size_match("select", "Rows of ", "condition", condition.rows(), "rows of ", "then", then.rows()); } if (condition.cols() != base::dynamic && then.cols() != base::dynamic) { check_size_match("select", "Columns of ", "condition", condition.cols(), "columns of ", "then", then.cols()); } if (condition.rows() != base::dynamic && els.rows() != base::dynamic) { check_size_match("select", "Rows of ", "condition", condition.rows(), "rows of ", "else", els.rows()); } if (condition.cols() != base::dynamic && els.cols() != base::dynamic) { check_size_match("select", "Columns of ", "condition", condition.cols(), "columns of ", "else", els.cols()); } } /** * generates kernel code for this expression. * @param i row index variable name * @param j column index variable name * @param var_name_condition variable name of the condition expression * @param var_name_else variable name of the then expression * @param var_name_then variable name of the else expression * @return part of kernel with code for this expression */ inline kernel_parts generate(const std::string& i, const std::string& j, const std::string& var_name_condition, const std::string& var_name_then, const std::string& var_name_else) const { kernel_parts res{}; res.body = type_str<Scalar>() + " " + var_name + " = " + var_name_condition + " ? " + var_name_then + " : " + var_name_else + ";\n"; return res; } /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { matrix_cl_view condition_view = std::get<0>(arguments_).view(); matrix_cl_view then_view = std::get<1>(arguments_).view(); matrix_cl_view else_view = std::get<2>(arguments_).view(); return both(either(then_view, else_view), both(condition_view, then_view)); } }; /** * Selection operation on kernel generator expressions. This is element wise * ternary operator <code> condition ? then : els </code>. * @tparam T_condition type of condition expression * @tparam T_then type of then expression * @tparam T_else type of else expression * @param condition condition expression * @param then then expression * @param els else expression * @return selection operation expression */ template <typename T_condition, typename T_then, typename T_else, typename = require_all_valid_expressions_t<T_condition, T_then, T_else>> inline select_<as_operation_cl_t<T_condition>, as_operation_cl_t<T_then>, as_operation_cl_t<T_else>> select(T_condition&& condition, T_then&& then, T_else&& els) { // NOLINT return {as_operation_cl(std::forward<T_condition>(condition)), as_operation_cl(std::forward<T_then>(then)), as_operation_cl(std::forward<T_else>(els))}; } } // namespace math } // namespace stan #endif #endif <commit_msg>changed doc<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP #define STAN_MATH_OPENCL_KERNEL_GENERATOR_SELECT_HPP #ifdef STAN_OPENCL #include <stan/math/prim/meta.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/kernel_generator/type_str.hpp> #include <stan/math/opencl/kernel_generator/name_generator.hpp> #include <stan/math/opencl/kernel_generator/operation_cl.hpp> #include <stan/math/opencl/kernel_generator/as_operation_cl.hpp> #include <stan/math/opencl/kernel_generator/is_valid_expression.hpp> #include <stan/math/opencl/kernel_generator/common_return_scalar.hpp> #include <set> #include <string> #include <type_traits> #include <utility> namespace stan { namespace math { /** * Represents a selection operation in kernel generator expressions. This is * element wise ternary operator <code>condition ? then : els</code>, also * equivalent to Eigen's \c .select(). * @tparam Derived derived type * @tparam T_condition type of condition * @tparam T_then type of then expression * @tparam T_else type of else expression */ template <typename T_condition, typename T_then, typename T_else> class select_ : public operation_cl<select_<T_condition, T_then, T_else>, common_scalar_t<T_then, T_else>, T_condition, T_then, T_else> { public: using Scalar = common_scalar_t<T_then, T_else>; using base = operation_cl<select_<T_condition, T_then, T_else>, Scalar, T_condition, T_then, T_else>; using base::var_name; protected: using base::arguments_; public: /** * Constructor * @param condition condition expression * @param then then expression * @param els else expression */ select_(T_condition&& condition, T_then&& then, T_else&& els) // NOLINT : base(std::forward<T_condition>(condition), std::forward<T_then>(then), std::forward<T_else>(els)) { if (condition.rows() != base::dynamic && then.rows() != base::dynamic) { check_size_match("select", "Rows of ", "condition", condition.rows(), "rows of ", "then", then.rows()); } if (condition.cols() != base::dynamic && then.cols() != base::dynamic) { check_size_match("select", "Columns of ", "condition", condition.cols(), "columns of ", "then", then.cols()); } if (condition.rows() != base::dynamic && els.rows() != base::dynamic) { check_size_match("select", "Rows of ", "condition", condition.rows(), "rows of ", "else", els.rows()); } if (condition.cols() != base::dynamic && els.cols() != base::dynamic) { check_size_match("select", "Columns of ", "condition", condition.cols(), "columns of ", "else", els.cols()); } } /** * generates kernel code for this (select) operation. * @param i row index variable name * @param j column index variable name * @param var_name_condition variable name of the condition expression * @param var_name_else variable name of the then expression * @param var_name_then variable name of the else expression * @return part of kernel with code for this expression */ inline kernel_parts generate(const std::string& i, const std::string& j, const std::string& var_name_condition, const std::string& var_name_then, const std::string& var_name_else) const { kernel_parts res{}; res.body = type_str<Scalar>() + " " + var_name + " = " + var_name_condition + " ? " + var_name_then + " : " + var_name_else + ";\n"; return res; } /** * View of a matrix that would be the result of evaluating this expression. * @return view */ inline matrix_cl_view view() const { matrix_cl_view condition_view = std::get<0>(arguments_).view(); matrix_cl_view then_view = std::get<1>(arguments_).view(); matrix_cl_view else_view = std::get<2>(arguments_).view(); return both(either(then_view, else_view), both(condition_view, then_view)); } }; /** * Selection operation on kernel generator expressions. This is element wise * ternary operator <code> condition ? then : els </code>. * @tparam T_condition type of condition expression * @tparam T_then type of then expression * @tparam T_else type of else expression * @param condition condition expression * @param then then expression * @param els else expression * @return selection operation expression */ template <typename T_condition, typename T_then, typename T_else, typename = require_all_valid_expressions_t<T_condition, T_then, T_else>> inline select_<as_operation_cl_t<T_condition>, as_operation_cl_t<T_then>, as_operation_cl_t<T_else>> select(T_condition&& condition, T_then&& then, T_else&& els) { // NOLINT return {as_operation_cl(std::forward<T_condition>(condition)), as_operation_cl(std::forward<T_then>(then)), as_operation_cl(std::forward<T_else>(els))}; } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>/// JSON encoding and decoding // Encoding Lua tables to JSON strings, and decoding JSON strings to Lua tables. // @module json #include "JSON.h" #include <Poco/JSON/Parser.h> #include <Poco/JSON/Handler.h> #include <Poco/JSON/JSONException.h> #include <Poco/SharedPtr.h> #include "Userdata.h" #include "LuaPocoUtils.h" int luaopen_poco_json(lua_State* L) { struct LuaPoco::UserdataMethod methods[] = { { "encode", LuaPoco::JSON::encode }, { "decode", LuaPoco::JSON::decode }, { "emptyObject", LuaPoco::JSON::getEmptyObject }, { "emptyArray", LuaPoco::JSON::getEmptyArray }, { NULL, NULL} }; lua_createtable(L, 0, 2); setMetatableFunctions(L, methods); return 1; } namespace LuaPoco { char jsonNull[] = "Poco.JSON.null"; char jsonEmptyArray[] = "Poco.JSON.Empty.Array"; char jsonEmptyObject[] = "Poco.JSON.Empty.Object"; struct TableInfo { enum TableType { object, array} tableType; size_t currentArrayIndex; int tableStackIndex; }; class LuaHandler : public Poco::JSON::Handler { public: LuaHandler(lua_State* L) : mState(L), mBaseTop(lua_gettop(L)) {} virtual ~LuaHandler() {} virtual void reset() { lua_settop(mState, mBaseTop); } virtual void startObject() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endObject() { mTableQueue.pop_back(); setValue(); } virtual void startArray() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::array, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endArray() { mTableQueue.pop_back(); setValue(); } virtual void key(const std::string& k) { // leave the key on the stack such that on a value, setValue is called to pop both off. lua_pushlstring(mState, k.c_str(), k.size()); } virtual void null() { // use sentinel value jsonNull lua_pushlightuserdata(mState, static_cast<void*>(jsonNull)); setValue(); } // based on the poco code, int and unsigned are pure virtual functions, but will never be // called as ParserImpl only uses Int64s for whatever reason. this will make them work // regardless, if for some reason they're turned on in the future. virtual void value(int v) { lua_Integer i = 0; if (checkSignedToLuaInteger<int>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(unsigned v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<unsigned>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #if defined(POCO_HAVE_INT64) virtual void value(Poco::Int64 v) { lua_Integer i = 0; if (checkSignedToLuaInteger<Poco::Int64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(Poco::UInt64 v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<Poco::UInt64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #endif virtual void value(const std::string& s) { lua_pushlstring(mState, s.c_str(), s.size()); setValue(); } virtual void value(double d) { lua_pushnumber(mState, static_cast<lua_Number>(d)); setValue(); } virtual void value(bool b) { lua_pushboolean(mState, static_cast<int>(b)); setValue(); } private: // utility functions void setValue() { if (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { ++ti.currentArrayIndex; lua_rawseti(mState, ti.tableStackIndex, ti.currentArrayIndex); } else { const char *tn = lua_typename(mState, lua_type(mState, -1)); lua_rawset(mState, ti.tableStackIndex); } } else { // the last value is a table that should be left behind and returned. if (lua_type(mState, -1) != LUA_TTABLE) throw Poco::JSON::JSONException("attempt to set a value when no objects present"); } } lua_State* mState; int mBaseTop; std::vector<TableInfo> mTableQueue; }; /// encodes a table into a JSON string. // @table table to encode // @return value as string or nil. (error) // @return error message. // @function encode int JSON::encode(lua_State* L) { int rv = 0; try { rv = 1; } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// decodes a JSON string into a table. // @string JSON encoded string // @return table or nil. (error) // @return error message. // @function decode int JSON::decode(lua_State* L) { int rv = 0; const char* jss = luaL_checkstring(L, 1); try { Poco::SharedPtr<LuaHandler> lh(new LuaHandler(L)); Poco::JSON::Parser jsonParser(lh); jsonParser.parse(jss); rv = 1; } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// returns the 'null' sentinel value as a lightuserdata. // @return lightuserdata // @function null int JSON::getNull(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonNull)); return 1; } /// returns the 'emptyObject' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyObject int JSON::getEmptyObject(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyObject)); return 1; } /// returns the 'emptyArray' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyArray int JSON::getEmptyArray(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyArray)); return 1; } } // LuaPoco <commit_msg>add completed JSON encoding.<commit_after>/// JSON encoding and decoding // Encoding Lua tables to JSON strings, and decoding JSON strings to Lua tables. // @module json #include "JSON.h" #include <Poco/JSON/Parser.h> #include <Poco/JSON/Handler.h> #include <Poco/JSON/PrintHandler.h> #include <Poco/JSON/JSONException.h> #include <Poco/JSONString.h> #include <Poco/SharedPtr.h> #include "Userdata.h" #include "LuaPocoUtils.h" int luaopen_poco_json(lua_State* L) { struct LuaPoco::UserdataMethod methods[] = { { "encode", LuaPoco::JSON::encode }, { "decode", LuaPoco::JSON::decode }, { "null", LuaPoco::JSON::getNull }, { "emptyObject", LuaPoco::JSON::getEmptyObject }, { "emptyArray", LuaPoco::JSON::getEmptyArray }, { NULL, NULL} }; lua_createtable(L, 0, 2); setMetatableFunctions(L, methods); return 1; } namespace LuaPoco { char jsonNull[] = "Poco.JSON.null"; char jsonEmptyArray[] = "Poco.JSON.Empty.Array"; char jsonEmptyObject[] = "Poco.JSON.Empty.Object"; struct TableInfo { enum TableType { object, array} tableType; size_t currentArrayIndex; int tableStackIndex; }; class LuaHandler : public Poco::JSON::Handler { public: LuaHandler(lua_State* L) : mState(L), mBaseTop(lua_gettop(L)) {} virtual ~LuaHandler() {} virtual void reset() { lua_settop(mState, mBaseTop); } virtual void startObject() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endObject() { mTableQueue.pop_back(); setValue(); } virtual void startArray() { lua_newtable(mState); TableInfo ti = { TableInfo::TableType::array, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); } virtual void endArray() { mTableQueue.pop_back(); setValue(); } virtual void key(const std::string& k) { // leave the key on the stack such that on a value, setValue is called to pop both off. lua_pushlstring(mState, k.c_str(), k.size()); } virtual void null() { // use sentinel value jsonNull lua_pushlightuserdata(mState, static_cast<void*>(jsonNull)); setValue(); } // based on the poco code, int and unsigned are pure virtual functions, but will never be // called as ParserImpl only uses Int64s for whatever reason. including for completeness. virtual void value(int v) { lua_Integer i = 0; if (checkSignedToLuaInteger<int>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(unsigned v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<unsigned>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #if defined(POCO_HAVE_INT64) virtual void value(Poco::Int64 v) { lua_Integer i = 0; if (checkSignedToLuaInteger<Poco::Int64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } virtual void value(Poco::UInt64 v) { lua_Integer i = 0; if (checkUnsignedToLuaInteger<Poco::UInt64>(v, i)) { lua_pushinteger(mState, static_cast<lua_Integer>(i)); setValue(); } else throw Poco::JSON::JSONException("out of range number"); } #endif virtual void value(const std::string& s) { lua_pushlstring(mState, s.c_str(), s.size()); setValue(); } virtual void value(double d) { lua_pushnumber(mState, static_cast<lua_Number>(d)); setValue(); } virtual void value(bool b) { lua_pushboolean(mState, static_cast<int>(b)); setValue(); } private: // utility functions void setValue() { if (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { ++ti.currentArrayIndex; lua_rawseti(mState, ti.tableStackIndex, ti.currentArrayIndex); } else { const char *tn = lua_typename(mState, lua_type(mState, -1)); lua_rawset(mState, ti.tableStackIndex); } } else { // the last value is a table that should be left behind and returned. if (lua_type(mState, -1) != LUA_TTABLE) throw Poco::JSON::JSONException("attempt to set a value when no objects present"); } } lua_State* mState; int mBaseTop; std::vector<TableInfo> mTableQueue; }; class TableEncoder { public: TableEncoder(lua_State* L, unsigned indent) : mState(L), mStream(), mPrintHandler(mStream, indent) {} ~TableEncoder() {} bool encode() { handleTable(); while (mTableQueue.size() > 0) { TableInfo& ti = mTableQueue.back(); if (ti.tableType == TableInfo::TableType::array) { lua_rawgeti(mState, ti.tableStackIndex, ++ti.currentArrayIndex); if (!lua_isnil(mState, -1)) { handleValue(); } else { // pop nil, array lua_pop(mState, 2); mTableQueue.pop_back(); mPrintHandler.endArray(); } } else { // handleTable() leaves nil on the stack to for the nested table iteration. if (lua_next(mState, ti.tableStackIndex)) { if (lua_isstring(mState, -2)) { const char* key = lua_tostring(mState, -2); mPrintHandler.key(key); handleValue(); } else throw Poco::JSON::JSONException("encountered key value that is not a string."); } else { // done with object, pop it. lua_pop(mState, 1); mTableQueue.pop_back(); mPrintHandler.endObject(); } } } std::string jsonString = mStream.str(); lua_pushlstring(mState, jsonString.c_str(), jsonString.size()); // return all pending tables were processed return mTableQueue.empty(); } private: // arrays are defined as tables that operate as sequences from 1 to n with [n + 1] == nil to terminate. // objects are defined as not having an array part, and only string keys being present. bool isArray(int index) { lua_rawgeti(mState, index, 1); bool result = !lua_isnil(mState, -1); lua_pop(mState, 1); return result; } void handleTable() { // store table information in mQueue. TableInfo ti = { isArray(-1) ? TableInfo::TableType::array : TableInfo::TableType::object, 0, lua_gettop(mState) }; mTableQueue.push_back(ti); // leave key on the top of the stack so the loop can process it with calls to lua_next. // inform printer of the start of a new object/array. if (ti.tableType == TableInfo::TableType::object) { mPrintHandler.startObject(); lua_pushnil(mState); } else { mPrintHandler.startArray(); } } void handleValue() { int type = lua_type(mState, -1); switch (type) { case LUA_TNIL: throw Poco::JSON::JSONException("nil is an invalid value, use json.null"); break; case LUA_TNUMBER: #if LUA_VERSION_NUM > 502 if (lua_isinteger(mState, -1)) { lua_Integer i = lua_tointeger(mState, -1); mPrintHandler.value(i); } else #endif { lua_Number n = lua_tonumber(mState, -1); mPrintHandler.value(n); } break; case LUA_TBOOLEAN: { bool b = static_cast<bool>(lua_toboolean(mState, -1)); mPrintHandler.value(b); break; } case LUA_TSTRING: { const std::string str = lua_tostring(mState, -1); mPrintHandler.value(str); break; } case LUA_TTABLE: handleTable(); // the table value must stay on the top of the stack in order to be iterated by // encode loop. when the end of the table is encountered, it is popped. // returning here avoids the pop that is needed for all other values. return; break; case LUA_TFUNCTION: throw Poco::JSON::JSONException("function type invalid for json."); break; case LUA_TUSERDATA: throw Poco::JSON::JSONException("userdata type invalid for json."); break; case LUA_TTHREAD: throw Poco::JSON::JSONException("thread type invalid for json."); break; case LUA_TLIGHTUSERDATA: { const char *lud = static_cast<const char*>(lua_touserdata(mState, -1)); if (lud == jsonNull) { mPrintHandler.null(); } else if (lud == jsonEmptyArray) { mPrintHandler.startArray(); mPrintHandler.endArray(); } else if (lud == jsonEmptyObject) { mPrintHandler.startObject(); mPrintHandler.endObject(); } else throw Poco::JSON::JSONException("unknown json lightuserdata value."); break; } default: throw Poco::JSON::JSONException("unknown value for json conversion."); break; } // all values except for table needs to be popped. // the table case returns early to avoid this pop. lua_pop(mState, 1); } lua_State* mState; std::stringstream mStream; Poco::JSON::PrintHandler mPrintHandler; std::vector<TableInfo> mTableQueue; }; /// encodes a table into a JSON string. // @table table to encode // @return value as string or nil. (error) // @return error message. // @function encode int JSON::encode(lua_State* L) { int rv = 0; unsigned indent = 0; luaL_checktype(L, 1, LUA_TTABLE); if (lua_isinteger(L, 2)) { indent = static_cast<unsigned>(lua_tointeger(L, 2)); } // TableEncoder expects the table it is encoding at the top of the stack. lua_pushvalue(L, 1); try { TableEncoder te(L, indent); // either a string is returned at the top of the stack // or nil, errmsg if (te.encode()) { rv = 1; } else { rv = 2; } } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// decodes a JSON string into a table. // @string JSON encoded string // @return table or nil. (error) // @return error message. // @function decode int JSON::decode(lua_State* L) { int rv = 0; const char* jss = luaL_checkstring(L, 1); try { Poco::SharedPtr<LuaHandler> lh(new LuaHandler(L)); Poco::JSON::Parser jsonParser(lh); jsonParser.parse(jss); rv = 1; } catch (const Poco::Exception& e) { rv = pushPocoException(L, e); } catch (...) { rv = pushUnknownException(L); } return rv; } /// returns the 'null' sentinel value as a lightuserdata. // @return lightuserdata // @function null int JSON::getNull(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonNull)); return 1; } /// returns the 'emptyObject' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyObject int JSON::getEmptyObject(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyObject)); return 1; } /// returns the 'emptyArray' sentinel value as a lightuserdata. // @return lightuserdata // @function emptyArray int JSON::getEmptyArray(lua_State* L) { lua_pushlightuserdata(L, static_cast<void*>(jsonEmptyArray)); return 1; } } // LuaPoco <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" #include "cpp_utils/algorithm.hpp" // Trigonometric tests TEMPLATE_TEST_CASE_2("trigo/tan/1", "[trigo][tan]", Z, double, float) { etl::dyn_matrix<Z> a(3, 3, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1, 1.0, -0.5, 0.5)); etl::dyn_matrix<Z> b; b = etl::tan(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::tan(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/tan/2", "[trigo][tan]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tan(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::tan(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::tan(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/tan/3", "[trigo][tan]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tan(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::tan(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::tan(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/sin/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::sin(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::sin(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/sin/2", "[trigo][sin]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sin(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::sin(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::sin(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/sin/3", "[trigo][sin]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sin(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::sin(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::sin(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/cos/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::cos(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::cos(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/cos/2", "[trigo][cos]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cos(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::cos(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::cos(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/cos/3", "[trigo][cos]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cos(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::cos(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::cos(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/tanh/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::tanh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::tanh(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/tanh/2", "[trigo][tanh]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tanh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::tanh(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::tanh(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/tanh/3", "[trigo][tanh]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tanh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::tanh(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::tanh(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/sinh/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::sinh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::sinh(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/sinh/2", "[trigo][sinh]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sinh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::sinh(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::sinh(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/sinh/3", "[trigo][sinh]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sinh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::sinh(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::sinh(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/cosh/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::cosh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::cosh(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/cosh/2", "[trigo][cosh]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cosh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::cosh(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::cosh(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/cosh/3", "[trigo][cosh]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cosh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::cosh(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::cosh(a[i]).imag); } } <commit_msg>Improve trigonometric tests<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test_light.hpp" #include "cpp_utils/algorithm.hpp" // Trigonometric tests TEMPLATE_TEST_CASE_2("trigo/tan/1", "[trigo][tan]", Z, double, float) { etl::dyn_matrix<Z> a(3, 3, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1, 1.0, -0.5, 0.5)); etl::dyn_matrix<Z> b; b = etl::tan(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::tan(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/tan/2", "[trigo][tan]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tan(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::tan(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::tan(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/tan/3", "[trigo][tan]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tan(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::tan(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::tan(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/sin/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::sin(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::sin(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/sin/2", "[trigo][sin]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sin(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::sin(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::sin(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/sin/3", "[trigo][sin]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sin(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::sin(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::sin(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/cos/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 2, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1)); etl::dyn_matrix<Z> b; b = etl::cos(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::cos(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/cos/2", "[trigo][cos]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cos(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::cos(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::cos(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/cos/3", "[trigo][cos]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cos(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::cos(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::cos(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/tanh/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 3, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1, 0.2, 0.3, -0.2)); etl::dyn_matrix<Z> b; b = etl::tanh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::tanh(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/tanh/2", "[trigo][tanh]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tanh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::tanh(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::tanh(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/tanh/3", "[trigo][tanh]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::tanh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::tanh(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::tanh(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/sinh/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 3, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1, 0.2, 0.3, -0.2)); etl::dyn_matrix<Z> b; b = etl::sinh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::sinh(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/sinh/2", "[trigo][sinh]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sinh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::sinh(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::sinh(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/sinh/3", "[trigo][sinh]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::sinh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::sinh(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::sinh(a[i]).imag); } } TEMPLATE_TEST_CASE_2("trigo/cosh/1", "dyn_matrix::dyn_matrix(T)", Z, double, float) { etl::dyn_matrix<Z> a(3, 3, etl::values(1.0, 2.0, -1.0, -0.5, 0.6, 0.1, 0.2, 0.3, -0.1)); etl::dyn_matrix<Z> b; b = etl::cosh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i], std::cosh(a[i])); } } TEMPLATE_TEST_CASE_2("trigo/cosh/2", "[trigo][cosh]", Z, std::complex<float>, std::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cosh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real(), std::cosh(a[i]).real()); REQUIRE_EQUALS_APPROX(b[i].imag(), std::cosh(a[i]).imag()); } } TEMPLATE_TEST_CASE_2("trigo/cosh/3", "[trigo][cosh]", Z, etl::complex<float>, etl::complex<double>) { etl::dyn_matrix<Z> a(3, 2, etl::values(Z(1.0, 0.1), Z(2.0, 0.1), Z(-1.0, 0.2), Z(-0.5, 1.0), Z(0.6, 1.0), Z(0.1, 0.4))); etl::dyn_matrix<Z> b; b = etl::cosh(a); for (size_t i = 0; i < b.size(); ++i) { REQUIRE_EQUALS_APPROX(b[i].real, etl::cosh(a[i]).real); REQUIRE_EQUALS_APPROX(b[i].imag, etl::cosh(a[i]).imag); } } <|endoftext|>
<commit_before>#include <RcppArmadillo.h> using namespace Rcpp; using namespace arma; //' @title Compute Tau-Overlap Allan Variance //' @description Computation of Tau-Overlap Allan Variance //' @usage avarto_arma(x) //' @param x A \code{vector} with dimensions N x 1. //' @return av A \code{list} that contains: //' \itemize{ //' \item{"clusters"}{The size of the cluster} //' \item{"allan"}{The allan variance} //' \item{"errors"}{The error associated with the variance calculation.} //' } //' @details //' Given \eqn{N} equally spaced samples with averaging time \eqn{\tau = n\tau _0}{tau = n*tau_0}, //' where \eqn{n} is an integer such that \eqn{ 1 \le n \le \frac{N}{2}}{1<= n <= N/2}. //' Therefore, \eqn{n} is able to be selected from \eqn{\left\{ {n|n < \left\lfloor {{{\log }_2}\left( N \right)} \right\rfloor } \right\}}{{n|n< floor(log2(N))}} //' Then, a sampling of \eqn{m = \left\lfloor {\frac{{N - 1}}{n}} \right\rfloor - 1} samples exist. //' The tau-overlap estimator is given as: //' //' where \eqn{ {{\bar y}_t}\left( \tau \right) = \frac{1}{\tau }\sum\limits_{i = 0}^{\tau - 1} {{{\bar y}_{t - i}}} }. //' //' @author JJB //' @references Recipes for Degrees of Freedom of Frequency Stability Estimators, Charles A. Greenhall //' @examples //' set.seed(999) //' # Simulate white noise (P 1) with sigma^2 = 4 //' N = 100000 //' white.noise = rnorm(N, 0, 2) //' #plot(white.noise,ylab="Simulated white noise process",xlab="Time",type="o") //' #Simulate random walk (P 4) //' random.walk = cumsum(0.1*rnorm(N, 0, 2)) //' combined.ts = white.noise+random.walk //' av_mat = avar_to_arma(combined.ts) // [[Rcpp::export]] Rcpp::List avar_to_arma(arma::vec x) { // Length of vector unsigned int T = x.n_elem; // Create the number of halves possible and use it to find the number of clusters unsigned int J = floor(log10(T)/log10(2))-1; // Allan Variance Matrix arma::mat av = arma::zeros<arma::mat>(J,3); for (unsigned int i = 1; i <= J; i++){ // Tau unsigned int tau = pow(2,i); // Y.Bar unsigned int N = floor(T/tau); arma::vec yBar = arma::zeros<arma::vec>(N); for(unsigned int j = 0; j < N;j++){ yBar(j) = sum( x.rows(tau*j, tau*j+tau - 1) )/tau; } // Clusters unsigned int M = floor(T/(2*tau) ); double summed = 0; for(unsigned int k = 0; k < M; k++){ summed += pow(yBar(2*k+1) - yBar(2*k),2); } // Cluster size av(i-1,0) = tau; // Compute the Allan Variance estimate av(i-1,1) = summed/(2*M); // Compute Error av(i-1,2) = 1/sqrt(2*( (double(T)/tau) - 1) ); } // Prep export arma::vec clusters = av.col(0); arma::vec allan = av.col(1); arma::vec errors = av.col(2); // Return as list return Rcpp::List::create( Rcpp::Named("clusters", clusters), Rcpp::Named("allan", allan), Rcpp::Named("errors", errors) ); } /* # Nonoverlapped estimator given in (4) avar = function(y){ N = length(y) J = floor(log2(length(y))) - 1 av = rep(NA,J) for (i in 1:J){ tau = 2^i yBar = y.bar(y,tau) M = floor( N/(2*tau) ) print(paste("Value of M:", M)) summed = rep(NA,M) for (k in 1:M){ summed[k] = (yBar[(2*k)] - yBar[(2*k - 1)])^2 } av[i] = sum(summed)/(2*M) } return(av) } y.bar = function(y,tau){ N = floor(length(y)/tau) yBar = rep(NA,N) for (i in 1:N){ index = (1:tau)+(i-1)*tau yBar[i] = mean(y[index]) } return(yBar) } # Maximal-overlap estimator given in (5) avar2 = function(y){ N = length(y) J = floor(log2(N)) - 1 av = rep(NA,J) for (i in 1:J){ tau = 2^i yBar = y.bar2(y,tau) M = (N-2*tau) summed = rep(NA,M) print(paste("Value of M:", M)) for (k in 1:M){ summed[k] = (yBar[k] - yBar[(k+tau)])^2 } av[i] = sum(summed)/(2*(N - 2*tau + 1)) } return(av) } y.bar2 = function(y,tau){ N = length(y) yBar = rep(NA,N) for (i in 1:N){ index = (1:tau)+(i-1) yBar[i] = mean(y[index]) } return(yBar) } */ //' @title Compute Maximal-Overlap Allan Variance using Means //' @description Computation of Maximal-Overlap Allan Varianc e //' @usage avar_mo_arma(x) //' @param x A \code{vector} with dimensions N x 1. //' @return av A \code{list} that contains: //' \itemize{ //' \item{"clusters"}{The size of the cluster} //' \item{"allan"}{The allan variance} //' \item{"errors"}{The error associated with the variance calculation.} //' } //' @details //' Given \eqn{N} equally spaced samples with averaging time \eqn{\tau = n\tau _0}{tau = n*tau_0}, //' where \eqn{n} is an integer such that \eqn{ 1 \le n \le \frac{N}{2}}{1<= n <= N/2}. //' Therefore, \eqn{n} is able to be selected from \eqn{\left\{ {n|n < \left\lfloor {{{\log }_2}\left( N \right)} \right\rfloor } \right\}}{{n|n< floor(log2(N))}} //' Then, \eqn{M = N - 2n} samples exist. //' The Maximal-overlap estimator is given as: //' \eqn{\frac{1}{{2\left( {N - 2k + 1} \right)}}\sum\limits_{t = 2k}^N {{{\left[ {{{\bar Y}_t}\left( k \right) - {{\bar Y}_{t - k}}\left( k \right)} \right]}^2}} } //' //' @author JJB //' @references Recipes for Degrees of Freedom of Frequency Stability Estimators, Charles A. Greenhall //' @examples //' set.seed(999) //' # Simulate white noise (P 1) with sigma^2 = 4 //' N = 100000 //' white.noise = rnorm(N, 0, 2) //' #plot(white.noise,ylab="Simulated white noise process",xlab="Time",type="o") //' #Simulate random walk (P 4) //' random.walk = cumsum(0.1*rnorm(N, 0, 2)) //' combined.ts = white.noise+random.walk //' av_mat = avar_to_arma(combined.ts) // [[Rcpp::export]] Rcpp::List avar_mo_arma(arma::vec x) { // Length of vector unsigned int T = x.n_elem; // Create the number of halves possible and use it to find the number of clusters unsigned int J = floor(log10(T)/log10(2))-1; // Allan Variance Matrix arma::mat av = arma::zeros<arma::mat>(J,3); for (unsigned int i = 1; i <= J; i++){ // Tau unsigned int tau = pow(2,i); // Y.Bar arma::vec yBar = arma::zeros<arma::vec>(T); for(unsigned int j = 0; j <= T-tau; j++){ yBar(j) = sum( x.rows(j, tau+j -1) ) / tau; } // Clusters unsigned int M = T-2*tau; double summed = 0; for(unsigned int k = 0; k < M; k++){ summed += pow(yBar(k) - yBar(k+tau),2); } // Cluster size av(i-1,0) = tau; // Compute the Allan Variance estimate av(i-1,1) = summed/(2*(T - 2*tau + 1)); // Compute Error av(i-1,2) = 1/sqrt(2*( (double(T)/tau) - 1) ); } // Prep export arma::vec clusters = av.col(0); arma::vec allan = av.col(1); arma::vec errors = av.col(2); // Return as list return Rcpp::List::create( Rcpp::Named("clusters", clusters), Rcpp::Named("allan", allan), Rcpp::Named("errors", errors) ); }<commit_msg>Cleaned it up and added documentation.<commit_after>#include <RcppArmadillo.h> using namespace Rcpp; using namespace arma; //' @title Compute Tau-Overlap Allan Variance //' @description Computation of Tau-Overlap Allan Variance //' @usage avarto_arma(x) //' @param x A \code{vector} with dimensions N x 1. //' @return av A \code{list} that contains: //' \itemize{ //' \item{"clusters"}{The size of the cluster} //' \item{"allan"}{The allan variance} //' \item{"errors"}{The error associated with the variance calculation.} //' } //' @details //' Given \eqn{N} equally spaced samples with averaging time \eqn{\tau = n\tau _0}{tau = n*tau_0}, //' where \eqn{n} is an integer such that \eqn{ 1 \le n \le \frac{N}{2}}{1<= n <= N/2}. //' Therefore, \eqn{n} is able to be selected from \eqn{\left\{ {n|n < \left\lfloor {{{\log }_2}\left( N \right)} \right\rfloor } \right\}}{{n|n< floor(log2(N))}} //' Then, a sampling of \eqn{m = \left\lfloor {\frac{{N - 1}}{n}} \right\rfloor - 1} samples exist. //' The tau-overlap estimator is given as: //' //' where \eqn{ {{\bar y}_t}\left( \tau \right) = \frac{1}{\tau }\sum\limits_{i = 0}^{\tau - 1} {{{\bar y}_{t - i}}} }. //' //' @author JJB //' @references Long-Memory Processes, the Allan Variance and Wavelets, D. B. Percival and P. Guttorp //' @examples //' set.seed(999) //' # Simulate white noise (P 1) with sigma^2 = 4 //' N = 100000 //' white.noise = rnorm(N, 0, 2) //' #plot(white.noise,ylab="Simulated white noise process",xlab="Time",type="o") //' #Simulate random walk (P 4) //' random.walk = cumsum(0.1*rnorm(N, 0, 2)) //' combined.ts = white.noise+random.walk //' av_mat = avar_to_arma(combined.ts) // [[Rcpp::export]] Rcpp::List avar_to_arma(arma::vec x) { // Length of vector unsigned int T = x.n_elem; // Create the number of halves possible and use it to find the number of clusters unsigned int J = floor(log10(T)/log10(2))-1; // Allan Variance Matrix arma::mat av = arma::zeros<arma::mat>(J,3); for (unsigned int i = 1; i <= J; i++){ // Tau unsigned int tau = pow(2,i); // Y.Bar unsigned int N = floor(T/tau); arma::vec yBar = arma::zeros<arma::vec>(N); for(unsigned int j = 0; j < N;j++){ yBar(j) = sum( x.rows(tau*j, tau*j+tau - 1) )/tau; } // Clusters unsigned int M = floor(T/(2*tau) ); double summed = 0; for(unsigned int k = 0; k < M; k++){ summed += pow(yBar(2*k+1) - yBar(2*k),2); } // Cluster size av(i-1,0) = tau; // Compute the Allan Variance estimate av(i-1,1) = summed/(2*M); // Compute Error av(i-1,2) = 1/sqrt(2*( (double(T)/tau) - 1) ); } // Prep export arma::vec clusters = av.col(0); arma::vec allan = av.col(1); arma::vec errors = av.col(2); // Return as list return Rcpp::List::create( Rcpp::Named("clusters", clusters), Rcpp::Named("allan", allan), Rcpp::Named("errors", errors) ); } //' @title Compute Maximal-Overlap Allan Variance using Means //' @description Computation of Maximal-Overlap Allan Variance //' @usage avar_mo_arma(x) //' @param x A \code{vector} with dimensions N x 1. //' @return av A \code{list} that contains: //' \itemize{ //' \item{"clusters"}{The size of the cluster} //' \item{"allan"}{The allan variance} //' \item{"errors"}{The error associated with the variance calculation.} //' } //' @details //' Given \eqn{N} equally spaced samples with averaging time \eqn{\tau = n\tau _0}{tau = n*tau_0}, //' where \eqn{n} is an integer such that \eqn{ 1 \le n \le \frac{N}{2}}{1<= n <= N/2}. //' Therefore, \eqn{n} is able to be selected from \eqn{\left\{ {n|n < \left\lfloor {{{\log }_2}\left( N \right)} \right\rfloor } \right\}}{{n|n< floor(log2(N))}} //' Then, \eqn{M = N - 2n} samples exist. //' The Maximal-overlap estimator is given as: //' \eqn{\frac{1}{{2\left( {N - 2k + 1} \right)}}\sum\limits_{t = 2k}^N {{{\left[ {{{\bar Y}_t}\left( k \right) - {{\bar Y}_{t - k}}\left( k \right)} \right]}^2}} } //' //' where \eqn{ {{\bar y}_t}\left( \tau \right) = \frac{1}{\tau }\sum\limits_{i = 0}^{\tau - 1} {{{\bar y}_{t - i}}} }. //' @author JJB //' @references Long-Memory Processes, the Allan Variance and Wavelets, D. B. Percival and P. Guttorp //' @examples //' set.seed(999) //' # Simulate white noise (P 1) with sigma^2 = 4 //' N = 100000 //' white.noise = rnorm(N, 0, 2) //' #plot(white.noise,ylab="Simulated white noise process",xlab="Time",type="o") //' #Simulate random walk (P 4) //' random.walk = cumsum(0.1*rnorm(N, 0, 2)) //' combined.ts = white.noise+random.walk //' av_mat = avar_mo_arma(combined.ts) // [[Rcpp::export]] Rcpp::List avar_mo_arma(arma::vec x) { // Length of vector unsigned int T = x.n_elem; // Create the number of halves possible and use it to find the number of clusters unsigned int J = floor(log10(T)/log10(2))-1; // Allan Variance Matrix arma::mat av = arma::zeros<arma::mat>(J,3); for (unsigned int i = 1; i <= J; i++){ // Tau unsigned int tau = pow(2,i); // Y.Bar arma::vec yBar = arma::zeros<arma::vec>(T); for(unsigned int j = 0; j <= T-tau; j++){ yBar(j) = sum( x.rows(j, tau+j -1) ) / tau; } // Clusters unsigned int M = T-2*tau; double summed = 0; for(unsigned int k = 0; k < M; k++){ summed += pow(yBar(k) - yBar(k+tau),2); } // Cluster size av(i-1,0) = tau; // Compute the Allan Variance estimate av(i-1,1) = summed/(2*(T - 2*tau + 1)); // Compute Error av(i-1,2) = 1/sqrt(2*( (double(T)/tau) - 1) ); } // Prep export arma::vec clusters = av.col(0); arma::vec allan = av.col(1); arma::vec errors = av.col(2); // Return as list return Rcpp::List::create( Rcpp::Named("clusters", clusters), Rcpp::Named("allan", allan), Rcpp::Named("errors", errors) ); }<|endoftext|>
<commit_before>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2017, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "ContentTypes.h" using namespace std; using namespace cb; using namespace cb::HTTP; ContentTypes::ContentTypes(Inaccessible) { insert(value_type("png", "image/png")); insert(value_type("jpg", "image/jpeg")); insert(value_type("jpeg", "image/jpeg")); insert(value_type("gif", "image/gif")); insert(value_type("ico", "image/x-icon")); insert(value_type("css", "text/css")); insert(value_type("txt", "text/plain")); insert(value_type("c", "text/plain")); insert(value_type("cpp", "text/plain")); insert(value_type("c++", "text/plain")); insert(value_type("h", "text/plain")); insert(value_type("hpp", "text/plain")); insert(value_type("py", "text/plain")); insert(value_type("xml", "text/xml")); insert(value_type("html", "text/html")); insert(value_type("htm", "text/html")); insert(value_type("js", "text/javascript")); insert(value_type("json", "application/json")); insert(value_type("tar", "application/x-tar")); insert(value_type("bz2", "application/x-bzip2")); insert(value_type("gz", "application/x-gzip")); insert(value_type("crt", "application/x-x509-ca-cert")); } <commit_msg>Added application/pdf<commit_after>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2017, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "ContentTypes.h" using namespace std; using namespace cb; using namespace cb::HTTP; ContentTypes::ContentTypes(Inaccessible) { insert(value_type("png", "image/png")); insert(value_type("jpg", "image/jpeg")); insert(value_type("jpeg", "image/jpeg")); insert(value_type("gif", "image/gif")); insert(value_type("ico", "image/x-icon")); insert(value_type("css", "text/css")); insert(value_type("txt", "text/plain")); insert(value_type("c", "text/plain")); insert(value_type("cpp", "text/plain")); insert(value_type("c++", "text/plain")); insert(value_type("h", "text/plain")); insert(value_type("hpp", "text/plain")); insert(value_type("py", "text/plain")); insert(value_type("xml", "text/xml")); insert(value_type("html", "text/html")); insert(value_type("htm", "text/html")); insert(value_type("js", "text/javascript")); insert(value_type("json", "application/json")); insert(value_type("tar", "application/x-tar")); insert(value_type("bz2", "application/x-bzip2")); insert(value_type("gz", "application/x-gzip")); insert(value_type("crt", "application/x-x509-ca-cert")); insert(value_type("pdf", "application/pdf")); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016, <copyright holder> <email> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY <copyright holder> <email> ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> <email> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "JsonReport.hh" #include "Options.hh" #include "CommitTimeline.hh" #include "TreeMetrics.hh" #include "FileMetrics.hh" #include "Stock.hh" #include <jsoncpp/json/writer.h> #include <fstream> #include <mutex> #include <errno.h> using namespace std; namespace gitstock { namespace { const static string *WEEK_DAY_NAMES = new string[7] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; } class JsonReportImpl { public: GitStockOptions& opts; ofstream stream; Json::StreamWriter *writer; mutex streamLock; JsonReportImpl(GitStockOptions& opts) : opts(opts) { Json::StreamWriterBuilder bldr; bldr["indentation"] = ""; writer = bldr.newStreamWriter(); openStream(opts.destination, stream); //openStream(opts.destination, "stocks.json", stocks); //openStream(opts.destination, "files.json", files); //openStream(opts.destination, "stock_files.json", stockFiles); } int openStream(const string& filename, ofstream& stream) { stream.open(filename); if(!stream.good()) { string msg = "failed to open output file "; msg += filename; msg += ": "; msg += strerror(errno); throw runtime_error(msg); } return stream.good() ? 0 : errno; } Json::Value& normalize(const CommitDay *day, Json::Value& json) { json["Timestamp"] = (Json::Int64)day->timestamp(); return json; } void report(const CommitDay *day, const TreeMetrics *metrics) { // files // tree.json => tree information // stocks.json => stock information // files.json => file information // stock_files.json => stocks within files information unique_lock<mutex> lock(streamLock); mpz_class offset = opts.nowTimestamp ? opts.nowTimestamp : metrics->lastCommitTimestamp(); Json::Value treeJson = metrics->toJson(offset); Json::Value dayJson = dayToJson(day); writer->write(dayJson, &stream); stream << "\n"; writer->write(normalize(day, treeJson), &stream); stream << "\n"; //tree << "\n"; for(const FileMetrics *file : *metrics) { Json::Value fileJson = file->toJson(offset); writer->write(normalize(day, fileJson), &stream); stream << "\n"; for(const Stock *stock : file->stocks()) { Json::Value stockJson = stock->toJson(offset); stockJson["FilePath"] = file->path(); stockJson["_type"] = "stock-file"; writer->write(normalize(day, stockJson), &stream); stream << "\n"; } } for(const Stock* stock : metrics->stocks()) { Json::Value stockJson = stock->toJson(offset); writer->write(normalize(day, stockJson), &stream); stream << "\n"; } for(git_commit *commit : day->commits()) { //TODO Json::Value json = commitToJson(commit); writer->write(json, &stream); stream << "\n"; } } Json::Value dayToJson(const CommitDay *day) { Json::Value json(Json::objectValue); json["_type"] = "commit-day"; json["Timestamp"] = (Json::Int64)day->timestamp(); json["CommitCount"] = (Json::Int)day->commits().size(); return json; } Json::Value commitToJson(git_commit *commit) const { Json::Value json(Json::objectValue); const git_signature *sig = git_commit_committer(commit); int64_t timestamp = git_commit_time(commit); tm *t = localtime(&timestamp); const char *msg = git_commit_message(commit); json["Message"] = msg ? msg : ""; //git_commit_body(commit); json["Timestamp"] = (Json::Int64)timestamp; json["DayOfTheWeek"] = WEEK_DAY_NAMES[t->tm_wday]; json["HourOfTheDay"] = t->tm_hour; json["_type"] = "commit"; if(sig) { pair<string, string> resolved = GitStockOptions::get().resolveSignature(sig->email, sig->name); json["AuthorEmail"] = resolved.first; json["AuthorName"] = resolved.second; } return json; } }; JsonReport::JsonReport(GitStockOptions& opts) : pImpl(new JsonReportImpl(opts)) { } JsonReport::~JsonReport() { delete pImpl; } void JsonReport::report(const CommitDay* day, const TreeMetrics* metrics) { pImpl->report(day, metrics); } void JsonReport::close() { pImpl->stream.close(); } } <commit_msg>add number prefix for week day name<commit_after>/* * Copyright (c) 2016, <copyright holder> <email> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY <copyright holder> <email> ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> <email> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "JsonReport.hh" #include "Options.hh" #include "CommitTimeline.hh" #include "TreeMetrics.hh" #include "FileMetrics.hh" #include "Stock.hh" #include <jsoncpp/json/writer.h> #include <fstream> #include <mutex> #include <errno.h> using namespace std; namespace gitstock { namespace { const static string *WEEK_DAY_NAMES = new string[7] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; string getWeekDayName(int wday) { stringstream ss; ss << wday << " " << WEEK_DAY_NAMES[wday]; return ss.str(); } } class JsonReportImpl { public: GitStockOptions& opts; ofstream stream; Json::StreamWriter *writer; mutex streamLock; JsonReportImpl(GitStockOptions& opts) : opts(opts) { Json::StreamWriterBuilder bldr; bldr["indentation"] = ""; writer = bldr.newStreamWriter(); openStream(opts.destination, stream); //openStream(opts.destination, "stocks.json", stocks); //openStream(opts.destination, "files.json", files); //openStream(opts.destination, "stock_files.json", stockFiles); } int openStream(const string& filename, ofstream& stream) { stream.open(filename); if(!stream.good()) { string msg = "failed to open output file "; msg += filename; msg += ": "; msg += strerror(errno); throw runtime_error(msg); } return stream.good() ? 0 : errno; } Json::Value& normalize(const CommitDay *day, Json::Value& json) { json["Timestamp"] = (Json::Int64)day->timestamp(); return json; } void report(const CommitDay *day, const TreeMetrics *metrics) { // files // tree.json => tree information // stocks.json => stock information // files.json => file information // stock_files.json => stocks within files information unique_lock<mutex> lock(streamLock); mpz_class offset = opts.nowTimestamp ? opts.nowTimestamp : metrics->lastCommitTimestamp(); Json::Value treeJson = metrics->toJson(offset); Json::Value dayJson = dayToJson(day); writer->write(dayJson, &stream); stream << "\n"; writer->write(normalize(day, treeJson), &stream); stream << "\n"; //tree << "\n"; for(const FileMetrics *file : *metrics) { Json::Value fileJson = file->toJson(offset); writer->write(normalize(day, fileJson), &stream); stream << "\n"; for(const Stock *stock : file->stocks()) { Json::Value stockJson = stock->toJson(offset); stockJson["FilePath"] = file->path(); stockJson["_type"] = "stock-file"; writer->write(normalize(day, stockJson), &stream); stream << "\n"; } } for(const Stock* stock : metrics->stocks()) { Json::Value stockJson = stock->toJson(offset); writer->write(normalize(day, stockJson), &stream); stream << "\n"; } for(git_commit *commit : day->commits()) { //TODO Json::Value json = commitToJson(commit); writer->write(json, &stream); stream << "\n"; } } Json::Value dayToJson(const CommitDay *day) { Json::Value json(Json::objectValue); json["_type"] = "commit-day"; json["Timestamp"] = (Json::Int64)day->timestamp(); json["CommitCount"] = (Json::Int)day->commits().size(); return json; } Json::Value commitToJson(git_commit *commit) const { Json::Value json(Json::objectValue); const git_signature *sig = git_commit_committer(commit); int64_t timestamp = git_commit_time(commit); tm *t = localtime(&timestamp); const char *msg = git_commit_message(commit); json["Message"] = msg ? msg : ""; //git_commit_body(commit); json["Timestamp"] = (Json::Int64)timestamp; json["DayOfTheWeek"] = getWeekDayName(t->tm_wday); json["HourOfTheDay"] = t->tm_hour; json["_type"] = "commit"; if(sig) { pair<string, string> resolved = GitStockOptions::get().resolveSignature(sig->email, sig->name); json["AuthorEmail"] = resolved.first; json["AuthorName"] = resolved.second; } return json; } }; JsonReport::JsonReport(GitStockOptions& opts) : pImpl(new JsonReportImpl(opts)) { } JsonReport::~JsonReport() { delete pImpl; } void JsonReport::report(const CommitDay* day, const TreeMetrics* metrics) { pImpl->report(day, metrics); } void JsonReport::close() { pImpl->stream.close(); } } <|endoftext|>
<commit_before>#include "KingJelly.h" #include "lib/effect_runner.h" #include "NetworkController.h" #include "KeyboardController.h" #include "EffectManager.h" #include "JellyEffect.h" // Detect releasing button 0 // TODO: Refactor to cleaner input->event system? bool ReleaseButton0(const IController& controller) { static bool sLastState = false; bool currentState = controller.Digital(0); bool clickRelease = sLastState && !currentState; sLastState = currentState; return clickRelease; } int main(int argc, char** argv) { // System components EffectManager manager; EffectRunner runner; // KeyboardController controller; GpioController controller; // Defaults, overridable with command line options runner.setMaxFrameRate(300); runner.setLayout("scripts/jelly16x100.json"); if (!runner.parseArguments(argc, argv)) return 1; while (true) { // Switch to next effect? if (ReleaseButton0(controller)) manager.NextEffect(); JellyEffect& activeEffect = manager.GetActiveInstance(); // Transfer analog control inputs to effect controller.Update(); const uint32_t kInputCount = 4; for (uint32_t inputIndex = 0; inputIndex < kInputCount; ++inputIndex) activeEffect.SetInput(inputIndex, controller.Analog(inputIndex)); // Draw effect frame runner.setEffect(&activeEffect); runner.doFrame(); } return 0; } <commit_msg>Switch to GpioController in KingJelly.cpp<commit_after>#include "KingJelly.h" #include "lib/effect_runner.h" #include "NetworkController.h" #include "KeyboardController.h" #include "GpioController.h" #include "EffectManager.h" #include "JellyEffect.h" // Detect releasing button 0 // TODO: Refactor to cleaner input->event system? bool ReleaseButton0(const IController& controller) { static bool sLastState = false; bool currentState = controller.Digital(0); bool clickRelease = sLastState && !currentState; sLastState = currentState; return clickRelease; } int main(int argc, char** argv) { // System components EffectManager manager; EffectRunner runner; GpioController controller; // Defaults, overridable with command line options runner.setMaxFrameRate(300); runner.setLayout("scripts/jelly16x100.json"); if (!runner.parseArguments(argc, argv)) return 1; while (true) { // Switch to next effect? if (ReleaseButton0(controller)) manager.NextEffect(); JellyEffect& activeEffect = manager.GetActiveInstance(); // Transfer analog control inputs to effect controller.Update(); const uint32_t kInputCount = 4; for (uint32_t inputIndex = 0; inputIndex < kInputCount; ++inputIndex) activeEffect.SetInput(inputIndex, controller.Analog(inputIndex)); // Draw effect frame runner.setEffect(&activeEffect); runner.doFrame(); } return 0; } <|endoftext|>
<commit_before>#include "KingJelly.h" #include "lib/effect_runner.h" #include "NetworkController.h" #include "KeyboardController.h" #include "AdcController.h" #include "AutoController.h" #include "EffectManager.h" #include "JellyEffect.h" // Detect releasing button 0 // TODO: Refactor to cleaner input->event system? bool ReleaseButton(const BaseController& controller, uint32_t buttonIndex) { static bool sLastState[4] = {false,false,false,false}; buttonIndex = min<uint32_t>(buttonIndex, 3); bool currentState = controller.Digital(buttonIndex); bool clickRelease = sLastState[buttonIndex] && !currentState; sLastState[buttonIndex] = currentState; return clickRelease; } BaseController& GetController() { static AdcController adcController; adcController.Update(); if (adcController.IsEnabled()) return adcController; static KeyboardController keyController; keyController.Update(); if (keyController.IsEnabled()) return keyController; static NetworkController netController; netController.Update(); if (adcController.IsEnabled()) return netController; static AutoController autoController; autoController.Update(); return autoController; } int main(int argc, char** argv) { // System components EffectManager manager; EffectRunner runner; // Defaults, overridable with command line options runner.setMaxFrameRate(300); runner.setLayout("scripts/jelly16x100.json"); if (!runner.parseArguments(argc, argv)) return 1; while (true) { // Select controller based on 'enabled' reading BaseController& controller = GetController(); // Switch to next or previous effect? if (ReleaseButton(controller, 0)) manager.NextEffect(false); if (ReleaseButton(controller, 1)) manager.NextEffect(true); JellyEffect& activeEffect = manager.GetActiveInstance(); // Transfer analog control inputs to effect controller.Update(); const uint32_t kInputCount = 4; for (uint32_t inputIndex = 0; inputIndex < kInputCount; ++inputIndex) activeEffect.SetInput(inputIndex, controller.Analog(inputIndex)); // Draw effect frame runner.setEffect(&activeEffect); runner.doFrame(); } return 0; } <commit_msg>Activate network controller when ADC is not active<commit_after>#include "KingJelly.h" #include "lib/effect_runner.h" #include "NetworkController.h" #include "KeyboardController.h" #include "AdcController.h" #include "AutoController.h" #include "EffectManager.h" #include "JellyEffect.h" // Detect releasing button 0 // TODO: Refactor to cleaner input->event system? bool ReleaseButton(const BaseController& controller, uint32_t buttonIndex) { static bool sLastState[4] = {false,false,false,false}; buttonIndex = min<uint32_t>(buttonIndex, 3); bool currentState = controller.Digital(buttonIndex); bool clickRelease = sLastState[buttonIndex] && !currentState; sLastState[buttonIndex] = currentState; return clickRelease; } BaseController& GetController() { static AdcController adcController; adcController.Update(); if (adcController.IsEnabled()) return adcController; static KeyboardController keyController; keyController.Update(); if (keyController.IsEnabled()) return keyController; static NetworkController netController; netController.Update(); if (!adcController.IsEnabled()) return netController; static AutoController autoController; autoController.Update(); return autoController; } int main(int argc, char** argv) { // System components EffectManager manager; EffectRunner runner; // Defaults, overridable with command line options runner.setMaxFrameRate(300); runner.setLayout("scripts/jelly16x100.json"); if (!runner.parseArguments(argc, argv)) return 1; while (true) { // Select controller based on 'enabled' reading BaseController& controller = GetController(); // Switch to next or previous effect? if (ReleaseButton(controller, 0)) manager.NextEffect(false); if (ReleaseButton(controller, 1)) manager.NextEffect(true); JellyEffect& activeEffect = manager.GetActiveInstance(); // Transfer analog control inputs to effect controller.Update(); const uint32_t kInputCount = 4; for (uint32_t inputIndex = 0; inputIndex < kInputCount; ++inputIndex) activeEffect.SetInput(inputIndex, controller.Analog(inputIndex)); // Draw effect frame runner.setEffect(&activeEffect); runner.doFrame(); } return 0; } <|endoftext|>
<commit_before>// @(#)root/graf:$Name: $:$Id: TPaveStats.cxx,v 1.8 2002/03/13 17:00:33 rdm Exp $ // Author: Rene Brun 15/03/99 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "Riostream.h" #include "TPaveStats.h" #include "TVirtualPad.h" #include "TStyle.h" #include "TFile.h" #include "TClass.h" #include "TLatex.h" ClassImp(TPaveStats) //______________________________________________________________________________ // A PaveStats is a PaveText to draw histogram statistics // The type of information printed in the histogram statistics box // can be selected via gStyle->SetOptStat(mode). // or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode). // The parameter mode can be = ourmen (default = 001111) // n = 1; name of histogram is printed // e = 1; number of entries printed // m = 1; mean value printed // r = 1; rms printed // u = 1; number of underflows printed // o = 1; number of overflows printed // Example: gStyle->SetOptStat(11); // print only name of histogram and number of entries. // // The type of information about fit parameters printed in the histogram // statistics box can be selected via the parameter mode. // The parameter mode can be = pcev (default = 0111) // v = 1; print name/values of parameters // e = 1; print errors (if e=1, v must be 1) // c = 1; print Chisquare/Number of degress of freedom // p = 1; print Probability // Example: gStyle->SetOptFit(1011); // or this->SetOptFit(1011); // print fit probability, parameter names/values and errors. // //______________________________________________________________________________ TPaveStats::TPaveStats(): TPaveText() { // TPaveStats default constructor } //______________________________________________________________________________ TPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Option_t *option) :TPaveText(x1,y1,x2,y2,option) { // TPaveStats normal constructor fOptFit = gStyle->GetOptFit(); fOptStat = gStyle->GetOptStat(); SetFitFormat(gStyle->GetFitFormat()); SetStatFormat(gStyle->GetStatFormat()); } //______________________________________________________________________________ TPaveStats::~TPaveStats() { // TPaveStats default destructor } //______________________________________________________________________________ void TPaveStats::SaveStyle() { // Save This TPaveStats options in current style gStyle->SetOptFit(fOptFit); gStyle->SetOptStat(fOptStat); gStyle->SetFitFormat(fFitFormat.Data()); gStyle->SetStatFormat(fStatFormat.Data()); } //______________________________________________________________________________ void TPaveStats::SetFitFormat(const char *form) { // Change (i.e. set) the format for printing fit parameters in statistics box fFitFormat = form; } //______________________________________________________________________________ void TPaveStats::SetStatFormat(const char *form) { // Change (i.e. set) the format for printing statistics fStatFormat = form; } //______________________________________________________________________________ void TPaveStats::Paint(Option_t *option) { TPave::ConvertNDCtoPad(); TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option); if (!fLines) return; Double_t dx = fX2 - fX1; Double_t dy = fY2 - fY1; Double_t textsize = GetTextSize(); Int_t nlines = GetSize(); if (nlines == 0) nlines = 5; // Evaluate text size as a function of the number of lines Double_t y1 = gPad->GetY1(); Double_t y2 = gPad->GetY2(); Float_t margin = fMargin*(fX2-fX1); Double_t yspace = (fY2 - fY1)/Double_t(nlines); Double_t textsave = textsize; TObject *line; TLatex *latex, *latex_tok; TIter next(fLines); Double_t longest = 0; Double_t w, wtok[2]; char *st, *sl; if (textsize == 0) { textsize = 0.85*yspace/(y2 - y1); wtok[0] = 0; wtok[1] = 0; while ((line = (TObject*) next())) { if (line->IsA() == TLatex::Class()) { latex = (TLatex*)line; sl = new char[strlen(latex->GetTitle())+1]; strcpy(sl, latex->GetTitle()); if (strpbrk(sl, "=") !=0) { st = strtok(sl, "="); Int_t itok = 0; while ( st !=0 ) { latex_tok = new TLatex(0.,0.,st); latex_tok->SetTextSize(textsize); w = latex_tok->GetXsize(); if (w > wtok[itok]) wtok[itok] = w; st = strtok(0, "="); ++itok; delete latex_tok; } } } } longest = wtok[0]+wtok[1]+2.*margin; if (longest > 0.98*dx) textsize *= 0.98*dx/longest; SetTextSize(textsize); } Double_t ytext = fY2 + 0.5*yspace; Double_t xtext = 0; // Iterate over all lines // Copy pavetext attributes to line attributes if line attributes not set next.Reset(); while ((line = (TObject*) next())) { if (line->IsA() == TLatex::Class()) { latex = (TLatex*)line; ytext -= yspace; Double_t xl = latex->GetX(); Double_t yl = latex->GetY(); Short_t talign = latex->GetTextAlign(); Color_t tcolor = latex->GetTextColor(); Style_t tfont = latex->GetTextFont(); Size_t tsize = latex->GetTextSize(); if (tcolor == 0) latex->SetTextColor(GetTextColor()); if (tfont == 0) latex->SetTextFont(GetTextFont()); if (tsize == 0) latex->SetTextSize(GetTextSize()); sl = new char[strlen(latex->GetTitle())+1]; strcpy(sl, latex->GetTitle()); // Draw all the histogram except the 2D under/overflow if (strpbrk(sl, "=") !=0) { st = strtok(sl, "="); Int_t halign = 12; while ( st !=0 ) { latex->SetTextAlign(halign); if (halign == 12) xtext = fX1 + margin; if (halign == 32) { xtext = fX2 - margin; // Clean trailing blanks in case of right alignment. char *stc; stc=st+strlen(st)-1; while (*stc == ' ') { *stc = '\0'; --stc; } } latex->PaintLatex(xtext,ytext,latex->GetTextAngle(), latex->GetTextSize(), st); st = strtok(0, "="); halign = 32; } // Draw the 2D under/overflow } else if (strpbrk(sl, "|") !=0) { Double_t Yline1 = ytext+yspace/2.; Double_t Yline2 = ytext-yspace/2.; Double_t Xline1 = (fX2-fX1)/3+fX1; Double_t Xline2 = 2*(fX2-fX1)/3+fX1; gPad->PaintLine(fX1,Yline1,fX2,Yline1); gPad->PaintLine(Xline1,Yline1,Xline1,Yline2); gPad->PaintLine(Xline2,Yline1,Xline2,Yline2); st = strtok(sl, "|"); Int_t Index = 0; while ( st !=0 ) { latex->SetTextAlign(22); if (Index == 0) xtext = 0.5*(fX1+Xline1); if (Index == 1) xtext = 0.5*(fX1+fX2); if (Index == 2) xtext = 0.5*(Xline2+fX2); latex->PaintLatex(xtext,ytext,latex->GetTextAngle(), latex->GetTextSize(), st); Index++; st = strtok(0, "|"); } // Draw the histogram identifier } else { latex->SetTextAlign(22); xtext = 0.5*(fX1+fX2); latex->PaintLatex(xtext,ytext,latex->GetTextAngle(), latex->GetTextSize(), sl); gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace); } delete [] sl; latex->SetTextAlign(talign); latex->SetTextColor(tcolor); latex->SetTextFont(tfont); latex->SetTextSize(tsize); latex->SetX(xl); //paintlatex modifies fX and fY latex->SetY(yl); } } SetTextSize(textsave); } //______________________________________________________________________________ void TPaveStats::Streamer(TBuffer &R__b) { // Stream an object of class TPaveStats. if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 2) { TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TPaveText::Streamer(R__b); R__b >> fOptFit; R__b >> fOptStat; TFile *file = (TFile*)R__b.GetParent(); if (R__v > 1 || (file && file->GetVersion() == 22304)) { fFitFormat.Streamer(R__b); fStatFormat.Streamer(R__b); } else { SetFitFormat(); SetStatFormat(); } R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA()); //====end of old versions } else { TPaveStats::Class()->WriteBuffer(R__b,this); } } <commit_msg>remove unused dy.<commit_after>// @(#)root/graf:$Name: $:$Id: TPaveStats.cxx,v 1.9 2002/03/16 08:52:43 brun Exp $ // Author: Rene Brun 15/03/99 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "Riostream.h" #include "TPaveStats.h" #include "TVirtualPad.h" #include "TStyle.h" #include "TFile.h" #include "TClass.h" #include "TLatex.h" ClassImp(TPaveStats) //______________________________________________________________________________ // A PaveStats is a PaveText to draw histogram statistics // The type of information printed in the histogram statistics box // can be selected via gStyle->SetOptStat(mode). // or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode). // The parameter mode can be = ourmen (default = 001111) // n = 1; name of histogram is printed // e = 1; number of entries printed // m = 1; mean value printed // r = 1; rms printed // u = 1; number of underflows printed // o = 1; number of overflows printed // Example: gStyle->SetOptStat(11); // print only name of histogram and number of entries. // // The type of information about fit parameters printed in the histogram // statistics box can be selected via the parameter mode. // The parameter mode can be = pcev (default = 0111) // v = 1; print name/values of parameters // e = 1; print errors (if e=1, v must be 1) // c = 1; print Chisquare/Number of degress of freedom // p = 1; print Probability // Example: gStyle->SetOptFit(1011); // or this->SetOptFit(1011); // print fit probability, parameter names/values and errors. // //______________________________________________________________________________ TPaveStats::TPaveStats(): TPaveText() { // TPaveStats default constructor } //______________________________________________________________________________ TPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Option_t *option) :TPaveText(x1,y1,x2,y2,option) { // TPaveStats normal constructor fOptFit = gStyle->GetOptFit(); fOptStat = gStyle->GetOptStat(); SetFitFormat(gStyle->GetFitFormat()); SetStatFormat(gStyle->GetStatFormat()); } //______________________________________________________________________________ TPaveStats::~TPaveStats() { // TPaveStats default destructor } //______________________________________________________________________________ void TPaveStats::SaveStyle() { // Save This TPaveStats options in current style gStyle->SetOptFit(fOptFit); gStyle->SetOptStat(fOptStat); gStyle->SetFitFormat(fFitFormat.Data()); gStyle->SetStatFormat(fStatFormat.Data()); } //______________________________________________________________________________ void TPaveStats::SetFitFormat(const char *form) { // Change (i.e. set) the format for printing fit parameters in statistics box fFitFormat = form; } //______________________________________________________________________________ void TPaveStats::SetStatFormat(const char *form) { // Change (i.e. set) the format for printing statistics fStatFormat = form; } //______________________________________________________________________________ void TPaveStats::Paint(Option_t *option) { TPave::ConvertNDCtoPad(); TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option); if (!fLines) return; Double_t dx = fX2 - fX1; Double_t textsize = GetTextSize(); Int_t nlines = GetSize(); if (nlines == 0) nlines = 5; // Evaluate text size as a function of the number of lines Double_t y1 = gPad->GetY1(); Double_t y2 = gPad->GetY2(); Float_t margin = fMargin*(fX2-fX1); Double_t yspace = (fY2 - fY1)/Double_t(nlines); Double_t textsave = textsize; TObject *line; TLatex *latex, *latex_tok; TIter next(fLines); Double_t longest = 0; Double_t w, wtok[2]; char *st, *sl; if (textsize == 0) { textsize = 0.85*yspace/(y2 - y1); wtok[0] = 0; wtok[1] = 0; while ((line = (TObject*) next())) { if (line->IsA() == TLatex::Class()) { latex = (TLatex*)line; sl = new char[strlen(latex->GetTitle())+1]; strcpy(sl, latex->GetTitle()); if (strpbrk(sl, "=") !=0) { st = strtok(sl, "="); Int_t itok = 0; while ( st !=0 ) { latex_tok = new TLatex(0.,0.,st); latex_tok->SetTextSize(textsize); w = latex_tok->GetXsize(); if (w > wtok[itok]) wtok[itok] = w; st = strtok(0, "="); ++itok; delete latex_tok; } } } } longest = wtok[0]+wtok[1]+2.*margin; if (longest > 0.98*dx) textsize *= 0.98*dx/longest; SetTextSize(textsize); } Double_t ytext = fY2 + 0.5*yspace; Double_t xtext = 0; // Iterate over all lines // Copy pavetext attributes to line attributes if line attributes not set next.Reset(); while ((line = (TObject*) next())) { if (line->IsA() == TLatex::Class()) { latex = (TLatex*)line; ytext -= yspace; Double_t xl = latex->GetX(); Double_t yl = latex->GetY(); Short_t talign = latex->GetTextAlign(); Color_t tcolor = latex->GetTextColor(); Style_t tfont = latex->GetTextFont(); Size_t tsize = latex->GetTextSize(); if (tcolor == 0) latex->SetTextColor(GetTextColor()); if (tfont == 0) latex->SetTextFont(GetTextFont()); if (tsize == 0) latex->SetTextSize(GetTextSize()); sl = new char[strlen(latex->GetTitle())+1]; strcpy(sl, latex->GetTitle()); // Draw all the histogram except the 2D under/overflow if (strpbrk(sl, "=") !=0) { st = strtok(sl, "="); Int_t halign = 12; while ( st !=0 ) { latex->SetTextAlign(halign); if (halign == 12) xtext = fX1 + margin; if (halign == 32) { xtext = fX2 - margin; // Clean trailing blanks in case of right alignment. char *stc; stc=st+strlen(st)-1; while (*stc == ' ') { *stc = '\0'; --stc; } } latex->PaintLatex(xtext,ytext,latex->GetTextAngle(), latex->GetTextSize(), st); st = strtok(0, "="); halign = 32; } // Draw the 2D under/overflow } else if (strpbrk(sl, "|") !=0) { Double_t Yline1 = ytext+yspace/2.; Double_t Yline2 = ytext-yspace/2.; Double_t Xline1 = (fX2-fX1)/3+fX1; Double_t Xline2 = 2*(fX2-fX1)/3+fX1; gPad->PaintLine(fX1,Yline1,fX2,Yline1); gPad->PaintLine(Xline1,Yline1,Xline1,Yline2); gPad->PaintLine(Xline2,Yline1,Xline2,Yline2); st = strtok(sl, "|"); Int_t Index = 0; while ( st !=0 ) { latex->SetTextAlign(22); if (Index == 0) xtext = 0.5*(fX1+Xline1); if (Index == 1) xtext = 0.5*(fX1+fX2); if (Index == 2) xtext = 0.5*(Xline2+fX2); latex->PaintLatex(xtext,ytext,latex->GetTextAngle(), latex->GetTextSize(), st); Index++; st = strtok(0, "|"); } // Draw the histogram identifier } else { latex->SetTextAlign(22); xtext = 0.5*(fX1+fX2); latex->PaintLatex(xtext,ytext,latex->GetTextAngle(), latex->GetTextSize(), sl); gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace); } delete [] sl; latex->SetTextAlign(talign); latex->SetTextColor(tcolor); latex->SetTextFont(tfont); latex->SetTextSize(tsize); latex->SetX(xl); //paintlatex modifies fX and fY latex->SetY(yl); } } SetTextSize(textsave); } //______________________________________________________________________________ void TPaveStats::Streamer(TBuffer &R__b) { // Stream an object of class TPaveStats. if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 2) { TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c); return; } //====process old versions before automatic schema evolution TPaveText::Streamer(R__b); R__b >> fOptFit; R__b >> fOptStat; TFile *file = (TFile*)R__b.GetParent(); if (R__v > 1 || (file && file->GetVersion() == 22304)) { fFitFormat.Streamer(R__b); fStatFormat.Streamer(R__b); } else { SetFitFormat(); SetStatFormat(); } R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA()); //====end of old versions } else { TPaveStats::Class()->WriteBuffer(R__b,this); } } <|endoftext|>
<commit_before>#include <sensor_msgs/image_encodings.h> #include <tf/transform_datatypes.h> #include "chessboard_localization/chessboard_localization.h"" namespace chessboard_localization { ChessboardLocalization::ChessboardLocalization() { // configure the message subscriber and publishers img_sub_ = nh_.subscribe("image_raw", 1, &ChessboardLocalization::imageCb, this); pose_pub_ = nh_.advertise<geometry_msgs::Pose>("pose", 1); // initialize parameters from the launch procedures double c_box_size; std::string calib_file_name; // the number of inner corner of the chessboard in width ros::param::param<int32_t>("~chessboard_width", c_width_, 8); // the number of inner corner of the chessboard in height ros::param::param<int32_t>("~chessboard_height", c_height_, 6); // the size of the box in meters ros::param::param<double>("~chessboard_box_size", c_box_size, 0.1); // path of the intrinsic calibration file ros::param::param<std::string>("~calib_file_name", calib_file_name, "/tmp/camera_calib.yml"); // read in intrinsic calibration parameters for the camera try { cv::FileStorage fs(calib_file_name, cv::FileStorage::READ); fs["distortion_coefficients"] >> dist_coeffs_; fs["camera_matrix"] >> cam_matrix_; } catch (cv::Exception& e) { ROS_ERROR("Failed to read calibration file, Exception msg: %s", e.what()); } cam_matrix_ = cv::Mat_<double>(cam_matrix_); dist_coeffs_ = cv::Mat_<double>(dist_coeffs_); // construct a vector of 3d points for the chessboard corners in the chessboard frame int32_t k = 0; board_points_.resize(c_width_*c_height_); for (int32_t i = 0; i < c_width_; i++) { for (int32_t j = 0; j < c_height_; j++) { board_points_[k++] = cv::Point3f(i*c_box_size, j*c_box_size, 0.0); } } // open a cv window for display cv::namedWindow("Chessboard"); } void ChessboardLocalization::imageCb(const sensor_msgs::ImageConstPtr& msg) { // convert image into opencv Mat cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cv::Mat frame = cv_ptr->image; // solve a PnP problem using extracted corners features and board points cv::Mat rvec(3, 3, CV_64F); cv::Mat tvec(3, 1, CV_64F); std::vector<cv::Point2f> board_corners; cv::Size num_corners = cv::Size(c_width_, c_height_); bool found = cv::findChessboardCorners(cv_ptr->image, num_corners, board_corners, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK); cv::drawChessboardCorners(frame, num_corners, board_corners, found); cv::imshow("Chessboard", frame); cv::waitKey(1); if (!found) { ROS_ERROR("Chessboard not found"); return; } cv::solvePnP(cv::Mat(board_points_), cv::Mat(board_corners), cam_matrix_, dist_coeffs_, rvec, tvec, false); // transform cv pose format into a tf structure for visualization purposes cv::Mat rot_matrix; cv::Rodrigues(rvec, rot_matrix); rot_matrix = rot_matrix.t(); tf::Transform pose_tf; pose_tf.getBasis().setValue( rot_matrix.at<double>(0, 0), rot_matrix.at<double>(0, 1), rot_matrix.at<double>(0, 2), rot_matrix.at<double>(1, 0), rot_matrix.at<double>(1, 1), rot_matrix.at<double>(1, 2), rot_matrix.at<double>(2, 0), rot_matrix.at<double>(2, 1), rot_matrix.at<double>(2, 2)); pose_tf.setOrigin(tf::Vector3(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2))); tf_broadcaster_.sendTransform(tf::StampedTransform(pose_tf, ros::Time::now(), "chessboard", "camera")); } } <commit_msg>Update chessboard_localization.cpp<commit_after>#include <sensor_msgs/image_encodings.h> #include <tf/transform_datatypes.h> #include "chessboard_localization/chessboard_localization.h" namespace chessboard_localization { ChessboardLocalization::ChessboardLocalization() { // configure the message subscriber and publishers img_sub_ = nh_.subscribe("image_raw", 1, &ChessboardLocalization::imageCb, this); pose_pub_ = nh_.advertise<geometry_msgs::Pose>("pose", 1); // initialize parameters from the launch procedures double c_box_size; std::string calib_file_name; // the number of inner corner of the chessboard in width ros::param::param<int32_t>("~chessboard_width", c_width_, 8); // the number of inner corner of the chessboard in height ros::param::param<int32_t>("~chessboard_height", c_height_, 6); // the size of the box in meters ros::param::param<double>("~chessboard_box_size", c_box_size, 0.1); // path of the intrinsic calibration file ros::param::param<std::string>("~calib_file_name", calib_file_name, "/tmp/camera_calib.yml"); // read in intrinsic calibration parameters for the camera try { cv::FileStorage fs(calib_file_name, cv::FileStorage::READ); fs["distortion_coefficients"] >> dist_coeffs_; fs["camera_matrix"] >> cam_matrix_; } catch (cv::Exception& e) { ROS_ERROR("Failed to read calibration file, Exception msg: %s", e.what()); } cam_matrix_ = cv::Mat_<double>(cam_matrix_); dist_coeffs_ = cv::Mat_<double>(dist_coeffs_); // construct a vector of 3d points for the chessboard corners in the chessboard frame int32_t k = 0; board_points_.resize(c_width_*c_height_); for (int32_t i = 0; i < c_width_; i++) { for (int32_t j = 0; j < c_height_; j++) { board_points_[k++] = cv::Point3f(i*c_box_size, j*c_box_size, 0.0); } } // open a cv window for display cv::namedWindow("Chessboard"); } void ChessboardLocalization::imageCb(const sensor_msgs::ImageConstPtr& msg) { // convert image into opencv Mat cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cv::Mat frame = cv_ptr->image; // solve a PnP problem using extracted corners features and board points cv::Mat rvec(3, 3, CV_64F); cv::Mat tvec(3, 1, CV_64F); std::vector<cv::Point2f> board_corners; cv::Size num_corners = cv::Size(c_width_, c_height_); bool found = cv::findChessboardCorners(cv_ptr->image, num_corners, board_corners, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK); cv::drawChessboardCorners(frame, num_corners, board_corners, found); cv::imshow("Chessboard", frame); cv::waitKey(1); if (!found) { ROS_ERROR("Chessboard not found"); return; } cv::solvePnP(cv::Mat(board_points_), cv::Mat(board_corners), cam_matrix_, dist_coeffs_, rvec, tvec, false); // transform cv pose format into a tf structure for visualization purposes cv::Mat rot_matrix; cv::Rodrigues(rvec, rot_matrix); rot_matrix = rot_matrix.t(); tf::Transform pose_tf; pose_tf.getBasis().setValue( rot_matrix.at<double>(0, 0), rot_matrix.at<double>(0, 1), rot_matrix.at<double>(0, 2), rot_matrix.at<double>(1, 0), rot_matrix.at<double>(1, 1), rot_matrix.at<double>(1, 2), rot_matrix.at<double>(2, 0), rot_matrix.at<double>(2, 1), rot_matrix.at<double>(2, 2)); pose_tf.setOrigin(tf::Vector3(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2))); tf_broadcaster_.sendTransform(tf::StampedTransform(pose_tf, ros::Time::now(), "chessboard", "camera")); } } <|endoftext|>
<commit_before>#include "cmake.h" #include "singletons.h" #include "filesystem.h" #include <boost/regex.hpp> #include "dialogs.h" #include <iostream> //TODO: remove using namespace std; //TODO: remove CMake::CMake(const boost::filesystem::path &path) { const auto find_cmake_project=[this](const boost::filesystem::path &cmake_path) { for(auto &line: filesystem::read_lines(cmake_path)) { const boost::regex project_regex("^ *project *\\(.*$"); boost::smatch sm; if(boost::regex_match(line, sm, project_regex)) { return true; } } return false; }; auto search_path=path; auto search_cmake_path=search_path; search_cmake_path+="/CMakeLists.txt"; if(boost::filesystem::exists(search_cmake_path)) paths.emplace(paths.begin(), search_cmake_path); if(find_cmake_project(search_cmake_path)) project_path=search_path; else { do { search_path=search_path.parent_path(); search_cmake_path=search_path; search_cmake_path+="/CMakeLists.txt"; if(boost::filesystem::exists(search_cmake_path)) paths.emplace(paths.begin(), search_cmake_path); if(find_cmake_project(search_cmake_path)) { project_path=search_path; break; } } while(search_path!=search_path.root_directory()); } if(!project_path.empty()) { if(boost::filesystem::exists(project_path/"CMakeLists.txt") && !boost::filesystem::exists(project_path/"compile_commands.json")) create_compile_commands(project_path); } } bool CMake::create_compile_commands(const boost::filesystem::path &path) { Dialog::Message message("Creating "+path.string()+"/compile_commands.json"); auto exit_code=Singleton::terminal->execute(Singleton::config->terminal.cmake_command+" . -DCMAKE_EXPORT_COMPILE_COMMANDS=ON", path); message.hide(); if(exit_code==EXIT_SUCCESS) { #ifdef _WIN32 //Temporary fix to MSYS2's libclang auto compile_commands_path=path; compile_commands_path+="/compile_commands.json"; auto compile_commands_file=filesystem::read(compile_commands_path); size_t pos=0; while((pos=compile_commands_file.find("-I/", pos))!=std::string::npos) { if(pos+3<compile_commands_file.size()) { std::string drive; drive+=compile_commands_file[pos+3]; compile_commands_file.replace(pos, 4, "-I"+drive+":"); } else break; } filesystem::write(compile_commands_path, compile_commands_file); #endif return true; } return false; } void CMake::read_files() { for(auto &path: paths) files.emplace_back(filesystem::read(path)); } void CMake::remove_tabs() { for(auto &file: files) { for(auto &chr: file) { if(chr=='\t') chr=' '; } } } void CMake::remove_comments() { for(auto &file: files) { size_t pos=0; size_t comment_start; bool inside_comment=false; while(pos<file.size()) { if(!inside_comment && file[pos]=='#') { comment_start=pos; inside_comment=true; } if(inside_comment && file[pos]=='\n') { file.erase(comment_start, pos-comment_start); pos-=pos-comment_start; inside_comment=false; } pos++; } if(inside_comment) file.erase(comment_start); } } void CMake::remove_newlines_inside_parentheses() { for(auto &file: files) { size_t pos=0; bool inside_para=false; bool inside_quote=false; char last_char=0; while(pos<file.size()) { if(!inside_quote && file[pos]=='"' && last_char!='\\') inside_quote=true; else if(inside_quote && file[pos]=='"' && last_char!='\\') inside_quote=false; else if(!inside_quote && file[pos]=='(') inside_para=true; else if(!inside_quote && file[pos]==')') inside_para=false; else if(inside_para && file[pos]=='\n') file.replace(pos, 1, 1, ' '); last_char=file[pos]; pos++; } } } void CMake::find_variables() { for(auto &file: files) { size_t pos=0; while(pos<file.size()) { auto start_line=pos; auto end_line=file.find('\n', start_line); if(end_line==std::string::npos) end_line=file.size(); if(end_line>start_line) { auto line=file.substr(start_line, end_line-start_line); const boost::regex set_regex("^ *set *\\( *([A-Za-z_][A-Za-z_0-9]*) +(.*)\\) *$"); boost::smatch sm; if(boost::regex_match(line, sm, set_regex)) { auto data=sm[2].str(); while(data.size()>0 && data.back()==' ') data.pop_back(); parse_variable_parameters(data); variables[sm[1].str()]=data; } } pos=end_line+1; } } } void CMake::parse_variable_parameters(std::string &data) { size_t pos=0; bool inside_quote=false; char last_char=0; while(pos<data.size()) { if(!inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=true; data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test} pos--; } else if(inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=false; data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test} pos--; } else if(!inside_quote && data[pos]==' ' && pos+1<data.size() && data[pos+1]==' ') { data.erase(pos, 1); pos--; } last_char=data[pos]; pos++; } for(auto &var: variables) { auto pos=data.find("${"+var.first+'}'); while(pos!=std::string::npos) { data.replace(pos, var.first.size()+3, var.second); pos=data.find("${"+var.first+'}'); } } //Remove variables we do not know: pos=data.find("${"); auto pos_end=data.find("}", pos+2); while(pos!=std::string::npos && pos_end!=std::string::npos) { data.erase(pos, pos_end-pos+1); pos=data.find("${"); pos_end=data.find("}", pos+2); } } void CMake::parse() { read_files(); remove_tabs(); remove_comments(); remove_newlines_inside_parentheses(); find_variables(); parsed=true; } std::vector<std::string> CMake::get_function_parameters(std::string &data) { std::vector<std::string> parameters; size_t pos=0; size_t parameter_pos=0; bool inside_quote=false; char last_char=0; while(pos<data.size()) { if(!inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=true; data.erase(pos, 1); pos--; } else if(inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=false; data.erase(pos, 1); pos--; } else if(!inside_quote && pos+1<data.size() && data[pos]==' ' && data[pos+1]==' ') { data.erase(pos, 1); pos--; } else if(!inside_quote && data[pos]==' ') { parameters.emplace_back(data.substr(parameter_pos, pos-parameter_pos)); if(pos+1<data.size()) parameter_pos=pos+1; } last_char=data[pos]; pos++; } parameters.emplace_back(data.substr(parameter_pos)); for(auto &var: variables) { for(auto &parameter: parameters) { auto pos=parameter.find("${"+var.first+'}'); while(pos!=std::string::npos) { parameter.replace(pos, var.first.size()+3, var.second); pos=parameter.find("${"+var.first+'}'); } } } return parameters; } std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > CMake::get_functions_parameters(const std::string &name) { if(!parsed) parse(); std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > functions; size_t file_c=0; for(auto &file: files) { size_t pos=0; while(pos<file.size()) { auto start_line=pos; auto end_line=file.find('\n', start_line); if(end_line==std::string::npos) end_line=file.size(); if(end_line>start_line) { auto line=file.substr(start_line, end_line-start_line); const boost::regex function_regex("^ *"+name+" *\\( *(.*)\\) *$"); boost::smatch sm; if(boost::regex_match(line, sm, function_regex)) { auto data=sm[1].str(); while(data.size()>0 && data.back()==' ') data.pop_back(); auto parameters=get_function_parameters(data); functions.emplace(functions.begin(), paths[file_c], parameters); } } pos=end_line+1; } file_c++; } return functions; } <commit_msg>use std::rgex instead boost::regex<commit_after>#include "cmake.h" #include "singletons.h" #include "filesystem.h" #include "dialogs.h" #include <regex> #include <iostream> //TODO: remove using namespace std; //TODO: remove CMake::CMake(const boost::filesystem::path &path) { const auto find_cmake_project=[this](const boost::filesystem::path &cmake_path) { for(auto &line: filesystem::read_lines(cmake_path)) { const std::regex project_regex("^ *project *\\(.*$"); std::smatch sm; if(std::regex_match(line, sm, project_regex)) { return true; } } return false; }; auto search_path=path; auto search_cmake_path=search_path; search_cmake_path+="/CMakeLists.txt"; if(boost::filesystem::exists(search_cmake_path)) paths.emplace(paths.begin(), search_cmake_path); if(find_cmake_project(search_cmake_path)) project_path=search_path; else { do { search_path=search_path.parent_path(); search_cmake_path=search_path; search_cmake_path+="/CMakeLists.txt"; if(boost::filesystem::exists(search_cmake_path)) paths.emplace(paths.begin(), search_cmake_path); if(find_cmake_project(search_cmake_path)) { project_path=search_path; break; } } while(search_path!=search_path.root_directory()); } if(!project_path.empty()) { if(boost::filesystem::exists(project_path/"CMakeLists.txt") && !boost::filesystem::exists(project_path/"compile_commands.json")) create_compile_commands(project_path); } } bool CMake::create_compile_commands(const boost::filesystem::path &path) { Dialog::Message message("Creating "+path.string()+"/compile_commands.json"); auto exit_code=Singleton::terminal->execute(Singleton::config->terminal.cmake_command+" . -DCMAKE_EXPORT_COMPILE_COMMANDS=ON", path); message.hide(); if(exit_code==EXIT_SUCCESS) { #ifdef _WIN32 //Temporary fix to MSYS2's libclang auto compile_commands_path=path; compile_commands_path+="/compile_commands.json"; auto compile_commands_file=filesystem::read(compile_commands_path); size_t pos=0; while((pos=compile_commands_file.find("-I/", pos))!=std::string::npos) { if(pos+3<compile_commands_file.size()) { std::string drive; drive+=compile_commands_file[pos+3]; compile_commands_file.replace(pos, 4, "-I"+drive+":"); } else break; } filesystem::write(compile_commands_path, compile_commands_file); #endif return true; } return false; } void CMake::read_files() { for(auto &path: paths) files.emplace_back(filesystem::read(path)); } void CMake::remove_tabs() { for(auto &file: files) { for(auto &chr: file) { if(chr=='\t') chr=' '; } } } void CMake::remove_comments() { for(auto &file: files) { size_t pos=0; size_t comment_start; bool inside_comment=false; while(pos<file.size()) { if(!inside_comment && file[pos]=='#') { comment_start=pos; inside_comment=true; } if(inside_comment && file[pos]=='\n') { file.erase(comment_start, pos-comment_start); pos-=pos-comment_start; inside_comment=false; } pos++; } if(inside_comment) file.erase(comment_start); } } void CMake::remove_newlines_inside_parentheses() { for(auto &file: files) { size_t pos=0; bool inside_para=false; bool inside_quote=false; char last_char=0; while(pos<file.size()) { if(!inside_quote && file[pos]=='"' && last_char!='\\') inside_quote=true; else if(inside_quote && file[pos]=='"' && last_char!='\\') inside_quote=false; else if(!inside_quote && file[pos]=='(') inside_para=true; else if(!inside_quote && file[pos]==')') inside_para=false; else if(inside_para && file[pos]=='\n') file.replace(pos, 1, 1, ' '); last_char=file[pos]; pos++; } } } void CMake::find_variables() { for(auto &file: files) { size_t pos=0; while(pos<file.size()) { auto start_line=pos; auto end_line=file.find('\n', start_line); if(end_line==std::string::npos) end_line=file.size(); if(end_line>start_line) { auto line=file.substr(start_line, end_line-start_line); const std::regex set_regex("^ *set *\\( *([A-Za-z_][A-Za-z_0-9]*) +(.*)\\) *$"); std::smatch sm; if(std::regex_match(line, sm, set_regex)) { auto data=sm[2].str(); while(data.size()>0 && data.back()==' ') data.pop_back(); parse_variable_parameters(data); variables[sm[1].str()]=data; } } pos=end_line+1; } } } void CMake::parse_variable_parameters(std::string &data) { size_t pos=0; bool inside_quote=false; char last_char=0; while(pos<data.size()) { if(!inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=true; data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test} pos--; } else if(inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=false; data.erase(pos, 1); //TODO: instead remove quote-mark if pasted into a quote, for instance: "test${test}test"<-remove quotes from ${test} pos--; } else if(!inside_quote && data[pos]==' ' && pos+1<data.size() && data[pos+1]==' ') { data.erase(pos, 1); pos--; } last_char=data[pos]; pos++; } for(auto &var: variables) { auto pos=data.find("${"+var.first+'}'); while(pos!=std::string::npos) { data.replace(pos, var.first.size()+3, var.second); pos=data.find("${"+var.first+'}'); } } //Remove variables we do not know: pos=data.find("${"); auto pos_end=data.find("}", pos+2); while(pos!=std::string::npos && pos_end!=std::string::npos) { data.erase(pos, pos_end-pos+1); pos=data.find("${"); pos_end=data.find("}", pos+2); } } void CMake::parse() { read_files(); remove_tabs(); remove_comments(); remove_newlines_inside_parentheses(); find_variables(); parsed=true; } std::vector<std::string> CMake::get_function_parameters(std::string &data) { std::vector<std::string> parameters; size_t pos=0; size_t parameter_pos=0; bool inside_quote=false; char last_char=0; while(pos<data.size()) { if(!inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=true; data.erase(pos, 1); pos--; } else if(inside_quote && data[pos]=='"' && last_char!='\\') { inside_quote=false; data.erase(pos, 1); pos--; } else if(!inside_quote && pos+1<data.size() && data[pos]==' ' && data[pos+1]==' ') { data.erase(pos, 1); pos--; } else if(!inside_quote && data[pos]==' ') { parameters.emplace_back(data.substr(parameter_pos, pos-parameter_pos)); if(pos+1<data.size()) parameter_pos=pos+1; } last_char=data[pos]; pos++; } parameters.emplace_back(data.substr(parameter_pos)); for(auto &var: variables) { for(auto &parameter: parameters) { auto pos=parameter.find("${"+var.first+'}'); while(pos!=std::string::npos) { parameter.replace(pos, var.first.size()+3, var.second); pos=parameter.find("${"+var.first+'}'); } } } return parameters; } std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > CMake::get_functions_parameters(const std::string &name) { if(!parsed) parse(); std::vector<std::pair<boost::filesystem::path, std::vector<std::string> > > functions; size_t file_c=0; for(auto &file: files) { size_t pos=0; while(pos<file.size()) { auto start_line=pos; auto end_line=file.find('\n', start_line); if(end_line==std::string::npos) end_line=file.size(); if(end_line>start_line) { auto line=file.substr(start_line, end_line-start_line); const std::regex function_regex("^ *"+name+" *\\( *(.*)\\) *$"); std::smatch sm; if(std::regex_match(line, sm, function_regex)) { auto data=sm[1].str(); while(data.size()>0 && data.back()==' ') data.pop_back(); auto parameters=get_function_parameters(data); functions.emplace(functions.begin(), paths[file_c], parameters); } } pos=end_line+1; } file_c++; } return functions; } <|endoftext|>
<commit_before>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libts.h" #include "Regex.h" #ifdef PCRE_CONFIG_JIT struct RegexThreadKey { RegexThreadKey() { pthread_key_create(&this->key, (void (*)(void *)) &pcre_jit_stack_free); } pthread_key_t key; }; static RegexThreadKey k; static pcre_jit_stack * get_jit_stack(void *data ATS_UNUSED) { pcre_jit_stack *jit_stack; if ((jit_stack = (pcre_jit_stack *) pthread_getspecific(k.key)) == NULL) { jit_stack = pcre_jit_stack_alloc(ats_pagesize(), 1024 * 1024); // 1 page min and 1MB max pthread_setspecific(k.key, (void *)jit_stack); } return jit_stack; } #endif bool Regex::compile(const char *pattern, unsigned flags) { const char *error; int erroffset; int options = 0; int study_opts = 0; if (regex) return false; if (flags & RE_CASE_INSENSITIVE) { options |= PCRE_CASELESS; } if (flags & RE_ANCHORED) { options |= PCRE_ANCHORED; } regex = pcre_compile(pattern, options, &error, &erroffset, NULL); if (error) { regex = NULL; return false; } #ifdef PCRE_CONFIG_JIT study_opts |= PCRE_STUDY_JIT_COMPILE; #endif regex_extra = pcre_study(regex, study_opts, &error); #ifdef PCRE_CONFIG_JIT if (regex_extra) pcre_assign_jit_stack(regex_extra, &get_jit_stack, NULL); #endif return true; } bool Regex::exec(const char *str) { return exec(str, strlen(str)); } bool Regex::exec(const char *str, int length) { int ovector[30], rv; rv = pcre_exec(regex, regex_extra, str, length , 0, 0, ovector, countof(ovector)); return rv > 0 ? true : false; } Regex::~Regex() { if (regex_extra) #ifdef PCRE_CONFIG_JIT pcre_free_study(regex_extra); #else pcre_free(regex_extra); #endif if (regex) pcre_free(regex); } DFA::~DFA() { dfa_pattern * p = _my_patterns; dfa_pattern * t; while(p) { if (p->_re) delete p->_re; if(p->_p) ats_free(p->_p); t = p->_next; ats_free(p); p = t; } } dfa_pattern * DFA::build(const char *pattern, unsigned flags) { dfa_pattern* ret; int rv; if (!(flags & RE_UNANCHORED)) { flags |= RE_ANCHORED; } ret = (dfa_pattern*)ats_malloc(sizeof(dfa_pattern)); ret->_p = NULL; ret->_re = new Regex(); rv = ret->_re->compile(pattern, flags); if (rv == -1) { delete ret->_re; ats_free(ret); return NULL; } ret->_idx = 0; ret->_p = ats_strndup(pattern, strlen(pattern)); ret->_next = NULL; return ret; } int DFA::compile(const char *pattern, unsigned flags) { ink_assert(_my_patterns == NULL); _my_patterns = build(pattern,flags); if (_my_patterns) return 0; else return -1; } int DFA::compile(const char **patterns, int npatterns, unsigned flags) { const char *pattern; dfa_pattern *ret = NULL; dfa_pattern *end = NULL; int i; for (i = 0; i < npatterns; i++) { pattern = patterns[i]; ret = build(pattern,flags); if (!ret) { continue; } if (!_my_patterns) { _my_patterns = ret; _my_patterns->_next = NULL; _my_patterns->_idx = i; } else { end = _my_patterns; while( end->_next ) { end = end->_next; } end->_next = ret; //add to end ret->_idx = i; } } return 0; } int DFA::match(const char *str) const { return match(str,strlen(str)); } int DFA::match(const char *str, int length) const { int rc; dfa_pattern * p = _my_patterns; while(p) { rc = p->_re->exec(str, length); if (rc > 0) { return p->_idx; } p = p->_next; } return -1; } <commit_msg>Use libts pthread key wrappers<commit_after>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libts.h" #include "Regex.h" #ifdef PCRE_CONFIG_JIT struct RegexThreadKey { RegexThreadKey() { ink_thread_key_create(&this->key, (void (*)(void *)) &pcre_jit_stack_free); } ink_thread_key key; }; static RegexThreadKey k; static pcre_jit_stack * get_jit_stack(void *data ATS_UNUSED) { pcre_jit_stack *jit_stack; if ((jit_stack = (pcre_jit_stack *) ink_thread_getspecific(k.key)) == NULL) { jit_stack = pcre_jit_stack_alloc(ats_pagesize(), 1024 * 1024); // 1 page min and 1MB max ink_thread_setspecific(k.key, (void *)jit_stack); } return jit_stack; } #endif bool Regex::compile(const char *pattern, unsigned flags) { const char *error; int erroffset; int options = 0; int study_opts = 0; if (regex) return false; if (flags & RE_CASE_INSENSITIVE) { options |= PCRE_CASELESS; } if (flags & RE_ANCHORED) { options |= PCRE_ANCHORED; } regex = pcre_compile(pattern, options, &error, &erroffset, NULL); if (error) { regex = NULL; return false; } #ifdef PCRE_CONFIG_JIT study_opts |= PCRE_STUDY_JIT_COMPILE; #endif regex_extra = pcre_study(regex, study_opts, &error); #ifdef PCRE_CONFIG_JIT if (regex_extra) pcre_assign_jit_stack(regex_extra, &get_jit_stack, NULL); #endif return true; } bool Regex::exec(const char *str) { return exec(str, strlen(str)); } bool Regex::exec(const char *str, int length) { int ovector[30], rv; rv = pcre_exec(regex, regex_extra, str, length , 0, 0, ovector, countof(ovector)); return rv > 0 ? true : false; } Regex::~Regex() { if (regex_extra) #ifdef PCRE_CONFIG_JIT pcre_free_study(regex_extra); #else pcre_free(regex_extra); #endif if (regex) pcre_free(regex); } DFA::~DFA() { dfa_pattern * p = _my_patterns; dfa_pattern * t; while(p) { if (p->_re) delete p->_re; if(p->_p) ats_free(p->_p); t = p->_next; ats_free(p); p = t; } } dfa_pattern * DFA::build(const char *pattern, unsigned flags) { dfa_pattern* ret; int rv; if (!(flags & RE_UNANCHORED)) { flags |= RE_ANCHORED; } ret = (dfa_pattern*)ats_malloc(sizeof(dfa_pattern)); ret->_p = NULL; ret->_re = new Regex(); rv = ret->_re->compile(pattern, flags); if (rv == -1) { delete ret->_re; ats_free(ret); return NULL; } ret->_idx = 0; ret->_p = ats_strndup(pattern, strlen(pattern)); ret->_next = NULL; return ret; } int DFA::compile(const char *pattern, unsigned flags) { ink_assert(_my_patterns == NULL); _my_patterns = build(pattern,flags); if (_my_patterns) return 0; else return -1; } int DFA::compile(const char **patterns, int npatterns, unsigned flags) { const char *pattern; dfa_pattern *ret = NULL; dfa_pattern *end = NULL; int i; for (i = 0; i < npatterns; i++) { pattern = patterns[i]; ret = build(pattern,flags); if (!ret) { continue; } if (!_my_patterns) { _my_patterns = ret; _my_patterns->_next = NULL; _my_patterns->_idx = i; } else { end = _my_patterns; while( end->_next ) { end = end->_next; } end->_next = ret; //add to end ret->_idx = i; } } return 0; } int DFA::match(const char *str) const { return match(str,strlen(str)); } int DFA::match(const char *str, int length) const { int rc; dfa_pattern * p = _my_patterns; while(p) { rc = p->_re->exec(str, length); if (rc > 0) { return p->_idx; } p = p->_next; } return -1; } <|endoftext|>
<commit_before>/* * Copyright 2010-2015, Tarantool AUTHORS, please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "coeio.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <netdb.h> #include <sys/socket.h> #include "fiber.h" #include "exception.h" #include "third_party/tarantool_ev.h" /* * Asynchronous IO Tasks (libeio wrapper). * --------------------------------------- * * libeio request processing is designed in edge-trigger * manner, when libeio is ready to process some requests it * calls coeio_poller callback. * * Due to libeio design, want_poll callback is called while * locks are being held, so it's not possible to call any libeio * function inside this callback. Thus coeio_want_poll raises an * async event which will be dealt with normally as part of the * main Tarantool event loop. * * The async event handler, in turn, performs eio_poll(), which * will run on_complete callback for all ready eio tasks. * In case if some of the requests are not complete by the time * eio_poll() has been called, coeio_idle watcher is started, which * would periodically invoke eio_poll() until all requests are * complete. * * See for details: * http://pod.tst.eu/http://cvs.schmorp.de/libeio/eio.pod */ struct coeio_manager { ev_loop *loop; ev_idle coeio_idle; ev_async coeio_async; } coeio_manager; static void coeio_idle_cb(ev_loop *loop, struct ev_idle *w, int /* events */) { if (eio_poll() != -1) { /* nothing to do */ ev_idle_stop(loop, w); } } static void coeio_async_cb(ev_loop *loop, struct ev_async *w __attribute__((unused)), int events __attribute__((unused))) { if (eio_poll() == -1) { /* not all tasks are complete. */ ev_idle_start(loop, &coeio_manager.coeio_idle); } } static void coeio_want_poll_cb(void) { ev_async_send(coeio_manager.loop, &coeio_manager.coeio_async); } /** * Init coeio subsystem. * * Create idle and async watchers, init eio. */ void coeio_init(void) { eio_init(coeio_want_poll_cb, NULL); coeio_manager.loop = loop(); ev_idle_init(&coeio_manager.coeio_idle, coeio_idle_cb); ev_async_init(&coeio_manager.coeio_async, coeio_async_cb); ev_async_start(loop(), &coeio_manager.coeio_async); } /** * ReInit coeio subsystem (for example after 'fork') */ void coeio_reinit(void) { eio_init(coeio_want_poll_cb, NULL); } static void coio_on_exec(eio_req *req) { struct coio_task *task = (struct coio_task *) req; req->result = task->task_cb(task); } /** * A callback invoked by eio_poll when associated * eio_request is complete. */ static int coio_on_finish(eio_req *req) { struct coio_task *task = (struct coio_task *) req; if (task->fiber == NULL) { /* timed out (only coio_task() )*/ if (task->timeout_cb != NULL) { task->timeout_cb(task); } return 0; } task->complete = 1; fiber_wakeup(task->fiber); return 0; } ssize_t coio_task(struct coio_task *task, coio_task_cb func, coio_task_timeout_cb on_timeout, double timeout) { /* from eio.c: REQ() definition */ memset(&task->base, 0, sizeof(task->base)); task->base.type = EIO_CUSTOM; task->base.feed = coio_on_exec; task->base.finish = coio_on_finish; /* task->base.destroy = NULL; */ /* task->base.pri = 0; */ task->fiber = fiber(); task->task_cb = func; task->timeout_cb = on_timeout; task->complete = 0; eio_submit(&task->base); fiber_yield_timeout(timeout); if (!task->complete) { /* timed out or cancelled. */ task->fiber = NULL; fiber_testcancel(); tnt_raise(TimedOut); } return task->base.result; } static void coio_on_call(eio_req *req) { struct coio_task *task = (struct coio_task *) req; req->result = task->call_cb(task->ap); } ssize_t coio_call(ssize_t (*func)(va_list ap), ...) { struct coio_task *task = (struct coio_task *) calloc(1, sizeof(*task)); if (task == NULL) return -1; /* errno = ENOMEM */ /* from eio.c: REQ() definition */ task->base.type = EIO_CUSTOM; task->base.feed = coio_on_call; task->base.finish = coio_on_finish; /* task->base.destroy = NULL; */ /* task->base.pri = 0; */ task->fiber = fiber(); task->call_cb = func; task->complete = 0; bool cancellable = fiber_set_cancellable(false); va_start(task->ap, func); eio_submit(&task->base); fiber_yield(); assert(task->complete); va_end(task->ap); fiber_set_cancellable(cancellable); ssize_t result = task->base.result; int save_errno = errno; free(task); errno = save_errno; return result; } struct async_getaddrinfo_task { struct coio_task base; struct addrinfo *result; int rc; char *host; char *port; struct addrinfo hints; }; #ifndef EAI_ADDRFAMILY #define EAI_ADDRFAMILY EAI_BADFLAGS /* EAI_ADDRFAMILY is deprecated on BSD */ #endif /* * Resolver function, run in separate thread by * coeio (libeio). */ static ssize_t getaddrinfo_cb(struct coio_task *ptr) { struct async_getaddrinfo_task *task = (struct async_getaddrinfo_task *) ptr; task->rc = getaddrinfo(task->host, task->port, &task->hints, &task->result); /* getaddrinfo can return EAI_ADDRFAMILY on attempt * to resolve ::1, if machine has no public ipv6 addresses * configured. Retry without AI_ADDRCONFIG flag set. * * See for details: https://bugs.launchpad.net/tarantool/+bug/1160877 */ if ((task->rc == EAI_BADFLAGS || task->rc == EAI_ADDRFAMILY) && (task->hints.ai_flags & AI_ADDRCONFIG)) { task->hints.ai_flags &= ~AI_ADDRCONFIG; task->rc = getaddrinfo(task->host, task->port, &task->hints, &task->result); } return 0; } static void getaddrinfo_free_cb(struct coio_task *ptr) { struct async_getaddrinfo_task *task = (struct async_getaddrinfo_task *) ptr; free(task->host); free(task->port); if (task->result != NULL) freeaddrinfo(task->result); free(task); } int coio_getaddrinfo(const char *host, const char *port, const struct addrinfo *hints, struct addrinfo **res, double timeout) { int rc = EAI_SYSTEM; int save_errno = 0; struct async_getaddrinfo_task *task = (struct async_getaddrinfo_task *) calloc(1, sizeof(*task)); if (task == NULL) return rc; /* Fill hinting information for use by connect(2) or bind(2). */ memcpy(&task->hints, hints, sizeof(task->hints)); /* make no difference between empty string and NULL for host */ if (host != NULL && *host) { task->host = strdup(host); if (task->host == NULL) { save_errno = errno; goto cleanup_task; } } if (port != NULL) { task->port = strdup(port); if (task->port == NULL) { save_errno = errno; goto cleanup_host; } } /* do resolving */ /* coio_task() don't throw. */ if (coio_task(&task->base, getaddrinfo_cb, getaddrinfo_free_cb, timeout) == -1) tnt_raise(TimedOut); rc = task->rc; *res = task->result; free(task->port); cleanup_host: free(task->host); cleanup_task: free(task); errno = save_errno; return rc; } static ssize_t cord_cojoin_cb(va_list ap) { struct cord *cord = va_arg(ap, struct cord *); void *retval = NULL; int res = tt_pthread_join(cord->id, &retval); return res; } int cord_cojoin(struct cord *cord) { assert(cord() != cord); /* Can't join self. */ int rc = coio_call(cord_cojoin_cb, cord); if (rc == 0 && !diag_is_empty(&cord->fiber->diag)) { diag_move(&cord->fiber->diag, &fiber()->diag); cord_destroy(cord); /* re-throw exception in this fiber */ diag_last_error(&fiber()->diag)->raise(); } cord_destroy(cord); return rc; } <commit_msg>gh-1107: getaddrinfo crash on osx upto osx 10.8<commit_after>/* * Copyright 2010-2015, Tarantool AUTHORS, please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "coeio.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <netdb.h> #include <sys/socket.h> #include "fiber.h" #include "exception.h" #include "third_party/tarantool_ev.h" /* * Asynchronous IO Tasks (libeio wrapper). * --------------------------------------- * * libeio request processing is designed in edge-trigger * manner, when libeio is ready to process some requests it * calls coeio_poller callback. * * Due to libeio design, want_poll callback is called while * locks are being held, so it's not possible to call any libeio * function inside this callback. Thus coeio_want_poll raises an * async event which will be dealt with normally as part of the * main Tarantool event loop. * * The async event handler, in turn, performs eio_poll(), which * will run on_complete callback for all ready eio tasks. * In case if some of the requests are not complete by the time * eio_poll() has been called, coeio_idle watcher is started, which * would periodically invoke eio_poll() until all requests are * complete. * * See for details: * http://pod.tst.eu/http://cvs.schmorp.de/libeio/eio.pod */ struct coeio_manager { ev_loop *loop; ev_idle coeio_idle; ev_async coeio_async; } coeio_manager; static void coeio_idle_cb(ev_loop *loop, struct ev_idle *w, int /* events */) { if (eio_poll() != -1) { /* nothing to do */ ev_idle_stop(loop, w); } } static void coeio_async_cb(ev_loop *loop, struct ev_async *w __attribute__((unused)), int events __attribute__((unused))) { if (eio_poll() == -1) { /* not all tasks are complete. */ ev_idle_start(loop, &coeio_manager.coeio_idle); } } static void coeio_want_poll_cb(void) { ev_async_send(coeio_manager.loop, &coeio_manager.coeio_async); } /** * Init coeio subsystem. * * Create idle and async watchers, init eio. */ void coeio_init(void) { eio_init(coeio_want_poll_cb, NULL); coeio_manager.loop = loop(); ev_idle_init(&coeio_manager.coeio_idle, coeio_idle_cb); ev_async_init(&coeio_manager.coeio_async, coeio_async_cb); ev_async_start(loop(), &coeio_manager.coeio_async); } /** * ReInit coeio subsystem (for example after 'fork') */ void coeio_reinit(void) { eio_init(coeio_want_poll_cb, NULL); } static void coio_on_exec(eio_req *req) { struct coio_task *task = (struct coio_task *) req; req->result = task->task_cb(task); } /** * A callback invoked by eio_poll when associated * eio_request is complete. */ static int coio_on_finish(eio_req *req) { struct coio_task *task = (struct coio_task *) req; if (task->fiber == NULL) { /* timed out (only coio_task() )*/ if (task->timeout_cb != NULL) { task->timeout_cb(task); } return 0; } task->complete = 1; fiber_wakeup(task->fiber); return 0; } ssize_t coio_task(struct coio_task *task, coio_task_cb func, coio_task_timeout_cb on_timeout, double timeout) { /* from eio.c: REQ() definition */ memset(&task->base, 0, sizeof(task->base)); task->base.type = EIO_CUSTOM; task->base.feed = coio_on_exec; task->base.finish = coio_on_finish; /* task->base.destroy = NULL; */ /* task->base.pri = 0; */ task->fiber = fiber(); task->task_cb = func; task->timeout_cb = on_timeout; task->complete = 0; eio_submit(&task->base); fiber_yield_timeout(timeout); if (!task->complete) { /* timed out or cancelled. */ task->fiber = NULL; fiber_testcancel(); tnt_raise(TimedOut); } return task->base.result; } static void coio_on_call(eio_req *req) { struct coio_task *task = (struct coio_task *) req; req->result = task->call_cb(task->ap); } ssize_t coio_call(ssize_t (*func)(va_list ap), ...) { struct coio_task *task = (struct coio_task *) calloc(1, sizeof(*task)); if (task == NULL) return -1; /* errno = ENOMEM */ /* from eio.c: REQ() definition */ task->base.type = EIO_CUSTOM; task->base.feed = coio_on_call; task->base.finish = coio_on_finish; /* task->base.destroy = NULL; */ /* task->base.pri = 0; */ task->fiber = fiber(); task->call_cb = func; task->complete = 0; bool cancellable = fiber_set_cancellable(false); va_start(task->ap, func); eio_submit(&task->base); fiber_yield(); assert(task->complete); va_end(task->ap); fiber_set_cancellable(cancellable); ssize_t result = task->base.result; int save_errno = errno; free(task); errno = save_errno; return result; } struct async_getaddrinfo_task { struct coio_task base; struct addrinfo *result; int rc; char *host; char *port; struct addrinfo hints; }; #ifndef EAI_ADDRFAMILY #define EAI_ADDRFAMILY EAI_BADFLAGS /* EAI_ADDRFAMILY is deprecated on BSD */ #endif /* * Resolver function, run in separate thread by * coeio (libeio). */ static ssize_t getaddrinfo_cb(struct coio_task *ptr) { struct async_getaddrinfo_task *task = (struct async_getaddrinfo_task *) ptr; task->rc = getaddrinfo(task->host, task->port, &task->hints, &task->result); /* getaddrinfo can return EAI_ADDRFAMILY on attempt * to resolve ::1, if machine has no public ipv6 addresses * configured. Retry without AI_ADDRCONFIG flag set. * * See for details: https://bugs.launchpad.net/tarantool/+bug/1160877 */ if ((task->rc == EAI_BADFLAGS || task->rc == EAI_ADDRFAMILY) && (task->hints.ai_flags & AI_ADDRCONFIG)) { task->hints.ai_flags &= ~AI_ADDRCONFIG; task->rc = getaddrinfo(task->host, task->port, &task->hints, &task->result); } return 0; } static void getaddrinfo_free_cb(struct coio_task *ptr) { struct async_getaddrinfo_task *task = (struct async_getaddrinfo_task *) ptr; free(task->host); free(task->port); if (task->result != NULL) freeaddrinfo(task->result); free(task); } int coio_getaddrinfo(const char *host, const char *port, const struct addrinfo *hints, struct addrinfo **res, double timeout) { int rc = EAI_SYSTEM; int save_errno = 0; struct async_getaddrinfo_task *task = (struct async_getaddrinfo_task *) calloc(1, sizeof(*task)); if (task == NULL) return rc; /* * getaddrinfo() on osx upto osx 10.8 crashes when AI_NUMERICSERV is * set and servername is either NULL or "0" ("00" works fine) * * Based on the workaround in https://bugs.python.org/issue17269 */ #if defined(__APPLE__) && defined(AI_NUMERICSERV) if (hints && (hints->ai_flags & AI_NUMERICSERV) && (port == NULL || (port[0]=='0' && port[1]=='\0'))) port = "00"; #endif /* Fill hinting information for use by connect(2) or bind(2). */ memcpy(&task->hints, hints, sizeof(task->hints)); /* make no difference between empty string and NULL for host */ if (host != NULL && *host) { task->host = strdup(host); if (task->host == NULL) { save_errno = errno; goto cleanup_task; } } if (port != NULL) { task->port = strdup(port); if (task->port == NULL) { save_errno = errno; goto cleanup_host; } } /* do resolving */ /* coio_task() don't throw. */ if (coio_task(&task->base, getaddrinfo_cb, getaddrinfo_free_cb, timeout) == -1) tnt_raise(TimedOut); rc = task->rc; *res = task->result; free(task->port); cleanup_host: free(task->host); cleanup_task: free(task); errno = save_errno; return rc; } static ssize_t cord_cojoin_cb(va_list ap) { struct cord *cord = va_arg(ap, struct cord *); void *retval = NULL; int res = tt_pthread_join(cord->id, &retval); return res; } int cord_cojoin(struct cord *cord) { assert(cord() != cord); /* Can't join self. */ int rc = coio_call(cord_cojoin_cb, cord); if (rc == 0 && !diag_is_empty(&cord->fiber->diag)) { diag_move(&cord->fiber->diag, &fiber()->diag); cord_destroy(cord); /* re-throw exception in this fiber */ diag_last_error(&fiber()->diag)->raise(); } cord_destroy(cord); return rc; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include <Eigen/StdVector> #include "main.h" #include <Eigen/Geometry> template<typename MatrixType> void check_stdvector_matrix(const MatrixType& m) { int rows = m.rows(); int cols = m.cols(); MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols); std::vector<MatrixType> v(10, MatrixType(rows,cols)), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) MatrixType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i]==w[(i-23)%w.size()]); } } template<typename TransformType> void check_stdvector_transform(const TransformType&) { typedef typename TransformType::MatrixType MatrixType; TransformType x(MatrixType::Random()), y(MatrixType::Random()); std::vector<TransformType> v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) TransformType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix()); } } template<typename QuaternionType> void check_stdvector_quaternion(const QuaternionType&) { typedef typename QuaternionType::Coefficients Coefficients; QuaternionType x(Coefficients::Random()), y(Coefficients::Random()); std::vector<QuaternionType> v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) QuaternionType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs()); } } void test_stdvector() { // some non vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Vector2f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3d())); // some vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Matrix2f())); CALL_SUBTEST(check_stdvector_matrix(Vector4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4d())); // some dynamic sizes CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1))); CALL_SUBTEST(check_stdvector_matrix(VectorXd(20))); CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20))); CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10))); // some Transform CALL_SUBTEST(check_stdvector_transform(Transform2f())); CALL_SUBTEST(check_stdvector_transform(Transform3f())); CALL_SUBTEST(check_stdvector_transform(Transform3d())); //CALL_SUBTEST(check_stdvector_transform(Transform4d())); // some Quaternion CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); } <commit_msg>"forgot to commit the required changes in stdvector unit test"<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include <Eigen/StdVector> #include "main.h" #include <Eigen/Geometry> template<typename MatrixType> void check_stdvector_matrix(const MatrixType& m) { int rows = m.rows(); int cols = m.cols(); MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols); std::vector<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) MatrixType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i]==w[(i-23)%w.size()]); } } template<typename TransformType> void check_stdvector_transform(const TransformType&) { typedef typename TransformType::MatrixType MatrixType; TransformType x(MatrixType::Random()), y(MatrixType::Random()); std::vector<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) TransformType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix()); } } template<typename QuaternionType> void check_stdvector_quaternion(const QuaternionType&) { typedef typename QuaternionType::Coefficients Coefficients; QuaternionType x(Coefficients::Random()), y(Coefficients::Random()); std::vector<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y); v[5] = x; w[6] = v[5]; VERIFY_IS_APPROX(w[6], v[5]); v = w; for(int i = 0; i < 20; i++) { VERIFY_IS_APPROX(w[i], v[i]); } v.resize(21); v[20] = x; VERIFY_IS_APPROX(v[20], x); v.resize(22,y); VERIFY_IS_APPROX(v[21], y); v.push_back(x); VERIFY_IS_APPROX(v[22], x); VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType)); // do a lot of push_back such that the vector gets internally resized // (with memory reallocation) QuaternionType* ref = &w[0]; for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i) v.push_back(w[i%w.size()]); for(unsigned int i=23; i<v.size(); ++i) { VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs()); } } void test_stdvector() { // some non vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Vector2f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3f())); CALL_SUBTEST(check_stdvector_matrix(Matrix3d())); // some vectorizable fixed sizes CALL_SUBTEST(check_stdvector_matrix(Matrix2f())); CALL_SUBTEST(check_stdvector_matrix(Vector4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4f())); CALL_SUBTEST(check_stdvector_matrix(Matrix4d())); // some dynamic sizes CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1))); CALL_SUBTEST(check_stdvector_matrix(VectorXd(20))); CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20))); CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10))); // some Transform CALL_SUBTEST(check_stdvector_transform(Transform2f())); CALL_SUBTEST(check_stdvector_transform(Transform3f())); CALL_SUBTEST(check_stdvector_transform(Transform3d())); //CALL_SUBTEST(check_stdvector_transform(Transform4d())); // some Quaternion CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); CALL_SUBTEST(check_stdvector_quaternion(Quaternionf())); } <|endoftext|>
<commit_before>#include "MPPreview.h" MPPreview::MPPreview(int ideaID) : BWindow(BRect(100, 100, 900, 700), "tmp", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE) { // initialize controls BRect r = Bounds(); r.bottom = r.bottom - 50; previewTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW); previewTextView->SetStylable(true); previewTextView->MakeEditable(false); previewTextView->MakeSelectable(true); previewTextView->MakeResizable(true); backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW); backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(backView); // gui layout builder backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0)); backView->AddChild(BGridLayoutBuilder() .Add(new BScrollView("scroll_editor", previewTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 0) .SetInsets(0, 0, 0, 0) ); currentideaID = ideaID; // pass current idea id selected to editor window for use if(currentideaID != -1) // if id has a real value { sqlObject = new SqlObject(ideaStatement, "7"); sqlObject->PrepareSql("select ideatext, ideaname, ismp from ideatable where ideaid = ?"); sqlObject->BindValue(1, currentideaID); sqlObject->StepSql(); if(sqlObject->ReturnInt(2) == 0) // thought was selected to preview { rawText = sqlObject->ReturnText(0); previewTextView->SetText(rawText); BString tmpText; tmpText = "MasterPiece Preview - "; tmpText += sqlObject->ReturnText(1); this->SetTitle(tmpText); IdeaParser(rawText, previewTextView); // parse rawText here.... // getfontandcolor, store it, modify it, then setfontandcolor // ParseRawText(rawText, previewTextView); /* { previewTextView->InsertText(parsed lines); BEST METHOD MIGHT BE TO SETTEXT IN PREVIEWTEXTVIEW, THEN SELECT THE TEXT AND PARSE ACCORDINGLY USING SETFONTANDCOLOR } */ // display text in previewTextView such as... } else if(sqlObject->ReturnInt(2) == 1) // masterpiece was selected to preview { // sql query to get all thoughts // parse rawText for each thought and call insert to previewtextview here.... } sqlObject->FinalizeSql(); sqlObject->CloseSql(); } } /* void GetFontAndColor(BFont *font, uint32 *sameProperties, rgb_color *color = NULL, bool *sameColor = NULL) void SetFontAndColor(const BFont *font, uint32 properties = B_FONT_ALL, rgb_color *color = NULL) BFont font; uint32 sameProperties; theTextView->GetFontAndColor(&font, &sameProperties); font.SetSize(24.0); theTextView->SetFontAndColor(&font, B_FONT_ALL); BFont theBigFont(be_plain_font); theBigFont.SetSize(48.0); theBigFont.SetRotation(-45.0); theBigFont.SetShear(120.0); theTextView->SetFontAndColor(&theBigFont, B_FONT_SIZE); BFont font; uint32 sameProperties; rgb_color redColor = {255, 0, 0, 255}; theTextView->GetFontAndColor(&font, &sameProperties); theTextView->SetFontAndColor(&font, B_FONT_ALL, &redColor); */ void MPPreview::IdeaParser(BString inputText, BTextView* displayTextView) { displayTextView->SelectAll(); displayTextView->GetSelection(&startPos, &endPos); displayTextView->GetFontAndColor(&parseFont, &sameProperties); parseFont.SetSize(24.0); displayTextView->SetFontAndColor(startPos, endPos, &parseFont, B_FONT_SIZE); // create parser here //return displayTextView; // TEST REGEX PARSER - this works and handles the parser conversion from BString to C string and back... /* string s; int i; pcrecpp::RE re("(\\w+):(\\d+)"); re.FullMatch("ruby:1234 ruby:123", &s, &i); printf("\r\n%d\r\n", i); reTester = s.c_str(); eAlert = new ErrorAlert(reTester); eAlert->Launch(); s = "yabba dabba doo"; pcrecpp::RE("b+").GlobalReplace("d", &s); eAlert = new ErrorAlert(s.c_str()); eAlert->Launch(); */ // TEST REGEX PARSER // 1. it seems to do this, i will need to copy the entire string from the textview // 2. split the string into substrings based on the parsing... (possibly capture the length) // 2.4 strlen to get the length. // 2.5 get the length, then use offset=0 + length for each substring as i go... // 3. add the formatting requirements to the substrings based on the parsing // 3. use InsertText(text, length, offset, runs) to add the formatted text // EXAMPLE TEXT "Test of some *bold* text and more *bold* text." // ACTUAL REGEX PARSER TEST // 1. use global replace to search for a pattern in the textview string string s; s = "Test of some |bold| text and more |bold| text."; pcrecpp::RE("\|[^\|]*\|").GlobalReplace("bb", &s); eAlert = new ErrorAlert(s.c_str()); eAlert->Launch(); } void MPPreview::MessageReceived(BMessage* msg) { switch(msg->what) { default: { BWindow::MessageReceived(msg); break; } } } bool MPPreview::QuitRequested(void) { return true; } <commit_msg>going away from my preview to python html webpositive preview<commit_after>#include "MPPreview.h" MPPreview::MPPreview(int ideaID) : BWindow(BRect(100, 100, 900, 700), "tmp", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE) { // initialize controls BRect r = Bounds(); r.bottom = r.bottom - 50; previewTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW); previewTextView->SetStylable(true); previewTextView->MakeEditable(false); previewTextView->MakeSelectable(true); previewTextView->MakeResizable(true); backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW); backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(backView); // gui layout builder backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0)); backView->AddChild(BGridLayoutBuilder() .Add(new BScrollView("scroll_editor", previewTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 0) .SetInsets(0, 0, 0, 0) ); currentideaID = ideaID; // pass current idea id selected to editor window for use if(currentideaID != -1) // if id has a real value { sqlObject = new SqlObject(ideaStatement, "7"); sqlObject->PrepareSql("select ideatext, ideaname, ismp from ideatable where ideaid = ?"); sqlObject->BindValue(1, currentideaID); sqlObject->StepSql(); if(sqlObject->ReturnInt(2) == 0) // thought was selected to preview { rawText = sqlObject->ReturnText(0); previewTextView->SetText(rawText); BString tmpText; tmpText = "MasterPiece Preview - "; tmpText += sqlObject->ReturnText(1); this->SetTitle(tmpText); IdeaParser(rawText, previewTextView); // parse rawText here.... // getfontandcolor, store it, modify it, then setfontandcolor // ParseRawText(rawText, previewTextView); /* { previewTextView->InsertText(parsed lines); BEST METHOD MIGHT BE TO SETTEXT IN PREVIEWTEXTVIEW, THEN SELECT THE TEXT AND PARSE ACCORDINGLY USING SETFONTANDCOLOR } */ // display text in previewTextView such as... } else if(sqlObject->ReturnInt(2) == 1) // masterpiece was selected to preview { // sql query to get all thoughts // parse rawText for each thought and call insert to previewtextview here.... } sqlObject->FinalizeSql(); sqlObject->CloseSql(); } } /* void GetFontAndColor(BFont *font, uint32 *sameProperties, rgb_color *color = NULL, bool *sameColor = NULL) void SetFontAndColor(const BFont *font, uint32 properties = B_FONT_ALL, rgb_color *color = NULL) BFont font; uint32 sameProperties; theTextView->GetFontAndColor(&font, &sameProperties); font.SetSize(24.0); theTextView->SetFontAndColor(&font, B_FONT_ALL); BFont theBigFont(be_plain_font); theBigFont.SetSize(48.0); theBigFont.SetRotation(-45.0); theBigFont.SetShear(120.0); theTextView->SetFontAndColor(&theBigFont, B_FONT_SIZE); BFont font; uint32 sameProperties; rgb_color redColor = {255, 0, 0, 255}; theTextView->GetFontAndColor(&font, &sameProperties); theTextView->SetFontAndColor(&font, B_FONT_ALL, &redColor); */ void MPPreview::IdeaParser(BString inputText, BTextView* displayTextView) { displayTextView->SelectAll(); displayTextView->GetSelection(&startPos, &endPos); displayTextView->GetFontAndColor(&parseFont, &sameProperties); parseFont.SetSize(24.0); displayTextView->SetFontAndColor(startPos, endPos, &parseFont, B_FONT_SIZE); // create parser here //return displayTextView; // TEST REGEX PARSER - this works and handles the parser conversion from BString to C string and back... /* string s; int i; pcrecpp::RE re("(\\w+):(\\d+)"); re.FullMatch("ruby:1234 ruby:123", &s, &i); printf("\r\n%d\r\n", i); reTester = s.c_str(); eAlert = new ErrorAlert(reTester); eAlert->Launch(); s = "yabba dabba doo"; pcrecpp::RE("b+").GlobalReplace("d", &s); eAlert = new ErrorAlert(s.c_str()); eAlert->Launch(); */ // TEST REGEX PARSER // 1. it seems to do this, i will need to copy the entire string from the textview // 2. split the string into substrings based on the parsing... (possibly capture the length) // 2.4 strlen to get the length. // 2.5 get the length, then use offset=0 + length for each substring as i go... // 3. add the formatting requirements to the substrings based on the parsing // 3. use InsertText(text, length, offset, runs) to add the formatted text // EXAMPLE TEXT "Test of some *bold* text and more *bold* text." // ACTUAL REGEX PARSER TEST // 1. use global replace to search for a pattern in the textview string //string s; //s = "Test of some |bold| text and more |bold| text."; //pcrecpp::RE("\|[^\|]*\|").GlobalReplace("bb", &s); //eAlert = new ErrorAlert(s.c_str()); //eAlert->Launch(); } void MPPreview::MessageReceived(BMessage* msg) { switch(msg->what) { default: { BWindow::MessageReceived(msg); break; } } } bool MPPreview::QuitRequested(void) { return true; } <|endoftext|>
<commit_before>//===- LowerGuardIntrinsic.cpp - Lower the guard intrinsic ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass lowers the llvm.experimental.guard intrinsic to a conditional call // to @llvm.experimental.deoptimize. Once this happens, the guard can no longer // be widened. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/ADT/SmallVector.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; static cl::opt<uint32_t> LikelyBranchWeight( "guards-likely-branch-weight", cl::Hidden, cl::init(1 << 20), cl::desc("The probability of a guard failing is assumed to be the " "reciprocal of this value (default = 1 << 20)")); namespace { struct LowerGuardIntrinsic : public FunctionPass { static char ID; LowerGuardIntrinsic() : FunctionPass(ID) { initializeLowerGuardIntrinsicPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function &F) override; }; } static void MakeGuardControlFlowExplicit(Function *DeoptIntrinsic, CallInst *CI) { OperandBundleDef DeoptOB(*CI->getOperandBundle(LLVMContext::OB_deopt)); SmallVector<Value *, 4> Args(std::next(CI->arg_begin()), CI->arg_end()); auto *CheckBB = CI->getParent(); auto *DeoptBlockTerm = SplitBlockAndInsertIfThen(CI->getArgOperand(0), CI, true); auto *CheckBI = cast<BranchInst>(CheckBB->getTerminator()); // SplitBlockAndInsertIfThen inserts control flow that branches to // DeoptBlockTerm if the condition is true. We want the opposite. CheckBI->swapSuccessors(); CheckBI->getSuccessor(0)->setName("guarded"); CheckBI->getSuccessor(1)->setName("deopt"); if (auto *MD = CI->getMetadata(LLVMContext::MD_make_implicit)) CheckBI->setMetadata(LLVMContext::MD_make_implicit, MD); MDBuilder MDB(CI->getContext()); CheckBI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(LikelyBranchWeight, 1)); IRBuilder<> B(DeoptBlockTerm); auto *DeoptCall = B.CreateCall(DeoptIntrinsic, Args, {DeoptOB}, ""); if (DeoptIntrinsic->getReturnType()->isVoidTy()) { B.CreateRetVoid(); } else { DeoptCall->setName("deoptcall"); B.CreateRet(DeoptCall); } DeoptCall->setCallingConv(CI->getCallingConv()); DeoptBlockTerm->eraseFromParent(); } bool LowerGuardIntrinsic::runOnFunction(Function &F) { // Check if we can cheaply rule out the possibility of not having any work to // do. auto *GuardDecl = F.getParent()->getFunction( Intrinsic::getName(Intrinsic::experimental_guard)); if (!GuardDecl || GuardDecl->use_empty()) return false; SmallVector<CallInst *, 8> ToLower; for (auto &I : instructions(F)) if (auto *CI = dyn_cast<CallInst>(&I)) if (auto *F = CI->getCalledFunction()) if (F->getIntrinsicID() == Intrinsic::experimental_guard) ToLower.push_back(CI); if (ToLower.empty()) return false; auto *DeoptIntrinsic = Intrinsic::getDeclaration( F.getParent(), Intrinsic::experimental_deoptimize, {F.getReturnType()}); DeoptIntrinsic->setCallingConv(GuardDecl->getCallingConv()); for (auto *CI : ToLower) { MakeGuardControlFlowExplicit(DeoptIntrinsic, CI); CI->eraseFromParent(); } return true; } char LowerGuardIntrinsic::ID = 0; INITIALIZE_PASS(LowerGuardIntrinsic, "lower-guard-intrinsic", "Lower the guard intrinsic to normal control flow", false, false) Pass *llvm::createLowerGuardIntrinsicPass() { return new LowerGuardIntrinsic(); } <commit_msg>[LowerGuards] Rename variable; NFC<commit_after>//===- LowerGuardIntrinsic.cpp - Lower the guard intrinsic ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass lowers the llvm.experimental.guard intrinsic to a conditional call // to @llvm.experimental.deoptimize. Once this happens, the guard can no longer // be widened. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/ADT/SmallVector.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; static cl::opt<uint32_t> PredicatePassBranchWeight( "guards-predicate-pass-branch-weight", cl::Hidden, cl::init(1 << 20), cl::desc("The probability of a guard failing is assumed to be the " "reciprocal of this value (default = 1 << 20)")); namespace { struct LowerGuardIntrinsic : public FunctionPass { static char ID; LowerGuardIntrinsic() : FunctionPass(ID) { initializeLowerGuardIntrinsicPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function &F) override; }; } static void MakeGuardControlFlowExplicit(Function *DeoptIntrinsic, CallInst *CI) { OperandBundleDef DeoptOB(*CI->getOperandBundle(LLVMContext::OB_deopt)); SmallVector<Value *, 4> Args(std::next(CI->arg_begin()), CI->arg_end()); auto *CheckBB = CI->getParent(); auto *DeoptBlockTerm = SplitBlockAndInsertIfThen(CI->getArgOperand(0), CI, true); auto *CheckBI = cast<BranchInst>(CheckBB->getTerminator()); // SplitBlockAndInsertIfThen inserts control flow that branches to // DeoptBlockTerm if the condition is true. We want the opposite. CheckBI->swapSuccessors(); CheckBI->getSuccessor(0)->setName("guarded"); CheckBI->getSuccessor(1)->setName("deopt"); if (auto *MD = CI->getMetadata(LLVMContext::MD_make_implicit)) CheckBI->setMetadata(LLVMContext::MD_make_implicit, MD); MDBuilder MDB(CI->getContext()); CheckBI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(PredicatePassBranchWeight, 1)); IRBuilder<> B(DeoptBlockTerm); auto *DeoptCall = B.CreateCall(DeoptIntrinsic, Args, {DeoptOB}, ""); if (DeoptIntrinsic->getReturnType()->isVoidTy()) { B.CreateRetVoid(); } else { DeoptCall->setName("deoptcall"); B.CreateRet(DeoptCall); } DeoptCall->setCallingConv(CI->getCallingConv()); DeoptBlockTerm->eraseFromParent(); } bool LowerGuardIntrinsic::runOnFunction(Function &F) { // Check if we can cheaply rule out the possibility of not having any work to // do. auto *GuardDecl = F.getParent()->getFunction( Intrinsic::getName(Intrinsic::experimental_guard)); if (!GuardDecl || GuardDecl->use_empty()) return false; SmallVector<CallInst *, 8> ToLower; for (auto &I : instructions(F)) if (auto *CI = dyn_cast<CallInst>(&I)) if (auto *F = CI->getCalledFunction()) if (F->getIntrinsicID() == Intrinsic::experimental_guard) ToLower.push_back(CI); if (ToLower.empty()) return false; auto *DeoptIntrinsic = Intrinsic::getDeclaration( F.getParent(), Intrinsic::experimental_deoptimize, {F.getReturnType()}); DeoptIntrinsic->setCallingConv(GuardDecl->getCallingConv()); for (auto *CI : ToLower) { MakeGuardControlFlowExplicit(DeoptIntrinsic, CI); CI->eraseFromParent(); } return true; } char LowerGuardIntrinsic::ID = 0; INITIALIZE_PASS(LowerGuardIntrinsic, "lower-guard-intrinsic", "Lower the guard intrinsic to normal control flow", false, false) Pass *llvm::createLowerGuardIntrinsicPass() { return new LowerGuardIntrinsic(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ManifestExport.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2006-10-13 11:47:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_package.hxx" #ifndef _MANIFEST_EXPORT_HXX #include <ManifestExport.hxx> #endif #ifndef _MANIFEST_DEFINES_HXX #include <ManifestDefines.hxx> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HXX #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _BASE64_CODEC_HXX_ #include <Base64Codec.hxx> #endif #ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HXX #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_BEANS_PROPERTYVALUE_HPP #include <com/sun/star/beans/PropertyValue.hpp> #endif #include <comphelper/documentconstants.hxx> #include <comphelper/attributelist.hxx> using namespace rtl; using namespace com::sun::star::beans; using namespace com::sun::star::uno; using namespace com::sun::star::xml::sax; ManifestExport::ManifestExport(Reference < XDocumentHandler > xHandler, const Sequence < Sequence < PropertyValue > > &rManList ) { const OUString sFileEntryElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) ); const OUString sManifestElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) ); const OUString sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) ); const OUString sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) ); const OUString sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) ); const OUString sCdataAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) ); const OUString sMediaTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) ); const OUString sFullPathAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) ); const OUString sSizeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) ); const OUString sSaltAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) ); const OUString sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) ); const OUString sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) ); const OUString sAlgorithmNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) ); const OUString sKeyDerivationNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) ); const OUString sChecksumTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) ); const OUString sChecksumAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM) ); const OUString sFullPathProperty ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) ); const OUString sMediaTypeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) ); const OUString sIterationCountProperty ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) ); const OUString sSaltProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) ); const OUString sInitialisationVectorProperty( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) ); const OUString sSizeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) ); const OUString sDigestProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) ); const OUString sWhiteSpace ( RTL_CONSTASCII_USTRINGPARAM ( " " ) ); const OUString sBlowfish ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) ); const OUString sPBKDF2 ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) ); const OUString sChecksumType ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) ); ::comphelper::AttributeList * pRootAttrList = new ::comphelper::AttributeList; const Sequence < PropertyValue > *pSequence = rManList.getConstArray(); const sal_uInt32 nManLength = rManList.getLength(); // find the mediatype of the document if any OUString aDocMediaType; for (sal_uInt32 nInd = 0; nInd < nManLength ; nInd++ ) { OUString aMediaType; OUString aPath; const PropertyValue *pValue = pSequence[nInd].getConstArray(); for (sal_uInt32 j = 0, nNum = pSequence[nInd].getLength(); j < nNum; j++, pValue++) { if (pValue->Name.equals (sMediaTypeProperty) ) { pValue->Value >>= aMediaType; } else if (pValue->Name.equals (sFullPathProperty) ) { pValue->Value >>= aPath; } if ( aPath.getLength() && aMediaType.getLength() ) break; } if ( aPath.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ) ) { aDocMediaType = aMediaType; break; } } sal_Bool bProvideDTD = sal_False; if ( aDocMediaType.getLength() ) { if ( aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII ) ) ) ) { // oasis format pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ), sCdataAttribute, OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_OASIS_NAMESPACE ) ) ); } else { // even if it is no SO6 format the namespace must be specified // thus SO6 format is used as default one pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ), sCdataAttribute, OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_NAMESPACE ) ) ); bProvideDTD = sal_True; } } Reference < XAttributeList > xRootAttrList (pRootAttrList); xHandler->startDocument(); Reference < XExtendedDocumentHandler > xExtHandler ( xHandler, UNO_QUERY ); if ( xExtHandler.is() && bProvideDTD ) { OUString aDocType ( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_DOCTYPE ) ); xExtHandler->unknown ( aDocType ); xHandler->ignorableWhitespace ( sWhiteSpace ); } xHandler->startElement( sManifestElement, xRootAttrList ); for (sal_uInt32 i = 0 ; i < nManLength ; i++) { ::comphelper::AttributeList *pAttrList = new ::comphelper::AttributeList; const PropertyValue *pValue = pSequence[i].getConstArray(); OUString aString; const PropertyValue *pVector = NULL, *pSalt = NULL, *pIterationCount = NULL, *pDigest = NULL; for (sal_uInt32 j = 0, nNum = pSequence[i].getLength(); j < nNum; j++, pValue++) { if (pValue->Name.equals (sMediaTypeProperty) ) { pValue->Value >>= aString; pAttrList->AddAttribute ( sMediaTypeAttribute, sCdataAttribute, aString ); } else if (pValue->Name.equals (sFullPathProperty) ) { pValue->Value >>= aString; pAttrList->AddAttribute ( sFullPathAttribute, sCdataAttribute, aString ); } else if (pValue->Name.equals (sSizeProperty) ) { sal_Int32 nSize; pValue->Value >>= nSize; OUStringBuffer aBuffer; aBuffer.append ( nSize ); pAttrList->AddAttribute ( sSizeAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); } else if (pValue->Name.equals (sInitialisationVectorProperty) ) pVector = pValue; else if (pValue->Name.equals (sSaltProperty) ) pSalt = pValue; else if (pValue->Name.equals (sIterationCountProperty) ) pIterationCount = pValue; else if (pValue->Name.equals ( sDigestProperty ) ) pDigest = pValue; } xHandler->ignorableWhitespace ( sWhiteSpace ); Reference < XAttributeList > xAttrList ( pAttrList ); xHandler->startElement( sFileEntryElement , xAttrList); if ( pVector && pSalt && pIterationCount ) { ::comphelper::AttributeList * pNewAttrList = new ::comphelper::AttributeList; Reference < XAttributeList > xNewAttrList (pNewAttrList); OUStringBuffer aBuffer; Sequence < sal_uInt8 > aSequence; xHandler->ignorableWhitespace ( sWhiteSpace ); if ( pDigest ) { pNewAttrList->AddAttribute ( sChecksumTypeAttribute, sCdataAttribute, sChecksumType ); pDigest->Value >>= aSequence; Base64Codec::encodeBase64 ( aBuffer, aSequence ); pNewAttrList->AddAttribute ( sChecksumAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); } xHandler->startElement( sEncryptionDataElement , xNewAttrList); pNewAttrList = new ::comphelper::AttributeList; xNewAttrList = pNewAttrList; pNewAttrList->AddAttribute ( sAlgorithmNameAttribute, sCdataAttribute, sBlowfish ); pVector->Value >>= aSequence; Base64Codec::encodeBase64 ( aBuffer, aSequence ); pNewAttrList->AddAttribute ( sInitialisationVectorAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->startElement( sAlgorithmElement , xNewAttrList); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sAlgorithmElement ); pNewAttrList = new ::comphelper::AttributeList; xNewAttrList = pNewAttrList; pNewAttrList->AddAttribute ( sKeyDerivationNameAttribute, sCdataAttribute, sPBKDF2 ); sal_Int32 nCount; pIterationCount->Value >>= nCount; aBuffer.append (nCount); pNewAttrList->AddAttribute ( sIterationCountAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); pSalt->Value >>= aSequence; Base64Codec::encodeBase64 ( aBuffer, aSequence ); pNewAttrList->AddAttribute ( sSaltAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->startElement( sKeyDerivationElement , xNewAttrList); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sKeyDerivationElement ); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sEncryptionDataElement ); } xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sFileEntryElement ); } xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sManifestElement ); xHandler->endDocument(); } <commit_msg>INTEGRATION: CWS pj65 (1.15.14); FILE MERGED 2006/10/31 13:32:34 pjanik 1.15.14.1: #i71027#: prevent warnings on Mac OS X with gcc 4.0.1.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ManifestExport.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: vg $ $Date: 2006-11-21 17:51:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_package.hxx" #ifndef _MANIFEST_EXPORT_HXX #include <ManifestExport.hxx> #endif #ifndef _MANIFEST_DEFINES_HXX #include <ManifestDefines.hxx> #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HXX #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _BASE64_CODEC_HXX_ #include <Base64Codec.hxx> #endif #ifndef _COM_SUN_STAR_XML_SAX_XEXTENDEDDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HXX #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_XML_BEANS_PROPERTYVALUE_HPP #include <com/sun/star/beans/PropertyValue.hpp> #endif #include <comphelper/documentconstants.hxx> #include <comphelper/attributelist.hxx> using namespace rtl; using namespace com::sun::star::beans; using namespace com::sun::star::uno; using namespace com::sun::star::xml::sax; ManifestExport::ManifestExport(Reference < XDocumentHandler > xHandler, const Sequence < Sequence < PropertyValue > > &rManList ) { const OUString sFileEntryElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_FILE_ENTRY ) ); const OUString sManifestElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_MANIFEST ) ); const OUString sEncryptionDataElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ENCRYPTION_DATA ) ); const OUString sAlgorithmElement ( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_ALGORITHM ) ); const OUString sKeyDerivationElement( RTL_CONSTASCII_USTRINGPARAM ( ELEMENT_KEY_DERIVATION ) ); const OUString sCdataAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CDATA ) ); const OUString sMediaTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_MEDIA_TYPE ) ); const OUString sFullPathAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_FULL_PATH ) ); const OUString sSizeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SIZE ) ); const OUString sSaltAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_SALT ) ); const OUString sInitialisationVectorAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_INITIALISATION_VECTOR ) ); const OUString sIterationCountAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ITERATION_COUNT ) ); const OUString sAlgorithmNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_ALGORITHM_NAME ) ); const OUString sKeyDerivationNameAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_KEY_DERIVATION_NAME ) ); const OUString sChecksumTypeAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM_TYPE ) ); const OUString sChecksumAttribute ( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_CHECKSUM) ); const OUString sFullPathProperty ( RTL_CONSTASCII_USTRINGPARAM ( "FullPath" ) ); const OUString sMediaTypeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "MediaType" ) ); const OUString sIterationCountProperty ( RTL_CONSTASCII_USTRINGPARAM ( "IterationCount" ) ); const OUString sSaltProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Salt" ) ); const OUString sInitialisationVectorProperty( RTL_CONSTASCII_USTRINGPARAM ( "InitialisationVector" ) ); const OUString sSizeProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Size" ) ); const OUString sDigestProperty ( RTL_CONSTASCII_USTRINGPARAM ( "Digest" ) ); const OUString sWhiteSpace ( RTL_CONSTASCII_USTRINGPARAM ( " " ) ); const OUString sBlowfish ( RTL_CONSTASCII_USTRINGPARAM ( "Blowfish CFB" ) ); const OUString sPBKDF2 ( RTL_CONSTASCII_USTRINGPARAM ( "PBKDF2" ) ); const OUString sChecksumType ( RTL_CONSTASCII_USTRINGPARAM ( CHECKSUM_TYPE ) ); ::comphelper::AttributeList * pRootAttrList = new ::comphelper::AttributeList; const Sequence < PropertyValue > *pSequence = rManList.getConstArray(); const sal_uInt32 nManLength = rManList.getLength(); // find the mediatype of the document if any OUString aDocMediaType; for (sal_uInt32 nInd = 0; nInd < nManLength ; nInd++ ) { OUString aMediaType; OUString aPath; const PropertyValue *pValue = pSequence[nInd].getConstArray(); for (sal_uInt32 j = 0, nNum = pSequence[nInd].getLength(); j < nNum; j++, pValue++) { if (pValue->Name.equals (sMediaTypeProperty) ) { pValue->Value >>= aMediaType; } else if (pValue->Name.equals (sFullPathProperty) ) { pValue->Value >>= aPath; } if ( aPath.getLength() && aMediaType.getLength() ) break; } if ( aPath.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) ) ) ) { aDocMediaType = aMediaType; break; } } sal_Bool bProvideDTD = sal_False; if ( aDocMediaType.getLength() ) { if ( aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII ) ) ) || aDocMediaType.equals( OUString( RTL_CONSTASCII_USTRINGPARAM( MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII ) ) ) ) { // oasis format pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ), sCdataAttribute, OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_OASIS_NAMESPACE ) ) ); } else { // even if it is no SO6 format the namespace must be specified // thus SO6 format is used as default one pRootAttrList->AddAttribute ( OUString( RTL_CONSTASCII_USTRINGPARAM ( ATTRIBUTE_XMLNS ) ), sCdataAttribute, OUString( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_NAMESPACE ) ) ); bProvideDTD = sal_True; } } Reference < XAttributeList > xRootAttrList (pRootAttrList); xHandler->startDocument(); Reference < XExtendedDocumentHandler > xExtHandler ( xHandler, UNO_QUERY ); if ( xExtHandler.is() && bProvideDTD ) { OUString aDocType ( RTL_CONSTASCII_USTRINGPARAM ( MANIFEST_DOCTYPE ) ); xExtHandler->unknown ( aDocType ); xHandler->ignorableWhitespace ( sWhiteSpace ); } xHandler->startElement( sManifestElement, xRootAttrList ); for (sal_uInt32 i = 0 ; i < nManLength ; i++) { ::comphelper::AttributeList *pAttrList = new ::comphelper::AttributeList; const PropertyValue *pValue = pSequence[i].getConstArray(); OUString aString; const PropertyValue *pVector = NULL, *pSalt = NULL, *pIterationCount = NULL, *pDigest = NULL; for (sal_uInt32 j = 0, nNum = pSequence[i].getLength(); j < nNum; j++, pValue++) { if (pValue->Name.equals (sMediaTypeProperty) ) { pValue->Value >>= aString; pAttrList->AddAttribute ( sMediaTypeAttribute, sCdataAttribute, aString ); } else if (pValue->Name.equals (sFullPathProperty) ) { pValue->Value >>= aString; pAttrList->AddAttribute ( sFullPathAttribute, sCdataAttribute, aString ); } else if (pValue->Name.equals (sSizeProperty) ) { sal_Int32 nSize = 0; pValue->Value >>= nSize; OUStringBuffer aBuffer; aBuffer.append ( nSize ); pAttrList->AddAttribute ( sSizeAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); } else if (pValue->Name.equals (sInitialisationVectorProperty) ) pVector = pValue; else if (pValue->Name.equals (sSaltProperty) ) pSalt = pValue; else if (pValue->Name.equals (sIterationCountProperty) ) pIterationCount = pValue; else if (pValue->Name.equals ( sDigestProperty ) ) pDigest = pValue; } xHandler->ignorableWhitespace ( sWhiteSpace ); Reference < XAttributeList > xAttrList ( pAttrList ); xHandler->startElement( sFileEntryElement , xAttrList); if ( pVector && pSalt && pIterationCount ) { ::comphelper::AttributeList * pNewAttrList = new ::comphelper::AttributeList; Reference < XAttributeList > xNewAttrList (pNewAttrList); OUStringBuffer aBuffer; Sequence < sal_uInt8 > aSequence; xHandler->ignorableWhitespace ( sWhiteSpace ); if ( pDigest ) { pNewAttrList->AddAttribute ( sChecksumTypeAttribute, sCdataAttribute, sChecksumType ); pDigest->Value >>= aSequence; Base64Codec::encodeBase64 ( aBuffer, aSequence ); pNewAttrList->AddAttribute ( sChecksumAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); } xHandler->startElement( sEncryptionDataElement , xNewAttrList); pNewAttrList = new ::comphelper::AttributeList; xNewAttrList = pNewAttrList; pNewAttrList->AddAttribute ( sAlgorithmNameAttribute, sCdataAttribute, sBlowfish ); pVector->Value >>= aSequence; Base64Codec::encodeBase64 ( aBuffer, aSequence ); pNewAttrList->AddAttribute ( sInitialisationVectorAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->startElement( sAlgorithmElement , xNewAttrList); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sAlgorithmElement ); pNewAttrList = new ::comphelper::AttributeList; xNewAttrList = pNewAttrList; pNewAttrList->AddAttribute ( sKeyDerivationNameAttribute, sCdataAttribute, sPBKDF2 ); sal_Int32 nCount = 0; pIterationCount->Value >>= nCount; aBuffer.append (nCount); pNewAttrList->AddAttribute ( sIterationCountAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); pSalt->Value >>= aSequence; Base64Codec::encodeBase64 ( aBuffer, aSequence ); pNewAttrList->AddAttribute ( sSaltAttribute, sCdataAttribute, aBuffer.makeStringAndClear() ); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->startElement( sKeyDerivationElement , xNewAttrList); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sKeyDerivationElement ); xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sEncryptionDataElement ); } xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sFileEntryElement ); } xHandler->ignorableWhitespace ( sWhiteSpace ); xHandler->endElement( sManifestElement ); xHandler->endDocument(); } <|endoftext|>
<commit_before>#ifndef STAN_LANG_GENERATOR_GENERATE_INDEXED_EXPR_HPP #define STAN_LANG_GENERATOR_GENERATE_INDEXED_EXPR_HPP #include <stan/lang/ast.hpp> #include <stan/lang/generator/generate_indexed_expr_user.hpp> #include <stan/lang/generator/generate_quoted_string.hpp> #include <ostream> #include <string> #include <vector> namespace stan { namespace lang { /** * Generate the specified expression indexed with the specified * indices with the specified base type of expression being * indexed, number of dimensions, and a flag indicating whether * the generation is for user output or C++ compilation. * Depending on the base type, two layers of parens may be written * in the underlying code. * * @tparam isLHS true if indexed expression appears on left-hand * side of an assignment * @param[in] expr string for expression * @param[in] indexes indexes for expression * @param[in] base_type base type of expression * @param[in] user_facing true if expression might be reported to user * @param[in,out] o stream for generating */ template <bool isLHS> void generate_indexed_expr(const std::string& expr, const std::vector<expression>& indexes, bare_expr_type base_type, bool user_facing, std::ostream& o) { if (user_facing) { generate_indexed_expr_user(expr, indexes, o); return; } if (indexes.size() == 0) { o << expr; return; } if (base_type.innermost_type().is_matrix_type() && base_type.num_dims() == indexes.size()) { for (size_t n = 0; n < indexes.size() - 1; ++n) o << (isLHS ? "get_base1_lhs(" : "get_base1("); o << expr; for (size_t n = 0; n < indexes.size() - 2 ; ++n) { o << ", "; generate_expression(indexes[n], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (n + 1) << ')'; } o << ", "; generate_expression(indexes[indexes.size() - 2U], user_facing, o); o << ", "; generate_expression(indexes[indexes.size() - 1U], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (indexes.size() - 1U) << ')'; return; } for (size_t n = 0; n < indexes.size(); ++n) o << (isLHS ? "get_base1_lhs(" : "get_base1("); o << expr; for (size_t n = 0; n < indexes.size() - 1; ++n) { o << ", "; generate_expression(indexes[n], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (n + 1) << ')'; } o << ", "; generate_expression(indexes[indexes.size() - 1U], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (indexes.size()) << ')'; } } } #endif <commit_msg>undoing cleanup<commit_after>#ifndef STAN_LANG_GENERATOR_GENERATE_INDEXED_EXPR_HPP #define STAN_LANG_GENERATOR_GENERATE_INDEXED_EXPR_HPP #include <stan/lang/ast.hpp> #include <stan/lang/generator/generate_indexed_expr_user.hpp> #include <stan/lang/generator/generate_quoted_string.hpp> #include <ostream> #include <string> #include <vector> namespace stan { namespace lang { /** * Generate the specified expression indexed with the specified * indices with the specified base type of expression being * indexed, number of dimensions, and a flag indicating whether * the generation is for user output or C++ compilation. * Depending on the base type, two layers of parens may be written * in the underlying code. * * @tparam isLHS true if indexed expression appears on left-hand * side of an assignment * @param[in] expr string for expression * @param[in] indexes indexes for expression * @param[in] base_type base type of expression * @param[in] user_facing true if expression might be reported to user * @param[in,out] o stream for generating */ template <bool isLHS> void generate_indexed_expr(const std::string& expr, const std::vector<expression>& indexes, bare_expr_type base_type, bool user_facing, std::ostream& o) { if (user_facing) { generate_indexed_expr_user(expr, indexes, o); return; } if (indexes.size() == 0) { o << expr; return; } if (indexes.size() > 1 && base_type.innermost_type().is_matrix_type() && !(base_type.num_dims() - indexes.size() == 1)) { for (size_t n = 0; n < indexes.size() - 1; ++n) o << (isLHS ? "get_base1_lhs(" : "get_base1("); o << expr; for (size_t n = 0; n < indexes.size() - 2 ; ++n) { o << ", "; generate_expression(indexes[n], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (n + 1) << ')'; } o << ", "; generate_expression(indexes[indexes.size() - 2U], user_facing, o); o << ", "; generate_expression(indexes[indexes.size() - 1U], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (indexes.size() - 1U) << ')'; return; } for (size_t n = 0; n < indexes.size(); ++n) o << (isLHS ? "get_base1_lhs(" : "get_base1("); o << expr; for (size_t n = 0; n < indexes.size() - 1; ++n) { o << ", "; generate_expression(indexes[n], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (n + 1) << ')'; } o << ", "; generate_expression(indexes[indexes.size() - 1U], user_facing, o); o << ", "; generate_quoted_string(expr, o); o << ", " << (indexes.size()) << ')'; } } } #endif <|endoftext|>
<commit_before>#ifndef STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP #define STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP #include <stan/lang/grammars/expression_grammar.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <sstream> #include <string> #include <vector> BOOST_FUSION_ADAPT_STRUCT(stan::lang::conditional_op, (stan::lang::expression, cond_) (stan::lang::expression, true_val_) (stan::lang::expression, false_val_) ) namespace stan { namespace lang { template <typename Iterator> expression_grammar<Iterator>::expression_grammar(variable_map& var_map, std::stringstream& error_msgs) : expression_grammar::base_type(expression_r), var_map_(var_map), error_msgs_(error_msgs), expression07_g(var_map, error_msgs, *this) { using boost::spirit::qi::lit; using boost::spirit::qi::_1; using boost::spirit::qi::labels::_r1; using boost::spirit::qi::_val; // _r1 : var_origin expression_r.name("expression"); expression_r %= conditional_op_r(_r1) || expression15_r(_r1); conditional_op_r %= expression15_r(_r1) >> lit("?") > expression_r(_r1) > lit(":") > expression_r(_r1); expression15_r = expression14_r(_r1)[assign_lhs_f(_val, _1)] > *(lit("||") > expression14_r(_r1) [binary_op_f(_val, _1, "||", "logical_or", boost::phoenix::ref(error_msgs))]); expression14_r.name("expression"); expression14_r = expression10_r(_r1)[assign_lhs_f(_val, _1)] > *(lit("&&") > expression10_r(_r1) [binary_op_f(_val, _1, "&&", "logical_and", boost::phoenix::ref(error_msgs))]); expression10_r.name("expression"); expression10_r = expression09_r(_r1)[assign_lhs_f(_val, _1)] > *((lit("==") > expression09_r(_r1) [binary_op_f(_val, _1, "==", "logical_eq", boost::phoenix::ref(error_msgs))]) | (lit("!=") > expression09_r(_r1) [binary_op_f(_val, _1, "!=", "logical_neq", boost::phoenix::ref(error_msgs))])); expression09_r.name("expression"); expression09_r = expression07_g(_r1)[assign_lhs_f(_val, _1)] > *((lit("<=") > expression07_g(_r1) [binary_op_f(_val, _1, "<", "logical_lte", boost::phoenix::ref(error_msgs))]) | (lit("<") > expression07_g(_r1) [binary_op_f(_val, _1, "<=", "logical_lt", boost::phoenix::ref(error_msgs))]) | (lit(">=") > expression07_g(_r1) [binary_op_f(_val, _1, ">", "logical_gte", boost::phoenix::ref(error_msgs))]) | (lit(">") > expression07_g(_r1) [binary_op_f(_val, _1, ">=", "logical_gt", boost::phoenix::ref(error_msgs))])); } } } #endif <commit_msg>fixed typo; passes existing unit test<commit_after>#ifndef STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP #define STAN_LANG_GRAMMARS_EXPRESSION_GRAMMAR_DEF_HPP #include <stan/lang/grammars/expression_grammar.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <sstream> #include <string> #include <vector> BOOST_FUSION_ADAPT_STRUCT(stan::lang::conditional_op, (stan::lang::expression, cond_) (stan::lang::expression, true_val_) (stan::lang::expression, false_val_) ) namespace stan { namespace lang { template <typename Iterator> expression_grammar<Iterator>::expression_grammar(variable_map& var_map, std::stringstream& error_msgs) : expression_grammar::base_type(expression_r), var_map_(var_map), error_msgs_(error_msgs), expression07_g(var_map, error_msgs, *this) { using boost::spirit::qi::lit; using boost::spirit::qi::_1; using boost::spirit::qi::labels::_r1; using boost::spirit::qi::_val; // _r1 : var_origin expression_r.name("expression"); expression_r %= conditional_op_r(_r1) | expression15_r(_r1); conditional_op_r %= expression15_r(_r1) >> lit("?") > expression_r(_r1) > lit(":") > expression_r(_r1); expression15_r = expression14_r(_r1)[assign_lhs_f(_val, _1)] > *(lit("||") > expression14_r(_r1) [binary_op_f(_val, _1, "||", "logical_or", boost::phoenix::ref(error_msgs))]); expression14_r.name("expression"); expression14_r = expression10_r(_r1)[assign_lhs_f(_val, _1)] > *(lit("&&") > expression10_r(_r1) [binary_op_f(_val, _1, "&&", "logical_and", boost::phoenix::ref(error_msgs))]); expression10_r.name("expression"); expression10_r = expression09_r(_r1)[assign_lhs_f(_val, _1)] > *((lit("==") > expression09_r(_r1) [binary_op_f(_val, _1, "==", "logical_eq", boost::phoenix::ref(error_msgs))]) | (lit("!=") > expression09_r(_r1) [binary_op_f(_val, _1, "!=", "logical_neq", boost::phoenix::ref(error_msgs))])); expression09_r.name("expression"); expression09_r = expression07_g(_r1)[assign_lhs_f(_val, _1)] > *((lit("<=") > expression07_g(_r1) [binary_op_f(_val, _1, "<", "logical_lte", boost::phoenix::ref(error_msgs))]) | (lit("<") > expression07_g(_r1) [binary_op_f(_val, _1, "<=", "logical_lt", boost::phoenix::ref(error_msgs))]) | (lit(">=") > expression07_g(_r1) [binary_op_f(_val, _1, ">", "logical_gte", boost::phoenix::ref(error_msgs))]) | (lit(">") > expression07_g(_r1) [binary_op_f(_val, _1, ">=", "logical_gt", boost::phoenix::ref(error_msgs))])); } } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2010 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #ifndef __BASE_DEBUG_HH__ #define __BASE_DEBUG_HH__ #include <map> #include <string> #include <vector> namespace Debug { void breakpoint(); class Flag { protected: const char *_name; const char *_desc; std::vector<Flag *> _kids; public: Flag(const char *name, const char *desc); virtual ~Flag(); std::string name() const { return _name; } std::string desc() const { return _desc; } std::vector<Flag *> kids() { return _kids; } virtual void enable() = 0; virtual void disable() = 0; }; class SimpleFlag : public Flag { protected: bool _status; public: SimpleFlag(const char *name, const char *desc) : Flag(name, desc) { } bool status() const { return _status; } operator bool() const { return _status; } bool operator!() const { return !_status; } void enable() { _status = true; } void disable() { _status = false; } }; class CompoundFlag : public SimpleFlag { protected: void addFlag(Flag &f) { if (&f != NULL) _kids.push_back(&f); } public: CompoundFlag(const char *name, const char *desc, Flag &f00 = *(Flag *)0, Flag &f01 = *(Flag *)0, Flag &f02 = *(Flag *)0, Flag &f03 = *(Flag *)0, Flag &f04 = *(Flag *)0, Flag &f05 = *(Flag *)0, Flag &f06 = *(Flag *)0, Flag &f07 = *(Flag *)0, Flag &f08 = *(Flag *)0, Flag &f09 = *(Flag *)0, Flag &f10 = *(Flag *)0, Flag &f11 = *(Flag *)0, Flag &f12 = *(Flag *)0, Flag &f13 = *(Flag *)0, Flag &f14 = *(Flag *)0, Flag &f15 = *(Flag *)0, Flag &f16 = *(Flag *)0, Flag &f17 = *(Flag *)0, Flag &f18 = *(Flag *)0, Flag &f19 = *(Flag *)0) : SimpleFlag(name, desc) { addFlag(f00); addFlag(f01); addFlag(f02); addFlag(f03); addFlag(f04); addFlag(f05); addFlag(f06); addFlag(f07); addFlag(f08); addFlag(f09); addFlag(f10); addFlag(f11); addFlag(f12); addFlag(f13); addFlag(f14); addFlag(f15); addFlag(f16); addFlag(f17); addFlag(f18); addFlag(f19); } void enable(); void disable(); }; typedef std::map<std::string, Flag *> FlagsMap; FlagsMap &allFlags(); Flag *findFlag(const std::string &name); bool changeFlag(const char *s, bool value); } // namespace Debug void setDebugFlag(const char *string); void clearDebugFlag(const char *string); void dumpDebugFlags(); #endif // __BASE_DEBUG_HH__ <commit_msg>base: explicitly suggest potential use of 'All' debug flags<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2010 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #ifndef __BASE_DEBUG_HH__ #define __BASE_DEBUG_HH__ #include <map> #include <string> #include <vector> namespace Debug { void breakpoint(); class Flag { protected: const char *_name; const char *_desc; std::vector<Flag *> _kids; public: Flag(const char *name, const char *desc); virtual ~Flag(); std::string name() const { return _name; } std::string desc() const { return _desc; } std::vector<Flag *> kids() { return _kids; } virtual void enable() = 0; virtual void disable() = 0; }; class SimpleFlag : public Flag { protected: bool _status; public: SimpleFlag(const char *name, const char *desc) : Flag(name, desc) { } bool status() const { return _status; } operator bool() const { return _status; } bool operator!() const { return !_status; } void enable() { _status = true; } void disable() { _status = false; } }; class CompoundFlag : public SimpleFlag { protected: void addFlag(Flag &f) { if (&f != NULL) _kids.push_back(&f); } public: CompoundFlag(const char *name, const char *desc, Flag &f00 = *(Flag *)0, Flag &f01 = *(Flag *)0, Flag &f02 = *(Flag *)0, Flag &f03 = *(Flag *)0, Flag &f04 = *(Flag *)0, Flag &f05 = *(Flag *)0, Flag &f06 = *(Flag *)0, Flag &f07 = *(Flag *)0, Flag &f08 = *(Flag *)0, Flag &f09 = *(Flag *)0, Flag &f10 = *(Flag *)0, Flag &f11 = *(Flag *)0, Flag &f12 = *(Flag *)0, Flag &f13 = *(Flag *)0, Flag &f14 = *(Flag *)0, Flag &f15 = *(Flag *)0, Flag &f16 = *(Flag *)0, Flag &f17 = *(Flag *)0, Flag &f18 = *(Flag *)0, Flag &f19 = *(Flag *)0) : SimpleFlag(name, desc) { addFlag(f00); addFlag(f01); addFlag(f02); addFlag(f03); addFlag(f04); addFlag(f05); addFlag(f06); addFlag(f07); addFlag(f08); addFlag(f09); addFlag(f10); addFlag(f11); addFlag(f12); addFlag(f13); addFlag(f14); addFlag(f15); addFlag(f16); addFlag(f17); addFlag(f18); addFlag(f19); } void enable(); void disable(); }; typedef std::map<std::string, Flag *> FlagsMap; FlagsMap &allFlags(); Flag *findFlag(const std::string &name); extern Flag *const All; bool changeFlag(const char *s, bool value); } // namespace Debug void setDebugFlag(const char *string); void clearDebugFlag(const char *string); void dumpDebugFlags(); #endif // __BASE_DEBUG_HH__ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SwXMLBlockListContext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: mtg $ $Date: 2001-07-11 11:31:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _SW_XMLBLOCKLIST_CONTEXT_HXX #include <SwXMLBlockListContext.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLKYWD_HXX #include <xmloff/xmlkywd.hxx> #endif #ifndef _SW_XMLBLOCKIMPORT_HXX #include <SwXMLBlockImport.hxx> #endif #ifndef _SW_XMLTEXTBLOCKS_HXX #include <SwXMLTextBlocks.hxx> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::xmloff::token; using namespace ::rtl; SwXMLBlockListContext::SwXMLBlockListContext( SwXMLBlockListImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef (rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for (sal_Int16 i=0; i < nAttrCount; i++) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName); const OUString& rAttrValue = xAttrList->getValueByIndex( i ); if (XML_NAMESPACE_BLOCKLIST == nPrefix) { if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) ) { rImport.getBlockList().SetName(rAttrValue); break; } } } } SwXMLBlockListContext::~SwXMLBlockListContext ( void ) { } SvXMLImportContext *SwXMLBlockListContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_BLOCKLIST && IsXMLToken ( rLocalName, XML_BLOCK ) ) pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList); else pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName); return pContext; } SwXMLBlockContext::SwXMLBlockContext( SwXMLBlockListImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { static const CharClass & rCC = GetAppCharClass(); String aShort, aLong, aPackageName; BOOL bTextOnly = FALSE; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for (sal_Int16 i=0; i < nAttrCount; i++) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName); const OUString& rAttrValue = xAttrList->getValueByIndex( i ); if (XML_NAMESPACE_BLOCKLIST == nPrefix) { if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) ) { aShort = rCC.upper(rAttrValue); } else if ( IsXMLToken ( aLocalName, XML_NAME ) ) { aLong = rAttrValue; } else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) ) { aPackageName = rAttrValue; } else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) ) { if ( IsXMLToken ( rAttrValue, XML_TRUE ) ) bTextOnly = TRUE; } } } if (!aShort.Len() || !aLong.Len() || !aPackageName.Len()) return; rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly); } SwXMLBlockContext::~SwXMLBlockContext ( void ) { } SwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext( SwXMLTextBlockImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { } SvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken ( rLocalName, XML_BODY ) ) pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList); else pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName); return pContext; } SwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void ) { } SwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext( SwXMLTextBlockImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { } SvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_TEXT && IsXMLToken ( rLocalName, XML_P ) ) pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList); else pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName); return pContext; } SwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void ) { } SwXMLTextBlockParContext::SwXMLTextBlockParContext( SwXMLTextBlockImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { } void SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars ) { rLocalRef.m_rText.Append ( rChars.getStr()); } SwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void ) { if (rLocalRef.bTextOnly) rLocalRef.m_rText.AppendAscii( "\015" ); else { if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' ) rLocalRef.m_rText.AppendAscii( " " ); } } <commit_msg>Bug #88180#: add missing headerfile<commit_after>/************************************************************************* * * $RCSfile: SwXMLBlockListContext.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: jp $ $Date: 2001-10-19 13:28:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #pragma hdrstop #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLKYWD_HXX #include <xmloff/xmlkywd.hxx> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _SW_XMLBLOCKIMPORT_HXX #include <SwXMLBlockImport.hxx> #endif #ifndef _SW_XMLTEXTBLOCKS_HXX #include <SwXMLTextBlocks.hxx> #endif #ifndef _SW_XMLBLOCKLIST_CONTEXT_HXX #include <SwXMLBlockListContext.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::xmloff::token; using namespace ::rtl; SwXMLBlockListContext::SwXMLBlockListContext( SwXMLBlockListImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef (rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for (sal_Int16 i=0; i < nAttrCount; i++) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName); const OUString& rAttrValue = xAttrList->getValueByIndex( i ); if (XML_NAMESPACE_BLOCKLIST == nPrefix) { if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) ) { rImport.getBlockList().SetName(rAttrValue); break; } } } } SwXMLBlockListContext::~SwXMLBlockListContext ( void ) { } SvXMLImportContext *SwXMLBlockListContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_BLOCKLIST && IsXMLToken ( rLocalName, XML_BLOCK ) ) pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList); else pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName); return pContext; } SwXMLBlockContext::SwXMLBlockContext( SwXMLBlockListImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { static const CharClass & rCC = GetAppCharClass(); String aShort, aLong, aPackageName; BOOL bTextOnly = FALSE; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for (sal_Int16 i=0; i < nAttrCount; i++) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName); const OUString& rAttrValue = xAttrList->getValueByIndex( i ); if (XML_NAMESPACE_BLOCKLIST == nPrefix) { if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) ) { aShort = rCC.upper(rAttrValue); } else if ( IsXMLToken ( aLocalName, XML_NAME ) ) { aLong = rAttrValue; } else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) ) { aPackageName = rAttrValue; } else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) ) { if ( IsXMLToken ( rAttrValue, XML_TRUE ) ) bTextOnly = TRUE; } } } if (!aShort.Len() || !aLong.Len() || !aPackageName.Len()) return; rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly); } SwXMLBlockContext::~SwXMLBlockContext ( void ) { } SwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext( SwXMLTextBlockImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { } SvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken ( rLocalName, XML_BODY ) ) pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList); else pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName); return pContext; } SwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void ) { } SwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext( SwXMLTextBlockImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { } SvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; if (nPrefix == XML_NAMESPACE_TEXT && IsXMLToken ( rLocalName, XML_P ) ) pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList); else pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName); return pContext; } SwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void ) { } SwXMLTextBlockParContext::SwXMLTextBlockParContext( SwXMLTextBlockImport& rImport, sal_uInt16 nPrefix, const OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList > & xAttrList ) : rLocalRef(rImport), SvXMLImportContext ( rImport, nPrefix, rLocalName ) { } void SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars ) { rLocalRef.m_rText.Append ( rChars.getStr()); } SwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void ) { if (rLocalRef.bTextOnly) rLocalRef.m_rText.AppendAscii( "\015" ); else { if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' ) rLocalRef.m_rText.AppendAscii( " " ); } } <|endoftext|>
<commit_before>#include <thectci/hash.hpp> #include <thectci/compile_time_value.hpp> #include <igloo/igloo_alt.h> using namespace igloo; Describe( a_hash ) { It( is_a_compile_time_hash ) { typedef the::ctci::compile_time< uint32_t, the::ctci::hash( "dogfood" ) > hash_type; } It( is_the_djb2_hash_algorithm ) { constexpr uint32_t test_hash( the::ctci::compile_time< uint32_t, the::ctci::hash( "dogfood" ) >::value ); const uint32_t djb2_hash( 535668743 ); static_assert( test_hash == djb2_hash, "hash value does not match" ); } }; <commit_msg>fix unused type and variable warning<commit_after>#include <thectci/hash.hpp> #include <thectci/compile_time_value.hpp> #include <igloo/igloo_alt.h> using namespace igloo; Describe( a_hash ) { It( is_a_compile_time_hash ) { typedef the::ctci::compile_time< uint32_t, the::ctci::hash( "dogfood" ) > hash_type; hash_type unused_variable; (void)unused_variable; } It( is_the_djb2_hash_algorithm ) { constexpr uint32_t test_hash( the::ctci::compile_time< uint32_t, the::ctci::hash( "dogfood" ) >::value ); const uint32_t djb2_hash( 535668743 ); static_assert( test_hash == djb2_hash, "hash value does not match" ); } }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdmod.cxx,v $ * * $Revision: 1.20 $ * * last change: $Author: rt $ $Date: 2003-09-19 08:16:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX #include <svtools/languageoptions.hxx> #endif #ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SV_STATUS_HXX //autogen #include <vcl/status.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SFXMSG_HXX //autogen #include <sfx2/msg.hxx> #endif #ifndef _SFXOBJFACE_HXX //autogen #include <sfx2/objface.hxx> #endif #ifndef _SFX_PRINTER_HXX #include <sfx2/printer.hxx> #endif #ifndef _SVX_PSZCTRL_HXX //autogen #include <svx/pszctrl.hxx> #endif #ifndef _SVX_ZOOMCTRL_HXX //autogen #include <svx/zoomctrl.hxx> #endif #ifndef _SVX_MODCTRL_HXX //autogen #include <svx/modctrl.hxx> #endif #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _EHDL_HXX #include <svtools/ehdl.hxx> #endif #define ITEMID_SEARCH SID_SEARCH_ITEM #include <svx/svxids.hrc> #include <offmgr/ofaids.hrc> #include <svx/srchitem.hxx> #pragma hdrstop #define _SD_DLL // fuer SD_MOD() #include "sderror.hxx" #include "sdmod.hxx" #include "sddll.hxx" #include "sdresid.hxx" #include "optsitem.hxx" #include "docshell.hxx" #include "drawdoc.hxx" #include "app.hrc" #include "glob.hrc" #include "strings.hrc" #include "res_bmp.hrc" #include "cfgids.hxx" TYPEINIT1( SdModule, SfxModule ); #define SdModule #include "sdslots.hxx" SFX_IMPL_INTERFACE(SdModule, SfxModule, SdResId(STR_APPLICATIONOBJECTBAR)) { SFX_STATUSBAR_REGISTRATION(RID_DRAW_STATUSBAR); } /************************************************************************* |* |* Ctor |* \************************************************************************/ SdModule::SdModule(SfxObjectFactory* pDrawObjFact, SfxObjectFactory* pGraphicObjFact) : SfxModule( SFX_APP()->CreateResManager("sd"), FALSE, pDrawObjFact, pGraphicObjFact, NULL ), bWaterCan(FALSE), pTransferClip(NULL), pTransferDrag(NULL), pTransferSelection(NULL), pImpressOptions(NULL), pDrawOptions(NULL), pSearchItem(NULL), pNumberFormatter( NULL ) { SetName( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "StarDraw" ) ) ); // Nicht uebersetzen! pSearchItem = new SvxSearchItem(ITEMID_SEARCH); pSearchItem->SetAppFlag(SVX_SEARCHAPP_DRAW); StartListening( *SFX_APP() ); mpErrorHdl = new SfxErrorHandler( RID_SD_ERRHDL, ERRCODE_AREA_SD, ERRCODE_AREA_SD_END, GetResMgr() ); mpVirtualRefDevice = new VirtualDevice; mpVirtualRefDevice->SetMapMode( MAP_100TH_MM ); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdModule::~SdModule() { delete pSearchItem; if( pNumberFormatter ) delete pNumberFormatter; delete mpErrorHdl; delete static_cast< VirtualDevice* >( mpVirtualRefDevice ); } /************************************************************************* |* |* Statusbar erzeugen |* \************************************************************************/ #define AUTOSIZE_WIDTH 180 #define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s)) void SdModule::FillStatusBar(StatusBar& rStatusBar) { // Hinweis rStatusBar.InsertItem( SID_CONTEXT, TEXT_WIDTH( String().Fill( 30, 'x' ) ), // vorher 52 SIB_IN | SIB_LEFT | SIB_AUTOSIZE ); // Groesse und Position rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), // vorher 42 SIB_IN | SIB_USERDRAW ); // SIB_AUTOSIZE | SIB_LEFT | SIB_OWNERDRAW ); // Massstab rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_IN | SIB_CENTER ); /* // Einfuege- / Uberschreibmodus rStatusBar.InsertItem( SID_ATTR_INSERT, TEXT_WIDTH( "EINFG" ), SIB_IN | SIB_CENTER ); // Selektionsmodus rStatusBar.InsertItem( SID_STATUS_SELMODE, TEXT_WIDTH( "ERG" ), SIB_IN | SIB_CENTER ); */ // Dokument geaendert rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar) ); // Seite rStatusBar.InsertItem( SID_STATUS_PAGE, TEXT_WIDTH( String().Fill( 24, 'X' ) ), SIB_IN | SIB_LEFT ); // Praesentationslayout rStatusBar.InsertItem( SID_STATUS_LAYOUT, TEXT_WIDTH( String().Fill( 10, 'X' ) ), SIB_IN | SIB_LEFT | SIB_AUTOSIZE ); } /************************************************************************* |* |* get notifications |* \************************************************************************/ void SdModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_DEINITIALIZING ) { delete pImpressOptions, pImpressOptions = NULL; delete pDrawOptions, pDrawOptions = NULL; } } /************************************************************************* |* |* Optionen zurueckgeben |* \************************************************************************/ SdOptions* SdModule::GetSdOptions(DocumentType eDocType) { SdOptions* pOptions = NULL; if (eDocType == DOCUMENT_TYPE_DRAW) { if (!pDrawOptions) pDrawOptions = new SdOptions( SDCFG_DRAW ); pOptions = pDrawOptions; } else if (eDocType == DOCUMENT_TYPE_IMPRESS) { if (!pImpressOptions) pImpressOptions = new SdOptions( SDCFG_IMPRESS ); pOptions = pImpressOptions; } if( pOptions ) { UINT16 nMetric = pOptions->GetMetric(); SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() ); SdDrawDocument* pDoc = NULL; if (pDocSh) pDoc = pDocSh->GetDoc(); if( nMetric != 0xffff && pDoc && eDocType == pDoc->GetDocumentType() ) PutItem( SfxUInt16Item( SID_ATTR_METRIC, nMetric ) ); } return(pOptions); } /************************************************************************* |* |* Optionen-Stream fuer interne Options oeffnen und zurueckgeben; |* falls der Stream zum Lesen geoeffnet wird, aber noch nicht |* angelegt wurde, wird ein 'leeres' RefObject zurueckgegeben |* \************************************************************************/ SvStorageStreamRef SdModule::GetOptionStream( const String& rOptionName, SdOptionStreamMode eMode ) { SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() ); SvStorageStreamRef xStm; if( pDocSh ) { DocumentType eType = pDocSh->GetDoc()->GetDocumentType(); String aStmName; if( !xOptionStorage.Is() ) { INetURLObject aURL( SvtPathOptions().GetUserConfigPath() ); aURL.Append( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "drawing.cfg" ) ) ); SvStream* pStm = ::utl::UcbStreamHelper::CreateStream( aURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE ); if( pStm ) xOptionStorage = new SvStorage( pStm, TRUE ); } if( DOCUMENT_TYPE_DRAW == eType ) aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Draw_" ) ); else aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Impress_" ) ); aStmName += rOptionName; if( SD_OPTION_STORE == eMode || xOptionStorage->IsContained( aStmName ) ) xStm = xOptionStorage->OpenStream( aStmName ); } return xStm; } /************************************************************************* |* \************************************************************************/ SvNumberFormatter* SdModule::GetNumberFormatter() { if( !pNumberFormatter ) pNumberFormatter = new SvNumberFormatter( ::comphelper::getProcessServiceFactory(), LANGUAGE_SYSTEM ); return pNumberFormatter; } /************************************************************************* |* \************************************************************************/ OutputDevice* SdModule::GetVirtualRefDevice (void) { return mpVirtualRefDevice; } /** This method is deprecated and only an alias to <member>GetVirtualRefDevice()</member>. The given argument is ignored. */ OutputDevice* SdModule::GetRefDevice (SdDrawDocShell& rDocShell) { return GetVirtualRefDevice(); } /************************************************************************* |* \************************************************************************/ ::com::sun::star::text::WritingMode SdModule::GetDefaultWritingMode() const { /* const SvtLanguageOptions aLanguageOptions; return( aLanguageOptions.IsCTLFontEnabled() ? ::com::sun::star::text::WritingMode_RL_TB : ::com::sun::star::text::WritingMode_LR_TB ); */ return ::com::sun::star::text::WritingMode_LR_TB; } <commit_msg>INTEGRATION: CWS geordi2q10 (1.20.42); FILE MERGED 2003/11/26 16:09:29 rt 1.20.42.1: #111934#: join CWS draw20pp1<commit_after>/************************************************************************* * * $RCSfile: sdmod.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: rt $ $Date: 2003-12-01 10:08:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX #include <svtools/languageoptions.hxx> #endif #ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX #include <unotools/ucbstreamhelper.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SV_STATUS_HXX //autogen #include <vcl/status.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SFXMSG_HXX //autogen #include <sfx2/msg.hxx> #endif #ifndef _SFXOBJFACE_HXX //autogen #include <sfx2/objface.hxx> #endif #ifndef _SFX_PRINTER_HXX #include <sfx2/printer.hxx> #endif #ifndef _SVX_PSZCTRL_HXX //autogen #include <svx/pszctrl.hxx> #endif #ifndef _SVX_ZOOMCTRL_HXX //autogen #include <svx/zoomctrl.hxx> #endif #ifndef _SVX_MODCTRL_HXX //autogen #include <svx/modctrl.hxx> #endif #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _EHDL_HXX #include <svtools/ehdl.hxx> #endif #define ITEMID_SEARCH SID_SEARCH_ITEM #include <svx/svxids.hrc> #include <offmgr/ofaids.hrc> #include <svx/srchitem.hxx> #pragma hdrstop #define _SD_DLL // fuer SD_MOD() #include "sderror.hxx" #include "sdmod.hxx" #include "sddll.hxx" #include "sdresid.hxx" #include "optsitem.hxx" #include "docshell.hxx" #include "drawdoc.hxx" #include "app.hrc" #include "glob.hrc" #include "strings.hrc" #include "res_bmp.hrc" #include "cfgids.hxx" TYPEINIT1( SdModule, SfxModule ); #define SdModule #include "sdslots.hxx" SFX_IMPL_INTERFACE(SdModule, SfxModule, SdResId(STR_APPLICATIONOBJECTBAR)) { SFX_STATUSBAR_REGISTRATION(RID_DRAW_STATUSBAR); } /************************************************************************* |* |* Ctor |* \************************************************************************/ SdModule::SdModule(SfxObjectFactory* pDrawObjFact, SfxObjectFactory* pGraphicObjFact) : SfxModule( SFX_APP()->CreateResManager("sd"), FALSE, pDrawObjFact, pGraphicObjFact, NULL ), bWaterCan(FALSE), pTransferClip(NULL), pTransferDrag(NULL), pTransferSelection(NULL), pImpressOptions(NULL), pDrawOptions(NULL), pSearchItem(NULL), pNumberFormatter( NULL ) { SetName( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "StarDraw" ) ) ); // Nicht uebersetzen! pSearchItem = new SvxSearchItem(ITEMID_SEARCH); pSearchItem->SetAppFlag(SVX_SEARCHAPP_DRAW); StartListening( *SFX_APP() ); mpErrorHdl = new SfxErrorHandler( RID_SD_ERRHDL, ERRCODE_AREA_SD, ERRCODE_AREA_SD_END, GetResMgr() ); // Create a new ref device and (by calling SetReferenceDevice()) // set its resolution to 600 DPI. This leads to a visually better // formatting of text in small sizes (6 point and below.) VirtualDevice* pDevice = new VirtualDevice; mpVirtualRefDevice = pDevice; pDevice->SetMapMode( MAP_100TH_MM ); pDevice->SetReferenceDevice (); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdModule::~SdModule() { delete pSearchItem; if( pNumberFormatter ) delete pNumberFormatter; delete mpErrorHdl; delete static_cast< VirtualDevice* >( mpVirtualRefDevice ); } /************************************************************************* |* |* Statusbar erzeugen |* \************************************************************************/ #define AUTOSIZE_WIDTH 180 #define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s)) void SdModule::FillStatusBar(StatusBar& rStatusBar) { // Hinweis rStatusBar.InsertItem( SID_CONTEXT, TEXT_WIDTH( String().Fill( 30, 'x' ) ), // vorher 52 SIB_IN | SIB_LEFT | SIB_AUTOSIZE ); // Groesse und Position rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), // vorher 42 SIB_IN | SIB_USERDRAW ); // SIB_AUTOSIZE | SIB_LEFT | SIB_OWNERDRAW ); // Massstab rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_IN | SIB_CENTER ); /* // Einfuege- / Uberschreibmodus rStatusBar.InsertItem( SID_ATTR_INSERT, TEXT_WIDTH( "EINFG" ), SIB_IN | SIB_CENTER ); // Selektionsmodus rStatusBar.InsertItem( SID_STATUS_SELMODE, TEXT_WIDTH( "ERG" ), SIB_IN | SIB_CENTER ); */ // Dokument geaendert rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar) ); // Seite rStatusBar.InsertItem( SID_STATUS_PAGE, TEXT_WIDTH( String().Fill( 24, 'X' ) ), SIB_IN | SIB_LEFT ); // Praesentationslayout rStatusBar.InsertItem( SID_STATUS_LAYOUT, TEXT_WIDTH( String().Fill( 10, 'X' ) ), SIB_IN | SIB_LEFT | SIB_AUTOSIZE ); } /************************************************************************* |* |* get notifications |* \************************************************************************/ void SdModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_DEINITIALIZING ) { delete pImpressOptions, pImpressOptions = NULL; delete pDrawOptions, pDrawOptions = NULL; } } /************************************************************************* |* |* Optionen zurueckgeben |* \************************************************************************/ SdOptions* SdModule::GetSdOptions(DocumentType eDocType) { SdOptions* pOptions = NULL; if (eDocType == DOCUMENT_TYPE_DRAW) { if (!pDrawOptions) pDrawOptions = new SdOptions( SDCFG_DRAW ); pOptions = pDrawOptions; } else if (eDocType == DOCUMENT_TYPE_IMPRESS) { if (!pImpressOptions) pImpressOptions = new SdOptions( SDCFG_IMPRESS ); pOptions = pImpressOptions; } if( pOptions ) { UINT16 nMetric = pOptions->GetMetric(); SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() ); SdDrawDocument* pDoc = NULL; if (pDocSh) pDoc = pDocSh->GetDoc(); if( nMetric != 0xffff && pDoc && eDocType == pDoc->GetDocumentType() ) PutItem( SfxUInt16Item( SID_ATTR_METRIC, nMetric ) ); } return(pOptions); } /************************************************************************* |* |* Optionen-Stream fuer interne Options oeffnen und zurueckgeben; |* falls der Stream zum Lesen geoeffnet wird, aber noch nicht |* angelegt wurde, wird ein 'leeres' RefObject zurueckgegeben |* \************************************************************************/ SvStorageStreamRef SdModule::GetOptionStream( const String& rOptionName, SdOptionStreamMode eMode ) { SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() ); SvStorageStreamRef xStm; if( pDocSh ) { DocumentType eType = pDocSh->GetDoc()->GetDocumentType(); String aStmName; if( !xOptionStorage.Is() ) { INetURLObject aURL( SvtPathOptions().GetUserConfigPath() ); aURL.Append( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "drawing.cfg" ) ) ); SvStream* pStm = ::utl::UcbStreamHelper::CreateStream( aURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE ); if( pStm ) xOptionStorage = new SvStorage( pStm, TRUE ); } if( DOCUMENT_TYPE_DRAW == eType ) aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Draw_" ) ); else aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Impress_" ) ); aStmName += rOptionName; if( SD_OPTION_STORE == eMode || xOptionStorage->IsContained( aStmName ) ) xStm = xOptionStorage->OpenStream( aStmName ); } return xStm; } /************************************************************************* |* \************************************************************************/ SvNumberFormatter* SdModule::GetNumberFormatter() { if( !pNumberFormatter ) pNumberFormatter = new SvNumberFormatter( ::comphelper::getProcessServiceFactory(), LANGUAGE_SYSTEM ); return pNumberFormatter; } /************************************************************************* |* \************************************************************************/ OutputDevice* SdModule::GetVirtualRefDevice (void) { return mpVirtualRefDevice; } /** This method is deprecated and only an alias to <member>GetVirtualRefDevice()</member>. The given argument is ignored. */ OutputDevice* SdModule::GetRefDevice (SdDrawDocShell& rDocShell) { return GetVirtualRefDevice(); } /************************************************************************* |* \************************************************************************/ ::com::sun::star::text::WritingMode SdModule::GetDefaultWritingMode() const { /* const SvtLanguageOptions aLanguageOptions; return( aLanguageOptions.IsCTLFontEnabled() ? ::com::sun::star::text::WritingMode_RL_TB : ::com::sun::star::text::WritingMode_LR_TB ); */ return ::com::sun::star::text::WritingMode_LR_TB; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 - 2014 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/base/Text.h> #include <fstream> namespace Carna { namespace base { namespace text { // ---------------------------------------------------------------------------------- // Text // ---------------------------------------------------------------------------------- std::string cat( const std::string& fileName ) { std::ifstream in( fileName.c_str(), std::ios::in ); return std::string( std::istreambuf_iterator< char >( in ), std::istreambuf_iterator< char >() ); } } // namespace Carna :: base :: text } // namespace Carna :: base } // namespace Carna <commit_msg>Fixed include typo on Linux build.<commit_after>/* * Copyright (C) 2010 - 2014 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/base/text.h> #include <fstream> namespace Carna { namespace base { namespace text { // ---------------------------------------------------------------------------------- // Text // ---------------------------------------------------------------------------------- std::string cat( const std::string& fileName ) { std::ifstream in( fileName.c_str(), std::ios::in ); return std::string( std::istreambuf_iterator< char >( in ), std::istreambuf_iterator< char >() ); } } // namespace Carna :: base :: text } // namespace Carna :: base } // namespace Carna <|endoftext|>
<commit_before>/*** * @file arma_extend.hpp * @author Ryan Curtin * * Include Armadillo extensions which currently are not part of the main * Armadillo codebase. * * This will allow the use of the ccov() function (which performs the same * function as cov(trans(X)) but without the cost of computing trans(X)). This * also gives sparse matrix support, if it is necessary. */ #ifndef __MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP #define __MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP // Add batch constructor for sparse matrix (if version <= 3.810.0). #define ARMA_EXTRA_SPMAT_PROTO mlpack/core/arma_extend/SpMat_extra_bones.hpp #define ARMA_EXTRA_SPMAT_MEAT mlpack/core/arma_extend/SpMat_extra_meat.hpp // add row_col_iterator and row_col_const_iterator for Mat #define ARMA_EXTRA_MAT_PROTO mlpack/core/arma_extend/Mat_extra_bones.hpp #define ARMA_EXTRA_MAT_MEAT mlpack/core/arma_extend/Mat_extra_meat.hpp #include <armadillo> namespace arma { // u64/s64 #include "typedef.hpp" #include "traits.hpp" #include "promote_type.hpp" #include "restrictors.hpp" #include "hdf5_misc.hpp" // ccov() #include "op_ccov_proto.hpp" #include "op_ccov_meat.hpp" #include "glue_ccov_proto.hpp" #include "glue_ccov_meat.hpp" #include "fn_ccov.hpp" // inplace_reshape() #include "fn_inplace_reshape.hpp" }; #endif <commit_msg>Set ARMA_USE_U64S64 in hopes that the types of problems Gilles is having on the mailing list will be solved.<commit_after>/*** * @file arma_extend.hpp * @author Ryan Curtin * * Include Armadillo extensions which currently are not part of the main * Armadillo codebase. * * This will allow the use of the ccov() function (which performs the same * function as cov(trans(X)) but without the cost of computing trans(X)). This * also gives sparse matrix support, if it is necessary. */ #ifndef __MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP #define __MLPACK_CORE_ARMA_EXTEND_ARMA_EXTEND_HPP // Add batch constructor for sparse matrix (if version <= 3.810.0). #define ARMA_EXTRA_SPMAT_PROTO mlpack/core/arma_extend/SpMat_extra_bones.hpp #define ARMA_EXTRA_SPMAT_MEAT mlpack/core/arma_extend/SpMat_extra_meat.hpp // Add row_col_iterator and row_col_const_iterator for Mat. #define ARMA_EXTRA_MAT_PROTO mlpack/core/arma_extend/Mat_extra_bones.hpp #define ARMA_EXTRA_MAT_MEAT mlpack/core/arma_extend/Mat_extra_meat.hpp // Make sure that U64 and S64 support is enabled. #ifndef ARMA_USE_U64S64 #define ARMA_USE_U64S64 #endif #include <armadillo> namespace arma { // u64/s64 #include "typedef.hpp" #include "traits.hpp" #include "promote_type.hpp" #include "restrictors.hpp" #include "hdf5_misc.hpp" // ccov() #include "op_ccov_proto.hpp" #include "op_ccov_meat.hpp" #include "glue_ccov_proto.hpp" #include "glue_ccov_meat.hpp" #include "fn_ccov.hpp" // inplace_reshape() #include "fn_inplace_reshape.hpp" }; #endif <|endoftext|>
<commit_before>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <cassert> #include <cmsis-plus/rtos/os.h> #include <cmsis-plus/rtos/port/os-inlines.h> // Better be the last, to undef putchar() #include <cmsis-plus/diag/trace.h> // ---------------------------------------------------------------------------- namespace os { /** * @details * The `os::rtos` namespace groups all RTOS specific declarations, * either directly or via nested namespaces. */ namespace rtos { /** * @details * The `os::rtos::scheduler` namespace groups scheduler types * and functions. */ namespace scheduler { /** * @details * No further changes allowed, the scheduler cannot be stopped, * in can be only locked. */ status_t is_started_ = false; /** * @details * Modified by `lock()` and restored to the previous value * by `unlock()`. */ status_t is_locked_ = false; /** * @details * This special list is set to empty during BSS initialisation, * since it must be available to register the very first statically * allocated thread. */ Top_threads_list top_threads_list_; #if !defined(OS_INCLUDE_RTOS_PORT_THREAD) Thread* current_thread_; Ready_threads_list ready_threads_list_; #endif /** * @details * Create all RTOS internal objects and be ready to run. * * @warning Cannot be invoked from Interrupt Service Routines. */ result_t initialize (void) { os_assert_err(!scheduler::in_handler_mode (), EPERM); #if defined(OS_INCLUDE_RTOS_PORT_THREAD) trace::printf ("%s() \n", __func__); return port::scheduler::initialize (); #else port::scheduler::initialize (); // A newline. trace::puts (" "); scheduler::_create_idle (); return result::ok; #endif } /** * * @note Can be invoked from Interrupt Service Routines (obviously). */ bool in_handler_mode (void) { return port::scheduler::in_handler_mode (); } /** * @details * The scheduler cannot be stopped, it will run forever, but * thread switching can be locked/unlocked. * * @warning Cannot be invoked from Interrupt Service Routines. */ result_t start (void) { os_assert_err(!scheduler::in_handler_mode (), EPERM); trace::printf ("%s() \n", __func__); is_started_ = true; is_locked_ = false; port::Systick_clock::start (); return port::scheduler::start (); } /** * @details * Lock the scheduler (prevent it for doing thread switches) and * return the previous status, to be restored by `unlock()`. * * @warning Cannot be invoked from Interrupt Service Routines. */ status_t lock (status_t status) { os_assert_throw(!scheduler::in_handler_mode (), EPERM); status_t tmp; { interrupts::Critical_section ics; tmp = is_locked_; is_locked_ = status; } port::scheduler::lock (is_locked_); return tmp; } /** * @details * Actually restore the scheduler status based on the given * parameter, usually returned by a `lock()`. This allows for * embedded critical sections to preserve the locked status * until the outer one completes and invokes `unlock()`. * * @warning Cannot be invoked from Interrupt Service Routines. */ void unlock (status_t status) { os_assert_throw(!scheduler::in_handler_mode (), EPERM); is_locked_ = status; port::scheduler::lock (is_locked_); } /** * @class Critical_section * @details * Use this class to define a critical section * protected to scheduler switches. The beginning of the * critical section is exactly the place where this class is * instantiated (the constructor will lock * the scheduler). The end of the critical * section is the end of the surrounding block (the destructor will * unlock the scheduler). * * @note Can be nested as many times as required without problems, * only the outer call will unlock the scheduler. * * @par Example * * @code{.cpp} * void * func(void) * { * // Do something * * { * scheduler::Critical_section cs; // Critical section begins here. * * // Inside the critical section. * // No scheduler switches will happen here. * * } // Critical section ends here. * * // Do something else. * } * @endcode */ /** * @var const status_t Critical_section::status_ * @details * The variable is constant, after being set by the constructor no * further changes are possible. * * The variable type usually is a `bool`, but a counter is also * possible if the scheduler uses a recursive lock. */ /** * @class Lock * @details * Locker meeting the standard `Lockable` requirements (30.2.5.3). */ /** * @var status_t Lock::status_ * @details * The variable type usually is a `bool`, but a counter is also * possible if the scheduler uses a recursive lock. */ } /* namespace scheduler */ namespace scheduler { void _link_node (Waiting_threads_list& list, Waiting_thread_node& node) { // Remove this thread from the ready list, if there. port::this_thread::prepare_suspend (); // Add this thread to the node waiting list. list.link (node); node.thread.waiting_node_ = &node; } void _unlink_node (Waiting_thread_node& node) { { interrupts::Critical_section ics; // ----- Critical section ----- // Remove the thread from the node waiting list, // if not already removed. node.thread.waiting_node_ = nullptr; node.unlink (); } } void _link_node (Waiting_threads_list& list, Waiting_thread_node& node, Clock_timestamps_list& timeout_list, Timeout_thread_node& timeout_node) { // Remove this thread from the ready list, if there. port::this_thread::prepare_suspend (); // Add this thread to the node waiting list. list.link (node); node.thread.waiting_node_ = &node; // Add this thread to the clock timeout list. timeout_list.link (timeout_node); timeout_node.thread.clock_node_ = &timeout_node; } void _unlink_node (Waiting_thread_node& node, Timeout_thread_node& timeout_node) { interrupts::Critical_section ics; // ----- Critical section ----- // Remove the thread from the clock timeout list, // if not already removed by the timer. timeout_node.thread.clock_node_ = nullptr; timeout_node.unlink (); // Remove the thread from the node waiting list, // if not already removed. node.thread.waiting_node_ = nullptr; node.unlink (); } } /* namespace this_thread */ #if 0 namespace scheduler { void __register_thread (Thread* thread) { // TODO #if defined(TESTING) thread->__run_function (); #endif } void __unregister_thread (Thread* thread) { return; } } /* namespace scheduler */ #endif /** * @details * The os::rtos::interrupts namespace groups interrupts related * types and enumerations. */ namespace interrupts { /** * @class Critical_section * @details * Use this class to define a critical section * protected to interrupts service routines. The begining of the * critical section is exactly the place where this class is * instantiated (the constructor will disable interrupts below * the scheduler priority). The end of the critical * section is the end of the surrounding block (the destructor will * enable the interrupts). * * @note Can be nested as many times as required without problems, * only the outer call will re-enable the interrupts. * * @par Example * * @code{.cpp} * void * func(void) * { * // Do something * * { * interrupts::Critical_section ics; // Critical section begins here. * * // Inside the critical section. * // No scheduler switches will happen here. * * } // Critical section ends here. * * // Do something else. * } * @endcode */ /** * @var const status_t Critical_section::status_ * @details * The variable is constant, after being set by the constructor no * further changes are possible. * * The variable type usually is an unsigned integer where * the status register is saved. */ // Enter an IRQ critical section status_t Critical_section::enter (void) { return port::interrupts::Critical_section::enter (); } // Exit an IRQ critical section void Critical_section::exit (status_t status) { port::interrupts::Critical_section::exit (status); } // Enter an IRQ uncritical section status_t Uncritical_section::enter (void) { return port::interrupts::Uncritical_section::enter (); } // Exit an IRQ uncritical section void Uncritical_section::exit (status_t status) { port::interrupts::Uncritical_section::exit (status); } /** * @class Lock * @details * Locker meeting the standard `Lockable` requirements (30.2.5.3). */ /** * @var status_t Lock::status_ * @details * The variable type usually is an unsigned integer where * the status register is saved. */ } /* namespace interrupts */ // ======================================================================== /** * @details * The os::rtos::flags namespace groups event types and enumerations. */ namespace flags { } /* namespace flags */ // ======================================================================== /** * @class Named_object * @details * This class serves as a base class for all objects that have a * name (most of the RTOS classes do have a name). */ /** * @var const char* const Named_object::name_ * @details * To save space, the null terminated string passed to the * constructor is not copied locally. Instead, the pointer to * the string is copied, so the * caller must ensure that the pointer life cycle * is at least as long as the object life cycle. A constant * string (stored in flash) is preferred. */ #if 1 /** * @details * To save space, instead of copying the null terminated string * locally, the pointer to the string * is copied, so the caller must ensure that the pointer * life cycle is at least as long as the object life cycle. * A constant string (stored in flash) is preferred. */ Named_object::Named_object (const char* name) : name_ (name != nullptr ? name : "-") { ; } #endif // ========================================================================== } /* namespace rtos */ } /* namespace os */ <commit_msg>rtos/os-core: silence lists global constructor warnings<commit_after>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <cassert> #include <cmsis-plus/rtos/os.h> #include <cmsis-plus/rtos/port/os-inlines.h> // Better be the last, to undef putchar() #include <cmsis-plus/diag/trace.h> // ---------------------------------------------------------------------------- namespace os { /** * @details * The `os::rtos` namespace groups all RTOS specific declarations, * either directly or via nested namespaces. */ namespace rtos { /** * @details * The `os::rtos::scheduler` namespace groups scheduler types * and functions. */ namespace scheduler { /** * @details * No further changes allowed, the scheduler cannot be stopped, * in can be only locked. */ status_t is_started_ = false; /** * @details * Modified by `lock()` and restored to the previous value * by `unlock()`. */ status_t is_locked_ = false; /** * @details * This special list is set to empty during BSS initialisation, * since it must be available to register the very first statically * allocated thread. */ #pragma GCC diagnostic push #if defined(__clang__) #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wexit-time-destructors" #endif Top_threads_list top_threads_list_; #pragma GCC diagnostic pop #if !defined(OS_INCLUDE_RTOS_PORT_THREAD) Thread* current_thread_; #pragma GCC diagnostic push #if defined(__clang__) #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wexit-time-destructors" #endif Ready_threads_list ready_threads_list_; #pragma GCC diagnostic pop #endif /** * @details * Create all RTOS internal objects and be ready to run. * * @warning Cannot be invoked from Interrupt Service Routines. */ result_t initialize (void) { os_assert_err(!scheduler::in_handler_mode (), EPERM); #if defined(OS_INCLUDE_RTOS_PORT_THREAD) trace::printf ("%s() \n", __func__); return port::scheduler::initialize (); #else port::scheduler::initialize (); // A newline. trace::puts (" "); scheduler::_create_idle (); return result::ok; #endif } /** * * @note Can be invoked from Interrupt Service Routines (obviously). */ bool in_handler_mode (void) { return port::scheduler::in_handler_mode (); } /** * @details * The scheduler cannot be stopped, it will run forever, but * thread switching can be locked/unlocked. * * @warning Cannot be invoked from Interrupt Service Routines. */ result_t start (void) { os_assert_err(!scheduler::in_handler_mode (), EPERM); trace::printf ("%s() \n", __func__); is_started_ = true; is_locked_ = false; port::Systick_clock::start (); return port::scheduler::start (); } /** * @details * Lock the scheduler (prevent it for doing thread switches) and * return the previous status, to be restored by `unlock()`. * * @warning Cannot be invoked from Interrupt Service Routines. */ status_t lock (status_t status) { os_assert_throw(!scheduler::in_handler_mode (), EPERM); status_t tmp; { interrupts::Critical_section ics; tmp = is_locked_; is_locked_ = status; } port::scheduler::lock (is_locked_); return tmp; } /** * @details * Actually restore the scheduler status based on the given * parameter, usually returned by a `lock()`. This allows for * embedded critical sections to preserve the locked status * until the outer one completes and invokes `unlock()`. * * @warning Cannot be invoked from Interrupt Service Routines. */ void unlock (status_t status) { os_assert_throw(!scheduler::in_handler_mode (), EPERM); is_locked_ = status; port::scheduler::lock (is_locked_); } /** * @class Critical_section * @details * Use this class to define a critical section * protected to scheduler switches. The beginning of the * critical section is exactly the place where this class is * instantiated (the constructor will lock * the scheduler). The end of the critical * section is the end of the surrounding block (the destructor will * unlock the scheduler). * * @note Can be nested as many times as required without problems, * only the outer call will unlock the scheduler. * * @par Example * * @code{.cpp} * void * func(void) * { * // Do something * * { * scheduler::Critical_section cs; // Critical section begins here. * * // Inside the critical section. * // No scheduler switches will happen here. * * } // Critical section ends here. * * // Do something else. * } * @endcode */ /** * @var const status_t Critical_section::status_ * @details * The variable is constant, after being set by the constructor no * further changes are possible. * * The variable type usually is a `bool`, but a counter is also * possible if the scheduler uses a recursive lock. */ /** * @class Lock * @details * Locker meeting the standard `Lockable` requirements (30.2.5.3). */ /** * @var status_t Lock::status_ * @details * The variable type usually is a `bool`, but a counter is also * possible if the scheduler uses a recursive lock. */ } /* namespace scheduler */ namespace scheduler { void _link_node (Waiting_threads_list& list, Waiting_thread_node& node) { // Remove this thread from the ready list, if there. port::this_thread::prepare_suspend (); // Add this thread to the node waiting list. list.link (node); node.thread.waiting_node_ = &node; } void _unlink_node (Waiting_thread_node& node) { { interrupts::Critical_section ics; // ----- Critical section ----- // Remove the thread from the node waiting list, // if not already removed. node.thread.waiting_node_ = nullptr; node.unlink (); } } void _link_node (Waiting_threads_list& list, Waiting_thread_node& node, Clock_timestamps_list& timeout_list, Timeout_thread_node& timeout_node) { // Remove this thread from the ready list, if there. port::this_thread::prepare_suspend (); // Add this thread to the node waiting list. list.link (node); node.thread.waiting_node_ = &node; // Add this thread to the clock timeout list. timeout_list.link (timeout_node); timeout_node.thread.clock_node_ = &timeout_node; } void _unlink_node (Waiting_thread_node& node, Timeout_thread_node& timeout_node) { interrupts::Critical_section ics; // ----- Critical section ----- // Remove the thread from the clock timeout list, // if not already removed by the timer. timeout_node.thread.clock_node_ = nullptr; timeout_node.unlink (); // Remove the thread from the node waiting list, // if not already removed. node.thread.waiting_node_ = nullptr; node.unlink (); } } /* namespace this_thread */ #if 0 namespace scheduler { void __register_thread (Thread* thread) { // TODO #if defined(TESTING) thread->__run_function (); #endif } void __unregister_thread (Thread* thread) { return; } } /* namespace scheduler */ #endif /** * @details * The os::rtos::interrupts namespace groups interrupts related * types and enumerations. */ namespace interrupts { /** * @class Critical_section * @details * Use this class to define a critical section * protected to interrupts service routines. The begining of the * critical section is exactly the place where this class is * instantiated (the constructor will disable interrupts below * the scheduler priority). The end of the critical * section is the end of the surrounding block (the destructor will * enable the interrupts). * * @note Can be nested as many times as required without problems, * only the outer call will re-enable the interrupts. * * @par Example * * @code{.cpp} * void * func(void) * { * // Do something * * { * interrupts::Critical_section ics; // Critical section begins here. * * // Inside the critical section. * // No scheduler switches will happen here. * * } // Critical section ends here. * * // Do something else. * } * @endcode */ /** * @var const status_t Critical_section::status_ * @details * The variable is constant, after being set by the constructor no * further changes are possible. * * The variable type usually is an unsigned integer where * the status register is saved. */ // Enter an IRQ critical section status_t Critical_section::enter (void) { return port::interrupts::Critical_section::enter (); } // Exit an IRQ critical section void Critical_section::exit (status_t status) { port::interrupts::Critical_section::exit (status); } // Enter an IRQ uncritical section status_t Uncritical_section::enter (void) { return port::interrupts::Uncritical_section::enter (); } // Exit an IRQ uncritical section void Uncritical_section::exit (status_t status) { port::interrupts::Uncritical_section::exit (status); } /** * @class Lock * @details * Locker meeting the standard `Lockable` requirements (30.2.5.3). */ /** * @var status_t Lock::status_ * @details * The variable type usually is an unsigned integer where * the status register is saved. */ } /* namespace interrupts */ // ======================================================================== /** * @details * The os::rtos::flags namespace groups event types and enumerations. */ namespace flags { } /* namespace flags */ // ======================================================================== /** * @class Named_object * @details * This class serves as a base class for all objects that have a * name (most of the RTOS classes do have a name). */ /** * @var const char* const Named_object::name_ * @details * To save space, the null terminated string passed to the * constructor is not copied locally. Instead, the pointer to * the string is copied, so the * caller must ensure that the pointer life cycle * is at least as long as the object life cycle. A constant * string (stored in flash) is preferred. */ #if 1 /** * @details * To save space, instead of copying the null terminated string * locally, the pointer to the string * is copied, so the caller must ensure that the pointer * life cycle is at least as long as the object life cycle. * A constant string (stored in flash) is preferred. */ Named_object::Named_object (const char* name) : name_ (name != nullptr ? name : "-") { ; } #endif // ========================================================================== } /* namespace rtos */ } /* namespace os */ <|endoftext|>
<commit_before>#include <algorithm> #include <map> #include <string> #include <limits> #include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" namespace Halide { namespace Internal { namespace { const char kBufName[] = "ProfilerBuffer"; const char kToplevel[] = "$total$"; const char kOverhead[] = "$overhead$"; const char kIgnore[] = "$ignore$"; const char kIgnoreBuf[] = "$ignore_buf$"; } int profiling_level() { char *trace = getenv("HL_PROFILE"); return trace ? atoi(trace) : 0; } int profiling_loop_level() { char *loop_level = getenv("HL_PROFILE_LOOP_LEVEL"); return loop_level ? atoi(loop_level) : std::numeric_limits<int>::max(); } using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: InjectProfiling(string func_name) : level(profiling_level()), maximum_loop_level(profiling_loop_level()), current_loop_level(0), func_name(sanitize(func_name)), dummy(Variable::make(Int(32), "dummy")), dummy_counter(0) { } Stmt inject(Stmt s) { if (level >= 1) { // Add calls to the nsec and timer at the start and end, // so that we can get an estimate of how long a single // tick of the profiling_timer is (since it may be dependent // on e.g. processor clock rate) { PushCallStack st(this, kToplevel, kToplevel); s = mutate(s); } s = add_count_and_ticks(kToplevel, kToplevel, s); s = add_nsec(kToplevel, kToplevel, s); // Note that this is tacked on to the front of the block, since it must come // before the calls to halide_current_time_ns. Expr begin_clock_call = Call::make(Int(32), "halide_start_clock", vector<Expr>(), Call::Extern); Stmt begin_clock = AssertStmt::make(begin_clock_call == 0, "Failed to start clock"); s = Block::make(begin_clock, s); // Do a little calibration: make a loop that does a large number of calls to add_ticks // and measures the total time, so we can calculate the average overhead // and subtract it from the final results. (The "body" of this loop is just // a store of 0 to scratch that we expect to be optimized away.) This isn't a perfect // solution, but is much better than nothing. // // Note that we deliberately unroll a bit to minimize loop overhead, otherwise our // estimate will be too high. // // NOTE: we deliberately do this *after* measuring // the total, so this should *not* be included in "kToplevel". Expr j = Variable::make(Int(32), "j"); const int kIters = 1000000; const int kUnroll = 4; Stmt ticker_block = Stmt(); for (int i = 0; i < kUnroll; i++) { ticker_block = Block::make( add_ticks(kIgnore, kIgnore, Store::make(kIgnoreBuf, Cast::make(UInt(32), 0), 0)), ticker_block); } Stmt do_timings = For::make("j", 0, kIters, For::Serial, ticker_block); do_timings = add_ticks(kOverhead, kOverhead, do_timings); do_timings = add_delta("count", kOverhead, kOverhead, Cast::make(UInt(64), 0), Cast::make(UInt(64), kIters * kUnroll), do_timings); s = Block::make(s, do_timings); s = Allocate::make(kIgnoreBuf, UInt(32), vec(Expr(1)), const_true(), s); // Tack on code to print the counters. for (map<string, int>::const_iterator it = indices.begin(); it != indices.end(); ++it) { int idx = it->second; Expr val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Expr print_val = print(it->first, val); Stmt print_stmt = Evaluate::make(print_val); s = Block::make(s, print_stmt); } // Now that we know the final size, allocate the buffer and init to zero. Expr i = Variable::make(Int(32), "i"); Stmt init = For::make("i", 0, (int)indices.size(), For::Serial, Store::make(kBufName, Cast::make(UInt(64), 0), i)); s = Block::make(init, s); s = Allocate::make(kBufName, UInt(64), vec(Expr((int)indices.size())), const_true(), s); } else { s = mutate(s); } return s; } private: using IRMutator::visit; const int level; const int maximum_loop_level; int current_loop_level; const string func_name; map<string, int> indices; // map name -> index in buffer. vector<string> call_stack; // names of the nodes upstream Expr dummy; int dummy_counter; class PushCallStack { public: InjectProfiling* ip; PushCallStack(InjectProfiling* ip, const string& op_type, const string& op_name) : ip(ip) { ip->call_stack.push_back(op_type + " " + op_name); } ~PushCallStack() { ip->call_stack.pop_back(); } }; // replace all spaces with '_' static string sanitize(const string& s) { string san = s; std::replace(san.begin(), san.end(), ' ', '_'); return san; } Expr get_index(const string& s) { if (indices.find(s) == indices.end()) { int idx = indices.size(); indices[s] = idx; } return indices[s]; } Stmt add_count_and_ticks(const string& op_type, const string& op_name, Stmt s) { s = add_count(op_type, op_name, s); s = add_ticks(op_type, op_name, s); return s; } Stmt add_count(const string& op_type, const string& op_name, Stmt s) { return add_delta("count", op_type, op_name, Cast::make(UInt(64), 0), Cast::make(UInt(64), 1), s); } Stmt add_ticks(const string& op_type, const string& op_name, Stmt s) { std::vector<Expr> args; args.push_back(dummy + dummy_counter++); Expr ticks = Call::make(UInt(64), Internal::Call::profiling_timer, args, Call::Intrinsic); return add_delta("ticks", op_type, op_name, ticks, ticks, s); } Stmt add_nsec(const string& op_type, const string& op_name, Stmt s) { Expr nsec = Call::make(UInt(64), "halide_current_time_ns", std::vector<Expr>(), Call::Extern); return add_delta("nsec", op_type, op_name, nsec, nsec, s); } Stmt add_delta(const string& metric_name, const string& op_type, const string& op_name, Expr begin_val, Expr end_val, Stmt s) { string parent_name_pair = call_stack.empty() ? "null null" : call_stack.back(); string full_name = "halide_profiler " + metric_name + " " + func_name + " " + op_type + " " + sanitize(op_name) + " " + parent_name_pair; internal_assert(begin_val.type() == UInt(64)); internal_assert(end_val.type() == UInt(64)); Expr idx = get_index(full_name); string begin_var_name = "begin_" + full_name; // variable name doesn't matter at all, but de-spacing // makes the Stmt output easier to read std::replace(begin_var_name.begin(), begin_var_name.end(), ' ', '_'); Expr begin_var = Variable::make(UInt(64), begin_var_name); Expr old_val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Expr delta_val = Sub::make(end_val, begin_var); Expr new_val = Add::make(old_val, delta_val); s = Block::make(s, Store::make(kBufName, new_val, idx)); s = LetStmt::make(begin_var_name, begin_val, s); return s; } void visit(const Pipeline *op) { if (level >= 1) { Stmt produce, update, consume; { PushCallStack st(this, "produce", op->name); produce = mutate(op->produce); } { PushCallStack st(this, "update", op->name); update = op->update.defined() ? mutate(op->update) : Stmt(); } { PushCallStack st(this, "consume", op->name); consume = mutate(op->consume); } produce = add_count_and_ticks("produce", op->name, produce); update = update.defined() ? add_count_and_ticks("update", op->name, update) : Stmt(); consume = add_count_and_ticks("consume", op->name, consume); stmt = Pipeline::make(op->name, produce, update, consume); } else { IRMutator::visit(op); } } void visit(const For *op) { current_loop_level++; if (op->for_type == For::Parallel && level >= 1) { std::cerr << "Warning: The Halide profiler does not yet support " << "parallel schedules. Not profiling inside the loop over " << op->name << "\n"; stmt = op; } else { PushCallStack st(this, "forloop", op->name); IRMutator::visit(op); } // We only instrument loops at profiling level 2 or higher if (level >= 2 && current_loop_level <= maximum_loop_level) { stmt = add_count_and_ticks("forloop", op->name, stmt); } current_loop_level--; } }; Stmt inject_profiling(Stmt s, string name) { InjectProfiling profiling(name); s = profiling.inject(s); return s; } } } <commit_msg>Skip profiling around loops with Vectorized type<commit_after>#include <algorithm> #include <map> #include <string> #include <limits> #include "Profiling.h" #include "IRMutator.h" #include "IROperator.h" namespace Halide { namespace Internal { namespace { const char kBufName[] = "ProfilerBuffer"; const char kToplevel[] = "$total$"; const char kOverhead[] = "$overhead$"; const char kIgnore[] = "$ignore$"; const char kIgnoreBuf[] = "$ignore_buf$"; } int profiling_level() { char *trace = getenv("HL_PROFILE"); return trace ? atoi(trace) : 0; } int profiling_loop_level() { char *loop_level = getenv("HL_PROFILE_LOOP_LEVEL"); return loop_level ? atoi(loop_level) : std::numeric_limits<int>::max(); } using std::map; using std::string; using std::vector; class InjectProfiling : public IRMutator { public: InjectProfiling(string func_name) : level(profiling_level()), maximum_loop_level(profiling_loop_level()), current_loop_level(0), func_name(sanitize(func_name)), dummy(Variable::make(Int(32), "dummy")), dummy_counter(0) { } Stmt inject(Stmt s) { if (level >= 1) { // Add calls to the nsec and timer at the start and end, // so that we can get an estimate of how long a single // tick of the profiling_timer is (since it may be dependent // on e.g. processor clock rate) { PushCallStack st(this, kToplevel, kToplevel); s = mutate(s); } s = add_count_and_ticks(kToplevel, kToplevel, s); s = add_nsec(kToplevel, kToplevel, s); // Note that this is tacked on to the front of the block, since it must come // before the calls to halide_current_time_ns. Expr begin_clock_call = Call::make(Int(32), "halide_start_clock", vector<Expr>(), Call::Extern); Stmt begin_clock = AssertStmt::make(begin_clock_call == 0, "Failed to start clock"); s = Block::make(begin_clock, s); // Do a little calibration: make a loop that does a large number of calls to add_ticks // and measures the total time, so we can calculate the average overhead // and subtract it from the final results. (The "body" of this loop is just // a store of 0 to scratch that we expect to be optimized away.) This isn't a perfect // solution, but is much better than nothing. // // Note that we deliberately unroll a bit to minimize loop overhead, otherwise our // estimate will be too high. // // NOTE: we deliberately do this *after* measuring // the total, so this should *not* be included in "kToplevel". Expr j = Variable::make(Int(32), "j"); const int kIters = 1000000; const int kUnroll = 4; Stmt ticker_block = Stmt(); for (int i = 0; i < kUnroll; i++) { ticker_block = Block::make( add_ticks(kIgnore, kIgnore, Store::make(kIgnoreBuf, Cast::make(UInt(32), 0), 0)), ticker_block); } Stmt do_timings = For::make("j", 0, kIters, For::Serial, ticker_block); do_timings = add_ticks(kOverhead, kOverhead, do_timings); do_timings = add_delta("count", kOverhead, kOverhead, Cast::make(UInt(64), 0), Cast::make(UInt(64), kIters * kUnroll), do_timings); s = Block::make(s, do_timings); s = Allocate::make(kIgnoreBuf, UInt(32), vec(Expr(1)), const_true(), s); // Tack on code to print the counters. for (map<string, int>::const_iterator it = indices.begin(); it != indices.end(); ++it) { int idx = it->second; Expr val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Expr print_val = print(it->first, val); Stmt print_stmt = Evaluate::make(print_val); s = Block::make(s, print_stmt); } // Now that we know the final size, allocate the buffer and init to zero. Expr i = Variable::make(Int(32), "i"); Stmt init = For::make("i", 0, (int)indices.size(), For::Serial, Store::make(kBufName, Cast::make(UInt(64), 0), i)); s = Block::make(init, s); s = Allocate::make(kBufName, UInt(64), vec(Expr((int)indices.size())), const_true(), s); } else { s = mutate(s); } return s; } private: using IRMutator::visit; const int level; const int maximum_loop_level; int current_loop_level; const string func_name; map<string, int> indices; // map name -> index in buffer. vector<string> call_stack; // names of the nodes upstream Expr dummy; int dummy_counter; class PushCallStack { public: InjectProfiling* ip; PushCallStack(InjectProfiling* ip, const string& op_type, const string& op_name) : ip(ip) { ip->call_stack.push_back(op_type + " " + op_name); } ~PushCallStack() { ip->call_stack.pop_back(); } }; // replace all spaces with '_' static string sanitize(const string& s) { string san = s; std::replace(san.begin(), san.end(), ' ', '_'); return san; } Expr get_index(const string& s) { if (indices.find(s) == indices.end()) { int idx = indices.size(); indices[s] = idx; } return indices[s]; } Stmt add_count_and_ticks(const string& op_type, const string& op_name, Stmt s) { s = add_count(op_type, op_name, s); s = add_ticks(op_type, op_name, s); return s; } Stmt add_count(const string& op_type, const string& op_name, Stmt s) { return add_delta("count", op_type, op_name, Cast::make(UInt(64), 0), Cast::make(UInt(64), 1), s); } Stmt add_ticks(const string& op_type, const string& op_name, Stmt s) { std::vector<Expr> args; args.push_back(dummy + dummy_counter++); Expr ticks = Call::make(UInt(64), Internal::Call::profiling_timer, args, Call::Intrinsic); return add_delta("ticks", op_type, op_name, ticks, ticks, s); } Stmt add_nsec(const string& op_type, const string& op_name, Stmt s) { Expr nsec = Call::make(UInt(64), "halide_current_time_ns", std::vector<Expr>(), Call::Extern); return add_delta("nsec", op_type, op_name, nsec, nsec, s); } Stmt add_delta(const string& metric_name, const string& op_type, const string& op_name, Expr begin_val, Expr end_val, Stmt s) { string parent_name_pair = call_stack.empty() ? "null null" : call_stack.back(); string full_name = "halide_profiler " + metric_name + " " + func_name + " " + op_type + " " + sanitize(op_name) + " " + parent_name_pair; internal_assert(begin_val.type() == UInt(64)); internal_assert(end_val.type() == UInt(64)); Expr idx = get_index(full_name); string begin_var_name = "begin_" + full_name; // variable name doesn't matter at all, but de-spacing // makes the Stmt output easier to read std::replace(begin_var_name.begin(), begin_var_name.end(), ' ', '_'); Expr begin_var = Variable::make(UInt(64), begin_var_name); Expr old_val = Load::make(UInt(64), kBufName, idx, Buffer(), Parameter()); Expr delta_val = Sub::make(end_val, begin_var); Expr new_val = Add::make(old_val, delta_val); s = Block::make(s, Store::make(kBufName, new_val, idx)); s = LetStmt::make(begin_var_name, begin_val, s); return s; } void visit(const Pipeline *op) { if (level >= 1) { Stmt produce, update, consume; { PushCallStack st(this, "produce", op->name); produce = mutate(op->produce); } { PushCallStack st(this, "update", op->name); update = op->update.defined() ? mutate(op->update) : Stmt(); } { PushCallStack st(this, "consume", op->name); consume = mutate(op->consume); } produce = add_count_and_ticks("produce", op->name, produce); update = update.defined() ? add_count_and_ticks("update", op->name, update) : Stmt(); consume = add_count_and_ticks("consume", op->name, consume); stmt = Pipeline::make(op->name, produce, update, consume); } else { IRMutator::visit(op); } } void visit(const For *op) { current_loop_level++; if (op->for_type == For::Parallel && level >= 1) { std::cerr << "Warning: The Halide profiler does not yet support " << "parallel schedules. Not profiling inside the loop over " << op->name << "\n"; stmt = op; } else { PushCallStack st(this, "forloop", op->name); IRMutator::visit(op); } // We only instrument loops at profiling level 2 or higher if ((level >= 2) && (current_loop_level <= maximum_loop_level) && (op->for_type != For::Vectorized)) { stmt = add_count_and_ticks("forloop", op->name, stmt); } current_loop_level--; } }; Stmt inject_profiling(Stmt s, string name) { InjectProfiling profiling(name); s = profiling.inject(s); return s; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, 2019 ARM Limited * All rights reserved * * Copyright (c) 2001-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BASE_TRACE_HH__ #define __BASE_TRACE_HH__ #include <string> #include "base/cprintf.hh" #include "base/debug.hh" #include "base/match.hh" #include "base/types.hh" #include "sim/core.hh" namespace Trace { /** Debug logging base class. Handles formatting and outputting * time/name/message messages */ class Logger { protected: /** Name match for objects to ignore */ ObjectMatch ignore; public: /** Log a single message */ template <typename ...Args> void dprintf(Tick when, const std::string &name, const char *fmt, const Args &...args) { dprintf_flag(when, name, "", fmt, args...); } /** Log a single message with a flag prefix. */ template <typename ...Args> void dprintf_flag(Tick when, const std::string &name, const std::string &flag, const char *fmt, const Args &...args) { if (!name.empty() && ignore.match(name)) return; std::ostringstream line; ccprintf(line, fmt, args...); logMessage(when, name, flag, line.str()); } /** Dump a block of data of length len */ void dump(Tick when, const std::string &name, const void *d, int len, const std::string &flag); /** Log formatted message */ virtual void logMessage(Tick when, const std::string &name, const std::string &flag, const std::string &message) = 0; /** Return an ostream that can be used to send messages to * the 'same place' as formatted logMessage messages. This * can be implemented to use a logger's underlying ostream, * to provide an ostream which formats the output in some * way, or just set to one of std::cout, std::cerr */ virtual std::ostream &getOstream() = 0; /** Set objects to ignore */ void setIgnore(ObjectMatch &ignore_) { ignore = ignore_; } /** Add objects to ignore */ void addIgnore(const ObjectMatch &ignore_) { ignore.add(ignore_); } virtual ~Logger() { } }; /** Logging wrapper for ostreams with the format: * <when>: <name>: <message-body> */ class OstreamLogger : public Logger { protected: std::ostream &stream; public: OstreamLogger(std::ostream &stream_) : stream(stream_) { } void logMessage(Tick when, const std::string &name, const std::string &flag, const std::string &message) override; std::ostream &getOstream() override { return stream; } }; /** Get the current global debug logger. This takes ownership of the given * logger which should be allocated using 'new' */ Logger *getDebugLogger(); /** Get the ostream from the current global logger */ std::ostream &output(); /** Delete the current global logger and assign a new one */ void setDebugLogger(Logger *logger); /** Enable/disable debug logging */ void enable(); void disable(); } // namespace Trace // This silly little class allows us to wrap a string in a functor // object so that we can give a name() that DPRINTF will like struct StringWrap { std::string str; StringWrap(const std::string &s) : str(s) {} const std::string &operator()() const { return str; } }; // Return the global context name "global". This function gets called when // the DPRINTF macros are used in a context without a visible name() function const std::string &name(); // Interface for things with names. (cf. SimObject but without other // functionality). This is useful when using DPRINTF class Named { protected: const std::string _name; public: Named(const std::string &name_) : _name(name_) { } public: const std::string &name() const { return _name; } }; /** * DPRINTF is a debugging trace facility that allows one to * selectively enable tracing statements. To use DPRINTF, there must * be a function or functor called name() that returns a const * std::string & in the current scope. * * If you desire that the automatic printing not occur, use DPRINTFR * (R for raw) * * \def DDUMP(x, data, count) * \def DPRINTF(x, ...) * \def DPRINTFS(x, s, ...) * \def DPRINTFR(x, ...) * \def DDUMPN(data, count) * \def DPRINTFN(...) * \def DPRINTFNR(...) * \def DPRINTF_UNCONDITIONAL(x, ...) * * @ingroup api_trace * @{ */ #if TRACING_ON #define DDUMP(x, data, count) do { \ using namespace Debug; \ if (DTRACE(x)) \ Trace::getDebugLogger()->dump( \ curTick(), name(), data, count, #x); \ } while (0) #define DPRINTF(x, ...) do { \ using namespace Debug; \ if (DTRACE(x)) { \ Trace::getDebugLogger()->dprintf_flag( \ curTick(), name(), #x, __VA_ARGS__); \ } \ } while (0) #define DPRINTFS(x, s, ...) do { \ using namespace Debug; \ if (DTRACE(x)) { \ Trace::getDebugLogger()->dprintf_flag( \ curTick(), s->name(), #x, __VA_ARGS__); \ } \ } while (0) #define DPRINTFR(x, ...) do { \ using namespace Debug; \ if (DTRACE(x)) { \ Trace::getDebugLogger()->dprintf_flag( \ (Tick)-1, std::string(), #x, __VA_ARGS__); \ } \ } while (0) #define DDUMPN(data, count) do { \ Trace::getDebugLogger()->dump(curTick(), name(), data, count); \ } while (0) #define DPRINTFN(...) do { \ Trace::getDebugLogger()->dprintf(curTick(), name(), __VA_ARGS__); \ } while (0) #define DPRINTFNR(...) do { \ Trace::getDebugLogger()->dprintf((Tick)-1, std::string(), __VA_ARGS__); \ } while (0) #define DPRINTF_UNCONDITIONAL(x, ...) do { \ Trace::getDebugLogger()->dprintf_flag( \ curTick(), name(), #x, __VA_ARGS__); \ } while (0) #else // !TRACING_ON #define DDUMP(x, data, count) do {} while (0) #define DPRINTF(x, ...) do {} while (0) #define DPRINTFS(x, ...) do {} while (0) #define DPRINTFR(...) do {} while (0) #define DDUMPN(data, count) do {} while (0) #define DPRINTFN(...) do {} while (0) #define DPRINTFNR(...) do {} while (0) #define DPRINTF_UNCONDITIONAL(x, ...) do {} while (0) #endif // TRACING_ON /** @} */ // end of api_trace #endif // __BASE_TRACE_HH__ <commit_msg>base: Use M5_UNLIKELY with conditional DPRINTF family functions.<commit_after>/* * Copyright (c) 2014, 2019 ARM Limited * All rights reserved * * Copyright (c) 2001-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BASE_TRACE_HH__ #define __BASE_TRACE_HH__ #include <string> #include "base/cprintf.hh" #include "base/debug.hh" #include "base/match.hh" #include "base/types.hh" #include "sim/core.hh" namespace Trace { /** Debug logging base class. Handles formatting and outputting * time/name/message messages */ class Logger { protected: /** Name match for objects to ignore */ ObjectMatch ignore; public: /** Log a single message */ template <typename ...Args> void dprintf(Tick when, const std::string &name, const char *fmt, const Args &...args) { dprintf_flag(when, name, "", fmt, args...); } /** Log a single message with a flag prefix. */ template <typename ...Args> void dprintf_flag(Tick when, const std::string &name, const std::string &flag, const char *fmt, const Args &...args) { if (!name.empty() && ignore.match(name)) return; std::ostringstream line; ccprintf(line, fmt, args...); logMessage(when, name, flag, line.str()); } /** Dump a block of data of length len */ void dump(Tick when, const std::string &name, const void *d, int len, const std::string &flag); /** Log formatted message */ virtual void logMessage(Tick when, const std::string &name, const std::string &flag, const std::string &message) = 0; /** Return an ostream that can be used to send messages to * the 'same place' as formatted logMessage messages. This * can be implemented to use a logger's underlying ostream, * to provide an ostream which formats the output in some * way, or just set to one of std::cout, std::cerr */ virtual std::ostream &getOstream() = 0; /** Set objects to ignore */ void setIgnore(ObjectMatch &ignore_) { ignore = ignore_; } /** Add objects to ignore */ void addIgnore(const ObjectMatch &ignore_) { ignore.add(ignore_); } virtual ~Logger() { } }; /** Logging wrapper for ostreams with the format: * <when>: <name>: <message-body> */ class OstreamLogger : public Logger { protected: std::ostream &stream; public: OstreamLogger(std::ostream &stream_) : stream(stream_) { } void logMessage(Tick when, const std::string &name, const std::string &flag, const std::string &message) override; std::ostream &getOstream() override { return stream; } }; /** Get the current global debug logger. This takes ownership of the given * logger which should be allocated using 'new' */ Logger *getDebugLogger(); /** Get the ostream from the current global logger */ std::ostream &output(); /** Delete the current global logger and assign a new one */ void setDebugLogger(Logger *logger); /** Enable/disable debug logging */ void enable(); void disable(); } // namespace Trace // This silly little class allows us to wrap a string in a functor // object so that we can give a name() that DPRINTF will like struct StringWrap { std::string str; StringWrap(const std::string &s) : str(s) {} const std::string &operator()() const { return str; } }; // Return the global context name "global". This function gets called when // the DPRINTF macros are used in a context without a visible name() function const std::string &name(); // Interface for things with names. (cf. SimObject but without other // functionality). This is useful when using DPRINTF class Named { protected: const std::string _name; public: Named(const std::string &name_) : _name(name_) { } public: const std::string &name() const { return _name; } }; /** * DPRINTF is a debugging trace facility that allows one to * selectively enable tracing statements. To use DPRINTF, there must * be a function or functor called name() that returns a const * std::string & in the current scope. * * If you desire that the automatic printing not occur, use DPRINTFR * (R for raw) * * \def DDUMP(x, data, count) * \def DPRINTF(x, ...) * \def DPRINTFS(x, s, ...) * \def DPRINTFR(x, ...) * \def DDUMPN(data, count) * \def DPRINTFN(...) * \def DPRINTFNR(...) * \def DPRINTF_UNCONDITIONAL(x, ...) * * @ingroup api_trace * @{ */ #if TRACING_ON #define DDUMP(x, data, count) do { \ using namespace Debug; \ if (M5_UNLIKELY(DTRACE(x))) \ Trace::getDebugLogger()->dump( \ curTick(), name(), data, count, #x); \ } while (0) #define DPRINTF(x, ...) do { \ using namespace Debug; \ if (M5_UNLIKELY(DTRACE(x))) { \ Trace::getDebugLogger()->dprintf_flag( \ curTick(), name(), #x, __VA_ARGS__); \ } \ } while (0) #define DPRINTFS(x, s, ...) do { \ using namespace Debug; \ if (M5_UNLIKELY(DTRACE(x))) { \ Trace::getDebugLogger()->dprintf_flag( \ curTick(), s->name(), #x, __VA_ARGS__); \ } \ } while (0) #define DPRINTFR(x, ...) do { \ using namespace Debug; \ if (M5_UNLIKELY(DTRACE(x))) { \ Trace::getDebugLogger()->dprintf_flag( \ (Tick)-1, std::string(), #x, __VA_ARGS__); \ } \ } while (0) #define DDUMPN(data, count) do { \ Trace::getDebugLogger()->dump(curTick(), name(), data, count); \ } while (0) #define DPRINTFN(...) do { \ Trace::getDebugLogger()->dprintf(curTick(), name(), __VA_ARGS__); \ } while (0) #define DPRINTFNR(...) do { \ Trace::getDebugLogger()->dprintf((Tick)-1, std::string(), __VA_ARGS__); \ } while (0) #define DPRINTF_UNCONDITIONAL(x, ...) do { \ Trace::getDebugLogger()->dprintf_flag( \ curTick(), name(), #x, __VA_ARGS__); \ } while (0) #else // !TRACING_ON #define DDUMP(x, data, count) do {} while (0) #define DPRINTF(x, ...) do {} while (0) #define DPRINTFS(x, ...) do {} while (0) #define DPRINTFR(...) do {} while (0) #define DDUMPN(data, count) do {} while (0) #define DPRINTFN(...) do {} while (0) #define DPRINTFNR(...) do {} while (0) #define DPRINTF_UNCONDITIONAL(x, ...) do {} while (0) #endif // TRACING_ON /** @} */ // end of api_trace #endif // __BASE_TRACE_HH__ <|endoftext|>
<commit_before>/* * match.hpp * * Created on: 22.02.2017 * Author: Andreas Molzer */ #include "hdr/std.hpp" #include "hdr/types/maybe.hpp" /** Intended usage: * match var [(with template selector function)]... * Essentially works as a monad M where * (match var) constructs (M V) and * (with template selector function) constructs a (V -> M V) and * the monad overloads application to be bind */ namespace hdr::match { using ::hdr::std::Apply; using ::hdr::std::Const; using ::hdr::std::True; using ::hdr::std::False; using ::hdr::std::TemplateFunction; using ::hdr::std::TypeFunction; using ::hdr::std::compose; using ::hdr::std::flip; using ::hdr::std::when_else; using ::hdr::maybe::Just; using ::hdr::maybe::Nothing; using ::hdr::maybe::bind; using ::hdr::maybe::fmap; using ::hdr::maybe::freturn; using ::hdr::maybe::maybe; template<typename Var> struct Unmatched { template<typename With> using expr = Apply<With, Var>; }; template<typename Var> struct Matched { template<typename With> using expr = Matched<Var>; }; template<typename Key> struct Placeholder { using type = Key; }; struct PlaceholderAny; using _ = PlaceholderAny; template<typename _Key, typename _Val> struct KVPair{ using Key = _Key; using Val = _Val; }; template<typename ... KVs> struct KVList; template<typename K, typename L> struct _Join; using _join = TypeFunction<_Join>; template<typename ... KVs, typename ... KLs> struct _Join<KVList<KVs...>, KVList<KLs...>> { using type = KVList<KVs..., KLs...>; }; template<typename... Args> struct _Flatten; template<> struct _Flatten<> { using type = KVList<>; }; template<typename K> struct _Flatten<K> { using type = K; }; template<typename K, typename ... R> struct _Flatten<K, R...> { template<typename Ma, typename Mb> struct MaybeJoin { template<typename L, typename M> using Mjoin = Just<Apply<_join, L, M>>; using mjoin = TemplateFunction<Mjoin>; using first = Apply<maybe, Const<Nothing>, mjoin, Ma>; using type = Apply<bind, Mb, first>; }; using T = typename _Flatten<R...>::type; using type = Apply<TypeFunction<MaybeJoin>, K, T>; }; /** * A -> B -> Optional TemplateVars */ template<typename Template, typename Actual> struct Decompose { template<typename T, typename S> struct IsSame { using type = False; }; template<typename T> struct IsSame<T, T> { using type = True; }; using type = Apply<when_else, typename IsSame<Template, Actual>::type, Just<KVList<>>, Nothing>; }; using decompose = TypeFunction<Decompose>; template<typename PKey, typename A> struct Decompose<Placeholder<PKey>, A> { using type = Just<KVList<KVPair<PKey, A>>>; }; template<typename A> struct Decompose<PlaceholderAny, A> { using type = Just<KVList<>>; }; template<template<typename...> typename A, typename ... TArgs, typename ... Args> struct Decompose<A<TArgs...>, A<Args...>> { using type = typename _Flatten<Apply<decompose, TArgs, Args>...>::type; }; /** Constructs a WithClause * Template -> (TemplateVars -> Bool) -> (TemplateVars -> B) -> A -> Maybe B */ template<typename Template, typename Selector, typename Function> struct With { using maybe_decomp = Apply<decompose, Template>; // (A -> Maybe TemplateVars) using boolifier = Apply<fmap, Selector>; // (Maybe TemplateVars -> Maybe Bool) using get_result = Apply<fmap, Function>; // (Maybe TemplateVars -> Maybe B) using if_selected = Apply<Apply<flip, when_else>, get_result> ; // (Bool -> (Maybe TemplateVars -> Maybe B) -> (Maybe TemplateVars -> Maybe B)) using fmappable = Apply<Apply<flip, if_selected>, Const<Nothing>>;// (Bool -> (Maybe TemplateVars -> Maybe B)) using select_after = Apply<flip, fmappable>; // (Maybe TemplateVars -> Bool -> Maybe B) template<typename MTV> using _result_func = Apply<bind, Apply<boolifier, MTV>, Apply<select_after, MTV>>; // <>(Maybe TemplateVars -> Maybe B) using result_func = TemplateFunction<_result_func>; // (Maybe TemplateVars -> Maybe B) using maybe_result = Apply<compose, result_func, maybe_decomp>; // (A -> Maybe B) using type = maybe_result; }; using with = TypeFunction<With>; } <commit_msg>Nicer implementation, prepares for eventual single argument lambdas<commit_after>/* * match.hpp * * Created on: 22.02.2017 * Author: Andreas Molzer */ #include "hdr/std.hpp" #include "hdr/types/maybe.hpp" /** Intended usage: * match var [(with template selector function)]... * Essentially works as a monad M where * (match var) constructs (M V) and * (with template selector function) constructs a (V -> M V) and * the monad overloads application to be bind */ namespace hdr::match { using ::hdr::std::Apply; using ::hdr::std::Const; using ::hdr::std::True; using ::hdr::std::False; using ::hdr::std::TemplateFunction; using ::hdr::std::TypeFunction; using ::hdr::std::compose; using ::hdr::std::flip; using ::hdr::std::when_else; using ::hdr::maybe::Just; using ::hdr::maybe::Nothing; using ::hdr::maybe::bind; using ::hdr::maybe::fmap; using ::hdr::maybe::freturn; using ::hdr::maybe::maybe; template<typename Var> struct Unmatched { template<typename With> using expr = Apply<With, Var>; }; template<typename Var> struct Matched { template<typename With> using expr = Matched<Var>; }; template<typename Key> struct Placeholder { using type = Key; }; struct PlaceholderAny; using _ = PlaceholderAny; template<typename _Key, typename _Val> struct KVPair{ using Key = _Key; using Val = _Val; }; template<typename ... KVs> struct KVList; template<typename K, typename L> struct _Join; using _join = TypeFunction<_Join>; template<typename ... KVs, typename ... KLs> struct _Join<KVList<KVs...>, KVList<KLs...>> { using type = KVList<KVs..., KLs...>; }; template<typename... Args> struct _Flatten; template<> struct _Flatten<> { using type = KVList<>; }; template<typename K> struct _Flatten<K> { using type = K; }; template<typename K, typename ... R> struct _Flatten<K, R...> { template<typename Ma, typename Mb> struct MaybeJoin { template<typename L, typename M> using Mjoin = Just<Apply<_join, L, M>>; using mjoin = TemplateFunction<Mjoin>; using first = Apply<maybe, Const<Nothing>, mjoin, Ma>; using type = Apply<bind, Mb, first>; }; using T = typename _Flatten<R...>::type; using type = Apply<TypeFunction<MaybeJoin>, K, T>; }; /** * A -> B -> Optional TemplateVars */ template<typename Template, typename Actual> struct Decompose { template<typename T, typename S> struct IsSame { using type = False; }; template<typename T> struct IsSame<T, T> { using type = True; }; using type = Apply<when_else, typename IsSame<Template, Actual>::type, Just<KVList<>>, Nothing>; }; using decompose = TypeFunction<Decompose>; template<typename PKey, typename A> struct Decompose<Placeholder<PKey>, A> { using type = Just<KVList<KVPair<PKey, A>>>; }; template<typename A> struct Decompose<PlaceholderAny, A> { using type = Just<KVList<>>; }; template<template<typename...> typename A, typename ... TArgs, typename ... Args> struct Decompose<A<TArgs...>, A<Args...>> { using type = typename _Flatten<Apply<decompose, TArgs, Args>...>::type; }; /** Constructs a WithClause * Template -> (TemplateVars -> Bool) -> (TemplateVars -> B) -> A -> Maybe B */ template<typename Template, typename Selector, typename Function> struct With { using maybe_decomp = Apply<decompose, Template>; // (A -> Maybe TemplateVars) using boolifier = Apply<fmap, Selector>; // (Maybe TemplateVars -> Maybe Bool) using get_result = Apply<fmap, Function>; // (Maybe TemplateVars -> Maybe B) template<typename B> using _selector = Apply<when_else, B, get_result, Const<Nothing>>; using selector = TemplateFunction<_selector>; // (Bool -> (Maybe TemplateVars -> Maybe B)) using select_after = Apply<flip, selector>; // (Maybe TemplateVars -> Bool -> Maybe B) template<typename MTV> using _result_func = Apply<bind, Apply<boolifier, MTV>, Apply<select_after, MTV>>; using result_func = TemplateFunction<_result_func>; // (Maybe TemplateVars -> Maybe B) using maybe_result = Apply<compose, result_func, maybe_decomp>; // (A -> Maybe B) using type = maybe_result; }; using with = TypeFunction<With>; } <|endoftext|>
<commit_before>#include <stdio.h> #ifdef WIN32 #include <windows.h> #endif #include <GL/glut.h> #include "RayTracer.hpp" //temporary variables Vec3Df testRayOrigin; Vec3Df testRayDestination; string input; //use this function for any preprocessing of the mesh. void init(int argc, char **argv){ //load the mesh file //feel free to replace cube by a path to another model //please realize that not all OBJ files will successfully load. //Nonetheless, if they come from Blender, they should. //there is a difference between windows written objs and Linux written objs. //hence, some models might not yet work well. RayTracingResolutionX = 1000; // These resolutions should be the same as the window, RayTracingResolutionY = 1000; // otherwise unexpected behaviour occurs. if(argc == 2){ input = argv[1]; }else{ cout << "Mesh file name: (0: cube, 1: monkey, 2: dodgeColorTest)" << endl << "You can omit the mesh/ path and the .obj extension." << endl; cin >> input; } if (input == "0") input = "cube"; else if (input == "1") input = "monkey"; else if (input == "2") input = "dodgeColorTest"; input = string("mesh/").append(input).append(".obj"); MyMesh.loadMesh(input.c_str(), true); MyMesh.computeVertexNormals(); //one first move: initialize the first light source //at least ONE light source has to be in the scene!!! //here, we set it to the current location of the camera MyLightPositions.push_back(MyCameraPosition); } #define dot Vec3Df::dotProduct #define cross Vec3Df::crossProduct /** Calculate intersection between triangle and ray */ float intersect(const Triangle& t, const Ray& ray){ const Vec3Df& v0 = t.vertices[0].p, // Variables saved as locals for less external function calls, v1 = t.vertices[1].p, // less characters in the code and better readability. v2 = t.vertices[2].p, rayOrig = ray.getOrig(), rayDir = ray.getDir(); // The normalized direction of the ray. float angle = dot(t.normal, rayDir); // The cosine of the angle of the vectors (dotproduct of the vectors). /* Floats are only rarely exactly 0, are you sure this is correct? */ if (angle == 0) // If the ray and the plane are parallel (so their angle is 0), they won't intersect. return 10e6f; float rayD = -(dot(t.normal, rayOrig) + dot(t.normal, v0)) / angle; // The distance of the ray's origin // to the plane in which lies the triangle. Vec3Df rayHit = rayOrig + rayD * rayDir; // The intersection point of the ray and the plane in which lies the triangle. if (dot(t.normal, cross(v1 - v0, rayHit - v0)) < 0) return 10e6f; if (dot(t.normal, cross(v2 - v1, rayHit - v1)) < 0) return 10e6f; if (dot(t.normal, cross(v0 - v2, rayHit - v2)) < 0) return 10e6f; return rayD; } //return the color of your pixel. const Vec3Df& performRayTracing(const Vec3Df & origin, const Vec3Df & dest){ Vec3Df color = Vec3Df(0, 1, 0); Ray ray = Ray(color, origin, dest); /* Actual ray tracing code */ float hit = 10e6f; unsigned int amountOfTriangles = MyMesh.triangles.size(); for (unsigned int i = 0; i < amountOfTriangles; i++){ float ins = intersect(MyMesh.triangles[i], ray); if (ins < hit) hit = ins; } //hit = 1 / ((hit * 2) + 1); // Arithmetic function for getting a usable color. ray.setColor(Vec3Df(hit, hit / 5, hit * 5)); return Vec3Df(hit, hit / 5, hit * 5); } void yourDebugDraw(){ //draw open gl debug stuff //this function is called every frame //as an example: glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_LIGHTING); glColor3f(1, 0, 1); glBegin(GL_LINES); glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]); glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]); glEnd(); glPointSize(10); glBegin(GL_POINTS); glVertex3fv(MyLightPositions[0].pointer()); glEnd(); glPopAttrib(); } void yourKeyboardFunc(char t, int x, int y){ // do what you want with the keyboard input t. // x, y are the screen position //here I use it to get the coordinates of a ray, which I then draw in the debug function. produceRay(x, y, testRayOrigin, testRayDestination); std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl; } <commit_msg>fixed for objects behind the camera<commit_after>#include <stdio.h> #ifdef WIN32 #include <windows.h> #endif #include <GL/glut.h> #include "RayTracer.hpp" //temporary variables Vec3Df testRayOrigin; Vec3Df testRayDestination; string input; //use this function for any preprocessing of the mesh. void init(int argc, char **argv){ //load the mesh file //feel free to replace cube by a path to another model //please realize that not all OBJ files will successfully load. //Nonetheless, if they come from Blender, they should. //there is a difference between windows written objs and Linux written objs. //hence, some models might not yet work well. RayTracingResolutionX = 1000; // These resolutions should be the same as the window, RayTracingResolutionY = 1000; // otherwise unexpected behaviour occurs. if(argc == 2){ input = argv[1]; }else{ cout << "Mesh file name: (0: cube, 1: monkey, 2: dodgeColorTest)" << endl << "You can omit the mesh/ path and the .obj extension." << endl; cin >> input; } if (input == "0") input = "cube"; else if (input == "1") input = "monkey"; else if (input == "2") input = "dodgeColorTest"; input = string("mesh/").append(input).append(".obj"); MyMesh.loadMesh(input.c_str(), true); MyMesh.computeVertexNormals(); //one first move: initialize the first light source //at least ONE light source has to be in the scene!!! //here, we set it to the current location of the camera MyLightPositions.push_back(MyCameraPosition); } #define dot Vec3Df::dotProduct #define cross Vec3Df::crossProduct /** Calculate intersection between triangle and ray */ float intersect(const Triangle& t, const Ray& ray){ const Vec3Df& v0 = t.vertices[0].p, // Variables saved as locals for less external function calls, v1 = t.vertices[1].p, // less characters in the code and better readability. v2 = t.vertices[2].p, rayOrig = ray.getOrig(), rayDir = ray.getDir(); // The normalized direction of the ray. float angle = dot(t.normal, rayDir); // The cosine of the angle of the vectors (dotproduct of the vectors). /* Floats are only rarely exactly 0, are you sure this is correct? */ if (angle == 0) // If the ray and the plane are parallel (so their angle is 0), they won't intersect. return 10e6f; float rayD = -(dot(t.normal, rayOrig) + dot(t.normal, v0)) / angle; // The distance of the ray's origin // to the plane in which lies the triangle. Vec3Df rayHit = rayOrig + rayD * rayDir; // The intersection point of the ray and the plane in which lies the triangle. if (dot(t.normal, cross(v1 - v0, rayHit - v0)) < 0) return 10e6f; if (dot(t.normal, cross(v2 - v1, rayHit - v1)) < 0) return 10e6f; if (dot(t.normal, cross(v0 - v2, rayHit - v2)) < 0) return 10e6f; return rayD; } //return the color of your pixel. const Vec3Df& performRayTracing(const Vec3Df & origin, const Vec3Df & dest){ Vec3Df color = Vec3Df(0, 1, 0); Ray ray = Ray(color, origin, dest); /* Actual ray tracing code */ float hit = 10e6f; unsigned int amountOfTriangles = MyMesh.triangles.size(); for (unsigned int i = 0; i < amountOfTriangles; i++){ float ins = intersect(MyMesh.triangles[i], ray); if (ins < hit && ins > 0) hit = ins; } //hit = 1 / ((hit * 2) + 1); // Arithmetic function for getting a usable color. ray.setColor(Vec3Df(hit, hit / 5, hit * 5)); return Vec3Df(hit, hit / 5, hit * 5); } void yourDebugDraw(){ //draw open gl debug stuff //this function is called every frame //as an example: glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_LIGHTING); glColor3f(1, 0, 1); glBegin(GL_LINES); glVertex3f(testRayOrigin[0], testRayOrigin[1], testRayOrigin[2]); glVertex3f(testRayDestination[0], testRayDestination[1], testRayDestination[2]); glEnd(); glPointSize(10); glBegin(GL_POINTS); glVertex3fv(MyLightPositions[0].pointer()); glEnd(); glPopAttrib(); } void yourKeyboardFunc(char t, int x, int y){ // do what you want with the keyboard input t. // x, y are the screen position //here I use it to get the coordinates of a ray, which I then draw in the debug function. produceRay(x, y, testRayOrigin, testRayDestination); std::cout << t << " pressed! The mouse was in location " << x << "," << y << "!" << std::endl; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/include/voe_audio_processing.h" #include "gtest/gtest.h" #include "voice_engine/include/voe_base.h" namespace webrtc { namespace voe { namespace { class VoEAudioProcessingTest : public ::testing::Test { protected: VoEAudioProcessingTest() : voe_(VoiceEngine::Create()), base_(VoEBase::GetInterface(voe_)), audioproc_(VoEAudioProcessing::GetInterface(voe_)) { } virtual ~VoEAudioProcessingTest() { audioproc_->Release(); base_->Release(); VoiceEngine::Delete(voe_); } VoiceEngine* voe_; VoEBase* base_; VoEAudioProcessing* audioproc_; }; TEST_F(VoEAudioProcessingTest, FailureIfNotInitialized) { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } // TODO(andrew): Ideally, DriftCompensationSupported() would be mocked for this. TEST_F(VoEAudioProcessingTest, DriftCompensationIsEnabledIfSupported) { ASSERT_EQ(0, base_->Init()); bool supported = VoEAudioProcessing::DriftCompensationSupported(); if (supported) { EXPECT_EQ(0, audioproc_->EnableDriftCompensation(true)); EXPECT_TRUE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(0, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } else { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } } } // namespace } // namespace voe } // namespace webrtc <commit_msg>Trivial fix for memcheck error.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/include/voe_audio_processing.h" #include "gtest/gtest.h" #include "voice_engine/include/voe_base.h" namespace webrtc { namespace voe { namespace { class VoEAudioProcessingTest : public ::testing::Test { protected: VoEAudioProcessingTest() : voe_(VoiceEngine::Create()), base_(VoEBase::GetInterface(voe_)), audioproc_(VoEAudioProcessing::GetInterface(voe_)) { } virtual ~VoEAudioProcessingTest() { base_->Terminate(); audioproc_->Release(); base_->Release(); VoiceEngine::Delete(voe_); } VoiceEngine* voe_; VoEBase* base_; VoEAudioProcessing* audioproc_; }; TEST_F(VoEAudioProcessingTest, FailureIfNotInitialized) { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } // TODO(andrew): Ideally, DriftCompensationSupported() would be mocked for this. TEST_F(VoEAudioProcessingTest, DriftCompensationIsEnabledIfSupported) { ASSERT_EQ(0, base_->Init()); bool supported = VoEAudioProcessing::DriftCompensationSupported(); if (supported) { EXPECT_EQ(0, audioproc_->EnableDriftCompensation(true)); EXPECT_TRUE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(0, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } else { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } } } // namespace } // namespace voe } // namespace webrtc <|endoftext|>
<commit_before>/* Copyright 2016, Jernej Kovacic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file * @author Jernej Kovacic * * Implementation of functions within the namespace TriangularDist * that perform various triangular distribution related operations, * such as calculation of upper and lower tail probabilities * and quantiles, probability distribution function, etc. */ /* * More details about the triangular distribution: * https://en.wikipedia.org/wiki/Triangular_distribution */ // No #include "TriangularDistGeneric.hpp" !!! #include <algorithm> #include <cmath> #include "util/NumericUtil.hpp" #include "exception/StatisticsException.hpp" namespace math { namespace TriangularDist { namespace __private { /* * Checks if all triangular distribution's parameter satisfy * the criteria: a < c < b * * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * * @throw StatisticsException if the parameters are invalid */ template <typename F> void __checkParams(const F& a, const F& b, const F& c) throw (math::StatisticsException) { if ( ( (c-a) < math::NumericUtil::getEPS<F>() ) || (b-c) < math::NumericUtil::getEPS<F>() ) { throw math::StatisticsException(math::StatisticsException::INVALID_ARG); } } }}} // namespace math::TriangularDist::__private /** * Value of the triangular distribution's probability distribution * function (pdf) for the given 'x'. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param x - value to be calculated its probability distribution function * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * * @return pdf(x, a, b, c) * * @throw StatisticsException if the parameters 'a', 'b' and 'c' are invalid */ template <typename F> F math::TriangularDist::pdf( const F& x, const F& a, const F& b, const F& c ) throw (math::StatisticsException) { /* * Probability density function of the triangular distribution: * * / * | 0 <== x <= a * | * | 2*(x-a) * | ------------- <== a < x <= c * / (b-a)*(c-a) * pdf = { * \ 2*(b-x) * | ------------- <== c < x < b * | (b-a)*(b-c) * | * | 0 <== x >= b * \ */ // sanity check: math::TriangularDist::__private::__checkParams<F>(a, b, c); F pdf = static_cast<F>(0); if ( x>a && x <=c ) { pdf = 2*(x-a) / ((b-a)*(c-a)); } else if ( x>c && x<b) { pdf = 2*(b-x) / ((b-a)*(b-c)); } // else pdf = static_cast<F>(0); return pdf; } /** * Probability in the triangular distribution with specified * parameters that 'x' is greater than 'from' and less than 'to'. * * @note 'from' and 'to' are interchangeable, the result's sign will * not change in this case. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param from - lower limit of the interval * @param to - upper limit of the interval * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * * @return P(from<X<to) or P(to<X<from) * * @throw StatisticsException if the parameters 'a', 'b' and 'c' are invalid */ template <typename F> F math::TriangularDist::probInt( const F& from, const F& to, const F& a, const F& b, const F& c ) throw (math::StatisticsException) { /* * to * / * P(a<X<b) = | pdf(t) dt = cdf(b) - cdf(a) * / * from */ // sanity check will be performed by prob() const F upper = std::max<F>(from, to); const F lower = std::min<F>(from, to); return math::TriangularDist::prob<F>(upper, a, b, c, true) - math::TriangularDist::prob<F>(lower, a, b, c, true); } /** * Probability that a value is greater or smaller (depending on 'lowerTail') * than the given value 'x' for the specified triangular distribution. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param x - value * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * @param lowerTail - if true, returns P(t<x), otherwise P(t>x) (default: true) * * @return P(X<x) if 'lowerTail' equals true, P(X>x) if 'lowerTail' equals false * * @throw StatisticsException if the parameters 'a', 'b' and 'c' are invalid */ template <typename F> F math::TriangularDist::prob( const F& x, const F& a, const F& b, const F& c, const bool lowerTail ) throw (math::StatisticsException) { /* * The cdf represents probability that a value from the triangular * distribution is smaller than a specified value 'x' and can be * expressed as: * * x * / * cdf(x) = P(X<x) = | pdf(t) dt * / * -inf * * For the triangular distribution, cdf can be calculated as: * * / * | 0 <== x <= a * | * | 2 * | (x-a) * | ------------- <== a < x <= c * | (b-a)*(c-a) * / * cdf = { * \ * | 2 * | (b-x) * | 1 - ------------- <== c < x < b * | (b-a)*(b-c) * | * | 1 <== x >= b * \ * * For the upper tail probability ( P(X>x) ) just return the complement * of the lower tail probability: 1 - cdf(x) */ // sanity check math::TriangularDist::__private::__checkParams<F>(a, b, c); F cdf = static_cast<F>(0); if ( x <= a ) { cdf = static_cast<F>(0); } else if ( x>a && x<=c ) { const F xa = x - a; cdf = xa*xa / ((b-a)*(c-a)); } else if ( x>c && x<b ) { const F bx = b - x; cdf = static_cast<F>(1) - ( bx*bx / ((b-a)*(b-c)) ); } else // x >= b { cdf = static_cast<F>(1); } // the return value depends on 'lowerTail': return ( true==lowerTail ? cdf : static_cast<F>(1)-cdf ); } /** * Quantile function for the specified triangular distribution. * * If 'lowerTail' equals true, it returns such 'x' that P(X<x) = p * If 'lowerTail' equals false, it returns such 'x' that P(X>x) = p * * @note The function always returns a value between 'a' and 'b'. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param p - probability (must be greater than 0 and less than 1) * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * @param lowerTail - if true, returns q(X<x), otherwise q(X>x) (default: true) * * @return x: P(X<x) if 'lowerTail' equals true, x: P(X>x) if 'lowerTail' equals false * * @throw StatisticsException if parameters 'a', 'b', 'c' or 'p' are invalid */ template <typename F> F math::TriangularDist::quant( const F& p, const F& a, const F& b, const F& c, const bool lowerTail ) throw (math::StatisticsException) { // sanity check math::TriangularDist::__private::__checkParams<F>(a, b, c); if ( p < static_cast<F>(0) || p > static_cast<F>(1) ) { throw math::StatisticsException(math::StatisticsException::INVALID_PROBABILTY); } // The actual probability in the expressions above depends on 'lowerTail': const F P = (true==lowerTail ? p : static_cast<F>(1)-p); /* * Quantile is a value of 'x' that solves the nonlinear equation: * * cdf(x) = P * * When P ~= 0, any x<=a is valid, the function will return 'a'. * * When P ~= 1, any x>=b is valid, the function will return 'b'. * * When 0 < P < 1, x will be a value between 'a' and 'b' as shown below: * * At the mode, the CDF is equal to: * * c - a * CDF(c) = ------- * b - a * * Further evaluation of the quantile depends whether P is less than or * greater than CDF(c): * * / * | a <== P ~= 0 * | * | * | -+ +-----------------+ * | a + \/ P * (b-a) * (c-a) <== 0 < P <= (c-a)/(b-a) * / * quant(P) = { * \ * | -+ +---------------------+ * | b - \/ (1-P) * (b-a) * (b-c) <== (c-a)/(b-a) < P < 1 * | * | * | b <== P ~= 1 * \ */ F retVal = static_cast<F>(0); if ( P < math::NumericUtil::getEPS<F>() ) { retVal = a; } else if ( P > (static_cast<F>(1)-math::NumericUtil::getEPS<F>()) ) { retVal = b; } else if ( P <= ( (c-a) / (b-a) ) ) { retVal = a + std::sqrt( P * (b-a) * (c-a) ); } else // (c-a)/(b-a) < P < 1 { retVal = b - std::sqrt( (static_cast<F>(1)-P) * (b-a) * (b-c) ); } return retVal; } <commit_msg>rewrote pdf and cdf conditions<commit_after>/* Copyright 2016, Jernej Kovacic Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file * @author Jernej Kovacic * * Implementation of functions within the namespace TriangularDist * that perform various triangular distribution related operations, * such as calculation of upper and lower tail probabilities * and quantiles, probability distribution function, etc. */ /* * More details about the triangular distribution: * https://en.wikipedia.org/wiki/Triangular_distribution */ // No #include "TriangularDistGeneric.hpp" !!! #include <algorithm> #include <cmath> #include "util/NumericUtil.hpp" #include "exception/StatisticsException.hpp" namespace math { namespace TriangularDist { namespace __private { /* * Checks if all triangular distribution's parameter satisfy * the criteria: a < c < b * * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * * @throw StatisticsException if the parameters are invalid */ template <typename F> void __checkParams(const F& a, const F& b, const F& c) throw (math::StatisticsException) { if ( ( (c-a) < math::NumericUtil::getEPS<F>() ) || (b-c) < math::NumericUtil::getEPS<F>() ) { throw math::StatisticsException(math::StatisticsException::INVALID_ARG); } } }}} // namespace math::TriangularDist::__private /** * Value of the triangular distribution's probability distribution * function (pdf) for the given 'x'. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param x - value to be calculated its probability distribution function * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * * @return pdf(x, a, b, c) * * @throw StatisticsException if the parameters 'a', 'b' and 'c' are invalid */ template <typename F> F math::TriangularDist::pdf( const F& x, const F& a, const F& b, const F& c ) throw (math::StatisticsException) { /* * Probability density function of the triangular distribution: * * / * | 0 <== x <= a * | * | 2*(x-a) * | ------------- <== a < x <= c * / (b-a)*(c-a) * pdf = { * \ 2*(b-x) * | ------------- <== c < x < b * | (b-a)*(b-c) * | * | 0 <== x >= b * \ */ // sanity check: math::TriangularDist::__private::__checkParams<F>(a, b, c); F pdf = static_cast<F>(0); if ( a<x && x<=c ) { pdf = 2*(x-a) / ((b-a)*(c-a)); } else if ( c<x && x<b ) { pdf = 2*(b-x) / ((b-a)*(b-c)); } // else pdf = static_cast<F>(0); return pdf; } /** * Probability in the triangular distribution with specified * parameters that 'x' is greater than 'from' and less than 'to'. * * @note 'from' and 'to' are interchangeable, the result's sign will * not change in this case. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param from - lower limit of the interval * @param to - upper limit of the interval * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * * @return P(from<X<to) or P(to<X<from) * * @throw StatisticsException if the parameters 'a', 'b' and 'c' are invalid */ template <typename F> F math::TriangularDist::probInt( const F& from, const F& to, const F& a, const F& b, const F& c ) throw (math::StatisticsException) { /* * to * / * P(a<X<b) = | pdf(t) dt = cdf(b) - cdf(a) * / * from */ // sanity check will be performed by prob() const F upper = std::max<F>(from, to); const F lower = std::min<F>(from, to); return math::TriangularDist::prob<F>(upper, a, b, c, true) - math::TriangularDist::prob<F>(lower, a, b, c, true); } /** * Probability that a value is greater or smaller (depending on 'lowerTail') * than the given value 'x' for the specified triangular distribution. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param x - value * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * @param lowerTail - if true, returns P(t<x), otherwise P(t>x) (default: true) * * @return P(X<x) if 'lowerTail' equals true, P(X>x) if 'lowerTail' equals false * * @throw StatisticsException if the parameters 'a', 'b' and 'c' are invalid */ template <typename F> F math::TriangularDist::prob( const F& x, const F& a, const F& b, const F& c, const bool lowerTail ) throw (math::StatisticsException) { /* * The cdf represents probability that a value from the triangular * distribution is smaller than a specified value 'x' and can be * expressed as: * * x * / * cdf(x) = P(X<x) = | pdf(t) dt * / * -inf * * For the triangular distribution, cdf can be calculated as: * * / * | 0 <== x <= a * | * | 2 * | (x-a) * | ------------- <== a < x <= c * | (b-a)*(c-a) * / * cdf = { * \ * | 2 * | (b-x) * | 1 - ------------- <== c < x < b * | (b-a)*(b-c) * | * | 1 <== x >= b * \ * * For the upper tail probability ( P(X>x) ) just return the complement * of the lower tail probability: 1 - cdf(x) */ // sanity check math::TriangularDist::__private::__checkParams<F>(a, b, c); F cdf = static_cast<F>(0); if ( x <= a ) { cdf = static_cast<F>(0); } else if ( a<x && x<=c ) { const F xa = x - a; cdf = xa*xa / ((b-a)*(c-a)); } else if ( c<x && x<b ) { const F bx = b - x; cdf = static_cast<F>(1) - ( bx*bx / ((b-a)*(b-c)) ); } else // x >= b { cdf = static_cast<F>(1); } // the return value depends on 'lowerTail': return ( true==lowerTail ? cdf : static_cast<F>(1)-cdf ); } /** * Quantile function for the specified triangular distribution. * * If 'lowerTail' equals true, it returns such 'x' that P(X<x) = p * If 'lowerTail' equals false, it returns such 'x' that P(X>x) = p * * @note The function always returns a value between 'a' and 'b'. * * @note 'a', 'b' and 'c' must satisfy the criteria: a < c < b * * @param p - probability (must be greater than 0 and less than 1) * @param a - triangular distribution's lower limit * @param b - triangular distribution's upper limit * @param c - triangular distribution's mode * @param lowerTail - if true, returns q(X<x), otherwise q(X>x) (default: true) * * @return x: P(X<x) if 'lowerTail' equals true, x: P(X>x) if 'lowerTail' equals false * * @throw StatisticsException if parameters 'a', 'b', 'c' or 'p' are invalid */ template <typename F> F math::TriangularDist::quant( const F& p, const F& a, const F& b, const F& c, const bool lowerTail ) throw (math::StatisticsException) { // sanity check math::TriangularDist::__private::__checkParams<F>(a, b, c); if ( p < static_cast<F>(0) || p > static_cast<F>(1) ) { throw math::StatisticsException(math::StatisticsException::INVALID_PROBABILTY); } // The actual probability in the expressions above depends on 'lowerTail': const F P = (true==lowerTail ? p : static_cast<F>(1)-p); /* * Quantile is a value of 'x' that solves the nonlinear equation: * * cdf(x) = P * * When P ~= 0, any x<=a is valid, the function will return 'a'. * * When P ~= 1, any x>=b is valid, the function will return 'b'. * * When 0 < P < 1, x will be a value between 'a' and 'b' as shown below: * * At the mode, the CDF is equal to: * * c - a * CDF(c) = ------- * b - a * * Further evaluation of the quantile depends whether P is less than or * greater than CDF(c): * * / * | a <== P ~= 0 * | * | * | -+ +-----------------+ * | a + \/ P * (b-a) * (c-a) <== 0 < P <= (c-a)/(b-a) * / * quant(P) = { * \ * | -+ +---------------------+ * | b - \/ (1-P) * (b-a) * (b-c) <== (c-a)/(b-a) < P < 1 * | * | * | b <== P ~= 1 * \ */ F retVal = static_cast<F>(0); if ( P < math::NumericUtil::getEPS<F>() ) { retVal = a; } else if ( P > (static_cast<F>(1)-math::NumericUtil::getEPS<F>()) ) { retVal = b; } else if ( P <= ( (c-a) / (b-a) ) ) { retVal = a + std::sqrt( P * (b-a) * (c-a) ); } else // (c-a)/(b-a) < P < 1 { retVal = b - std::sqrt( (static_cast<F>(1)-P) * (b-a) * (b-c) ); } return retVal; } <|endoftext|>
<commit_before>/* * RelayNode.cpp * Homie Node for a Relay with optional status indicator LED * * Version: 1.0 * Author: Lübbe Onken (http://github.com/luebbe) */ #include "RelayNode.hpp" #include <Homie.hpp> #define RELAYPIN 0 HomieSetting<long> relayPinSetting("relayPin", "The pin to which the relay is connected"); RelayNode::RelayNode(const char *name, const int ledPin) : HomieNode(name, "RelayNode") { _ledPin = ledPin; relayPinSetting.setDefaultValue(RELAYPIN); if (_ledPin > -1) { pinMode(_ledPin, OUTPUT); setLed(false); } } void RelayNode::setLed(bool on) { if (_ledPin > -1) { digitalWrite(_ledPin, on ? LOW : HIGH); // LOW = LED on } } void RelayNode::setRelay(bool on) { digitalWrite(relayPinSetting.get(), on ? HIGH : LOW); setLed(on); setProperty("on").send(on ? "true" : "false"); Homie.getLogger() << "Relay is " << (on ? "on" : "off") << endl; } bool RelayNode::handleInput(const String& property, const HomieRange& range, const String& value) { Homie.getLogger() << "Message: " << value << endl; if (value != "true" && value != "false") return false; setRelay(value == "true"); return true; } void RelayNode::setup() { advertise("on").settable(); Homie.getLogger() << "Relay pin = " << relayPinSetting.get() << endl << "Was provided = " << relayPinSetting.wasProvided() << endl << "Led pin = " << _ledPin << endl; pinMode(relayPinSetting.get(), OUTPUT); Homie.getLogger() << "Set OUTPUT" << endl; digitalWrite(relayPinSetting.get(), LOW); Homie.getLogger() << "Set off" << endl; } // // void RelayNode::loop() { // } <commit_msg>Add comment<commit_after>/* * RelayNode.cpp * Homie Node for a Relay with optional status indicator LED * * Version: 1.0 * Author: Lübbe Onken (http://github.com/luebbe) */ #include "RelayNode.hpp" #include <Homie.hpp> #define RELAYPIN 0 HomieSetting<long> relayPinSetting("relayPin", "The pin to which the relay is connected"); RelayNode::RelayNode(const char *name, const int ledPin) : HomieNode(name, "RelayNode") { _ledPin = ledPin; relayPinSetting.setDefaultValue(RELAYPIN); if (_ledPin > -1) { pinMode(_ledPin, OUTPUT); setLed(false); } } void RelayNode::setLed(bool on) { if (_ledPin > -1) { digitalWrite(_ledPin, on ? LOW : HIGH); // LOW = LED on } } void RelayNode::setRelay(bool on) { digitalWrite(relayPinSetting.get(), on ? HIGH : LOW); // HIGH = close relay setLed(on); setProperty("on").send(on ? "true" : "false"); Homie.getLogger() << "Relay is " << (on ? "on" : "off") << endl; } bool RelayNode::handleInput(const String& property, const HomieRange& range, const String& value) { Homie.getLogger() << "Message: " << value << endl; if (value != "true" && value != "false") return false; setRelay(value == "true"); return true; } void RelayNode::setup() { advertise("on").settable(); Homie.getLogger() << "Relay pin = " << relayPinSetting.get() << endl << "Was provided = " << relayPinSetting.wasProvided() << endl << "Led pin = " << _ledPin << endl; pinMode(relayPinSetting.get(), OUTPUT); Homie.getLogger() << "Set OUTPUT" << endl; digitalWrite(relayPinSetting.get(), LOW); Homie.getLogger() << "Set off" << endl; } // // void RelayNode::loop() { // } <|endoftext|>
<commit_before>//===-- ipcd.cpp ----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements IPCD interface, communicates with ipcd via control socket // //===----------------------------------------------------------------------===// #include "ipcd.h" #include "debug.h" #include "real.h" #include "rename_fd.h" #include "magic_socket_nums.h" #include "lock.h" #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> static int ipcd_socket = 0; static int mypid = 0; // Must match that used by server, // currently defined in ipcd/clients.go const char *SOCK_PATH = "/tmp/ipcd.sock"; const char *IPCD_BIN_PATH = "/bin/ipcd"; const char *PRELOAD_PATH = "/etc/ld.so.preload"; const char *PRELOAD_TMP = "/tmp/preload.cfg"; const useconds_t SLEEP_AFTER_IPCD_START_INTERVAL = 10 * 1000; // 10ms? SimpleLock &getConnectLock() { static SimpleLock ConnectLock; return ConnectLock; } void fork_ipcd() { switch (__real_fork()) { case -1: break; case 0: // Child execl(IPCD_BIN_PATH, IPCD_BIN_PATH, (char *)NULL); perror("Failed to exec ipcd"); assert(0 && "Exec failed?"); break; default: // Wait for ipcd to start :P ipclog("Starting ipcd...\n"); usleep(SLEEP_AFTER_IPCD_START_INTERVAL); } } void connect_to_ipcd() { int s, len; struct sockaddr_un remote; if ((s = __real_socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) { perror("socket"); exit(1); } bool rename_success = rename_fd(s, MAGIC_SOCKET_FD, /* cloexec */ true); assert(rename_success); s = MAGIC_SOCKET_FD; remote.sun_family = AF_UNIX; strcpy(remote.sun_path, SOCK_PATH); len = strlen(remote.sun_path) + sizeof(remote.sun_family); if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) { // XXX: Super kludge! // If we can't connect to daemon, assume it hasn't been // started yet and attempt to run it ourselves. // This code is terrible, and is likely to break // badly in many situations, but works for now. if (errno == ENOENT || errno == ECONNREFUSED) { fork_ipcd(); if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) { perror("connect-after-fork"); exit(1); } } else { perror("connect"); ipclog("Error connecting to ipcd?\n"); exit(1); } } ipclog("Connected to IPCD, fd=%d\n", s); mypid = getpid(); ipcd_socket = s; } void __ipcd_init() { assert(ipcd_socket == 0); connect_to_ipcd(); } void __attribute__((destructor)) ipcd_dtor() { if (ipcd_socket == 0) { ipclog("Exiting without establishing connection to ipcd...\n"); return; } assert(ipcd_socket != 0); assert(mypid != 0); char buf[100]; int len = sprintf(buf, "REMOVEALL %d\n", mypid); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); const char *match = "200 REMOVED "; size_t matchlen = strlen(match); if (size_t(err) < matchlen) { perror("read"); exit(1); } bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0); if (!success) { ipclog("Failure, response=%s\n", buf); } assert(success && "Unable to unregister all fd's"); } void connect_if_needed() { if (mypid == getpid()) return; ipclog("Reconnecting to ipcd in child...\n"); __real_close(ipcd_socket); connect_to_ipcd(); } endpoint ipcd_register_socket(int fd) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd); assert(len > 5); assert(ipcd_socket); // ipclog("REGISTER %d -->\n", fd); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } // ipclog("REGISTER %d <--\n", fd); err = __real_read(ipcd_socket, buf, 50); assert(err > 5); buf[err] = 0; int id; int n = sscanf(buf, "200 ID %d\n", &id); assert(n == 1); // ipclog("Registered and got endpoint id=%d\n", id); return id; } bool ipcd_localize(endpoint local, endpoint remote) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); return strncmp(buf, "200 OK\n", err) == 0; } // GETLOCALFD int ipcd_getlocalfd(endpoint local) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "GETLOCALFD %d\n", local); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } int fd; { // Lots of magic const size_t CONTROLLEN = CMSG_LEN(sizeof(int)); struct iovec iov[1]; struct msghdr msg; struct cmsghdr *cmsg; char cmsg_buf[CONTROLLEN]; cmsg = (struct cmsghdr *)cmsg_buf; memset(&msg, 0, sizeof(msg)); iov[0].iov_base = buf; iov[0].iov_len = sizeof(buf); msg.msg_iov = iov; msg.msg_iovlen = 1; msg.msg_control = cmsg; msg.msg_controllen = CONTROLLEN; int ret = recvmsg(ipcd_socket, &msg, 0); if (ret <= 0) { perror("recvmsg"); exit(1); } // TODO: Understand and fix mismatch between // CONTROLLEN and msg.msg_controllen after recvmsg()! memcpy(&fd, CMSG_DATA(cmsg), sizeof(int)); ipclog("received local fd %d for endpoint %d\n", fd, local); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); bool success = strncmp(buf, "200 OK\n", err) == 0; assert(success); return fd; } // UNREGISTER bool ipcd_unregister_socket(endpoint ep) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "UNREGISTER %d\n", ep); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); return strncmp(buf, "200 OK\n", err) == 0; } // REREGISTER bool ipcd_reregister_socket(endpoint ep, int fd) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "REREGISTER %d %d %d\n", ep, getpid(), fd); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); return strncmp(buf, "200 OK\n", err) == 0; } endpoint ipcd_endpoint_kludge(endpoint local) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "ENDPOINT_KLUDGE %d\n", local); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); buf[err] = 0; int id; ipclog("endpoint_kludge(%d) = %s\n", local, buf); int n = sscanf(buf, "200 PAIR %d\n", &id); if (n == 1) { return id; } return EP_INVALID; } bool ipcd_is_protected(int fd) { return fd == ipcd_socket; } <commit_msg>libipc: Bah, keep ld.so.preload renaming kludge for now.<commit_after>//===-- ipcd.cpp ----------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements IPCD interface, communicates with ipcd via control socket // //===----------------------------------------------------------------------===// #include "ipcd.h" #include "debug.h" #include "real.h" #include "rename_fd.h" #include "magic_socket_nums.h" #include "lock.h" #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> static int ipcd_socket = 0; static int mypid = 0; // Must match that used by server, // currently defined in ipcd/clients.go const char *SOCK_PATH = "/tmp/ipcd.sock"; const char *IPCD_BIN_PATH = "/bin/ipcd"; const char *PRELOAD_PATH = "/etc/ld.so.preload"; const char *PRELOAD_TMP = "/tmp/preload.cfg"; const useconds_t SLEEP_AFTER_IPCD_START_INTERVAL = 10 * 1000; // 10ms? SimpleLock &getConnectLock() { static SimpleLock ConnectLock; return ConnectLock; } void fork_ipcd() { switch (__real_fork()) { case -1: break; case 0: // Child execl(IPCD_BIN_PATH, IPCD_BIN_PATH, (char *)NULL); perror("Failed to exec ipcd"); assert(0 && "Exec failed?"); break; default: // Wait for ipcd to start :P ipclog("Starting ipcd...\n"); usleep(SLEEP_AFTER_IPCD_START_INTERVAL); } } void connect_to_ipcd() { int s, len; struct sockaddr_un remote; if ((s = __real_socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) { perror("socket"); exit(1); } bool rename_success = rename_fd(s, MAGIC_SOCKET_FD, /* cloexec */ true); assert(rename_success); s = MAGIC_SOCKET_FD; remote.sun_family = AF_UNIX; strcpy(remote.sun_path, SOCK_PATH); len = strlen(remote.sun_path) + sizeof(remote.sun_family); if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) { // XXX: Super kludge! // If we can't connect to daemon, assume it hasn't been // started yet and attempt to run it ourselves. // This code is terrible, and is likely to break // badly in many situations, but works for now. if (errno == ENOENT || errno == ECONNREFUSED) { rename(PRELOAD_PATH, PRELOAD_TMP); fork_ipcd(); rename(PRELOAD_TMP, PRELOAD_PATH); if (__real_connect(s, (struct sockaddr *)&remote, len) == -1) { perror("connect-after-fork"); exit(1); } } else { perror("connect"); ipclog("Error connecting to ipcd?\n"); exit(1); } } ipclog("Connected to IPCD, fd=%d\n", s); mypid = getpid(); ipcd_socket = s; } void __ipcd_init() { assert(ipcd_socket == 0); connect_to_ipcd(); } void __attribute__((destructor)) ipcd_dtor() { if (ipcd_socket == 0) { ipclog("Exiting without establishing connection to ipcd...\n"); return; } assert(ipcd_socket != 0); assert(mypid != 0); char buf[100]; int len = sprintf(buf, "REMOVEALL %d\n", mypid); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); const char *match = "200 REMOVED "; size_t matchlen = strlen(match); if (size_t(err) < matchlen) { perror("read"); exit(1); } bool success = (strncmp(buf, "200 REMOVED ", matchlen) == 0); if (!success) { ipclog("Failure, response=%s\n", buf); } assert(success && "Unable to unregister all fd's"); } void connect_if_needed() { if (mypid == getpid()) return; ipclog("Reconnecting to ipcd in child...\n"); __real_close(ipcd_socket); connect_to_ipcd(); } endpoint ipcd_register_socket(int fd) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "REGISTER %d %d\n", getpid(), fd); assert(len > 5); assert(ipcd_socket); // ipclog("REGISTER %d -->\n", fd); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } // ipclog("REGISTER %d <--\n", fd); err = __real_read(ipcd_socket, buf, 50); assert(err > 5); buf[err] = 0; int id; int n = sscanf(buf, "200 ID %d\n", &id); assert(n == 1); // ipclog("Registered and got endpoint id=%d\n", id); return id; } bool ipcd_localize(endpoint local, endpoint remote) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "LOCALIZE %d %d\n", local, remote); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); return strncmp(buf, "200 OK\n", err) == 0; } // GETLOCALFD int ipcd_getlocalfd(endpoint local) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "GETLOCALFD %d\n", local); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } int fd; { // Lots of magic const size_t CONTROLLEN = CMSG_LEN(sizeof(int)); struct iovec iov[1]; struct msghdr msg; struct cmsghdr *cmsg; char cmsg_buf[CONTROLLEN]; cmsg = (struct cmsghdr *)cmsg_buf; memset(&msg, 0, sizeof(msg)); iov[0].iov_base = buf; iov[0].iov_len = sizeof(buf); msg.msg_iov = iov; msg.msg_iovlen = 1; msg.msg_control = cmsg; msg.msg_controllen = CONTROLLEN; int ret = recvmsg(ipcd_socket, &msg, 0); if (ret <= 0) { perror("recvmsg"); exit(1); } // TODO: Understand and fix mismatch between // CONTROLLEN and msg.msg_controllen after recvmsg()! memcpy(&fd, CMSG_DATA(cmsg), sizeof(int)); ipclog("received local fd %d for endpoint %d\n", fd, local); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); bool success = strncmp(buf, "200 OK\n", err) == 0; assert(success); return fd; } // UNREGISTER bool ipcd_unregister_socket(endpoint ep) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "UNREGISTER %d\n", ep); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); return strncmp(buf, "200 OK\n", err) == 0; } // REREGISTER bool ipcd_reregister_socket(endpoint ep, int fd) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "REREGISTER %d %d %d\n", ep, getpid(), fd); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); return strncmp(buf, "200 OK\n", err) == 0; } endpoint ipcd_endpoint_kludge(endpoint local) { ScopedLock L(getConnectLock()); connect_if_needed(); char buf[100]; int len = sprintf(buf, "ENDPOINT_KLUDGE %d\n", local); assert(len > 5); int err = __real_write(ipcd_socket, buf, len); if (err < 0) { perror("write"); exit(1); } err = __real_read(ipcd_socket, buf, 50); assert(err > 5); buf[err] = 0; int id; ipclog("endpoint_kludge(%d) = %s\n", local, buf); int n = sscanf(buf, "200 PAIR %d\n", &id); if (n == 1) { return id; } return EP_INVALID; } bool ipcd_is_protected(int fd) { return fd == ipcd_socket; } <|endoftext|>
<commit_before>#include "curl.hpp" #include <curl/curl.h> #include <string> #include <iostream> #include <vector> #define HANDLE_CURL_CODE(what) \ code = (what); \ if (code != ::CURLE_OK) { \ errorMessage = std::string("CURL error: ") + ::curl_easy_strerror(code); \ return false; \ } namespace { struct CURLHandle { ::CURL *value; CURLHandle() : value(nullptr) {} ~CURLHandle() { if (value) { ::curl_easy_cleanup(value); } } operator ::CURL*() { return value; } }; struct CURLSlist { struct ::curl_slist *list = nullptr; CURLSlist(const char *str) { append(str); } ~CURLSlist() { ::curl_slist_free_all(list); } void append(const char *str) { list = ::curl_slist_append(list, str); } const ::curl_slist* get() const { return list; } }; } bool HttpHead(const HttpParams& params, std::string& errorMessage) { CURLHandle handle; handle.value = ::curl_easy_init(); if (!handle.value) { errorMessage = "CURL init failed"; return false; } ::CURLcode code; HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_NOBODY, 1L)); // HEAD request HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_URL, params.url.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_TIMEOUT, static_cast<long>(params.timeout))); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_FOLLOWLOCATION, 1L)); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_SSL_VERIFYPEER, params.verifypeer ? 1L : 0L)); HANDLE_CURL_CODE(::curl_easy_perform(handle.value)); long http_code = 0; HANDLE_CURL_CODE(curl_easy_getinfo(handle.value, ::CURLINFO_RESPONSE_CODE, &http_code)); if (http_code != params.status) { errorMessage = "HTTP response code: " + std::to_string(http_code); return false; } return true; } struct EmailHelper { size_t lines_read = 0; std::vector<std::string> payload_text; size_t payload_source(void *ptr, size_t size, size_t nmemb); }; static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp) { EmailHelper *helper = reinterpret_cast<EmailHelper*>(userp); return helper->payload_source(ptr, size, nmemb); } size_t EmailHelper::payload_source(void *ptr, size_t size, size_t nmemb) { if (size == 0 || nmemb == 0 || lines_read >= payload_text.size()) { return 0; } // Note: this is assuming nmemb is big enough for each line, which it usually is set // to CURL_MAX_WRITE_SIZE which is default 16384. const std::string& str = payload_text.at(lines_read); const size_t len = str.size(); std::memcpy(ptr, str.c_str(), len); ++lines_read; return len; } bool Email(const EmailParams& params, unsigned timeout, std::string& errorMessage) { CURLHandle handle; handle.value = ::curl_easy_init(); if (!handle.value) { errorMessage = "CURL init failed"; return false; } ::CURLcode code; const CURLSlist recipients(params.to.c_str()); EmailHelper helper; const std::string crlf = "\r\n"; helper.payload_text.push_back("To: " + params.to + crlf); helper.payload_text.push_back("From: " + params.from + crlf); helper.payload_text.push_back("Subject: " + params.subject + crlf); helper.payload_text.push_back(crlf); helper.payload_text.push_back(params.body + crlf); const std::string url = "smtp://" + params.smtp_host; HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_USERNAME, params.smtp_user.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_PASSWORD, params.smtp_password.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_URL, url.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_MAIL_FROM, params.from.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_MAIL_RCPT, recipients.get())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_READFUNCTION, payload_source)); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_READDATA, &helper)); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_UPLOAD, 1L)); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_USE_SSL, static_cast<long>(CURLUSESSL_ALL))); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_TIMEOUT, static_cast<long>(timeout))); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_VERBOSE, 0L)); // set to 1 to debug connection issues HANDLE_CURL_CODE(::curl_easy_perform(handle)); long response_code = 0; HANDLE_CURL_CODE(curl_easy_getinfo(handle.value, ::CURLINFO_RESPONSE_CODE, &response_code)); if (response_code != 250) { errorMessage = "SMTP response code: " + std::to_string(response_code); return false; } return true; } <commit_msg>Fix “error: 'memcpy' is not a member of 'std’”<commit_after>#include "curl.hpp" #include <curl/curl.h> #include <cstring> #include <iostream> #include <vector> #define HANDLE_CURL_CODE(what) \ code = (what); \ if (code != ::CURLE_OK) { \ errorMessage = std::string("CURL error: ") + ::curl_easy_strerror(code); \ return false; \ } namespace { struct CURLHandle { ::CURL *value; CURLHandle() : value(nullptr) {} ~CURLHandle() { if (value) { ::curl_easy_cleanup(value); } } operator ::CURL*() { return value; } }; struct CURLSlist { struct ::curl_slist *list = nullptr; CURLSlist(const char *str) { append(str); } ~CURLSlist() { ::curl_slist_free_all(list); } void append(const char *str) { list = ::curl_slist_append(list, str); } const ::curl_slist* get() const { return list; } }; } bool HttpHead(const HttpParams& params, std::string& errorMessage) { CURLHandle handle; handle.value = ::curl_easy_init(); if (!handle.value) { errorMessage = "CURL init failed"; return false; } ::CURLcode code; HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_NOBODY, 1L)); // HEAD request HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_URL, params.url.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_TIMEOUT, static_cast<long>(params.timeout))); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_FOLLOWLOCATION, 1L)); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_SSL_VERIFYPEER, params.verifypeer ? 1L : 0L)); HANDLE_CURL_CODE(::curl_easy_perform(handle.value)); long http_code = 0; HANDLE_CURL_CODE(curl_easy_getinfo(handle.value, ::CURLINFO_RESPONSE_CODE, &http_code)); if (http_code != params.status) { errorMessage = "HTTP response code: " + std::to_string(http_code); return false; } return true; } struct EmailHelper { size_t lines_read = 0; std::vector<std::string> payload_text; size_t payload_source(void *ptr, size_t size, size_t nmemb); }; static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp) { EmailHelper *helper = reinterpret_cast<EmailHelper*>(userp); return helper->payload_source(ptr, size, nmemb); } size_t EmailHelper::payload_source(void *ptr, size_t size, size_t nmemb) { if (size == 0 || nmemb == 0 || lines_read >= payload_text.size()) { return 0; } // Note: this is assuming nmemb is big enough for each line, which it usually is set // to CURL_MAX_WRITE_SIZE which is default 16384. const std::string& str = payload_text.at(lines_read); const size_t len = str.size(); std::memcpy(ptr, str.c_str(), len); ++lines_read; return len; } bool Email(const EmailParams& params, unsigned timeout, std::string& errorMessage) { CURLHandle handle; handle.value = ::curl_easy_init(); if (!handle.value) { errorMessage = "CURL init failed"; return false; } ::CURLcode code; const CURLSlist recipients(params.to.c_str()); EmailHelper helper; const std::string crlf = "\r\n"; helper.payload_text.push_back("To: " + params.to + crlf); helper.payload_text.push_back("From: " + params.from + crlf); helper.payload_text.push_back("Subject: " + params.subject + crlf); helper.payload_text.push_back(crlf); helper.payload_text.push_back(params.body + crlf); const std::string url = "smtp://" + params.smtp_host; HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_USERNAME, params.smtp_user.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_PASSWORD, params.smtp_password.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_URL, url.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_MAIL_FROM, params.from.c_str())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_MAIL_RCPT, recipients.get())); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_READFUNCTION, payload_source)); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_READDATA, &helper)); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_UPLOAD, 1L)); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_USE_SSL, static_cast<long>(CURLUSESSL_ALL))); HANDLE_CURL_CODE(curl_easy_setopt(handle.value, ::CURLOPT_TIMEOUT, static_cast<long>(timeout))); HANDLE_CURL_CODE(curl_easy_setopt(handle, ::CURLOPT_VERBOSE, 0L)); // set to 1 to debug connection issues HANDLE_CURL_CODE(::curl_easy_perform(handle)); long response_code = 0; HANDLE_CURL_CODE(curl_easy_getinfo(handle.value, ::CURLINFO_RESPONSE_CODE, &response_code)); if (response_code != 250) { errorMessage = "SMTP response code: " + std::to_string(response_code); return false; } return true; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2017 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <vector> #include <string> #include <numeric> #include <utility> #include <fstream> #include <iostream> #include <iterator> #define CAF_SUITE stream_distribution_tree #include "caf/test/dsl.hpp" #include "caf/fused_scatterer.hpp" #include "caf/broadcast_topic_scatterer.hpp" #include "caf/detail/pull5_gatherer.hpp" #include "caf/detail/push5_scatterer.hpp" #include "caf/detail/stream_distribution_tree.hpp" using std::cout; using std::endl; using std::vector; using std::string; using namespace caf::detail; using namespace caf; namespace { using join_atom = atom_constant<atom("join")>; using peer_atom = atom_constant<atom("peer")>; struct prefix_match_t { using topic_type = string; using filter_type = vector<string>; bool operator()(const filter_type& filter, const topic_type& topic) const { for (auto& prefix : filter) if (topic.compare(0, prefix.size(), prefix.c_str()) == 0) return true; return false; } template <class T> bool operator()(const filter_type& filter, const std::pair<topic_type, T>& x) const { return (*this)(filter, x.first); } bool operator()(const filter_type& filter, const message& msg) const { if (!msg.match_element<topic_type>(0)) return false; return (*this)(filter, msg.get_as<topic_type>(0)); } }; constexpr prefix_match_t prefix_match = prefix_match_t{}; using peer_filter_type = std::pair<actor_addr, vector<string>>; struct peer_filter_cmp { actor_addr active_sender; template <class T> bool operator()(const peer_filter_type& f, const T& x) const { return f.first != active_sender && prefix_match(f.second, x); } }; class policy { public: using data = int; using internal_command = string; using topic = string; using filter_type = vector<string>; using gatherer_type = detail::pull5_gatherer; using peer_batch = std::vector<message>; using worker_batch = std::vector<std::pair<topic, data>>; using store_batch = std::vector<std::pair<topic, internal_command>>; using path_id = std::pair<stream_id, actor_addr>; using peer_to_path_map = std::map<actor, path_id>; using path_to_peer_map = std::map<path_id, actor>; template <class T> using substream_t = broadcast_topic_scatterer<std::pair<topic, T>, filter_type, prefix_match_t>; using main_stream_t = broadcast_topic_scatterer<message, peer_filter_type, peer_filter_cmp>; using scatterer_type = fused_scatterer<main_stream_t, substream_t<data>, substream_t<internal_command>>; policy(stream_distribution_tree<policy>* parent, filter_type filter); /// Returns true if 1) `shutting_down()`, 2) there is no more /// active local data source, and 3) there is no pending data to any peer. bool at_end() const { return shutting_down_ && peers().paths_clean() && workers().paths_clean() && stores().paths_clean(); } bool substream_local_data() const { return false; } void before_handle_batch(const stream_id&, const actor_addr& hdl, long, message&, int64_t) { parent_->out().main_stream().selector().active_sender = hdl; } void handle_batch(message& xs) { if (xs.match_elements<peer_batch>()) { // Only received from other peers. Extract content for to local workers // or stores and then forward to other peers. for (auto& msg : xs.get_mutable_as<peer_batch>(0)) { // Extract worker messages. if (msg.match_elements<topic, data>()) workers().push(msg.get_as<topic>(0), msg.get_as<data>(1)); // Extract store messages. if (msg.match_elements<topic, internal_command>()) stores().push(msg.get_as<topic>(0), msg.get_as<internal_command>(1)); // Forward to other peers. peers().push(std::move(msg)); } } else if (xs.match_elements<worker_batch>()) { // Inputs from local workers are only forwarded to peers. for (auto& x : xs.get_mutable_as<worker_batch>(0)) { parent_->out().push(make_message(std::move(x.first), std::move(x.second))); } } else if (xs.match_elements<store_batch>()) { // Inputs from stores are only forwarded to peers. for (auto& x : xs.get_mutable_as<store_batch>(0)) { parent_->out().push(make_message(std::move(x.first), std::move(x.second))); } } else { CAF_LOG_ERROR("unexpected batch:" << deep_to_string(xs)); } } void after_handle_batch(const stream_id&, const actor_addr&, int64_t) { parent_->out().main_stream().selector().active_sender = nullptr; } void ack_open_success(const stream_id& sid, const actor_addr& rebind_from, strong_actor_ptr rebind_to) { auto old_id = std::make_pair(sid, rebind_from); auto new_id = std::make_pair(sid, actor_cast<actor_addr>(rebind_to)); auto i = opath_to_peer_.find(old_id); if (i != opath_to_peer_.end()) { auto pp = std::move(i->second); peer_to_opath_[pp] = new_id; opath_to_peer_.erase(i); opath_to_peer_.emplace(new_id, std::move(pp)); } } void ack_open_failure(const stream_id& sid, const actor_addr& rebind_from, strong_actor_ptr rebind_to, const error&) { auto old_id = std::make_pair(sid, rebind_from); auto new_id = std::make_pair(sid, actor_cast<actor_addr>(rebind_to)); auto i = opath_to_peer_.find(old_id); if (i != opath_to_peer_.end()) { auto pp = std::move(i->second); peer_lost(pp); peer_to_opath_.erase(pp); opath_to_peer_.erase(i); } } void push_to_substreams(vector<message> vec) { CAF_LOG_TRACE(CAF_ARG(vec)); // Move elements from `xs` to the buffer for local subscribers. if (!workers().lanes().empty()) for (auto& x : vec) if (x.match_elements<topic, data>()) { x.force_unshare(); workers().push(x.get_as<topic>(0), std::move(x.get_mutable_as<data>(1))); } workers().emit_batches(); if (!stores().lanes().empty()) for (auto& x : vec) if (x.match_elements<topic, internal_command>()) { x.force_unshare(); stores().push(x.get_as<topic>(0), std::move(x.get_mutable_as<internal_command>(1))); } stores().emit_batches(); } optional<error> batch(const stream_id&, const actor_addr&, long, message& xs, int64_t) { if (xs.match_elements<std::vector<std::pair<topic, data>>>()) { return error{none}; } if (xs.match_elements<std::vector<std::pair<topic, internal_command>>>()) { return error{none}; } return none; } // -- callbacks -------------------------------------------------------------- void peer_lost(const actor&) { // nop } void local_input_closed(const stream_id&, const actor_addr&) { // nop } // -- state required by the distribution tree -------------------------------- bool shutting_down() { return shutting_down_; } void shutting_down(bool value) { shutting_down_ = value; } // -- peer management -------------------------------------------------------- /// Adds a new peer that isn't fully initialized yet. A peer is fully /// initialized if there is an upstream ID associated to it. bool add_peer(const caf::stream_id& sid, const strong_actor_ptr& downstream_handle, const actor& peer_handle, filter_type filter) { CAF_LOG_TRACE(CAF_ARG(sid) << CAF_ARG(downstream_handle) << CAF_ARG(peer_handle) << CAF_ARG(filter)); //TODO: auto ptr = peers().add_path(sid, downstream_handle); outbound_path* ptr = nullptr; if (ptr == nullptr) return false; auto downstream_addr = actor_cast<actor_addr>(downstream_handle); peers().set_filter(sid, downstream_handle, {downstream_addr, std::move(filter)}); peer_to_opath_.emplace(peer_handle, std::make_pair(sid, downstream_addr)); opath_to_peer_.emplace(std::make_pair(sid, downstream_addr), peer_handle); return true; } /// Fully initializes a peer by setting an upstream ID and inserting it into /// the `input_to_peer_` map. bool init_peer(const stream_id& sid, const strong_actor_ptr& upstream_handle, const actor& peer_handle) { auto upstream_addr = actor_cast<actor_addr>(upstream_handle); peer_to_ipath_.emplace(peer_handle, std::make_pair(sid, upstream_addr)); ipath_to_peer_.emplace(std::make_pair(sid, upstream_addr), peer_handle); return true; } /// Removes a peer, aborting any stream to & from that peer. bool remove_peer(const actor& hdl, error reason, bool silent) { CAF_LOG_TRACE(CAF_ARG(hdl)); { // lifetime scope of first iterator pair auto e = peer_to_opath_.end(); auto i = peer_to_opath_.find(hdl); if (i == e) return false; peers().remove_path(i->second.first, i->second.second, reason, silent); opath_to_peer_.erase(std::make_pair(i->second.first, i->second.second)); peer_to_opath_.erase(i); } { // lifetime scope of second iterator pair auto e = peer_to_ipath_.end(); auto i = peer_to_ipath_.find(hdl); CAF_IGNORE_UNUSED(e); CAF_ASSERT(i != e); parent_->in().remove_path(i->second.first, i->second.second, reason, silent); ipath_to_peer_.erase(std::make_pair(i->second.first, i->second.second)); peer_to_ipath_.erase(i); } peer_lost(hdl); if (shutting_down() && peer_to_opath_.empty()) { // Shutdown when the last peer stops listening. parent_->self()->quit(caf::exit_reason::user_shutdown); } else { // See whether we can make progress without that peer in the mix. parent_->in().assign_credit(parent_->out().credit()); parent_->push(); } return true; } /// Updates the filter of an existing peer. bool update_peer(const actor& hdl, filter_type filter) { CAF_LOG_TRACE(CAF_ARG(hdl) << CAF_ARG(filter)); auto e = peer_to_opath_.end(); auto i = peer_to_opath_.find(hdl); if (i == e) { CAF_LOG_DEBUG("cannot update filter on unknown peer"); return false; } peers().set_filter(i->second.first, i->second.second, {i->second.second, std::move(filter)}); return true; } // -- selectively pushing data into the streams ------------------------------ /// Pushes data to workers without forwarding it to peers. void local_push(topic x, data y) { workers().push(std::move(x), std::move(y)); workers().emit_batches(); } /// Pushes data to stores without forwarding it to peers. void local_push(topic x, internal_command y) { stores().push(std::move(x), std::move(y)); stores().emit_batches(); } /// Pushes data to peers only without forwarding it to local substreams. void remote_push(message msg) { peers().push(std::move(msg)); peers().emit_batches(); } /// Pushes data to peers and workers. void push(topic x, data y) { remote_push(make_message(x, y)); local_push(std::move(x), std::move(y)); } /// Pushes data to peers and stores. void push(topic x, internal_command y) { remote_push(make_message(x, y)); local_push(std::move(x), std::move(y)); } // -- state accessors -------------------------------------------------------- main_stream_t& peers() { return parent_->out().main_stream(); } const main_stream_t& peers() const { return parent_->out().main_stream(); } substream_t<data>& workers() { return parent_->out().substream<1>(); } const substream_t<data>& workers() const { return parent_->out().substream<1>(); } substream_t<internal_command>& stores() { return parent_->out().substream<2>(); } const substream_t<internal_command>& stores() const { return parent_->out().substream<2>(); } private: stream_distribution_tree<policy>* parent_; bool shutting_down_; // Maps peer handles to output path IDs. peer_to_path_map peer_to_opath_; // Maps output path IDs to peer handles. path_to_peer_map opath_to_peer_; // Maps peer handles to input path IDs. peer_to_path_map peer_to_ipath_; // Maps input path IDs to peer handles. path_to_peer_map ipath_to_peer_; }; policy::policy(stream_distribution_tree<policy>* parent, filter_type) : parent_(parent), shutting_down_(false) { // nop } policy::filter_type default_filter() { return {"foo", "bar"}; } /* behavior testee(event_based_actor* self) { auto sdt = make_counted<stream_distribution_tree<policy>>(self, default_filter()); return { }; } */ using fixture = test_coordinator_fixture<>; } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(stream_distribution_tree_tests, fixture) CAF_TEST(peer_management) { } CAF_TEST_FIXTURE_SCOPE_END() <commit_msg>Remove stream distribution tree test<commit_after><|endoftext|>
<commit_before>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include "NaryImageOperatorMainHelper.h" #include "NaryImageOperatorHelper.h" //------------------------------------------------------------------------------------- int main( int argc, char **argv ) { /** Check arguments for help. */ if ( argc < 5 ) { PrintHelp(); return 1; } /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); /** Get arguments. */ std::vector<std::string> inputFileNames; bool retin = parser->GetCommandLineArgument( "-in", inputFileNames ); std::string outputFileName = ""; bool retout = parser->GetCommandLineArgument( "-out", outputFileName ); std::string ops = ""; bool retops = parser->GetCommandLineArgument( "-ops", ops ); std::string argument = "0"; bool retarg = parser->GetCommandLineArgument( "-arg", argument ); std::string opct = ""; bool retopct = parser->GetCommandLineArgument( "-opct", opct ); const bool useCompression = parser->ArgumentExists( "-z" ); /** Support for streaming. */ unsigned int numberOfStreams = inputFileNames.size(); parser->GetCommandLineArgument( "-s", numberOfStreams ); /** Check if the required arguments are given. */ if ( !retin ) { std::cerr << "ERROR: You should specify \"-in\"." << std::endl; return 1; } if ( !retout ) { std::cerr << "ERROR: You should specify \"-out\"." << std::endl; return 1; } if ( !retops ) { std::cerr << "ERROR: You should specify \"-ops\"." << std::endl; return 1; } /** You should specify at least two input files. */ if ( inputFileNames.size() < 2 ) { std::cerr << "ERROR: You should specify at least two input file names." << std::endl; return 1; } /** Determine image properties. */ std::string ComponentTypeIn = "long"; std::string ComponentTypeOut = "long"; unsigned int inputDimension = 2; int retdip = DetermineImageProperties( inputFileNames, ComponentTypeIn, ComponentTypeOut, inputDimension ); if ( retdip ) return 1; /** Let the user override the output component type. */ if ( retopct ) { if ( !CheckForValidComponentType( opct ) ) { std::cerr << "ERROR: the you specified a wrong opct." << std::endl; return 1; } ComponentTypeOut = opct; ReplaceUnderscoreWithSpace( ComponentTypeOut ); if ( !TypeIsInteger( opct ) ) ComponentTypeIn = "double"; } /** Check if a valid operator is given. */ std::string opsCopy = ops; int retCO = CheckOperator( ops ); if ( retCO ) return retCO; /** For certain ops an argument is mandatory. */ bool retCOA = CheckOperatorAndArgument( ops, argument, retarg ); if ( !retCOA ) return 1; /** Run the program. */ bool supported = false; try { run( NaryImageOperator, long, char, 2 ); run( NaryImageOperator, long, unsigned char, 2 ); run( NaryImageOperator, long, short, 2 ); run( NaryImageOperator, long, unsigned short, 2 ); run( NaryImageOperator, long, int, 2 ); run( NaryImageOperator, long, unsigned int, 2 ); run( NaryImageOperator, long, long, 2 ); run( NaryImageOperator, long, unsigned long, 2 ); run( NaryImageOperator, double, float, 2 ); run( NaryImageOperator, double, double, 2 ); run( NaryImageOperator, long, char, 3 ); run( NaryImageOperator, long, unsigned char, 3 ); run( NaryImageOperator, long, short, 3 ); run( NaryImageOperator, long, unsigned short, 3 ); run( NaryImageOperator, long, int, 3 ); run( NaryImageOperator, long, unsigned int, 3 ); run( NaryImageOperator, long, long, 3 ); run( NaryImageOperator, long, unsigned long, 3 ); run( NaryImageOperator, double, float, 3 ); run( NaryImageOperator, double, double, 3 ); } // end try catch ( itk::ExceptionObject &e ) { std::cerr << "Caught ITK exception: " << e << std::endl; return 1; } if ( !supported ) { std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl; std::cerr << "pixel (component) type = " << ComponentTypeOut << " ; dimension = " << inputDimension << std::endl; return 1; } /** End program. */ return 0; } // end main <commit_msg>New style arguments for naryimageoperator<commit_after>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include "NaryImageOperatorMainHelper.h" #include "NaryImageOperatorHelper.h" //------------------------------------------------------------------------------------- int main( int argc, char **argv ) { /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); parser->MarkArgumentAsRequired( "-in", "The input filename." ); parser->MarkArgumentAsRequired( "-out", "The output filename." ); parser->MarkArgumentAsRequired( "-ops", "Operation." ); bool validateArguments = parser->CheckForRequiredArguments(); if(!validateArguments) { return EXIT_FAILURE; } /** Get arguments. */ std::vector<std::string> inputFileNames; parser->GetCommandLineArgument( "-in", inputFileNames ); std::string outputFileName = ""; parser->GetCommandLineArgument( "-out", outputFileName ); std::string ops = ""; parser->GetCommandLineArgument( "-ops", ops ); std::string argument = "0"; bool retarg = parser->GetCommandLineArgument( "-arg", argument ); std::string opct = ""; bool retopct = parser->GetCommandLineArgument( "-opct", opct ); const bool useCompression = parser->ArgumentExists( "-z" ); /** Support for streaming. */ unsigned int numberOfStreams = inputFileNames.size(); parser->GetCommandLineArgument( "-s", numberOfStreams ); /** You should specify at least two input files. */ if ( inputFileNames.size() < 2 ) { std::cerr << "ERROR: You should specify at least two input file names." << std::endl; return 1; } /** Determine image properties. */ std::string ComponentTypeIn = "long"; std::string ComponentTypeOut = "long"; unsigned int inputDimension = 2; int retdip = DetermineImageProperties( inputFileNames, ComponentTypeIn, ComponentTypeOut, inputDimension ); if ( retdip ) return 1; /** Let the user override the output component type. */ if ( retopct ) { if ( !CheckForValidComponentType( opct ) ) { std::cerr << "ERROR: the you specified a wrong opct." << std::endl; return 1; } ComponentTypeOut = opct; ReplaceUnderscoreWithSpace( ComponentTypeOut ); if ( !TypeIsInteger( opct ) ) ComponentTypeIn = "double"; } /** Check if a valid operator is given. */ std::string opsCopy = ops; int retCO = CheckOperator( ops ); if ( retCO ) return retCO; /** For certain ops an argument is mandatory. */ bool retCOA = CheckOperatorAndArgument( ops, argument, retarg ); if ( !retCOA ) return 1; /** Run the program. */ bool supported = false; try { run( NaryImageOperator, long, char, 2 ); run( NaryImageOperator, long, unsigned char, 2 ); run( NaryImageOperator, long, short, 2 ); run( NaryImageOperator, long, unsigned short, 2 ); run( NaryImageOperator, long, int, 2 ); run( NaryImageOperator, long, unsigned int, 2 ); run( NaryImageOperator, long, long, 2 ); run( NaryImageOperator, long, unsigned long, 2 ); run( NaryImageOperator, double, float, 2 ); run( NaryImageOperator, double, double, 2 ); run( NaryImageOperator, long, char, 3 ); run( NaryImageOperator, long, unsigned char, 3 ); run( NaryImageOperator, long, short, 3 ); run( NaryImageOperator, long, unsigned short, 3 ); run( NaryImageOperator, long, int, 3 ); run( NaryImageOperator, long, unsigned int, 3 ); run( NaryImageOperator, long, long, 3 ); run( NaryImageOperator, long, unsigned long, 3 ); run( NaryImageOperator, double, float, 3 ); run( NaryImageOperator, double, double, 3 ); } // end try catch ( itk::ExceptionObject &e ) { std::cerr << "Caught ITK exception: " << e << std::endl; return 1; } if ( !supported ) { std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl; std::cerr << "pixel (component) type = " << ComponentTypeOut << " ; dimension = " << inputDimension << std::endl; return 1; } /** End program. */ return 0; } // end main <|endoftext|>
<commit_before>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <commit_msg>fixed test_upnp<commit_after>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); upnp_handler->discover_device(); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "router: " << upnp_handler->router_model() << std::endl; std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <|endoftext|>
<commit_before> /* * AUTOGENERATED CODE, DO NOT EDIT * * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * * Copyright (C) 2010, 2012 Aldebaran Robotics */ #pragma once #ifndef _QI_MESSAGING_OBJECT_HXX_ #define _QI_MESSAGING_OBJECT_HXX_ #include <qimessaging/buffer.hpp> namespace qi { namespace detail { template<typename T> class FutureAdapter : public qi::FutureInterface<qi::MetaFunctionResult> { public: FutureAdapter(qi::Promise<T> prom) :prom(prom) {} ~FutureAdapter() {} virtual void onFutureFinished(const qi::MetaFunctionResult &future, void *data) { if (future.getMode() == MetaFunctionResult::Mode_MetaValue) { MetaValue val = future.getValue(); typedef std::pair<const T*, bool> ConvType; ConvType resConv = val.template as<T>(); if (resConv.first) prom.setValue(*resConv.first); else prom.setError("Unable to convert call result to target type"); if (resConv.second) delete const_cast<T*>(resConv.first); } else { T tmp; IDataStream in(future.getBuffer()); in >> tmp; prom.setValue(tmp); } delete this; } virtual void onFutureFailed(const std::string &error, void *data) { prom.setError(error); delete this; } qi::Promise<T> prom; }; template<> class FutureAdapter<void> : public qi::FutureInterface<qi::MetaFunctionResult> { public: FutureAdapter(qi::Promise<void> prom) :prom(prom) {} ~FutureAdapter() {} virtual void onFutureFinished(const qi::MetaFunctionResult &future, void *data) { prom.setValue(0); delete this; } virtual void onFutureFailed(const std::string &error, void *data) { prom.setError(error); delete this; } qi::Promise<void> prom; }; } template<typename R> qi::FutureSync<R> Object::call(const std::string& methodName, qi::AutoMetaValue p1, qi::AutoMetaValue p2, qi::AutoMetaValue p3, qi::AutoMetaValue p4, qi::AutoMetaValue p5, qi::AutoMetaValue p6, qi::AutoMetaValue p7, qi::AutoMetaValue p8) { qi::AutoMetaValue* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::MetaValue> params; for (unsigned i=0; i<8; ++i) if (vals[i]->value) params.push_back(*vals[i]); // Signature construction std::string signature = methodName + "::("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; std::string sigret; signatureFromType<R>::value(sigret); // Future adaptation qi::Promise<R> res; // Mark params as being on the stack MetaFunctionParameters p(params, true); qi::Future<qi::MetaFunctionResult> fmeta = xMetaCall(sigret, signature, p); fmeta.addCallbacks(new detail::FutureAdapter<R>(res)); return res.future(); } } #endif // _QI_MESSAGING_OBJECT_HXX_ <commit_msg>object.hxx: remove now false 'autogenerated' warning.<commit_after> /* * * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * * Copyright (C) 2010, 2012 Aldebaran Robotics */ #pragma once #ifndef _QI_MESSAGING_OBJECT_HXX_ #define _QI_MESSAGING_OBJECT_HXX_ #include <qimessaging/buffer.hpp> namespace qi { namespace detail { template<typename T> class FutureAdapter : public qi::FutureInterface<qi::MetaFunctionResult> { public: FutureAdapter(qi::Promise<T> prom) :prom(prom) {} ~FutureAdapter() {} virtual void onFutureFinished(const qi::MetaFunctionResult &future, void *data) { if (future.getMode() == MetaFunctionResult::Mode_MetaValue) { MetaValue val = future.getValue(); typedef std::pair<const T*, bool> ConvType; ConvType resConv = val.template as<T>(); if (resConv.first) prom.setValue(*resConv.first); else prom.setError("Unable to convert call result to target type"); if (resConv.second) delete const_cast<T*>(resConv.first); } else { T tmp; IDataStream in(future.getBuffer()); in >> tmp; prom.setValue(tmp); } delete this; } virtual void onFutureFailed(const std::string &error, void *data) { prom.setError(error); delete this; } qi::Promise<T> prom; }; template<> class FutureAdapter<void> : public qi::FutureInterface<qi::MetaFunctionResult> { public: FutureAdapter(qi::Promise<void> prom) :prom(prom) {} ~FutureAdapter() {} virtual void onFutureFinished(const qi::MetaFunctionResult &future, void *data) { prom.setValue(0); delete this; } virtual void onFutureFailed(const std::string &error, void *data) { prom.setError(error); delete this; } qi::Promise<void> prom; }; } template<typename R> qi::FutureSync<R> Object::call(const std::string& methodName, qi::AutoMetaValue p1, qi::AutoMetaValue p2, qi::AutoMetaValue p3, qi::AutoMetaValue p4, qi::AutoMetaValue p5, qi::AutoMetaValue p6, qi::AutoMetaValue p7, qi::AutoMetaValue p8) { qi::AutoMetaValue* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::MetaValue> params; for (unsigned i=0; i<8; ++i) if (vals[i]->value) params.push_back(*vals[i]); // Signature construction std::string signature = methodName + "::("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; std::string sigret; signatureFromType<R>::value(sigret); // Future adaptation qi::Promise<R> res; // Mark params as being on the stack MetaFunctionParameters p(params, true); qi::Future<qi::MetaFunctionResult> fmeta = xMetaCall(sigret, signature, p); fmeta.addCallbacks(new detail::FutureAdapter<R>(res)); return res.future(); } } #endif // _QI_MESSAGING_OBJECT_HXX_ <|endoftext|>
<commit_before>#include "debug.hh" #include "assert.hh" #include "buffer.hh" #include "buffer_manager.hh" #include "string.hh" namespace Kakoune { void write_debug(StringView str) { if (not BufferManager::has_instance()) { fprintf(stderr, "%s\n", (const char*)str.zstr()); return; } const StringView debug_buffer_name = "*debug*"; Buffer* buffer = BufferManager::instance().get_buffer_ifp(debug_buffer_name); if (not buffer) buffer = new Buffer(debug_buffer_name, Buffer::Flags::NoUndo); kak_assert(buffer); buffer->insert(buffer->end(), str); } } <commit_msg>Refactor write_debug to avoid empty first line in *debug* buffer<commit_after>#include "debug.hh" #include "assert.hh" #include "buffer.hh" #include "buffer_manager.hh" #include "string.hh" namespace Kakoune { void write_debug(StringView str) { if (not BufferManager::has_instance()) { fprintf(stderr, "%s\n", (const char*)str.zstr()); return; } const StringView debug_buffer_name = "*debug*"; if (Buffer* buffer = BufferManager::instance().get_buffer_ifp(debug_buffer_name)) buffer->insert(buffer->end(), str); else { String line = str + ((str.empty() or str.back() != '\n') ? "\n" : ""); new Buffer(debug_buffer_name, Buffer::Flags::NoUndo, { line }); } } } <|endoftext|>
<commit_before>#include "Util.h" #include "Introspection.h" #include "Debug.h" #include "Error.h" #include <sstream> #include <map> #include <atomic> #include <mutex> #include <string> #ifdef _MSC_VER #include <io.h> #else #include <unistd.h> #include <stdlib.h> #endif #include <sys/types.h> #include <sys/stat.h> #ifdef __linux__ #include <linux/limits.h> // For PATH_MAX #endif #ifdef _WIN32 #include <windows.h> #endif namespace Halide { namespace Internal { using std::string; using std::vector; using std::ostringstream; using std::map; std::string get_env_variable(char const *env_var_name, size_t &read) { if (!env_var_name) { return ""; } read = 0; #ifdef _MSC_VER char lvl[32]; getenv_s(&read, lvl, env_var_name); #else char *lvl = getenv(env_var_name); read = (lvl)?1:0; #endif if (read) { return std::string(lvl); } else { return ""; } } string running_program_name() { // linux specific currently. #ifndef __linux__ return ""; #else string program_name; char path[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", path, sizeof(path)-1); if (len != -1) { path[len] = '\0'; string tmp = std::string(path); program_name = tmp.substr(tmp.find_last_of("/")+1); } else { return ""; } return program_name; #endif } namespace { // We use 64K of memory to store unique counters for the purpose of // making names unique. Using less memory increases the likelihood of // hash collisions. This wouldn't break anything, but makes stmts // slightly confusing to read because names that are actually unique // will get suffixes that falsely hint that they are not. const int num_unique_name_counters = (1 << 14); std::atomic<int> unique_name_counters[num_unique_name_counters]; int unique_count(size_t h) { h = h & (num_unique_name_counters - 1); return unique_name_counters[h]++; } } // There are three possible families of names returned by the methods below: // 1) char pattern: (char that isn't '$') + number (e.g. v234) // 2) string pattern: (string without '$') + '$' + number (e.g. fr#nk82$42) // 3) a string that does not match the patterns above // There are no collisions within each family, due to the unique_count // done above, and there can be no collisions across families by // construction. string unique_name(char prefix) { if (prefix == '$') prefix = '_'; return prefix + std::to_string(unique_count((size_t)(prefix))); } string unique_name(const std::string &prefix) { string sanitized = prefix; // Does the input string look like something returned from unique_name(char)? bool matches_char_pattern = true; // Does the input string look like something returned from unique_name(string)? bool matches_string_pattern = true; // Rewrite '$' to '_'. This is a many-to-one mapping, but that's // OK, we're about to hash anyway. It just means that some names // will share the same counter. int num_dollars = 0; for (size_t i = 0; i < sanitized.size(); i++) { if (sanitized[i] == '$') { num_dollars++; sanitized[i] = '_'; } if (i > 0 && !isdigit(sanitized[i])) { // Found a non-digit after the first char matches_char_pattern = false; if (num_dollars) { // Found a non-digit after a '$' matches_string_pattern = false; } } } matches_string_pattern &= num_dollars == 1; matches_char_pattern &= prefix.size() > 1; // Then add a suffix that's globally unique relative to the hash // of the sanitized name. int count = unique_count(std::hash<std::string>()(sanitized)); if (count == 0) { // We can return the name as-is if there's no risk of it // looking like something unique_name has ever returned in the // past or will ever return in the future. if (!matches_char_pattern && !matches_string_pattern) { return prefix; } } return sanitized + "$" + std::to_string(count); } bool starts_with(const string &str, const string &prefix) { if (str.size() < prefix.size()) return false; for (size_t i = 0; i < prefix.size(); i++) { if (str[i] != prefix[i]) return false; } return true; } bool ends_with(const string &str, const string &suffix) { if (str.size() < suffix.size()) return false; size_t off = str.size() - suffix.size(); for (size_t i = 0; i < suffix.size(); i++) { if (str[off+i] != suffix[i]) return false; } return true; } string replace_all(const string &str, const string &find, const string &replace) { size_t pos = 0; string result = str; while ((pos = result.find(find, pos)) != string::npos) { result.replace(pos, find.length(), replace); pos += replace.length(); } return result; } string base_name(const string &name, char delim) { size_t off = name.rfind(delim); if (off == string::npos) { return name; } return name.substr(off+1); } string make_entity_name(void *stack_ptr, const string &type, char prefix) { string name = Introspection::get_variable_name(stack_ptr, type); if (name.empty()) { return unique_name(prefix); } else { // Halide names may not contain '.' for (size_t i = 0; i < name.size(); i++) { if (name[i] == '.') { name[i] = ':'; } } return unique_name(name); } } std::vector<std::string> split_string(const std::string &source, const std::string &delim) { std::vector<std::string> elements; size_t start = 0; size_t found = 0; while ((found = source.find(delim, start)) != std::string::npos) { elements.push_back(source.substr(start, found - start)); start = found + delim.size(); } // If start is exactly source.size(), the last thing in source is a // delimiter, in which case we want to add an empty string to elements. if (start <= source.size()) { elements.push_back(source.substr(start, std::string::npos)); } return elements; } std::string extract_namespaces(const std::string &name, std::vector<std::string> &namespaces) { namespaces = split_string(name, "::"); std::string result = namespaces.back(); namespaces.pop_back(); return result; } bool file_exists(const std::string &name) { #ifdef _MSC_VER return _access(name.c_str(), 0) == 0; #else return ::access(name.c_str(), F_OK) == 0; #endif } void file_unlink(const std::string &name) { #ifdef _MSC_VER _unlink(name.c_str()); #else ::unlink(name.c_str()); #endif } FileStat file_stat(const std::string &name) { #ifdef _MSC_VER struct _stat a; if (_stat(name.c_str(), &a) != 0) { user_error << "Could not stat " << name << "\n"; } #else struct stat a; if (::stat(name.c_str(), &a) != 0) { user_error << "Could not stat " << name << "\n"; } #endif return {static_cast<uint64_t>(a.st_size), static_cast<uint32_t>(a.st_mtime), static_cast<uint32_t>(a.st_uid), static_cast<uint32_t>(a.st_gid), static_cast<uint32_t>(a.st_mode)}; } std::string file_make_temp(const std::string &base, const std::string &ext) { #ifdef _MSC_VER // Windows implementations of mkstemp() try to create the file in the root // directory, which is... problematic. TCHAR tmp_path[MAX_PATH], tmp_file[MAX_PATH]; DWORD ret = GetTempPath(MAX_PATH, tmp_path); internal_assert(ret != 0); // Note that GetTempFileName() actually creates the file. ret = GetTempFileName(tmp_path, base.c_str(), 0, tmp_file); internal_assert(ret != 0); return std::string(tmp_file); #else std::string templ = base + "XXXXXX" + ext; // Copy into a temporary buffer, since mkstemp modifies the buffer in place. std::vector<char> buf(templ.size() + 1); strcpy(&buf[0], templ.c_str()); int fd = mkstemps(&buf[0], ext.size()); internal_assert(fd != -1) << "Unable to create temp file for " << base << ext; close(fd); return std::string(&buf[0]); #endif } } } <commit_msg>mingw doesn't have mkstemps, but should have GetTempPath<commit_after>#include "Util.h" #include "Introspection.h" #include "Debug.h" #include "Error.h" #include <sstream> #include <map> #include <atomic> #include <mutex> #include <string> #ifdef _MSC_VER #include <io.h> #else #include <unistd.h> #include <stdlib.h> #endif #include <sys/types.h> #include <sys/stat.h> #ifdef __linux__ #include <linux/limits.h> // For PATH_MAX #endif #ifdef _WIN32 #include <windows.h> #endif namespace Halide { namespace Internal { using std::string; using std::vector; using std::ostringstream; using std::map; std::string get_env_variable(char const *env_var_name, size_t &read) { if (!env_var_name) { return ""; } read = 0; #ifdef _MSC_VER char lvl[32]; getenv_s(&read, lvl, env_var_name); #else char *lvl = getenv(env_var_name); read = (lvl)?1:0; #endif if (read) { return std::string(lvl); } else { return ""; } } string running_program_name() { // linux specific currently. #ifndef __linux__ return ""; #else string program_name; char path[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", path, sizeof(path)-1); if (len != -1) { path[len] = '\0'; string tmp = std::string(path); program_name = tmp.substr(tmp.find_last_of("/")+1); } else { return ""; } return program_name; #endif } namespace { // We use 64K of memory to store unique counters for the purpose of // making names unique. Using less memory increases the likelihood of // hash collisions. This wouldn't break anything, but makes stmts // slightly confusing to read because names that are actually unique // will get suffixes that falsely hint that they are not. const int num_unique_name_counters = (1 << 14); std::atomic<int> unique_name_counters[num_unique_name_counters]; int unique_count(size_t h) { h = h & (num_unique_name_counters - 1); return unique_name_counters[h]++; } } // There are three possible families of names returned by the methods below: // 1) char pattern: (char that isn't '$') + number (e.g. v234) // 2) string pattern: (string without '$') + '$' + number (e.g. fr#nk82$42) // 3) a string that does not match the patterns above // There are no collisions within each family, due to the unique_count // done above, and there can be no collisions across families by // construction. string unique_name(char prefix) { if (prefix == '$') prefix = '_'; return prefix + std::to_string(unique_count((size_t)(prefix))); } string unique_name(const std::string &prefix) { string sanitized = prefix; // Does the input string look like something returned from unique_name(char)? bool matches_char_pattern = true; // Does the input string look like something returned from unique_name(string)? bool matches_string_pattern = true; // Rewrite '$' to '_'. This is a many-to-one mapping, but that's // OK, we're about to hash anyway. It just means that some names // will share the same counter. int num_dollars = 0; for (size_t i = 0; i < sanitized.size(); i++) { if (sanitized[i] == '$') { num_dollars++; sanitized[i] = '_'; } if (i > 0 && !isdigit(sanitized[i])) { // Found a non-digit after the first char matches_char_pattern = false; if (num_dollars) { // Found a non-digit after a '$' matches_string_pattern = false; } } } matches_string_pattern &= num_dollars == 1; matches_char_pattern &= prefix.size() > 1; // Then add a suffix that's globally unique relative to the hash // of the sanitized name. int count = unique_count(std::hash<std::string>()(sanitized)); if (count == 0) { // We can return the name as-is if there's no risk of it // looking like something unique_name has ever returned in the // past or will ever return in the future. if (!matches_char_pattern && !matches_string_pattern) { return prefix; } } return sanitized + "$" + std::to_string(count); } bool starts_with(const string &str, const string &prefix) { if (str.size() < prefix.size()) return false; for (size_t i = 0; i < prefix.size(); i++) { if (str[i] != prefix[i]) return false; } return true; } bool ends_with(const string &str, const string &suffix) { if (str.size() < suffix.size()) return false; size_t off = str.size() - suffix.size(); for (size_t i = 0; i < suffix.size(); i++) { if (str[off+i] != suffix[i]) return false; } return true; } string replace_all(const string &str, const string &find, const string &replace) { size_t pos = 0; string result = str; while ((pos = result.find(find, pos)) != string::npos) { result.replace(pos, find.length(), replace); pos += replace.length(); } return result; } string base_name(const string &name, char delim) { size_t off = name.rfind(delim); if (off == string::npos) { return name; } return name.substr(off+1); } string make_entity_name(void *stack_ptr, const string &type, char prefix) { string name = Introspection::get_variable_name(stack_ptr, type); if (name.empty()) { return unique_name(prefix); } else { // Halide names may not contain '.' for (size_t i = 0; i < name.size(); i++) { if (name[i] == '.') { name[i] = ':'; } } return unique_name(name); } } std::vector<std::string> split_string(const std::string &source, const std::string &delim) { std::vector<std::string> elements; size_t start = 0; size_t found = 0; while ((found = source.find(delim, start)) != std::string::npos) { elements.push_back(source.substr(start, found - start)); start = found + delim.size(); } // If start is exactly source.size(), the last thing in source is a // delimiter, in which case we want to add an empty string to elements. if (start <= source.size()) { elements.push_back(source.substr(start, std::string::npos)); } return elements; } std::string extract_namespaces(const std::string &name, std::vector<std::string> &namespaces) { namespaces = split_string(name, "::"); std::string result = namespaces.back(); namespaces.pop_back(); return result; } bool file_exists(const std::string &name) { #ifdef _MSC_VER return _access(name.c_str(), 0) == 0; #else return ::access(name.c_str(), F_OK) == 0; #endif } void file_unlink(const std::string &name) { #ifdef _MSC_VER _unlink(name.c_str()); #else ::unlink(name.c_str()); #endif } FileStat file_stat(const std::string &name) { #ifdef _MSC_VER struct _stat a; if (_stat(name.c_str(), &a) != 0) { user_error << "Could not stat " << name << "\n"; } #else struct stat a; if (::stat(name.c_str(), &a) != 0) { user_error << "Could not stat " << name << "\n"; } #endif return {static_cast<uint64_t>(a.st_size), static_cast<uint32_t>(a.st_mtime), static_cast<uint32_t>(a.st_uid), static_cast<uint32_t>(a.st_gid), static_cast<uint32_t>(a.st_mode)}; } std::string file_make_temp(const std::string &base, const std::string &ext) { #ifdef _WIN32 // Windows implementations of mkstemp() try to create the file in the root // directory, which is... problematic. TCHAR tmp_path[MAX_PATH], tmp_file[MAX_PATH]; DWORD ret = GetTempPath(MAX_PATH, tmp_path); internal_assert(ret != 0); // Note that GetTempFileName() actually creates the file. ret = GetTempFileName(tmp_path, base.c_str(), 0, tmp_file); internal_assert(ret != 0); return std::string(tmp_file); #else std::string templ = base + "XXXXXX" + ext; // Copy into a temporary buffer, since mkstemp modifies the buffer in place. std::vector<char> buf(templ.size() + 1); strcpy(&buf[0], templ.c_str()); int fd = mkstemps(&buf[0], ext.size()); internal_assert(fd != -1) << "Unable to create temp file for " << base << ext; close(fd); return std::string(&buf[0]); #endif } } } <|endoftext|>
<commit_before>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2017 Taras Kushnir <kushnirTV@gmail.com> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "videocachingworker.h" #include <QDir> #include <QImage> #include <QCryptographicHash> #include <vector> #include <cstdint> #include "../Helpers/constants.h" #include "imagecachingservice.h" #include "artworksupdatehub.h" #include "../MetadataIO/metadataioservice.h" #include "../Models/artitemsmodel.h" #include "../Commands/commandmanager.h" #include <thumbnailcreator.h> #define VIDEO_WORKER_SLEEP_DELAY 500 #define VIDEO_INDEX_BACKUP_STEP 50 #define THUMBNAIL_JPG_QUALITY 80 namespace QMLExtensions { QString getVideoPathHash(const QString &path, bool isQuickThumbnail) { QString hash = QString::fromLatin1(QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha256).toHex()); // TODO: in the video cache cleanup remove all with same hash without _s if (!isQuickThumbnail) { hash.append(QChar('s')); } return hash; } VideoCachingWorker::VideoCachingWorker(Helpers::DatabaseManager *dbManager, QObject *parent) : QObject(parent), m_ProcessedItemsCount(0), m_Cache(dbManager) { m_RolesToUpdate << Models::ArtItemsModel::ArtworkThumbnailRole; } bool VideoCachingWorker::initWorker() { LOG_DEBUG << "#"; m_ProcessedItemsCount = 0; QString appDataPath = XPIKS_USERDATA_PATH; if (!appDataPath.isEmpty()) { m_VideosCacheDir = QDir::cleanPath(appDataPath + QDir::separator() + Constants::VIDEO_CACHE_DIR); QDir imagesCacheDir(m_VideosCacheDir); if (!imagesCacheDir.exists()) { LOG_INFO << "Creating cache dir" << m_VideosCacheDir; QDir().mkpath(m_VideosCacheDir); } } else { m_VideosCacheDir = QDir::currentPath(); } LOG_INFO << "Using" << m_VideosCacheDir << "for videos cache"; m_Cache.initialize(); return true; } void VideoCachingWorker::processOneItem(std::shared_ptr<VideoCacheRequest> &item) { if (checkLockedIO(item)) { sleepIfNeeded(item); return; } if (isSeparator(item)) { saveIndex(); return; } if (checkProcessed(item)) { return; } const QString &originalPath = item->getFilepath(); const bool isQuickThumbnail = item->getIsQuickThumbnail(); LOG_INFO << (item->getNeedRecache() ? "Recaching" : "Caching") << originalPath; LOG_INFO << (isQuickThumbnail ? "Quick thumbnail" : "Good thumbnail") << "requested"; std::vector<uint8_t> buffer; int width = 0, height = 0; if (createThumbnail(item, buffer, width, height)) { QString thumbnailPath; QImage image((unsigned char*)&buffer[0], width, height, QImage::Format_RGB888); bool needsRefresh = false; if (saveThumbnail(image, originalPath, isQuickThumbnail, thumbnailPath)) { cacheImage(thumbnailPath); applyThumbnail(item, thumbnailPath); if (m_ProcessedItemsCount % VIDEO_INDEX_BACKUP_STEP == 0) { saveIndex(); } sleepIfNeeded(item); if (isQuickThumbnail && item->getGoodQualityAllowed()) { LOG_INTEGR_TESTS_OR_DEBUG << "Regenerating good quality thumb for" << originalPath; item->setGoodQualityRequest(); needsRefresh = true; } } else { // TODO: change global retry to smth smarter LOG_WARNING << "Retrying creating thumbnail which failed to save"; needsRefresh = true; } if (needsRefresh) { this->submitItem(item); } } } bool VideoCachingWorker::createThumbnail(std::shared_ptr<VideoCacheRequest> &item, std::vector<uint8_t> &buffer, int &width, int &height) { bool thumbnailCreated = false; const QString &originalPath = item->getFilepath(); const QString filepath = QDir::toNativeSeparators(originalPath); #ifdef Q_OS_WIN libthmbnlr::ThumbnailCreator thumbnailCreator(filepath.toStdWString()); #else libthmbnlr::ThumbnailCreator thumbnailCreator(filepath.toStdString()); #endif try { const libthmbnlr::ThumbnailCreator::CreationOption option = item->getIsQuickThumbnail() ? libthmbnlr::ThumbnailCreator::Quick : libthmbnlr::ThumbnailCreator::GoodQuality; thumbnailCreator.setCreationOption(option); thumbnailCreator.setSeekPercentage(50); thumbnailCreated = thumbnailCreator.createThumbnail(buffer, width, height); LOG_INTEGR_TESTS_OR_DEBUG << "Thumb generated for" << originalPath; if (thumbnailCreated) { item->setVideoMetadata(thumbnailCreator.getMetadata()); } } catch (...) { LOG_WARNING << "Unknown exception while creating thumbnail"; } return thumbnailCreated; } void VideoCachingWorker::workerStopped() { LOG_DEBUG << "#"; m_Cache.finalize(); emit stopped(); } bool VideoCachingWorker::tryGetVideoThumbnail(const QString &key, QString &cachedPath, bool &needsUpdate) { bool found = false; CachedVideo cachedVideo; if (m_Cache.tryGet(key, cachedVideo)) { QString cachedValue = QDir::cleanPath(m_VideosCacheDir + QDir::separator() + cachedVideo.m_Filename); QFileInfo fi(cachedValue); if (fi.exists()) { cachedVideo.m_RequestsServed++; cachedPath = cachedValue; needsUpdate = QFileInfo(key).lastModified() > cachedVideo.m_LastModified; found = true; } } return found; } void VideoCachingWorker::submitSaveIndexItem() { std::shared_ptr<VideoCacheRequest> separatorItem(new VideoCacheRequest()); this->submitItem(separatorItem); } bool VideoCachingWorker::saveThumbnail(QImage &image, const QString &originalPath, bool isQuickThumbnail, QString &thumbnailPath) { bool success = false; QFileInfo fi(originalPath); QString pathHash = getVideoPathHash(originalPath, isQuickThumbnail) + ".jpg"; QString cachedFilepath = QDir::cleanPath(m_VideosCacheDir + QDir::separator() + pathHash); if (image.save(cachedFilepath, "JPG", THUMBNAIL_JPG_QUALITY)) { CachedVideo cachedVideo; cachedVideo.m_Filename = pathHash; cachedVideo.m_LastModified = fi.lastModified(); cachedVideo.m_IsQuickThumbnail = isQuickThumbnail; m_Cache.update(originalPath, cachedVideo); m_ProcessedItemsCount++; thumbnailPath = cachedFilepath; success = true; } else { LOG_WARNING << "Failed to save thumbnail. Path:" << cachedFilepath; } return success; } void VideoCachingWorker::cacheImage(const QString &thumbnailPath) { auto *imageCachingService = m_CommandManager->getImageCachingService(); imageCachingService->cacheImage(thumbnailPath); } void VideoCachingWorker::applyThumbnail(std::shared_ptr<VideoCacheRequest> &item, const QString &thumbnailPath) { item->setThumbnailPath(thumbnailPath); auto *updateHub = m_CommandManager->getArtworksUpdateHub(); updateHub->updateArtwork(item->getArtworkID(), item->getLastKnownIndex(), m_RolesToUpdate); // write video metadata set to the artwork auto *metadataIOService = m_CommandManager->getMetadataIOService(); metadataIOService->writeArtwork(item->getArtwork()); } void VideoCachingWorker::saveIndex() { LOG_DEBUG << "#"; m_Cache.sync(); } bool VideoCachingWorker::checkLockedIO(std::shared_ptr<VideoCacheRequest> &item) { Models::VideoArtwork *video = item->getArtwork(); Q_ASSERT(video != nullptr); if (video->isLockedIO()) { this->submitItem(item); } } bool VideoCachingWorker::checkProcessed(std::shared_ptr<VideoCacheRequest> &item) { if (item->getNeedRecache()) { return false; } const QString &originalPath = item->getFilepath(); bool isAlreadyProcessed = false; QString cachedPath; bool needsUpdate = false; if (this->tryGetVideoThumbnail(originalPath, cachedPath, needsUpdate)) { isAlreadyProcessed = !needsUpdate; if (item->getThumbnailPath() != cachedPath) { LOG_DEBUG << "Updating outdated thumbnail of artwork #" << item->getArtworkID(); applyThumbnail(item, cachedPath); } } return isAlreadyProcessed; } bool VideoCachingWorker::isSeparator(const std::shared_ptr<VideoCacheRequest> &item) { bool result = item->isSeparator(); return result; } void VideoCachingWorker::sleepIfNeeded(const std::shared_ptr<VideoCacheRequest> &item) { if (item->getWithDelay()) { // force context switch for more imporant tasks QThread::msleep(VIDEO_WORKER_SLEEP_DELAY); } } } <commit_msg>Fix for windows build<commit_after>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2017 Taras Kushnir <kushnirTV@gmail.com> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "videocachingworker.h" #include <QDir> #include <QImage> #include <QCryptographicHash> #include <vector> #include <cstdint> #include "../Helpers/constants.h" #include "imagecachingservice.h" #include "artworksupdatehub.h" #include "../MetadataIO/metadataioservice.h" #include "../Models/artitemsmodel.h" #include "../Commands/commandmanager.h" #include <thumbnailcreator.h> #define VIDEO_WORKER_SLEEP_DELAY 500 #define VIDEO_INDEX_BACKUP_STEP 50 #define THUMBNAIL_JPG_QUALITY 80 namespace QMLExtensions { QString getVideoPathHash(const QString &path, bool isQuickThumbnail) { QString hash = QString::fromLatin1(QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha256).toHex()); // TODO: in the video cache cleanup remove all with same hash without _s if (!isQuickThumbnail) { hash.append(QChar('s')); } return hash; } VideoCachingWorker::VideoCachingWorker(Helpers::DatabaseManager *dbManager, QObject *parent) : QObject(parent), m_ProcessedItemsCount(0), m_Cache(dbManager) { m_RolesToUpdate << Models::ArtItemsModel::ArtworkThumbnailRole; } bool VideoCachingWorker::initWorker() { LOG_DEBUG << "#"; m_ProcessedItemsCount = 0; QString appDataPath = XPIKS_USERDATA_PATH; if (!appDataPath.isEmpty()) { m_VideosCacheDir = QDir::cleanPath(appDataPath + QDir::separator() + Constants::VIDEO_CACHE_DIR); QDir imagesCacheDir(m_VideosCacheDir); if (!imagesCacheDir.exists()) { LOG_INFO << "Creating cache dir" << m_VideosCacheDir; QDir().mkpath(m_VideosCacheDir); } } else { m_VideosCacheDir = QDir::currentPath(); } LOG_INFO << "Using" << m_VideosCacheDir << "for videos cache"; m_Cache.initialize(); return true; } void VideoCachingWorker::processOneItem(std::shared_ptr<VideoCacheRequest> &item) { if (checkLockedIO(item)) { sleepIfNeeded(item); return; } if (isSeparator(item)) { saveIndex(); return; } if (checkProcessed(item)) { return; } const QString &originalPath = item->getFilepath(); const bool isQuickThumbnail = item->getIsQuickThumbnail(); LOG_INFO << (item->getNeedRecache() ? "Recaching" : "Caching") << originalPath; LOG_INFO << (isQuickThumbnail ? "Quick thumbnail" : "Good thumbnail") << "requested"; std::vector<uint8_t> buffer; int width = 0, height = 0; if (createThumbnail(item, buffer, width, height)) { QString thumbnailPath; QImage image((unsigned char*)&buffer[0], width, height, QImage::Format_RGB888); bool needsRefresh = false; if (saveThumbnail(image, originalPath, isQuickThumbnail, thumbnailPath)) { cacheImage(thumbnailPath); applyThumbnail(item, thumbnailPath); if (m_ProcessedItemsCount % VIDEO_INDEX_BACKUP_STEP == 0) { saveIndex(); } sleepIfNeeded(item); if (isQuickThumbnail && item->getGoodQualityAllowed()) { LOG_INTEGR_TESTS_OR_DEBUG << "Regenerating good quality thumb for" << originalPath; item->setGoodQualityRequest(); needsRefresh = true; } } else { // TODO: change global retry to smth smarter LOG_WARNING << "Retrying creating thumbnail which failed to save"; needsRefresh = true; } if (needsRefresh) { this->submitItem(item); } } } bool VideoCachingWorker::createThumbnail(std::shared_ptr<VideoCacheRequest> &item, std::vector<uint8_t> &buffer, int &width, int &height) { bool thumbnailCreated = false; const QString &originalPath = item->getFilepath(); const QString filepath = QDir::toNativeSeparators(originalPath); #ifdef Q_OS_WIN libthmbnlr::ThumbnailCreator thumbnailCreator(filepath.toStdWString()); #else libthmbnlr::ThumbnailCreator thumbnailCreator(filepath.toStdString()); #endif try { const libthmbnlr::ThumbnailCreator::CreationOption option = item->getIsQuickThumbnail() ? libthmbnlr::ThumbnailCreator::Quick : libthmbnlr::ThumbnailCreator::GoodQuality; thumbnailCreator.setCreationOption(option); thumbnailCreator.setSeekPercentage(50); thumbnailCreated = thumbnailCreator.createThumbnail(buffer, width, height); LOG_INTEGR_TESTS_OR_DEBUG << "Thumb generated for" << originalPath; if (thumbnailCreated) { item->setVideoMetadata(thumbnailCreator.getMetadata()); } } catch (...) { LOG_WARNING << "Unknown exception while creating thumbnail"; } return thumbnailCreated; } void VideoCachingWorker::workerStopped() { LOG_DEBUG << "#"; m_Cache.finalize(); emit stopped(); } bool VideoCachingWorker::tryGetVideoThumbnail(const QString &key, QString &cachedPath, bool &needsUpdate) { bool found = false; CachedVideo cachedVideo; if (m_Cache.tryGet(key, cachedVideo)) { QString cachedValue = QDir::cleanPath(m_VideosCacheDir + QDir::separator() + cachedVideo.m_Filename); QFileInfo fi(cachedValue); if (fi.exists()) { cachedVideo.m_RequestsServed++; cachedPath = cachedValue; needsUpdate = QFileInfo(key).lastModified() > cachedVideo.m_LastModified; found = true; } } return found; } void VideoCachingWorker::submitSaveIndexItem() { std::shared_ptr<VideoCacheRequest> separatorItem(new VideoCacheRequest()); this->submitItem(separatorItem); } bool VideoCachingWorker::saveThumbnail(QImage &image, const QString &originalPath, bool isQuickThumbnail, QString &thumbnailPath) { bool success = false; QFileInfo fi(originalPath); QString pathHash = getVideoPathHash(originalPath, isQuickThumbnail) + ".jpg"; QString cachedFilepath = QDir::cleanPath(m_VideosCacheDir + QDir::separator() + pathHash); if (image.save(cachedFilepath, "JPG", THUMBNAIL_JPG_QUALITY)) { CachedVideo cachedVideo; cachedVideo.m_Filename = pathHash; cachedVideo.m_LastModified = fi.lastModified(); cachedVideo.m_IsQuickThumbnail = isQuickThumbnail; m_Cache.update(originalPath, cachedVideo); m_ProcessedItemsCount++; thumbnailPath = cachedFilepath; success = true; } else { LOG_WARNING << "Failed to save thumbnail. Path:" << cachedFilepath; } return success; } void VideoCachingWorker::cacheImage(const QString &thumbnailPath) { auto *imageCachingService = m_CommandManager->getImageCachingService(); imageCachingService->cacheImage(thumbnailPath); } void VideoCachingWorker::applyThumbnail(std::shared_ptr<VideoCacheRequest> &item, const QString &thumbnailPath) { item->setThumbnailPath(thumbnailPath); auto *updateHub = m_CommandManager->getArtworksUpdateHub(); updateHub->updateArtwork(item->getArtworkID(), item->getLastKnownIndex(), m_RolesToUpdate); // write video metadata set to the artwork auto *metadataIOService = m_CommandManager->getMetadataIOService(); metadataIOService->writeArtwork(item->getArtwork()); } void VideoCachingWorker::saveIndex() { LOG_DEBUG << "#"; m_Cache.sync(); } bool VideoCachingWorker::checkLockedIO(std::shared_ptr<VideoCacheRequest> &item) { bool isLocked = false; Models::VideoArtwork *video = item->getArtwork(); Q_ASSERT(video != nullptr); if (video->isLockedIO()) { this->submitItem(item); isLocked = true; } return isLocked; } bool VideoCachingWorker::checkProcessed(std::shared_ptr<VideoCacheRequest> &item) { if (item->getNeedRecache()) { return false; } const QString &originalPath = item->getFilepath(); bool isAlreadyProcessed = false; QString cachedPath; bool needsUpdate = false; if (this->tryGetVideoThumbnail(originalPath, cachedPath, needsUpdate)) { isAlreadyProcessed = !needsUpdate; if (item->getThumbnailPath() != cachedPath) { LOG_DEBUG << "Updating outdated thumbnail of artwork #" << item->getArtworkID(); applyThumbnail(item, cachedPath); } } return isAlreadyProcessed; } bool VideoCachingWorker::isSeparator(const std::shared_ptr<VideoCacheRequest> &item) { bool result = item->isSeparator(); return result; } void VideoCachingWorker::sleepIfNeeded(const std::shared_ptr<VideoCacheRequest> &item) { if (item->getWithDelay()) { // force context switch for more imporant tasks QThread::msleep(VIDEO_WORKER_SLEEP_DELAY); } } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Python.h" #include "SQFReader.h" #include <string> #include <sstream> #include "../src/ExceptionFetcher.h" #include <cstdio> #include <string> #include <vector> #include <utility> #include <iterator> #include <array> #include <algorithm> #include <chrono> using namespace std; namespace SQFReader { inline PyObject *try_parse_number(const char **start) { const char *end = *start; char isFloat = false; if (*end == '-') { end++; } // TODO: Check if '-' is present only once while ((*end >= '0' && *end <= '9') || *end == '.') { if (*end == '.') { if (isFloat) { // '.' is present twice! // TODO: Raise exception } isFloat = true; } end++; } std::string tmp_value(*start, end - *start); // TODO: reference counting PyObject *number; if (!isFloat) { number = PyLong_FromString(tmp_value.c_str(), nullptr, 10); } else { double cDouble = atof(tmp_value.c_str()); number = PyFloat_FromDouble(cDouble); } *start = end; return number; } inline PyObject *try_parse_string_noescape(const char **start) { (*start)++; const char *end = *start; while (*end != '\'') end++; // TODO: Check the size value with regard to utf-8 // TODO: reference counting PyObject *retval = PyUnicode_FromStringAndSize(*start, end - *start); *start = end + 1; return retval; } inline PyObject *try_parse_string_escape(const char **start) { (*start)++; int escapedCount = 0; const char *end = *start; // Compute the length of the real string for (;;end++) { if (*end == '\0') { // TODO: END OF C-STRING! Raise exception!!! return nullptr; } if (*end == '"') { if (end[1] != '"') { // End of SQF string break; } escapedCount++; end++; } } int realStringLength = end - *start - escapedCount; char *realString = new char[realStringLength + 1]; char* rp = realString; // Unescape the string for (const char *p = *start;; p++, rp++) { if (*p == '"') { if (p[1] != '"') { break; } p++; } *rp = *p; } realString[realStringLength] = '\0'; // TODO: Check the size value with regard to utf-8 // TODO: reference counting int len = rp - realString; PyObject *retval = PyUnicode_FromStringAndSize(realString, rp - realString); *start = end + 1; delete [] realString; return retval; } inline PyObject *try_parse_true(const char **start) { if (((*start)[1] == 'R' || (*start)[1] == 'r') && ((*start)[2] == 'U' || (*start)[2] == 'u') && ((*start)[3] == 'E' || (*start)[3] == 'e')) { *start += 4; // TODO: Handle reference counting Py_RETURN_TRUE; } return nullptr; } inline PyObject *try_parse_false(const char **start) { if (((*start)[1] == 'A' || (*start)[1] == 'a') && ((*start)[2] == 'L' || (*start)[2] == 'l') && ((*start)[3] == 'S' || (*start)[3] == 's') && ((*start)[4] == 'E' || (*start)[4] == 'e')) { *start += 5; // TODO: Handle reference counting Py_RETURN_FALSE; } return nullptr; } inline PyObject *try_parse_array(const char **start) { (*start)++; // TODO: Reference counting PyObject* list = PyList_New(0); while(true) { if (**start == ']') { (*start)++; return list; } PyObject *obj = decode(start); if (obj == nullptr) { // TODO: Fix this! return nullptr; } // TODO: Return value check int retval = PyList_Append(list, obj); while (**start == ' ') (*start)++; if (**start == ',') { (*start)++; } else if (**start != ']') { // TODO: Error handling! return nullptr; } } } PyObject *decode(const char **start) { // Drop whitespaces while (**start == ' ') (*start)++; // If number if ((**start >= '0' && **start <= '9') || **start == '-') { return try_parse_number(start); } else if (**start == '[') { return try_parse_array(start); } else if (**start == '"') { return try_parse_string_escape(start); } else if (**start == '\'') { return try_parse_string_noescape(start); } else if (**start == 'T' || **start == 't') { return try_parse_true(start); } else if (**start == 'F' || **start == 'f') { return try_parse_false(start); } // TODO: check that the buffer is empty return nullptr; } } <commit_msg>Reference couting of PyObjects to prevent memory leaks<commit_after>#include "stdafx.h" #include "Python.h" #include "SQFReader.h" //#include "../src/ExceptionFetcher.h" using namespace std; namespace SQFReader { // Returns a new PyObject reference or NULL on error inline PyObject *try_parse_number(const char **start) { const char *end = *start; char isFloat = false; if (*end == '-') { end++; } // TODO: Check if '-' is present only once while ((*end >= '0' && *end <= '9') || *end == '.') { if (*end == '.') { if (isFloat) { // '.' is present twice! // TODO: Raise exception } isFloat = true; } end++; } std::string tmp_value(*start, end - *start); // TODO: reference counting PyObject *number; if (!isFloat) { number = PyLong_FromString(tmp_value.c_str(), nullptr, 10); } else { double cDouble = atof(tmp_value.c_str()); number = PyFloat_FromDouble(cDouble); } *start = end; return number; } // Returns a new PyObject reference or NULL on error inline PyObject *try_parse_string_noescape(const char **start) { (*start)++; const char *end = *start; while (*end != '\'') end++; // TODO: reference counting PyObject *retval = PyUnicode_FromStringAndSize(*start, end - *start); *start = end + 1; return retval; } // Returns a new PyObject reference or NULL on error inline PyObject *try_parse_string_escape(const char **start) { (*start)++; int escapedCount = 0; const char *end = *start; // Compute the length of the real string for (;;end++) { if (*end == '\0') { // TODO: END OF C-STRING! Raise exception!!! return nullptr; } if (*end == '"') { if (end[1] != '"') { // End of SQF string break; } escapedCount++; end++; } } int realStringLength = end - *start - escapedCount; char *realString = new char[realStringLength + 1]; char* rp = realString; // Unescape the string for (const char *p = *start;; p++, rp++) { if (*p == '"') { if (p[1] != '"') { break; } p++; } *rp = *p; } realString[realStringLength] = '\0'; int len = rp - realString; PyObject *retval = PyUnicode_FromStringAndSize(realString, rp - realString); *start = end + 1; delete [] realString; return retval; } // Returns a new PyObject reference or NULL on error inline PyObject *try_parse_true(const char **start) { if (((*start)[1] == 'R' || (*start)[1] == 'r') && ((*start)[2] == 'U' || (*start)[2] == 'u') && ((*start)[3] == 'E' || (*start)[3] == 'e')) { *start += 4; Py_RETURN_TRUE; } return nullptr; } // Returns a new PyObject reference or NULL on error inline PyObject *try_parse_false(const char **start) { if (((*start)[1] == 'A' || (*start)[1] == 'a') && ((*start)[2] == 'L' || (*start)[2] == 'l') && ((*start)[3] == 'S' || (*start)[3] == 's') && ((*start)[4] == 'E' || (*start)[4] == 'e')) { *start += 5; Py_RETURN_FALSE; } return nullptr; } // Returns a new PyObject reference or NULL on error inline PyObject *try_parse_array(const char **start) { (*start)++; PyObject* list = PyList_New(0); if (list == nullptr) { // TODO: Log the error return nullptr; } while(true) { if (**start == ']') { (*start)++; return list; } PyObject *obj = decode(start); if (obj == nullptr) { // TODO: Return some message Py_DECREF(list); // garbage-collect the list and its contents return nullptr; } // TODO: Return value check int retval = PyList_Append(list, obj); // Increases obj's refcount Py_DECREF(obj); if (retval != 0) { // TODO: Return some message // The docs say that this raises an exception // Not sure how to act here Py_DECREF(list); // garbage-collect the list and its contents return nullptr; } while (**start == ' ') (*start)++; if (**start == ',') { (*start)++; } else if (**start != ']') { // TODO: Return some message Py_DECREF(list); // garbage-collect the list and its contents return nullptr; } } } // Returns a new PyObject reference or NULL on error // IMPORTANT: The object MUST be Py_DECREF'ed after use to prevent leakage PyObject *decode(const char **start) { // Drop whitespaces while (**start == ' ') (*start)++; if ((**start >= '0' && **start <= '9') || **start == '-') { return try_parse_number(start); } else if (**start == '[') { return try_parse_array(start); } else if (**start == '"') { return try_parse_string_escape(start); } else if (**start == '\'') { return try_parse_string_noescape(start); } else if (**start == 'T' || **start == 't') { return try_parse_true(start); } else if (**start == 'F' || **start == 'f') { return try_parse_false(start); } // TODO: check that the buffer is empty return nullptr; } } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2013-2017 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed.h" #include "greentea-client/test_env.h" #include "utest/utest.h" #include "unity/unity.h" #if !DEVICE_LPTICKER #error [NOT_SUPPORTED] Low power ticker not supported for this target #endif using utest::v1::Case; static const int test_timeout = 10; #define TICKER_COUNT 16 #define MULTI_TICKER_TIME_MS 100 /* Due to poor accuracy of LowPowerTicker on many platforms there is no sense to tune tolerance value as it was in Ticker tests. Tolerance value is set to 2000us to cover this diversity */ #define TOLERANCE_US 2000 volatile uint32_t ticker_callback_flag; volatile uint32_t multi_counter; Timer gtimer; void sem_release(Semaphore *sem) { sem->release(); } void stop_gtimer_set_flag(void) { gtimer.stop(); core_util_atomic_incr_u32((uint32_t*)&ticker_callback_flag, 1); } void increment_multi_counter(void) { core_util_atomic_incr_u32((uint32_t*)&multi_counter, 1);; } /** Test many tickers run one after the other Given many Tickers When schedule them one after the other with the same time intervals Then tickers properly execute callbacks When schedule them one after the other with the different time intervals Then tickers properly execute callbacks */ void test_multi_ticker(void) { LowPowerTicker ticker[TICKER_COUNT]; const uint32_t extra_wait = 10; // extra 10ms wait time multi_counter = 0; for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].attach_us(callback(increment_multi_counter), MULTI_TICKER_TIME_MS * 1000); } Thread::wait(MULTI_TICKER_TIME_MS + extra_wait); for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].detach(); } TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter); multi_counter = 0; for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].attach_us(callback(increment_multi_counter), (MULTI_TICKER_TIME_MS + i) * 1000); } Thread::wait(MULTI_TICKER_TIME_MS + TICKER_COUNT + extra_wait); for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].detach(); } TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter); } /** Test multi callback time Given a Ticker When the callback is attached multiple times Then ticker properly execute callback multiple times */ void test_multi_call_time(void) { LowPowerTicker ticker; int time_diff; const int attach_count = 10; for (int i = 0; i < attach_count; i++) { ticker_callback_flag = 0; gtimer.reset(); gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), MULTI_TICKER_TIME_MS * 1000); while(!ticker_callback_flag); time_diff = gtimer.read_us(); TEST_ASSERT_UINT32_WITHIN(TOLERANCE_US, MULTI_TICKER_TIME_MS * 1000, time_diff); } } /** Test if detach cancel scheduled callback event Given a Ticker with callback attached When the callback is detached Then the callback is not being called */ void test_detach(void) { LowPowerTicker ticker; int32_t ret; const float ticker_time_s = 0.1f; const uint32_t wait_time_ms = 500; Semaphore sem(0, 1); ticker.attach(callback(sem_release, &sem), ticker_time_s); ret = sem.wait(); TEST_ASSERT_TRUE(ret > 0); ret = sem.wait(); ticker.detach(); /* cancel */ TEST_ASSERT_TRUE(ret > 0); ret = sem.wait(wait_time_ms); TEST_ASSERT_EQUAL(0, ret); } /** Test single callback time via attach Given a Ticker When callback attached with time interval specified Then ticker properly executes callback within a specified time interval */ template<us_timestamp_t DELAY_US> void test_attach_time(void) { LowPowerTicker ticker; ticker_callback_flag = 0; gtimer.reset(); gtimer.start(); ticker.attach(callback(stop_gtimer_set_flag), ((float)DELAY_US) / 1000000.0f); while(!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US, DELAY_US, time_diff); } /** Test single callback time via attach_us Given a Ticker When callback attached with time interval specified Then ticker properly executes callback within a specified time interval */ template<us_timestamp_t DELAY_US> void test_attach_us_time(void) { LowPowerTicker ticker; ticker_callback_flag = 0; gtimer.reset(); gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), DELAY_US); while(!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US, DELAY_US, time_diff); } // Test cases Case cases[] = { Case("Test attach for 0.001s and time measure", test_attach_time<1000>), Case("Test attach_us for 1ms and time measure", test_attach_us_time<1000>), Case("Test attach for 0.01s and time measure", test_attach_time<10000>), Case("Test attach_us for 10ms and time measure", test_attach_us_time<10000>), Case("Test attach for 0.1s and time measure", test_attach_time<100000>), Case("Test attach_us for 100ms and time measure", test_attach_us_time<100000>), Case("Test attach for 0.5s and time measure", test_attach_time<500000>), Case("Test attach_us for 500ms and time measure", test_attach_us_time<500000>), Case("Test detach", test_detach), Case("Test multi call and time measure", test_multi_call_time), Case("Test multi ticker", test_multi_ticker), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(test_timeout, "timing_drift_auto"); return utest::v1::greentea_test_setup_handler(number_of_cases); } utest::v1::Specification specification(greentea_test_setup, cases, utest::v1::greentea_test_teardown_handler); int main() { utest::v1::Harness::run(specification); } <commit_msg>tests-mbed_drivers-lp_ticker: Adapt tolerance for new Ticker driver<commit_after>/* mbed Microcontroller Library * Copyright (c) 2013-2017 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed.h" #include "greentea-client/test_env.h" #include "utest/utest.h" #include "unity/unity.h" #if !DEVICE_LPTICKER #error [NOT_SUPPORTED] Low power ticker not supported for this target #endif using utest::v1::Case; static const int test_timeout = 10; #define TICKER_COUNT 16 #define MULTI_TICKER_TIME_MS 100 /* Due to poor accuracy of LowPowerTicker on many platforms there is no sense to tune tolerance value as it was in Ticker tests. Tolerance value is set to 500us for measurement inaccuracy + 5% tolerance for LowPowerTicker. */ #define TOLERANCE_US(DELAY) (500 + DELAY / 20) volatile uint32_t ticker_callback_flag; volatile uint32_t multi_counter; Timer gtimer; void sem_release(Semaphore *sem) { sem->release(); } void stop_gtimer_set_flag(void) { gtimer.stop(); core_util_atomic_incr_u32((uint32_t*)&ticker_callback_flag, 1); } void increment_multi_counter(void) { core_util_atomic_incr_u32((uint32_t*)&multi_counter, 1);; } /** Test many tickers run one after the other Given many Tickers When schedule them one after the other with the same time intervals Then tickers properly execute callbacks When schedule them one after the other with the different time intervals Then tickers properly execute callbacks */ void test_multi_ticker(void) { LowPowerTicker ticker[TICKER_COUNT]; const uint32_t extra_wait = 10; // extra 10ms wait time multi_counter = 0; for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].attach_us(callback(increment_multi_counter), MULTI_TICKER_TIME_MS * 1000); } Thread::wait(MULTI_TICKER_TIME_MS + extra_wait); for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].detach(); } TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter); multi_counter = 0; for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].attach_us(callback(increment_multi_counter), (MULTI_TICKER_TIME_MS + i) * 1000); } Thread::wait(MULTI_TICKER_TIME_MS + TICKER_COUNT + extra_wait); for (int i = 0; i < TICKER_COUNT; i++) { ticker[i].detach(); } TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter); } /** Test multi callback time Given a Ticker When the callback is attached multiple times Then ticker properly execute callback multiple times */ void test_multi_call_time(void) { LowPowerTicker ticker; int time_diff; const int attach_count = 10; for (int i = 0; i < attach_count; i++) { ticker_callback_flag = 0; gtimer.reset(); gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), MULTI_TICKER_TIME_MS * 1000); while(!ticker_callback_flag); time_diff = gtimer.read_us(); TEST_ASSERT_UINT32_WITHIN(TOLERANCE_US(MULTI_TICKER_TIME_MS * 1000), MULTI_TICKER_TIME_MS * 1000, time_diff); } } /** Test if detach cancel scheduled callback event Given a Ticker with callback attached When the callback is detached Then the callback is not being called */ void test_detach(void) { LowPowerTicker ticker; int32_t ret; const float ticker_time_s = 0.1f; const uint32_t wait_time_ms = 500; Semaphore sem(0, 1); ticker.attach(callback(sem_release, &sem), ticker_time_s); ret = sem.wait(); TEST_ASSERT_TRUE(ret > 0); ret = sem.wait(); ticker.detach(); /* cancel */ TEST_ASSERT_TRUE(ret > 0); ret = sem.wait(wait_time_ms); TEST_ASSERT_EQUAL(0, ret); } /** Test single callback time via attach Given a Ticker When callback attached with time interval specified Then ticker properly executes callback within a specified time interval */ template<us_timestamp_t DELAY_US> void test_attach_time(void) { LowPowerTicker ticker; ticker_callback_flag = 0; gtimer.reset(); gtimer.start(); ticker.attach(callback(stop_gtimer_set_flag), ((float)DELAY_US) / 1000000.0f); while(!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US(DELAY_US), DELAY_US, time_diff); } /** Test single callback time via attach_us Given a Ticker When callback attached with time interval specified Then ticker properly executes callback within a specified time interval */ template<us_timestamp_t DELAY_US> void test_attach_us_time(void) { LowPowerTicker ticker; ticker_callback_flag = 0; gtimer.reset(); gtimer.start(); ticker.attach_us(callback(stop_gtimer_set_flag), DELAY_US); while(!ticker_callback_flag); ticker.detach(); const int time_diff = gtimer.read_us(); TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US(DELAY_US), DELAY_US, time_diff); } // Test cases Case cases[] = { Case("Test attach for 0.001s and time measure", test_attach_time<1000>), Case("Test attach_us for 1ms and time measure", test_attach_us_time<1000>), Case("Test attach for 0.01s and time measure", test_attach_time<10000>), Case("Test attach_us for 10ms and time measure", test_attach_us_time<10000>), Case("Test attach for 0.1s and time measure", test_attach_time<100000>), Case("Test attach_us for 100ms and time measure", test_attach_us_time<100000>), Case("Test attach for 0.5s and time measure", test_attach_time<500000>), Case("Test attach_us for 500ms and time measure", test_attach_us_time<500000>), Case("Test detach", test_detach), Case("Test multi call and time measure", test_multi_call_time), Case("Test multi ticker", test_multi_ticker), }; utest::v1::status_t greentea_test_setup(const size_t number_of_cases) { GREENTEA_SETUP(test_timeout, "timing_drift_auto"); return utest::v1::greentea_test_setup_handler(number_of_cases); } utest::v1::Specification specification(greentea_test_setup, cases, utest::v1::greentea_test_teardown_handler); int main() { utest::v1::Harness::run(specification); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: ShapeType.h // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHAPE_TYPE_H #define NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHAPE_TYPE_H #include <algorithm> #include <LibUtilities/BasicUtils/ErrorUtil.hpp> #ifdef min #undef min #endif namespace Nektar { namespace LibUtilities { // Types of geometry types. enum ShapeType { eNoShapeType, ePoint, eSegment, eTriangle, eQuadrilateral, eTetrahedron, ePyramid, ePrism, eHexahedron, SIZE_ShapeType }; const char* const ShapeTypeMap[] = { "NoGeomShapeType", "Point", "Segment", "Triangle", "Quadrilateral", "Tetrahedron", "Pyramid", "Prism", "Hexahedron" }; // Hold the dimension of each of the types of shapes. const unsigned int ShapeTypeDimMap[SIZE_ShapeType] = { 0, // Unknown 0, // ePoint 1, // eSegment 2, // eTriangle 2, // eQuadrilateral 3, // eTetrahedron 3, // ePyramid 3, // ePrism 3, // eHexahedron }; namespace StdSegData { inline int getNumberOfCoefficients(int Na) { return Na; } inline int getNumberOfBndCoefficients(int Na) { return 2; } } // Dimensions of coefficients for each space namespace StdTriData { inline int getNumberOfCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Na <= Nb, "order in 'a' direction is higher " "than order in 'b' direction"); return Na*(Na+1)/2 + Na*(Nb-Na); } inline int getNumberOfBndCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Na <= Nb, "order in 'a' direction is higher " "than order in 'b' direction"); return (Na-1) + 2*(Nb-1); } } namespace StdQuadData { inline int getNumberOfCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); return Na*Nb; } inline int getNumberOfBndCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); return 2*(Na-1) + 2*(Nb-1); } } namespace StdHexData { inline int getNumberOfCoefficients( int Na, int Nb, int Nc ) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); return Na*Nb*Nc; } inline int getNumberOfBndCoefficients(int Na, int Nb, int Nc) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); return 2*Na*Nb + 2*Na*Nc + 2*Nb*Nc - 4*(Na + Nb + Nc) + 8; } } namespace StdTetData { /** * Adds up the number of cells in a truncated Nc by Nc by Nc * pyramid, where the longest Na rows and longest Nb columns are * kept. Example: (Na, Nb, Nc) = (3, 4, 5); The number of * coefficients is the sum of the elements of the following * matrix: * * |5 4 3 2 0| * |4 3 2 0 | * |3 2 0 | * |0 0 | * |0 | * * Sum = 28 = number of tet coefficients. */ inline int getNumberOfCoefficients(int Na, int Nb, int Nc) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "order in 'a' direction is higher " "than order in 'c' direction"); ASSERTL1(Nb <= Nc, "order in 'b' direction is higher " "than order in 'c' direction"); int nCoef = 0; for (int a = 0; a < Na; ++a) { for (int b = 0; b < Nb - a; ++b) { for (int c = 0; c < Nc - a - b; ++c) { ++nCoef; } } } return nCoef; } inline int getNumberOfBndCoefficients(int Na, int Nb, int Nc) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "order in 'a' direction is higher " "than order in 'c' direction"); ASSERTL1(Nb <= Nc, "order in 'b' direction is higher " "than order in 'c' direction"); int nCoef = Na*(Na+1)/2 + (Nb-Na)*Na // base + Na*(Na+1)/2 + (Nc-Na)*Na // front + 2*(Nb*(Nb+1)/2 + (Nc-Nb)*Nb)// 2 other sides - Na - 2*Nb - 3*Nc // less edges + 4; // plus vertices return nCoef; } } namespace StdPyrData { inline int getNumberOfCoefficients(int Na, int Nb, int Nc) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); ASSERTL1(Nb <= Nc, "Order in 'b' direction is higher " "than order in 'c' direction."); // Count number of coefficients explicitly. const int Pi = Na - 2, Qi = Nb - 2, Ri = Nc - 2; int nCoeff = 5 + // vertices Pi * 2 + Qi * 2 + Ri * 4 + // base edges Pi * Qi + // base quad Pi * (2*Ri - Pi - 1) + // p-r triangles; Qi * (2*Ri - Qi - 1); // q-r triangles; return nCoeff + StdTetData::getNumberOfCoefficients(Pi-1, Qi-1, Ri-1); } inline int getNumberOfBndCoefficients(int Na, int Nb, int Nc) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); ASSERTL1(Nb <= Nc, "Order in 'b' direction is higher " "than order in 'c' direction."); return Na*Nb // base + 2*(Na*(Na+1)/2 + (Nc-Na)*Na) // front and back + 2*(Nb*(Nb+1)/2 + (Nc-Nb)*Nb) // sides - 2*Na - 2*Nb - 4*Nc // less edges + 5; // plus vertices } } namespace StdPrismData { inline int getNumberOfCoefficients( int Na, int Nb, int Nc ) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); return Nb*StdTriData::getNumberOfCoefficients(Na,Nc); } inline int getNumberOfBndCoefficients( int Na, int Nb, int Nc) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); return Na*Nb + 2*Nb*Nc // rect faces + 2*( Na*(Na+1)/2 + (Nc-Na)*Na ) // tri faces - 2*Na - 3*Nb - 4*Nc // less edges + 6; // plus vertices } } inline int GetNumberOfCoefficients(ShapeType shape, std::vector<unsigned int> &modes, int offset) { int returnval = 0; switch(shape) { case eSegment: returnval = modes[offset]; break; case eTriangle: returnval = StdTriData::getNumberOfCoefficients(modes[offset],modes[offset+1]); break; case eQuadrilateral: returnval = modes[offset]*modes[offset+1]; break; case eTetrahedron: returnval = StdTetData::getNumberOfCoefficients(modes[offset],modes[offset+1],modes[offset+2]); break; case ePyramid: returnval = StdPyrData::getNumberOfCoefficients(modes[offset],modes[offset+1],modes[offset+2]); break; case ePrism: returnval = StdPrismData::getNumberOfCoefficients(modes[offset],modes[offset+1],modes[offset+2]); break; case eHexahedron: returnval = modes[offset]*modes[offset+1]*modes[offset+2]; break; default: ASSERTL0(false,"Unknown Shape Type"); break; } return returnval; } } } #endif <commit_msg>Fix issue with interior tetrahedron modes.<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: ShapeType.h // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHAPE_TYPE_H #define NEKTAR_LIB_UTILITIES_BASIC_UTILS_SHAPE_TYPE_H #include <algorithm> #include <LibUtilities/BasicUtils/ErrorUtil.hpp> #ifdef min #undef min #endif namespace Nektar { namespace LibUtilities { // Types of geometry types. enum ShapeType { eNoShapeType, ePoint, eSegment, eTriangle, eQuadrilateral, eTetrahedron, ePyramid, ePrism, eHexahedron, SIZE_ShapeType }; const char* const ShapeTypeMap[] = { "NoGeomShapeType", "Point", "Segment", "Triangle", "Quadrilateral", "Tetrahedron", "Pyramid", "Prism", "Hexahedron" }; // Hold the dimension of each of the types of shapes. const unsigned int ShapeTypeDimMap[SIZE_ShapeType] = { 0, // Unknown 0, // ePoint 1, // eSegment 2, // eTriangle 2, // eQuadrilateral 3, // eTetrahedron 3, // ePyramid 3, // ePrism 3, // eHexahedron }; namespace StdSegData { inline int getNumberOfCoefficients(int Na) { return Na; } inline int getNumberOfBndCoefficients(int Na) { return 2; } } // Dimensions of coefficients for each space namespace StdTriData { inline int getNumberOfCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Na <= Nb, "order in 'a' direction is higher " "than order in 'b' direction"); return Na*(Na+1)/2 + Na*(Nb-Na); } inline int getNumberOfBndCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Na <= Nb, "order in 'a' direction is higher " "than order in 'b' direction"); return (Na-1) + 2*(Nb-1); } } namespace StdQuadData { inline int getNumberOfCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); return Na*Nb; } inline int getNumberOfBndCoefficients(int Na, int Nb) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); return 2*(Na-1) + 2*(Nb-1); } } namespace StdHexData { inline int getNumberOfCoefficients( int Na, int Nb, int Nc ) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); return Na*Nb*Nc; } inline int getNumberOfBndCoefficients(int Na, int Nb, int Nc) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); return 2*Na*Nb + 2*Na*Nc + 2*Nb*Nc - 4*(Na + Nb + Nc) + 8; } } namespace StdTetData { /** * Adds up the number of cells in a truncated Nc by Nc by Nc * pyramid, where the longest Na rows and longest Nb columns are * kept. Example: (Na, Nb, Nc) = (3, 4, 5); The number of * coefficients is the sum of the elements of the following * matrix: * * |5 4 3 2 0| * |4 3 2 0 | * |3 2 0 | * |0 0 | * |0 | * * Sum = 28 = number of tet coefficients. */ inline int getNumberOfCoefficients(int Na, int Nb, int Nc) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "order in 'a' direction is higher " "than order in 'c' direction"); ASSERTL1(Nb <= Nc, "order in 'b' direction is higher " "than order in 'c' direction"); int nCoef = 0; for (int a = 0; a < Na; ++a) { for (int b = 0; b < Nb - a; ++b) { for (int c = 0; c < Nc - a - b; ++c) { ++nCoef; } } } return nCoef; } inline int getNumberOfBndCoefficients(int Na, int Nb, int Nc) { ASSERTL2(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL2(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL2(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "order in 'a' direction is higher " "than order in 'c' direction"); ASSERTL1(Nb <= Nc, "order in 'b' direction is higher " "than order in 'c' direction"); int nCoef = Na*(Na+1)/2 + (Nb-Na)*Na // base + Na*(Na+1)/2 + (Nc-Na)*Na // front + 2*(Nb*(Nb+1)/2 + (Nc-Nb)*Nb)// 2 other sides - Na - 2*Nb - 3*Nc // less edges + 4; // plus vertices return nCoef; } } namespace StdPyrData { inline int getNumberOfCoefficients(int Na, int Nb, int Nc) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); ASSERTL1(Nb <= Nc, "Order in 'b' direction is higher " "than order in 'c' direction."); // Count number of coefficients explicitly. const int Pi = Na - 2, Qi = Nb - 2, Ri = Nc - 2; int nCoeff = 5 + // vertices Pi * 2 + Qi * 2 + Ri * 4 + // base edges Pi * Qi + // base quad Pi * (2*Ri - Pi - 1) + // p-r triangles; Qi * (2*Ri - Qi - 1); // q-r triangles; // Count number of interior tet modes for (int a = 0; a < Pi - 1; ++a) { for (int b = 0; b < Qi - a - 1; ++b) { for (int c = 0; c < Ri - a - b -1; ++c) { ++nCoeff; } } } return nCoeff; } inline int getNumberOfBndCoefficients(int Na, int Nb, int Nc) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); ASSERTL1(Nb <= Nc, "Order in 'b' direction is higher " "than order in 'c' direction."); return Na*Nb // base + 2*(Na*(Na+1)/2 + (Nc-Na)*Na) // front and back + 2*(Nb*(Nb+1)/2 + (Nc-Nb)*Nb) // sides - 2*Na - 2*Nb - 4*Nc // less edges + 5; // plus vertices } } namespace StdPrismData { inline int getNumberOfCoefficients( int Na, int Nb, int Nc ) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); return Nb*StdTriData::getNumberOfCoefficients(Na,Nc); } inline int getNumberOfBndCoefficients( int Na, int Nb, int Nc) { ASSERTL1(Na > 1, "Order in 'a' direction must be > 1."); ASSERTL1(Nb > 1, "Order in 'b' direction must be > 1."); ASSERTL1(Nc > 1, "Order in 'c' direction must be > 1."); ASSERTL1(Na <= Nc, "Order in 'a' direction is higher " "than order in 'c' direction."); return Na*Nb + 2*Nb*Nc // rect faces + 2*( Na*(Na+1)/2 + (Nc-Na)*Na ) // tri faces - 2*Na - 3*Nb - 4*Nc // less edges + 6; // plus vertices } } inline int GetNumberOfCoefficients(ShapeType shape, std::vector<unsigned int> &modes, int offset) { int returnval = 0; switch(shape) { case eSegment: returnval = modes[offset]; break; case eTriangle: returnval = StdTriData::getNumberOfCoefficients(modes[offset],modes[offset+1]); break; case eQuadrilateral: returnval = modes[offset]*modes[offset+1]; break; case eTetrahedron: returnval = StdTetData::getNumberOfCoefficients(modes[offset],modes[offset+1],modes[offset+2]); break; case ePyramid: returnval = StdPyrData::getNumberOfCoefficients(modes[offset],modes[offset+1],modes[offset+2]); break; case ePrism: returnval = StdPrismData::getNumberOfCoefficients(modes[offset],modes[offset+1],modes[offset+2]); break; case eHexahedron: returnval = modes[offset]*modes[offset+1]*modes[offset+2]; break; default: ASSERTL0(false,"Unknown Shape Type"); break; } return returnval; } } } #endif <|endoftext|>
<commit_before>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AprMd5.hxx" #include "util/StringCompare.hxx" #include "util/StringView.hxx" #include <openssl/md5.h> #include <algorithm> /** * A C++ wrapper for libcrypto's MD5_CTX. */ class CryptoMD5 { MD5_CTX ctx; public: CryptoMD5() noexcept { MD5_Init(&ctx); } auto &Update(ConstBuffer<void> b) noexcept { MD5_Update(&ctx, b.data, b.size); return *this; } auto &Update(StringView s) noexcept { return Update(s.ToVoid()); } template<typename T, size_t size> auto &Update(const std::array<T, size> &a) noexcept { return Update(ConstBuffer<T>(&a.front(), a.size()).ToVoid()); } std::array<uint8_t, MD5_DIGEST_LENGTH> Final() noexcept { std::array<uint8_t, MD5_DIGEST_LENGTH> md; MD5_Final(&md.front(), &ctx); return md; } }; static constexpr char apr1_id[] = "$apr1$"; gcc_pure static StringView ExtractSalt(const char *s) noexcept { if (auto after_apr1_id = StringAfterPrefix(s, apr1_id)) s = after_apr1_id; const char *dollar = strchr(s, '$'); size_t length = dollar != nullptr ? size_t(dollar - s) : strlen(s); return {s, std::min<size_t>(length, 8)}; } template<typename T> static char * To64(char *s, T v, size_t n) noexcept { static constexpr char itoa64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < n; ++i) { *s++ = itoa64[v & 0x3f]; v >>= 6; } return s; } bool IsAprMd5(const char *crypted_password) noexcept { return StringAfterPrefix(crypted_password, apr1_id) != nullptr; } StringBuffer<120> AprMd5(const char *_pw, const char *_salt) noexcept { const StringView pw(_pw); const auto salt = ExtractSalt(_salt); CryptoMD5 ctx; ctx.Update(pw); ctx.Update(apr1_id); ctx.Update(salt); auto f = CryptoMD5().Update(pw).Update(salt).Update(pw).Final(); for (ssize_t i = pw.size; i > 0; i -= MD5_DIGEST_LENGTH) ctx.Update({&f.front(), std::min<size_t>(i, MD5_DIGEST_LENGTH)}); for (size_t i = pw.size; i != 0; i >>= 1) { if (i & 1) ctx.Update(StringView{"\0", 1}); else ctx.Update(StringView{pw.data, 1}); } f = ctx.Final(); for (unsigned i = 0; i < 1000; ++i) { CryptoMD5 ctx2; if (i & 1) ctx2.Update(pw); else ctx2.Update(f); if (i % 3) ctx2.Update(salt); if (i % 7) ctx2.Update(pw); if (i & 1) ctx2.Update(f); else ctx2.Update(pw); f = ctx2.Final(); } StringBuffer<120> result; char *p = result.data(); p = stpcpy(p, apr1_id); p = (char *)mempcpy(p, salt.data, salt.size); *p++ = '$'; p = To64(p, (f[0] << 16) | (f[6] << 8) | f[12], 4); p = To64(p, (f[1] << 16) | (f[7] << 8) | f[13], 4); p = To64(p, (f[2] << 16) | (f[8] << 8) | f[14], 4); p = To64(p, (f[3] << 16) | (f[9] << 8) | f[15], 4); p = To64(p, (f[4] << 16) | (f[10] << 8) | f[ 5], 4); p = To64(p, f[11], 2); *p = '\0'; return result; } <commit_msg>bp/AprMd5: disable -Wdeprecated-declarations<commit_after>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AprMd5.hxx" #include "util/StringCompare.hxx" #include "util/StringView.hxx" #include <openssl/md5.h> #include <algorithm> #if defined(__GNUC__) && OPENSSL_VERSION_NUMBER >= 0x30000000L /* the MD5 API is deprecated in OpenSSL 3.0, but we want to keep using it */ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif /** * A C++ wrapper for libcrypto's MD5_CTX. */ class CryptoMD5 { MD5_CTX ctx; public: CryptoMD5() noexcept { MD5_Init(&ctx); } auto &Update(ConstBuffer<void> b) noexcept { MD5_Update(&ctx, b.data, b.size); return *this; } auto &Update(StringView s) noexcept { return Update(s.ToVoid()); } template<typename T, size_t size> auto &Update(const std::array<T, size> &a) noexcept { return Update(ConstBuffer<T>(&a.front(), a.size()).ToVoid()); } std::array<uint8_t, MD5_DIGEST_LENGTH> Final() noexcept { std::array<uint8_t, MD5_DIGEST_LENGTH> md; MD5_Final(&md.front(), &ctx); return md; } }; static constexpr char apr1_id[] = "$apr1$"; gcc_pure static StringView ExtractSalt(const char *s) noexcept { if (auto after_apr1_id = StringAfterPrefix(s, apr1_id)) s = after_apr1_id; const char *dollar = strchr(s, '$'); size_t length = dollar != nullptr ? size_t(dollar - s) : strlen(s); return {s, std::min<size_t>(length, 8)}; } template<typename T> static char * To64(char *s, T v, size_t n) noexcept { static constexpr char itoa64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < n; ++i) { *s++ = itoa64[v & 0x3f]; v >>= 6; } return s; } bool IsAprMd5(const char *crypted_password) noexcept { return StringAfterPrefix(crypted_password, apr1_id) != nullptr; } StringBuffer<120> AprMd5(const char *_pw, const char *_salt) noexcept { const StringView pw(_pw); const auto salt = ExtractSalt(_salt); CryptoMD5 ctx; ctx.Update(pw); ctx.Update(apr1_id); ctx.Update(salt); auto f = CryptoMD5().Update(pw).Update(salt).Update(pw).Final(); for (ssize_t i = pw.size; i > 0; i -= MD5_DIGEST_LENGTH) ctx.Update({&f.front(), std::min<size_t>(i, MD5_DIGEST_LENGTH)}); for (size_t i = pw.size; i != 0; i >>= 1) { if (i & 1) ctx.Update(StringView{"\0", 1}); else ctx.Update(StringView{pw.data, 1}); } f = ctx.Final(); for (unsigned i = 0; i < 1000; ++i) { CryptoMD5 ctx2; if (i & 1) ctx2.Update(pw); else ctx2.Update(f); if (i % 3) ctx2.Update(salt); if (i % 7) ctx2.Update(pw); if (i & 1) ctx2.Update(f); else ctx2.Update(pw); f = ctx2.Final(); } StringBuffer<120> result; char *p = result.data(); p = stpcpy(p, apr1_id); p = (char *)mempcpy(p, salt.data, salt.size); *p++ = '$'; p = To64(p, (f[0] << 16) | (f[6] << 8) | f[12], 4); p = To64(p, (f[1] << 16) | (f[7] << 8) | f[13], 4); p = To64(p, (f[2] << 16) | (f[8] << 8) | f[14], 4); p = To64(p, (f[3] << 16) | (f[9] << 8) | f[15], 4); p = To64(p, (f[4] << 16) | (f[10] << 8) | f[ 5], 4); p = To64(p, f[11], 2); *p = '\0'; return result; } <|endoftext|>
<commit_before><commit_msg>Add log return fail<commit_after><|endoftext|>
<commit_before>#include "draw.hpp" #include <algorithm> #include <iostream> #include <sstream> #include "args.hpp" #include "config.hpp" #include "task.hpp" #include "todolist.hpp" #include "typer.hpp" #include "win.hpp" using std::string; using std::stringstream; // ===================| // internal functions | // ===================| std::string buildTitle(TodoList *list); void drawTitle(TodoList* list); void drawControls(); void drawTasks(TodoList* list, unsigned selected); void drawDivider(string div, int ypos); // ===================| // internal variables | // ===================| Win *titleWin; Win *taskWin; Win *controlWin; Win* inputWin; int startX; int startY; int width; int height; unsigned xpos; unsigned ypos; unsigned startTask = 0; unsigned endTask = 0; unsigned int listOff = 0; bool colors = false; ///////////////////////////////////////// // start curses mode and create windows void Draw::init() { std::cout << "\033]0;" << "todo" << "\7" << std::flush; initscr(); raw(); use_default_colors(); if (useColors() && has_colors()){ start_color(); init_pair(TITLE_COLOR_PAIR, TITLE_FOREGROUND, TITLE_BACKGROUND); init_pair(GUTTER_COLOR_PAIR, GUTTER_FOREGROUND, GUTTER_BACKGROUND); init_pair(SELECT_COLOR_PAIR, SELECT_FOREGROUND, SELECT_BACKGROUND); init_pair(BORDER_COLOR_PAIR, BORDER_FOREGROUND, BORDER_BACKGROUND); init_pair(MARK_COLOR_PAIR, MARK_FOREGROUND, MARK_BACKGROUND); init_pair(MARK_COLOR_PAIR_DONE, MARK_FOREGROUND_DONE, MARK_BACKGROUND_DONE); colors = true; } Win::setColors(colors); mouseinterval(0); keypad(stdscr, true); noecho(); clear(); refresh(); curs_set(0); startX = listStartX; startY = listStartY; width = COLS - startX - 2; height = LINES * listHeight; int inHeight = inputHeight * LINES; inHeight = std::max(inHeight, 4); titleWin = new Win(0, 0, COLS, titleHeight, "title", false); taskWin = new Win(startX, startY, width, height, "tasks"); controlWin = new Win(inputStartX, inputStartY, COLS - inputStartX - 2, inHeight, "controls"); inputWin = new Win(inputStartX, inputStartY, COLS - inputStartX - 2, inHeight, "new task"); } ////////////////////// // main draw function void Draw::draw(TodoList *list, unsigned selected) { drawTitle(list); drawControls(); drawTasks(list, selected); } //////////////////////// // act on mouse events void Draw::mouse(MEVENT event, TodoList *list, unsigned &selected, bool button) { int x = event.x; int y = event.y; if (taskWin->mouse(x, y)){ unsigned pos = listOff + y - 1; if (pos < list->size()){ list->adjustPos(pos, listOff); if (!button){ selected = pos; } else{ list->at(pos).toggleComplete(); } } } } /////////////////////////////////////// // get an input string for a new task string Draw::getInput(string str) { return type(inputWin, 128, str); } //////////////////// // draw the title void drawTitle(TodoList* list) { titleWin->clear(); titleWin->inverse(); titleWin->color(TITLE_COLOR_PAIR); titleWin->print(buildTitle(list), 0, 0); titleWin->colorOff(TITLE_COLOR_PAIR); titleWin->inverseOff(); titleWin->color(BORDER_COLOR_PAIR, true); titleWin->draw(); } // draw the control panel void drawControls() { controlWin->clear(); stringstream line; controlWin->move(0, 0); line << "[" << ((char) EXIT_KEY) << "] quit "; line << "[Space] new task "; line << "[" << ((char) MOVE_UP_KEY) << "] move task up "; controlWin->print(line.str()); line.str(""); controlWin->move(0, 1); line << "[" << ((char) REMOVE_KEY) << "] delete task "; line << "[Return] mark task done "; line << "[" << ((char) MOVE_DOWN_KEY) << "] move task down "; controlWin->print(line.str()); line.str(""); controlWin->color(BORDER_COLOR_PAIR, true); controlWin->draw(); } void drawTasks(TodoList* list, unsigned selected) { auto tasks = list->tasks(); taskWin->clear(); if (tasks && tasks->size()){ xpos = 1; ypos = 1; unsigned numTasks = height - 2; endTask = tasks->size(); if (endTask > numTasks) endTask = numTasks; unsigned divCount = 0; for (unsigned i = startTask + listOff; i < endTask + listOff && i < tasks->size(); i++){ if (tasks->at(i).div()) divCount++; } if (numTasks < tasks->size()){ while (selected > (int) endTask + listOff - 2 - divCount && selected != 0) listOff++; while (selected < (int) startTask + listOff && selected != list->size() - 1) listOff--; } else{ listOff = 0; } unsigned count = startTask + listOff; if (startTask + listOff != 0){ if (tasks->at(startTask + listOff - 1).div()){ ypos++; endTask++; } } for (unsigned i = startTask + listOff; i < endTask + listOff && i < tasks->size() ; i++){ Task t = tasks->at(i); if (showNumbers){ taskWin->inverse(); taskWin->color(GUTTER_COLOR_PAIR); std::string number = std::to_string(count); if (!zeroIndexNumbers) number = std::to_string(count + 1); while (number.size() < 2) number = "0"+number; taskWin->print(number + ")", xpos, ypos); taskWin->colorOff(GUTTER_COLOR_PAIR); taskWin->inverseOff(); xpos += 5; } if (i == selected){ std::string tmp = tasks->at(i).task(); if (tasks->at(i).div()){ taskWin->inverse(); taskWin->color(SELECT_COLOR_PAIR); drawDivider(tmp.substr(5, tmp.size() - 5), ypos); taskWin->colorOff(SELECT_COLOR_PAIR); taskWin->inverseOff(); ypos+=2; if (showNumbers){ xpos -= 5; } continue; } std::string line = tmp; if (highlightWholeLine){ for (int k = tmp.size() + xpos; k < width - 2; k++){ line += " "; } } std::string mark = line.substr(0, STRING_COMPLETE.size()); line = line.substr(mark.size()); taskWin->inverse(); taskWin->color(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->print(mark, xpos, ypos); taskWin->colorOff(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->color(SELECT_COLOR_PAIR); taskWin->print(line, xpos + mark.size(), ypos); taskWin->colorOff(SELECT_COLOR_PAIR); taskWin->inverseOff(); } else{ std::string tmp = tasks->at(i).task(); if (tasks->at(i).div()){ drawDivider(tmp.substr(5, tmp.size() - 5), ypos); ypos+= 2; if (showNumbers){ xpos -= 5; } continue; } std::string text = tmp; std::string mark = text.substr(0, STRING_COMPLETE.size()); text = text.substr(mark.size()); taskWin->color(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->print(mark, xpos, ypos); taskWin->colorOff(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->print(text, xpos + mark.size(), ypos); } ypos++; if (ypos > numTasks || i >= tasks->size() - 1){ break; } if (showNumbers){ xpos -= 5; count++; } } } taskWin->color(BORDER_COLOR_PAIR, true); taskWin->draw(); } /////////////////////////////////// // stop curses and delete windows void Draw::stop() { delete titleWin; delete taskWin; delete controlWin; delete inputWin; endwin(); curs_set(1); } // create the title string std::string buildTitle(TodoList *list) { std::string title = "[todo version "+vn+"]"; unsigned cent = (COLS - list->name.size() - 2) / 2; for (unsigned i = title.size(); i < cent; i++){ title += division; } title += "["; title += list->name; title += "]"; std::string stats = "[" + list->completedStr() + "]"; for (unsigned i = title.size() + stats.size(); i < (unsigned)COLS; i++){ title += division; } title += stats; return title; } void drawDivider(string div, int ypos) { while ((int) div.size() < width - 3){ div += division; } taskWin->print(div, 1, ypos); } <commit_msg>fix drawing of long lines<commit_after>#include "draw.hpp" #include <algorithm> #include <iostream> #include <sstream> #include "args.hpp" #include "config.hpp" #include "task.hpp" #include "todolist.hpp" #include "typer.hpp" #include "win.hpp" using std::string; using std::stringstream; // ===================| // internal functions | // ===================| std::string buildTitle(TodoList *list); void drawTitle(TodoList* list); void drawControls(); void drawTasks(TodoList* list, unsigned selected); void drawDivider(string div, int ypos); // ===================| // internal variables | // ===================| Win *titleWin; Win *taskWin; Win *controlWin; Win* inputWin; int startX; int startY; int width; int height; unsigned xpos; unsigned ypos; unsigned startTask = 0; unsigned endTask = 0; unsigned int listOff = 0; bool colors = false; ///////////////////////////////////////// // start curses mode and create windows void Draw::init() { std::cout << "\033]0;" << "todo" << "\7" << std::flush; initscr(); raw(); use_default_colors(); if (useColors() && has_colors()){ start_color(); init_pair(TITLE_COLOR_PAIR, TITLE_FOREGROUND, TITLE_BACKGROUND); init_pair(GUTTER_COLOR_PAIR, GUTTER_FOREGROUND, GUTTER_BACKGROUND); init_pair(SELECT_COLOR_PAIR, SELECT_FOREGROUND, SELECT_BACKGROUND); init_pair(BORDER_COLOR_PAIR, BORDER_FOREGROUND, BORDER_BACKGROUND); init_pair(MARK_COLOR_PAIR, MARK_FOREGROUND, MARK_BACKGROUND); init_pair(MARK_COLOR_PAIR_DONE, MARK_FOREGROUND_DONE, MARK_BACKGROUND_DONE); colors = true; } Win::setColors(colors); mouseinterval(0); keypad(stdscr, true); noecho(); clear(); refresh(); curs_set(0); startX = listStartX; startY = listStartY; width = COLS - startX - 2; height = LINES * listHeight; int inHeight = inputHeight * LINES; inHeight = std::max(inHeight, 4); titleWin = new Win(0, 0, COLS, titleHeight, "title", false); taskWin = new Win(startX, startY, width, height, "tasks"); controlWin = new Win(inputStartX, inputStartY, COLS - inputStartX - 2, inHeight, "controls"); inputWin = new Win(inputStartX, inputStartY, COLS - inputStartX - 2, inHeight, "new task"); } ////////////////////// // main draw function void Draw::draw(TodoList *list, unsigned selected) { drawTitle(list); drawControls(); drawTasks(list, selected); } //////////////////////// // act on mouse events void Draw::mouse(MEVENT event, TodoList *list, unsigned &selected, bool button) { int x = event.x; int y = event.y; if (taskWin->mouse(x, y)){ unsigned pos = listOff + y - 1; if (pos < list->size()){ list->adjustPos(pos, listOff); if (!button){ selected = pos; } else{ list->at(pos).toggleComplete(); } } } } /////////////////////////////////////// // get an input string for a new task string Draw::getInput(string str) { return type(inputWin, 128, str); } //////////////////// // draw the title void drawTitle(TodoList* list) { titleWin->clear(); titleWin->inverse(); titleWin->color(TITLE_COLOR_PAIR); titleWin->print(buildTitle(list), 0, 0); titleWin->colorOff(TITLE_COLOR_PAIR); titleWin->inverseOff(); titleWin->color(BORDER_COLOR_PAIR, true); titleWin->draw(); } // draw the control panel void drawControls() { controlWin->clear(); stringstream line; controlWin->move(0, 0); line << "[" << ((char) EXIT_KEY) << "] quit "; line << "[Space] new task "; line << "[" << ((char) MOVE_UP_KEY) << "] move task up "; controlWin->print(line.str()); line.str(""); controlWin->move(0, 1); line << "[" << ((char) REMOVE_KEY) << "] delete task "; line << "[Return] mark task done "; line << "[" << ((char) MOVE_DOWN_KEY) << "] move task down "; controlWin->print(line.str()); line.str(""); controlWin->color(BORDER_COLOR_PAIR, true); controlWin->draw(); } void drawTasks(TodoList* list, unsigned selected) { auto tasks = list->tasks(); taskWin->clear(); if (tasks && tasks->size()){ xpos = 1; ypos = 1; unsigned numTasks = height - 2; endTask = tasks->size(); if (endTask > numTasks) endTask = numTasks; unsigned divCount = 0; for (unsigned i = startTask + listOff; i < endTask + listOff && i < tasks->size(); i++){ if (tasks->at(i).div()) divCount++; } if (numTasks < tasks->size()){ while (selected > (int) endTask + listOff - 2 - divCount && selected != 0) listOff++; while (selected < (int) startTask + listOff && selected != list->size() - 1) listOff--; } else{ listOff = 0; } unsigned count = startTask + listOff; if (startTask + listOff != 0){ if (tasks->at(startTask + listOff - 1).div()){ ypos++; endTask++; } } for (unsigned i = startTask + listOff; i < endTask + listOff && i < tasks->size() ; i++){ Task t = tasks->at(i); if (showNumbers){ taskWin->inverse(); taskWin->color(GUTTER_COLOR_PAIR); std::string number = std::to_string(count); if (!zeroIndexNumbers) number = std::to_string(count + 1); while (number.size() < 2) number = "0"+number; taskWin->print(number + ")", xpos, ypos); taskWin->colorOff(GUTTER_COLOR_PAIR); taskWin->inverseOff(); xpos += 5; } if (i == selected){ std::string tmp = tasks->at(i).task(); if (tasks->at(i).div()){ taskWin->inverse(); taskWin->color(SELECT_COLOR_PAIR); drawDivider(tmp.substr(5, tmp.size() - 5), ypos); taskWin->colorOff(SELECT_COLOR_PAIR); taskWin->inverseOff(); ypos+=2; if (showNumbers){ xpos -= 5; } continue; } std::string line = tmp; unsigned pad = showNumbers ? 8 : 5; if (line.size() >= width - pad) { line = line.substr(0, width - pad - 3) + "..."; } if (highlightWholeLine){ for (int k = tmp.size() + xpos; k < width - 2; k++){ line += " "; } } std::string mark = line.substr(0, STRING_COMPLETE.size()); line = line.substr(mark.size()); taskWin->inverse(); taskWin->color(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->print(mark, xpos, ypos); taskWin->colorOff(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->color(SELECT_COLOR_PAIR); taskWin->print(line, xpos + mark.size(), ypos); taskWin->colorOff(SELECT_COLOR_PAIR); taskWin->inverseOff(); } else{ std::string tmp = tasks->at(i).task(); if (tasks->at(i).div()){ drawDivider(tmp.substr(5, tmp.size() - 5), ypos); ypos+= 2; if (showNumbers){ xpos -= 5; } continue; } std::string text = tmp; unsigned pad = showNumbers ? 8 : 5; if (text.size() >= width - pad) { text = text.substr(0, width - pad - 3) + "..."; } std::string mark = text.substr(0, STRING_COMPLETE.size()); text = text.substr(mark.size()); taskWin->color(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->print(mark, xpos, ypos); taskWin->colorOff(!t.completed() ? MARK_COLOR_PAIR : MARK_COLOR_PAIR_DONE); taskWin->print(text, xpos + mark.size(), ypos); } ypos++; if (ypos > numTasks || i >= tasks->size() - 1){ break; } if (showNumbers){ xpos -= 5; count++; } } } taskWin->color(BORDER_COLOR_PAIR, true); taskWin->draw(); } /////////////////////////////////// // stop curses and delete windows void Draw::stop() { delete titleWin; delete taskWin; delete controlWin; delete inputWin; endwin(); curs_set(1); } // create the title string std::string buildTitle(TodoList *list) { std::string title = "[todo version "+vn+"]"; unsigned cent = (COLS - list->name.size() - 2) / 2; for (unsigned i = title.size(); i < cent; i++){ title += division; } title += "["; title += list->name; title += "]"; std::string stats = "[" + list->completedStr() + "]"; for (unsigned i = title.size() + stats.size(); i < (unsigned)COLS; i++){ title += division; } title += stats; return title; } void drawDivider(string div, int ypos) { while ((int) div.size() < width - 3){ div += division; } taskWin->print(div, 1, ypos); } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "EyeTrackerRemoteFactory.h" #include "VRPNConnectionCollection.h" #include <osvr/Common/ClientInterface.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Util/ChannelCountC.h> #include <osvr/Util/UniquePtr.h> #include <osvr/Common/OriginalSource.h> #include "InterfaceTree.h" #include <osvr/Util/Verbosity.h> #include <osvr/Common/CreateDevice.h> #include <osvr/Common/EyeTrackerComponent.h> #include <osvr/Common/Location2DComponent.h> #include <osvr/Common/DirectionComponent.h> #include <osvr/Common/RoutingConstants.h> #include <osvr/Common/InterfaceState.h> // Library/third-party includes #include <boost/lexical_cast.hpp> #include <boost/any.hpp> #include <boost/variant/get.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <json/value.h> #include <json/reader.h> // Standard includes #include <iostream> #include <string> namespace osvr { namespace client { class EyeTrackerRemoteHandler : public RemoteHandler { public: struct Options { Options() : reportDirection(false), reportBasePoint(false), reportLocation2D(false), reportBlink(false), dirIface() {} bool reportDirection; bool reportBasePoint; bool reportLocation2D; bool reportBlink; osvr::common::ClientInterfacePtr dirIface; osvr::common::ClientInterfacePtr locationIface; osvr::common::ClientInterfacePtr trackerIface; osvr::common::ClientInterfacePtr buttonIface; }; EyeTrackerRemoteHandler(vrpn_ConnectionPtr const &conn, std::string const &deviceName, Options const &options, boost::optional<OSVR_ChannelCount> sensor, common::InterfaceList &ifaces) : m_dev(common::createClientDevice(deviceName, conn)), m_interfaces(ifaces), m_all(!sensor.is_initialized()), m_opts(options), m_sensor(sensor) { auto eyetracker = common::EyeTrackerComponent::create(); m_dev->addComponent(eyetracker); eyetracker->registerEyeHandler( [&](common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { m_handleEyeTracking(data, timestamp); }); OSVR_DEV_VERBOSE("Constructed an Eye Handler for " << deviceName); } /// @brief Deleted assignment operator. EyeTrackerRemoteHandler & operator=(EyeTrackerRemoteHandler const &) = delete; virtual ~EyeTrackerRemoteHandler() { /// @todo do we need to unregister? } virtual void update() { m_dev->update(); } private: void m_handleEyeTracking3d(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { OSVR_EyeTracker3DReport report; report.sensor = data.sensor; report.state.directionValid = false; report.state.basePointValid = false; util::time::TimeValue timest = timestamp; if (m_opts.reportDirection) { report.state.directionValid = m_opts.dirIface->getState<OSVR_DirectionReport>( timest, report.state.direction); } if (m_opts.reportBasePoint) { report.state.basePointValid = m_opts.trackerIface->getState<OSVR_PositionReport>( timest, report.state.basePoint); } if (!(report.state.basePointValid || report.state.directionValid)) { return; // don't send an empty report. } /// @todo what timestamp do we use - the one from the notification /// or the ones from the original reports? At least right now /// they're theoretically the same, but... for (auto &iface : m_interfaces) { iface->triggerCallbacks(timestamp, report); } } void m_handleEyeTracking2d(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { if (!m_opts.reportLocation2D) { return; } OSVR_EyeTracker2DReport report; report.sensor = data.sensor; bool locationValid = false; util::time::TimeValue reportTime; locationValid = m_opts.locationIface->getState<OSVR_Location2DReport>( reportTime, report.state); if (!locationValid) { return; // don't send an empty report. } /// @todo what timestamp do we use - the one from the notification /// or the one from the original report? At least right now they're /// the same, but... for (auto &iface : m_interfaces) { iface->triggerCallbacks(timestamp, report); } } void m_handleEyeBlink(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { if (!m_opts.reportBlink) { return; } OSVR_EyeTrackerBlinkReport report; report.sensor = data.sensor; bool haveBlink = false; util::time::TimeValue blinkTimestamp; haveBlink = m_opts.locationIface->getState<OSVR_ButtonReport>( blinkTimestamp, report.state); if (!haveBlink) { return; // don't send an empty report. } /// @todo what timestamp do we use - the one from the notification /// or the one from the original report? At least right now they're /// the same, but... for (auto &iface : m_interfaces) { iface->triggerCallbacks(timestamp, report); } } void m_handleEyeTracking(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { if (!m_all && *m_sensor != data.sensor) { /// doesn't match our filter. return; } m_handleEyeTracking3d(data, timestamp); m_handleEyeTracking2d(data, timestamp); m_handleEyeBlink(data, timestamp); } common::BaseDevicePtr m_dev; common::InterfaceList &m_interfaces; bool m_all; Options m_opts; boost::optional<OSVR_ChannelCount> m_sensor; }; EyeTrackerRemoteFactory::EyeTrackerRemoteFactory( VRPNConnectionCollection const &conns) : m_conns(conns) {} shared_ptr<RemoteHandler> EyeTrackerRemoteFactory:: operator()(common::OriginalSource const &source, common::InterfaceList &ifaces, common::ClientContext &ctx) { shared_ptr<RemoteHandler> ret; EyeTrackerRemoteHandler::Options opts; auto myDescriptor = source.getDeviceElement().getDescriptor(); auto devicePath = source.getDevicePath(); if (myDescriptor["interfaces"]["eyetracker"].isMember("direction")) { opts.reportDirection = true; const std::string iface = devicePath + "/direction"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.dirIface = ctx.getInterface(iface.c_str()); } if (myDescriptor["interfaces"]["eyetracker"].isMember("tracker")) { opts.reportBasePoint = true; const std::string iface = devicePath + "/tracker/"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.trackerIface = ctx.getInterface(iface.c_str()); } if (myDescriptor["interfaces"]["eyetracker"].isMember("location2D")) { opts.reportLocation2D = true; const std::string iface = devicePath + "/location2D/"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.locationIface = ctx.getInterface(iface.c_str()); } if (myDescriptor["interfaces"]["eyetracker"].isMember("button")) { opts.reportBlink = true; const std::string iface = devicePath + "/button/"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.buttonIface = ctx.getInterface(iface.c_str()); } if (source.hasTransform()) { OSVR_DEV_VERBOSE( "Ignoring transform found on route for Eye Tracker data!"); } auto const &devElt = source.getDeviceElement(); ret.reset(new EyeTrackerRemoteHandler( m_conns.getConnection(devElt), devElt.getFullDeviceName(), opts, source.getSensorNumberAsChannelCount(), ifaces)); return ret; } } // namespace client } // namespace osvr<commit_msg>Const ref descriptor access.<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "EyeTrackerRemoteFactory.h" #include "VRPNConnectionCollection.h" #include <osvr/Common/ClientInterface.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Util/ChannelCountC.h> #include <osvr/Util/UniquePtr.h> #include <osvr/Common/OriginalSource.h> #include "InterfaceTree.h" #include <osvr/Util/Verbosity.h> #include <osvr/Common/CreateDevice.h> #include <osvr/Common/EyeTrackerComponent.h> #include <osvr/Common/Location2DComponent.h> #include <osvr/Common/DirectionComponent.h> #include <osvr/Common/RoutingConstants.h> #include <osvr/Common/InterfaceState.h> // Library/third-party includes #include <boost/lexical_cast.hpp> #include <boost/any.hpp> #include <boost/variant/get.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <json/value.h> #include <json/reader.h> // Standard includes #include <iostream> #include <string> namespace osvr { namespace client { class EyeTrackerRemoteHandler : public RemoteHandler { public: struct Options { Options() : reportDirection(false), reportBasePoint(false), reportLocation2D(false), reportBlink(false), dirIface() {} bool reportDirection; bool reportBasePoint; bool reportLocation2D; bool reportBlink; osvr::common::ClientInterfacePtr dirIface; osvr::common::ClientInterfacePtr locationIface; osvr::common::ClientInterfacePtr trackerIface; osvr::common::ClientInterfacePtr buttonIface; }; EyeTrackerRemoteHandler(vrpn_ConnectionPtr const &conn, std::string const &deviceName, Options const &options, boost::optional<OSVR_ChannelCount> sensor, common::InterfaceList &ifaces) : m_dev(common::createClientDevice(deviceName, conn)), m_interfaces(ifaces), m_all(!sensor.is_initialized()), m_opts(options), m_sensor(sensor) { auto eyetracker = common::EyeTrackerComponent::create(); m_dev->addComponent(eyetracker); eyetracker->registerEyeHandler( [&](common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { m_handleEyeTracking(data, timestamp); }); OSVR_DEV_VERBOSE("Constructed an Eye Handler for " << deviceName); } /// @brief Deleted assignment operator. EyeTrackerRemoteHandler & operator=(EyeTrackerRemoteHandler const &) = delete; virtual ~EyeTrackerRemoteHandler() { /// @todo do we need to unregister? } virtual void update() { m_dev->update(); } private: void m_handleEyeTracking3d(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { OSVR_EyeTracker3DReport report; report.sensor = data.sensor; report.state.directionValid = false; report.state.basePointValid = false; util::time::TimeValue timest = timestamp; if (m_opts.reportDirection) { report.state.directionValid = m_opts.dirIface->getState<OSVR_DirectionReport>( timest, report.state.direction); } if (m_opts.reportBasePoint) { report.state.basePointValid = m_opts.trackerIface->getState<OSVR_PositionReport>( timest, report.state.basePoint); } if (!(report.state.basePointValid || report.state.directionValid)) { return; // don't send an empty report. } /// @todo what timestamp do we use - the one from the notification /// or the ones from the original reports? At least right now /// they're theoretically the same, but... for (auto &iface : m_interfaces) { iface->triggerCallbacks(timestamp, report); } } void m_handleEyeTracking2d(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { if (!m_opts.reportLocation2D) { return; } OSVR_EyeTracker2DReport report; report.sensor = data.sensor; bool locationValid = false; util::time::TimeValue reportTime; locationValid = m_opts.locationIface->getState<OSVR_Location2DReport>( reportTime, report.state); if (!locationValid) { return; // don't send an empty report. } /// @todo what timestamp do we use - the one from the notification /// or the one from the original report? At least right now they're /// the same, but... for (auto &iface : m_interfaces) { iface->triggerCallbacks(timestamp, report); } } void m_handleEyeBlink(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { if (!m_opts.reportBlink) { return; } OSVR_EyeTrackerBlinkReport report; report.sensor = data.sensor; bool haveBlink = false; util::time::TimeValue blinkTimestamp; haveBlink = m_opts.locationIface->getState<OSVR_ButtonReport>( blinkTimestamp, report.state); if (!haveBlink) { return; // don't send an empty report. } /// @todo what timestamp do we use - the one from the notification /// or the one from the original report? At least right now they're /// the same, but... for (auto &iface : m_interfaces) { iface->triggerCallbacks(timestamp, report); } } void m_handleEyeTracking(common::OSVR_EyeNotification const &data, util::time::TimeValue const &timestamp) { if (!m_all && *m_sensor != data.sensor) { /// doesn't match our filter. return; } m_handleEyeTracking3d(data, timestamp); m_handleEyeTracking2d(data, timestamp); m_handleEyeBlink(data, timestamp); } common::BaseDevicePtr m_dev; common::InterfaceList &m_interfaces; bool m_all; Options m_opts; boost::optional<OSVR_ChannelCount> m_sensor; }; EyeTrackerRemoteFactory::EyeTrackerRemoteFactory( VRPNConnectionCollection const &conns) : m_conns(conns) {} shared_ptr<RemoteHandler> EyeTrackerRemoteFactory:: operator()(common::OriginalSource const &source, common::InterfaceList &ifaces, common::ClientContext &ctx) { shared_ptr<RemoteHandler> ret; EyeTrackerRemoteHandler::Options opts; auto const &myDescriptor = source.getDeviceElement().getDescriptor(); auto devicePath = source.getDevicePath(); if (myDescriptor["interfaces"]["eyetracker"].isMember("direction")) { opts.reportDirection = true; const std::string iface = devicePath + "/direction"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.dirIface = ctx.getInterface(iface.c_str()); } if (myDescriptor["interfaces"]["eyetracker"].isMember("tracker")) { opts.reportBasePoint = true; const std::string iface = devicePath + "/tracker/"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.trackerIface = ctx.getInterface(iface.c_str()); } if (myDescriptor["interfaces"]["eyetracker"].isMember("location2D")) { opts.reportLocation2D = true; const std::string iface = devicePath + "/location2D/"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.locationIface = ctx.getInterface(iface.c_str()); } if (myDescriptor["interfaces"]["eyetracker"].isMember("button")) { opts.reportBlink = true; const std::string iface = devicePath + "/button/"; /// @todo need to append sensor number here! // boost::lexical_cast<std::string>(source.getSensorNumberAsChannelCount()) opts.buttonIface = ctx.getInterface(iface.c_str()); } if (source.hasTransform()) { OSVR_DEV_VERBOSE( "Ignoring transform found on route for Eye Tracker data!"); } auto const &devElt = source.getDeviceElement(); ret.reset(new EyeTrackerRemoteHandler( m_conns.getConnection(devElt), devElt.getFullDeviceName(), opts, source.getSensorNumberAsChannelCount(), ifaces)); return ret; } } // namespace client } // namespace osvr<|endoftext|>
<commit_before>// // peglint.cc // // Copyright (c) 2015 Yuji Hirose. All rights reserved. // MIT License // #include <peglib.h> #include <fstream> using namespace std; bool read_file(const char* path, vector<char>& buff) { ifstream ifs(path, ios::in | ios::binary); if (ifs.fail()) { return false; } buff.resize(ifs.seekg(0, ios::end).tellg()); ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size())); return true; } int main(int argc, const char** argv) { if (argc < 2 || string("--help") == argv[1]) { cerr << "usage: peglint [grammar file path] [source file path]" << endl; return 1; } // Check PEG grammar auto syntax_path = argv[1]; vector<char> syntax; if (!read_file(syntax_path, syntax)) { cerr << "can't open the grammar file." << endl; return -1; } peglib::peg peg(syntax.data(), syntax.size(), [&](size_t ln, size_t col, const string& msg) { cerr << syntax_path << ":" << ln << ":" << col << ": " << msg << endl; }); if (!peg) { return -1; } if (argc < 3) { return 0; } // Check source auto source_path = argv[2]; vector<char> source; if (!read_file(source_path, source)) { cerr << "can't open the source file." << endl; return -1; } auto ret = peg.lint(source.data(), source.size(), true, [&](size_t ln, size_t col, const string& msg) { cerr << source_path << ":" << ln << ":" << col << ": " << msg << endl; }); if (ret) { peg.parse(source.data(), source.size()); } return ret ? 0 : -1; } // vim: et ts=4 sw=4 cin cino={1s ff=unix <commit_msg>Fixed compiler warning.<commit_after>// // peglint.cc // // Copyright (c) 2015 Yuji Hirose. All rights reserved. // MIT License // #include <peglib.h> #include <fstream> using namespace std; bool read_file(const char* path, vector<char>& buff) { ifstream ifs(path, ios::in | ios::binary); if (ifs.fail()) { return false; } buff.resize(static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg())); ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size())); return true; } int main(int argc, const char** argv) { if (argc < 2 || string("--help") == argv[1]) { cerr << "usage: peglint [grammar file path] [source file path]" << endl; return 1; } // Check PEG grammar auto syntax_path = argv[1]; vector<char> syntax; if (!read_file(syntax_path, syntax)) { cerr << "can't open the grammar file." << endl; return -1; } peglib::peg peg(syntax.data(), syntax.size(), [&](size_t ln, size_t col, const string& msg) { cerr << syntax_path << ":" << ln << ":" << col << ": " << msg << endl; }); if (!peg) { return -1; } if (argc < 3) { return 0; } // Check source auto source_path = argv[2]; vector<char> source; if (!read_file(source_path, source)) { cerr << "can't open the source file." << endl; return -1; } auto ret = peg.lint(source.data(), source.size(), true, [&](size_t ln, size_t col, const string& msg) { cerr << source_path << ":" << ln << ":" << col << ": " << msg << endl; }); if (ret) { peg.parse(source.data(), source.size()); } return ret ? 0 : -1; } // vim: et ts=4 sw=4 cin cino={1s ff=unix <|endoftext|>
<commit_before>/* This file is part of the Multivariate Splines library. Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <vector> #include <datatable.h> #include <sstream> #include <cmath> // abs, nextafter #include <fstream> #include <iostream> #include <iomanip> #include <string> #include "bspline.h" #include "pspline.h" #include "rbfspline.h" using std::cout; using std::endl; using namespace MultivariateSplines; // Checks if a is within margin of b bool equalsWithinRange(double a, double b, double margin = 0.0) { return b - margin <= a && a <= b + margin; } bool is_identical(DataTable &a, DataTable &b) { if(a.getNumVariables() != b.getNumVariables()) return false; auto ait = a.cbegin(), bit = b.cbegin(); for(; ait != a.cend() && bit != b.cend(); ait++, bit++) { for(int i = 0; i < a.getNumVariables(); i++) { // std::cout << std::setprecision(SAVE_DOUBLE_PRECISION) << ait->getX().at(i) << " == " << std::setprecision(SAVE_DOUBLE_PRECISION) << bit->getX().at(i) << " "; if(!equalsWithinRange(ait->getX().at(i), bit->getX().at(i))) return false; } // std::cout << std::setprecision(SAVE_DOUBLE_PRECISION) << ait->getY().at(j) << " == " << std::setprecision(SAVE_DOUBLE_PRECISION) << bit->getY().at(j) << " "; if(!equalsWithinRange(ait->getY(), bit->getY())) return false; // std::cout << std::endl; } // std::cout << "Finished comparing samples..." << std::endl; return ait == a.cend() && bit == b.cend(); } bool test1() { DataTable table; auto x = std::vector<double>(1); double y; for(double i = -0.3; i <= 0.3; i += 0.04) { x.at(0) = i; y = 2 * i; table.addSample(x, y); } table.save("test1.datatable"); DataTable loadedTable; loadedTable.load("test1.datatable"); return is_identical(table, loadedTable); } bool test2() { DataTable table; auto x = std::vector<double>(2); double y; for(double i = -0.3; i <= 0.3; i += 0.04) { for(double j = -0.4; j <= 1.0; j += 0.08) { x.at(0) = i; x.at(1) = j; y = i * j; table.addSample(x, y); } } table.save("test2.datatable"); DataTable loadedTable; loadedTable.load("test2.datatable"); return is_identical(table, loadedTable); } bool test3() { DataTable table; auto x = std::vector<double>(2); double y; for(double i = -0.3; i <= 0.3; i += 0.04) { for(double j = -0.4; j <= 1.0; j += 0.03) { x.at(0) = i; x.at(1) = j; y = i * j; table.addSample(x, y); } } table.save("test3.datatable"); DataTable loadedTable; loadedTable.load("test3.datatable"); return is_identical(table, loadedTable); } bool test4() { DataTable table; auto x = std::vector<double>(3); double y; for(double i = -0.0001; i <= 0.0001; i += 0.000001) { for(double j = -0.01; j <= 0.01; j += 0.001) { for(double k = -0.01; k <= 0.01; k += 0.001) { x.at(0) = i; x.at(1) = j; x.at(2) = k; y = i * j; table.addSample(x, y); } } } table.save("test4.datatable"); DataTable loadedTable; loadedTable.load("test4.datatable"); return is_identical(table, loadedTable); } bool test5() { DataTable table; auto x = std::vector<double>(4); double y; for(double i = -0.0001; i <= 0.0001; i += 0.000001) { for(double j = -0.01; j <= 0.01; j += 0.001) { for(double k = -0.01; k <= 0.01; k += 0.001) { for(double l = -100000.0; l < 0.0; l += 13720.0) { x.at(0) = i; x.at(1) = j; x.at(2) = k; x.at(3) = l; y = i * j; table.addSample(x, y); } } } } table.save("test5.datatable"); DataTable loadedTable; loadedTable.load("test5.datatable"); return is_identical(table, loadedTable); } bool test6() { DataTable table; auto x = std::vector<double>(4); double y; int j = 0; for(double i = std::numeric_limits<double>::lowest(), k = std::numeric_limits<double>::max(); j < 10000; i = nextafter(i, std::numeric_limits<double>::max()), k = nextafter(k, std::numeric_limits<double>::lowest())) { x.at(0) = i; y = k; table.addSample(x, y); j++; } table.save("test6.datatable"); DataTable loadedTable; loadedTable.load("test6.datatable"); return is_identical(table, loadedTable); } // Six-hump camelback function double f(DenseVector x) { assert(x.rows() == 2); return (4 - 2.1*x(0)*x(0) + (1/3.)*x(0)*x(0)*x(0)*x(0))*x(0)*x(0) + x(0)*x(1) + (-4 + 4*x(1)*x(1))*x(1)*x(1); } void runExample() { // Create new DataTable to manage samples DataTable samples; // Sample function DenseVector x(2); double y; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { // Sample function at x x(0) = i*0.1; x(1) = j*0.1; y = f(x); // Store sample samples.addSample(x,y); } } // Build B-splines that interpolate the samples BSpline bspline1(samples, BSplineType::LINEAR); BSpline bspline3(samples, BSplineType::CUBIC_FREE); // Build penalized B-spline (P-spline) that smooths the samples PSpline pspline(samples, 0.03); // Build radial basis function spline that interpolate the samples RBFSpline rbfspline(samples, RadialBasisFunctionType::THIN_PLATE_SPLINE); // Evaluate the splines at x = (1,1) x(0) = 1; x(1) = 1; cout << "-------------------------------------------" << endl; cout << "Function at x: " << f(x) << endl; cout << "Linear B-spline at x: " << bspline1.eval(x) << endl; cout << "Cubic B-spline at x: " << bspline3.eval(x) << endl; cout << "P-spline at x: " << pspline.eval(x) << endl; cout << "Thin-plate spline at x: " << rbfspline.eval(x) << endl; cout << "-------------------------------------------" << endl; } int main(int argc, char **argv) { runExample(); exit(1); cout << "test1(): " << (test1() ? "success" : "fail") << endl; cout << "test2(): " << (test2() ? "success" : "fail") << endl; cout << "test3(): " << (test3() ? "success" : "fail") << endl; cout << "test4(): " << (test4() ? "success" : "fail") << endl; cout << "test5(): " << (test5() ? "success" : "fail") << endl; cout << "test6(): " << (test6() ? "success" : "fail") << endl; return 0; } <commit_msg>Enabled all tests<commit_after>/* This file is part of the Multivariate Splines library. Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <vector> #include <datatable.h> #include <sstream> #include <cmath> // abs, nextafter #include <fstream> #include <iostream> #include <iomanip> #include <string> #include "bspline.h" #include "pspline.h" #include "rbfspline.h" using std::cout; using std::endl; using namespace MultivariateSplines; // Checks if a is within margin of b bool equalsWithinRange(double a, double b, double margin = 0.0) { return b - margin <= a && a <= b + margin; } bool is_identical(DataTable &a, DataTable &b) { if(a.getNumVariables() != b.getNumVariables()) return false; auto ait = a.cbegin(), bit = b.cbegin(); for(; ait != a.cend() && bit != b.cend(); ait++, bit++) { for(int i = 0; i < a.getNumVariables(); i++) { // std::cout << std::setprecision(SAVE_DOUBLE_PRECISION) << ait->getX().at(i) << " == " << std::setprecision(SAVE_DOUBLE_PRECISION) << bit->getX().at(i) << " "; if(!equalsWithinRange(ait->getX().at(i), bit->getX().at(i))) return false; } // std::cout << std::setprecision(SAVE_DOUBLE_PRECISION) << ait->getY().at(j) << " == " << std::setprecision(SAVE_DOUBLE_PRECISION) << bit->getY().at(j) << " "; if(!equalsWithinRange(ait->getY(), bit->getY())) return false; // std::cout << std::endl; } // std::cout << "Finished comparing samples..." << std::endl; return ait == a.cend() && bit == b.cend(); } bool test1() { DataTable table; auto x = std::vector<double>(1); double y; for(double i = -0.3; i <= 0.3; i += 0.04) { x.at(0) = i; y = 2 * i; table.addSample(x, y); } table.save("test1.datatable"); DataTable loadedTable; loadedTable.load("test1.datatable"); return is_identical(table, loadedTable); } bool test2() { DataTable table; auto x = std::vector<double>(2); double y; for(double i = -0.3; i <= 0.3; i += 0.04) { for(double j = -0.4; j <= 1.0; j += 0.08) { x.at(0) = i; x.at(1) = j; y = i * j; table.addSample(x, y); } } table.save("test2.datatable"); DataTable loadedTable; loadedTable.load("test2.datatable"); return is_identical(table, loadedTable); } bool test3() { DataTable table; auto x = std::vector<double>(2); double y; for(double i = -0.3; i <= 0.3; i += 0.04) { for(double j = -0.4; j <= 1.0; j += 0.03) { x.at(0) = i; x.at(1) = j; y = i * j; table.addSample(x, y); } } table.save("test3.datatable"); DataTable loadedTable; loadedTable.load("test3.datatable"); return is_identical(table, loadedTable); } bool test4() { DataTable table; auto x = std::vector<double>(3); double y; for(double i = -0.0001; i <= 0.0001; i += 0.000001) { for(double j = -0.01; j <= 0.01; j += 0.001) { for(double k = -0.01; k <= 0.01; k += 0.001) { x.at(0) = i; x.at(1) = j; x.at(2) = k; y = i * j; table.addSample(x, y); } } } table.save("test4.datatable"); DataTable loadedTable; loadedTable.load("test4.datatable"); return is_identical(table, loadedTable); } bool test5() { DataTable table; auto x = std::vector<double>(4); double y; for(double i = -0.0001; i <= 0.0001; i += 0.000001) { for(double j = -0.01; j <= 0.01; j += 0.001) { for(double k = -0.01; k <= 0.01; k += 0.001) { for(double l = -100000.0; l < 0.0; l += 13720.0) { x.at(0) = i; x.at(1) = j; x.at(2) = k; x.at(3) = l; y = i * j; table.addSample(x, y); } } } } table.save("test5.datatable"); DataTable loadedTable; loadedTable.load("test5.datatable"); return is_identical(table, loadedTable); } bool test6() { DataTable table; auto x = std::vector<double>(4); double y; int j = 0; for(double i = std::numeric_limits<double>::lowest(), k = std::numeric_limits<double>::max(); j < 10000; i = nextafter(i, std::numeric_limits<double>::max()), k = nextafter(k, std::numeric_limits<double>::lowest())) { x.at(0) = i; y = k; table.addSample(x, y); j++; } table.save("test6.datatable"); DataTable loadedTable; loadedTable.load("test6.datatable"); return is_identical(table, loadedTable); } // Six-hump camelback function double f(DenseVector x) { assert(x.rows() == 2); return (4 - 2.1*x(0)*x(0) + (1/3.)*x(0)*x(0)*x(0)*x(0))*x(0)*x(0) + x(0)*x(1) + (-4 + 4*x(1)*x(1))*x(1)*x(1); } void runExample() { // Create new DataTable to manage samples DataTable samples; // Sample function DenseVector x(2); double y; for(int i = 0; i < 20; i++) { for(int j = 0; j < 20; j++) { // Sample function at x x(0) = i*0.1; x(1) = j*0.1; y = f(x); // Store sample samples.addSample(x,y); } } // Build B-splines that interpolate the samples BSpline bspline1(samples, BSplineType::LINEAR); BSpline bspline3(samples, BSplineType::CUBIC_FREE); // Build penalized B-spline (P-spline) that smooths the samples PSpline pspline(samples, 0.03); // Build radial basis function spline that interpolate the samples RBFSpline rbfspline(samples, RadialBasisFunctionType::THIN_PLATE_SPLINE); // Evaluate the splines at x = (1,1) x(0) = 1; x(1) = 1; cout << "-------------------------------------------" << endl; cout << "Function at x: " << f(x) << endl; cout << "Linear B-spline at x: " << bspline1.eval(x) << endl; cout << "Cubic B-spline at x: " << bspline3.eval(x) << endl; cout << "P-spline at x: " << pspline.eval(x) << endl; cout << "Thin-plate spline at x: " << rbfspline.eval(x) << endl; cout << "-------------------------------------------" << endl; } int main(int argc, char **argv) { runExample(); cout << "test1(): " << (test1() ? "success" : "fail") << endl; cout << "test2(): " << (test2() ? "success" : "fail") << endl; cout << "test3(): " << (test3() ? "success" : "fail") << endl; cout << "test4(): " << (test4() ? "success" : "fail") << endl; cout << "test5(): " << (test5() ? "success" : "fail") << endl; cout << "test6(): " << (test6() ? "success" : "fail") << endl; return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "simpletest.h" // foundation/core #include "foundation/test_iobj.h" #include "foundation/test_iobjcache.h" #include "foundation/test_iref.h" #include "foundation/test_iwref.h" #include "foundation/test_imeta.h" // foundation/memory #include "foundation/test_imemorystatistic.h" #include "foundation/test_imemory.h" // foundation/platform #include "foundation/test_imutex.h" #include "foundation/test_iatomic.h" #include "foundation/test_ientry.h" #include "foundation/test_iplatform.h" // foundation/container #include "foundation/test_iarray.h" #include "foundation/test_idict.h" // TODO: #include "foundation/test_iheap.h" #include "foundation/test_ineighbor.h" #include "foundation/test_irefcache.h" #include "foundation/test_ireflist.h" #include "foundation/test_islice.h" #include "foundation/test_itree.h" // TODO: // foundation/util #include "foundation/test_iarraytypes.h" #include "foundation/test_icmdarg.h" #include "foundation/test_iradix.h" #include "foundation/test_iringbuffer.h" #include "foundation/test_istring.h" // foundation/math #include "foundation/test_icircle.h" #include "foundation/test_iline.h" #include "foundation/test_imat.h" #include "foundation/test_imath.h" #include "foundation/test_iplane.h" #include "foundation/test_ipolygon.h" #include "foundation/test_ipos.h" #include "foundation/test_iquat.h" #include "foundation/test_irect.h" #include "foundation/test_isize.h" #include "foundation/test_ivec.h" iimplementapplication(); int ISeeMain(const icmdarg *arg) { iunused(arg); runAllTest(); return 0; } <commit_msg>add todos in unit-test<commit_after>#include <stdio.h> #include <stdlib.h> #include "simpletest.h" // foundation/core #include "foundation/test_iobj.h" #include "foundation/test_iobjcache.h" #include "foundation/test_iref.h" #include "foundation/test_iwref.h" #include "foundation/test_imeta.h" // foundation/memory #include "foundation/test_imemorystatistic.h" #include "foundation/test_imemory.h" // foundation/platform #include "foundation/test_imutex.h" #include "foundation/test_iatomic.h" #include "foundation/test_ientry.h" #include "foundation/test_iplatform.h" // foundation/container #include "foundation/test_iarray.h" #include "foundation/test_idict.h" // TODO: #include "foundation/test_iheap.h" #include "foundation/test_ineighbor.h" #include "foundation/test_irefcache.h" #include "foundation/test_ireflist.h" #include "foundation/test_islice.h" #include "foundation/test_itree.h" // TODO: // foundation/util #include "foundation/test_iarraytypes.h" #include "foundation/test_icmdarg.h" #include "foundation/test_iradix.h" // TODO: #include "foundation/test_istring.h" #include "foundation/test_iringbuffer.h" // TODO: // foundation/math #include "foundation/test_icircle.h" #include "foundation/test_iline.h" #include "foundation/test_imat.h" #include "foundation/test_iquat.h" #include "foundation/test_imath.h" #include "foundation/test_iplane.h" #include "foundation/test_ipolygon.h" #include "foundation/test_ipos.h" #include "foundation/test_irect.h" #include "foundation/test_isize.h" #include "foundation/test_ivec.h" iimplementapplication(); int ISeeMain(const icmdarg *arg) { iunused(arg); runAllTest(); return 0; } <|endoftext|>
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include "SkirtBrim.h" #include "support.h" namespace cura { void SkirtBrim::generate(SliceDataStorage& storage, int start_distance, unsigned int primary_line_count, bool outside_only) { bool is_skirt = start_distance > 0; bool external_only = is_skirt; // whether to include holes or not const int adhesion_extruder_nr = storage.getSettingAsIndex("adhesion_extruder_nr"); const ExtruderTrain* adhesion_extruder = storage.meshgroup->getExtruderTrain(adhesion_extruder_nr); const int primary_extruder_skirt_brim_line_width = adhesion_extruder->getSettingInMicrons("skirt_brim_line_width"); const int64_t primary_extruder_minimal_length = adhesion_extruder->getSettingInMicrons("skirt_brim_minimal_length"); Polygons& skirt_brim_primary_extruder = storage.skirt_brim[adhesion_extruder_nr]; Polygons first_layer_outline; const int layer_nr = 0; if (is_skirt) { const bool include_helper_parts = true; first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only); first_layer_outline = first_layer_outline.approxConvexHull(); } else { // add brim underneath support by removing support where there's brim around the model const bool include_helper_parts = false; // include manually below first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only); first_layer_outline.add(storage.primeTower.ground_poly); // don't remove parts of the prime tower, but make a brim for it if (outside_only) { first_layer_outline = first_layer_outline.removeEmptyHoles(); } if (storage.support.generated && primary_line_count > 0) { // remove model-brim from support const Polygons& model_brim_covered_area = first_layer_outline.offset(primary_line_count * primary_extruder_skirt_brim_line_width + primary_line_count % 2); // always leave a gap of an even number of brim lines, so that it fits if it's generating brim from both sides SupportLayer& support_layer = storage.support.supportLayers[0]; support_layer.supportAreas = support_layer.supportAreas.difference(model_brim_covered_area); first_layer_outline.add(support_layer.supportAreas); first_layer_outline.add(support_layer.skin); } } int offset_distance = start_distance - primary_extruder_skirt_brim_line_width / 2; for (unsigned int skirt_brim_number = 0; skirt_brim_number < primary_line_count; skirt_brim_number++) { offset_distance += primary_extruder_skirt_brim_line_width; Polygons outer_skirt_brim_line = first_layer_outline.offset(offset_distance, ClipperLib::jtRound); //Remove small inner skirt and brim holes. Holes have a negative area, remove anything smaller then 100x extrusion "area" for (unsigned int n = 0; n < outer_skirt_brim_line.size(); n++) { double area = outer_skirt_brim_line[n].area(); if (area < 0 && area > -primary_extruder_skirt_brim_line_width * primary_extruder_skirt_brim_line_width * 100) { outer_skirt_brim_line.remove(n--); } } skirt_brim_primary_extruder.add(outer_skirt_brim_line); int length = skirt_brim_primary_extruder.polygonLength(); if (skirt_brim_number + 1 >= primary_line_count && length > 0 && length < primary_extruder_minimal_length) //Make brim or skirt have more lines when total length is too small. { primary_line_count++; } } { // process other extruders' brim/skirt (as one brim line around the old brim) int last_width = primary_extruder_skirt_brim_line_width; for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount(); extruder++) { if (extruder == adhesion_extruder_nr || !storage.meshgroup->getExtruderTrain(extruder)->getIsUsed()) { continue; } const ExtruderTrain* train = storage.meshgroup->getExtruderTrain(extruder); const int width = train->getSettingInMicrons("skirt_brim_line_width"); const int64_t minimal_length = train->getSettingInMicrons("skirt_brim_minimal_length"); offset_distance += last_width / 2 + width/2; last_width = width; while (storage.skirt_brim[extruder].polygonLength() < minimal_length) { storage.skirt_brim[extruder].add(first_layer_outline.offset(offset_distance, ClipperLib::jtRound)); offset_distance += width; } } } } }//namespace cura <commit_msg>fix: always even number of brim lines between support and model (CURA-1062)<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include "SkirtBrim.h" #include "support.h" namespace cura { void SkirtBrim::generate(SliceDataStorage& storage, int start_distance, unsigned int primary_line_count, bool outside_only) { bool is_skirt = start_distance > 0; bool external_only = is_skirt; // whether to include holes or not const int adhesion_extruder_nr = storage.getSettingAsIndex("adhesion_extruder_nr"); const ExtruderTrain* adhesion_extruder = storage.meshgroup->getExtruderTrain(adhesion_extruder_nr); const int primary_extruder_skirt_brim_line_width = adhesion_extruder->getSettingInMicrons("skirt_brim_line_width"); const int64_t primary_extruder_minimal_length = adhesion_extruder->getSettingInMicrons("skirt_brim_minimal_length"); Polygons& skirt_brim_primary_extruder = storage.skirt_brim[adhesion_extruder_nr]; Polygons first_layer_outline; const int layer_nr = 0; if (is_skirt) { const bool include_helper_parts = true; first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only); first_layer_outline = first_layer_outline.approxConvexHull(); } else { // add brim underneath support by removing support where there's brim around the model const bool include_helper_parts = false; // include manually below first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, external_only); first_layer_outline.add(storage.primeTower.ground_poly); // don't remove parts of the prime tower, but make a brim for it if (outside_only) { first_layer_outline = first_layer_outline.removeEmptyHoles(); } if (storage.support.generated && primary_line_count > 0) { // remove model-brim from support const Polygons& model_brim_covered_area = first_layer_outline.offset(primary_extruder_skirt_brim_line_width * (primary_line_count + primary_line_count % 2)); // always leave a gap of an even number of brim lines, so that it fits if it's generating brim from both sides SupportLayer& support_layer = storage.support.supportLayers[0]; support_layer.supportAreas = support_layer.supportAreas.difference(model_brim_covered_area); first_layer_outline.add(support_layer.supportAreas); first_layer_outline.add(support_layer.skin); } } int offset_distance = start_distance - primary_extruder_skirt_brim_line_width / 2; for (unsigned int skirt_brim_number = 0; skirt_brim_number < primary_line_count; skirt_brim_number++) { offset_distance += primary_extruder_skirt_brim_line_width; Polygons outer_skirt_brim_line = first_layer_outline.offset(offset_distance, ClipperLib::jtRound); //Remove small inner skirt and brim holes. Holes have a negative area, remove anything smaller then 100x extrusion "area" for (unsigned int n = 0; n < outer_skirt_brim_line.size(); n++) { double area = outer_skirt_brim_line[n].area(); if (area < 0 && area > -primary_extruder_skirt_brim_line_width * primary_extruder_skirt_brim_line_width * 100) { outer_skirt_brim_line.remove(n--); } } skirt_brim_primary_extruder.add(outer_skirt_brim_line); int length = skirt_brim_primary_extruder.polygonLength(); if (skirt_brim_number + 1 >= primary_line_count && length > 0 && length < primary_extruder_minimal_length) //Make brim or skirt have more lines when total length is too small. { primary_line_count++; } } { // process other extruders' brim/skirt (as one brim line around the old brim) int last_width = primary_extruder_skirt_brim_line_width; for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount(); extruder++) { if (extruder == adhesion_extruder_nr || !storage.meshgroup->getExtruderTrain(extruder)->getIsUsed()) { continue; } const ExtruderTrain* train = storage.meshgroup->getExtruderTrain(extruder); const int width = train->getSettingInMicrons("skirt_brim_line_width"); const int64_t minimal_length = train->getSettingInMicrons("skirt_brim_minimal_length"); offset_distance += last_width / 2 + width/2; last_width = width; while (storage.skirt_brim[extruder].polygonLength() < minimal_length) { storage.skirt_brim[extruder].add(first_layer_outline.offset(offset_distance, ClipperLib::jtRound)); offset_distance += width; } } } } }//namespace cura <|endoftext|>
<commit_before>#include "algorithm-utils-cpp/algorithm-utils.h" #include <boost/foreach.hpp> #define foreach BOOST_FOREACH #include <iostream> bool is_even(const int& number) { return number % 2 == 0; } bool is_greater_than(int base, const int& number) { return number > base; } bool c_is_greater_than_a_plus_b(int a, int b, const int& c) { return c > a + b; } void test_item_exists() { std::vector<int> numbers; numbers.push_back(1); assert(!item_exists<int>(numbers, is_even)); numbers.push_back(2); assert(item_exists<int>(numbers, is_even)); std::cout << "test_item_exists: OK" << std::endl; } void test_remove_items_if() { std::vector<int> numbers; for (int i = 1; i < 10; ++i) numbers.push_back(i); remove_items_if<int>(numbers, is_even); assert(numbers.size() == 5); assert(numbers[1] == 3); std::cout << "test_remove_items_if: OK" << std::endl; } void test_copy_items_if() { std::vector<int> numbers; for (int i = 1; i < 10; ++i) numbers.push_back(i); std::vector<int> even = copy_items_if<int>(numbers, is_even); assert(even.size() == 4); assert(even[1] == 4); // Example of passing a curried function that binds only the first // parameter, but leaves the second open std::vector<int> greater_than_6 = copy_items_if<int>(numbers, boost::bind(is_greater_than, 6, _1)); assert(greater_than_6.size() == 3); assert(greater_than_6[0] == 7); // Example of negating criteria std::vector<int> odd = copy_items_if<int>(numbers, !boost::bind(is_even, _1)); assert(odd.size() == 5); assert(odd[1] == 3); // Example of bind more than one parameter in different order std::vector<int> greater_than_7 = copy_items_if<int>( numbers, boost::bind(c_is_greater_than_a_plus_b, 3, 4, _1)); assert(greater_than_7.size() == 2); assert(greater_than_7[0] == 8); // Example of leaving first parameter open and binding latter std::vector<int> less_than_4 = copy_items_if<int>( numbers, boost::bind(c_is_greater_than_a_plus_b, _1, 1, 5)); assert(less_than_4.size() == 3); assert(less_than_4[2] == 3); // Example of negating bind std::vector<int> not_less_than_5 = copy_items_if<int>( numbers, !boost::bind(is_greater_than, _1, 5)); assert(not_less_than_5.size() == 5); assert(not_less_than_5[4] == 9); std::cout << "test_copy_items_if: OK" << std::endl; } void test_find_item() { std::vector<int> numbers; for (int i = 1; i < 10; ++i) numbers.push_back(i); std::vector<int>::iterator found = find_item<int>(numbers, is_even); assert(*found == 2); assert(numbers[1] == *found); std::cout << "test_find_item: OK" << std::endl; } class Item { public: Item(int number) : _number(number) {} bool is_even() const { return _number % 2 == 0; } bool is_greater(int other) const { return _number > other; } int number() const { return _number; } private: int _number; }; void test_objects() { std::vector<Item> items; for (int i = 1; i < 10; ++i) items.push_back(Item(i)); std::vector<Item> even = copy_items_if<Item>(items, &Item::is_even); assert(even.size() == 4); assert(even[1].number() == 4); std::vector<Item> greater_than_3 = copy_items_if<Item>(items, boost::bind(&Item::is_greater, _1, 3)); assert(greater_than_3.size() == 6); assert(greater_than_3[1].number() == 5); std::cout << "test_objects: OK" << std::endl; } int main() { test_item_exists(); test_remove_items_if(); test_copy_items_if(); test_find_item(); test_objects(); return 0; } <commit_msg>Add comparison example.<commit_after>#include "algorithm-utils-cpp/algorithm-utils.h" #include <boost/foreach.hpp> #define foreach BOOST_FOREACH #include <iostream> bool is_even(const int& number) { return number % 2 == 0; } bool is_greater_than(int base, const int& number) { return number > base; } bool c_is_greater_than_a_plus_b(int a, int b, const int& c) { return c > a + b; } void test_item_exists() { std::vector<int> numbers; numbers.push_back(1); assert(!item_exists<int>(numbers, is_even)); numbers.push_back(2); assert(item_exists<int>(numbers, is_even)); std::cout << "test_item_exists: OK" << std::endl; } void test_remove_items_if() { std::vector<int> numbers; for (int i = 1; i < 10; ++i) numbers.push_back(i); remove_items_if<int>(numbers, is_even); assert(numbers.size() == 5); assert(numbers[1] == 3); std::cout << "test_remove_items_if: OK" << std::endl; } void test_copy_items_if() { std::vector<int> numbers; for (int i = 1; i < 10; ++i) numbers.push_back(i); std::vector<int> even = copy_items_if<int>(numbers, is_even); assert(even.size() == 4); assert(even[1] == 4); // Example of passing a curried function that binds only the first // parameter, but leaves the second open std::vector<int> greater_than_6 = copy_items_if<int>(numbers, boost::bind(is_greater_than, 6, _1)); assert(greater_than_6.size() == 3); assert(greater_than_6[0] == 7); // Example of negating criteria std::vector<int> odd = copy_items_if<int>(numbers, !boost::bind(is_even, _1)); assert(odd.size() == 5); assert(odd[1] == 3); // Example of bind more than one parameter in different order std::vector<int> greater_than_7 = copy_items_if<int>( numbers, boost::bind(c_is_greater_than_a_plus_b, 3, 4, _1)); assert(greater_than_7.size() == 2); assert(greater_than_7[0] == 8); // Example of leaving first parameter open and binding latter std::vector<int> less_than_4 = copy_items_if<int>( numbers, boost::bind(c_is_greater_than_a_plus_b, _1, 1, 5)); assert(less_than_4.size() == 3); assert(less_than_4[2] == 3); // Example of negating bind std::vector<int> not_less_than_5 = copy_items_if<int>( numbers, !boost::bind(is_greater_than, _1, 5)); assert(not_less_than_5.size() == 5); assert(not_less_than_5[4] == 9); std::cout << "test_copy_items_if: OK" << std::endl; } void test_find_item() { std::vector<int> numbers; for (int i = 1; i < 10; ++i) numbers.push_back(i); std::vector<int>::iterator found = find_item<int>(numbers, is_even); assert(*found == 2); assert(numbers[1] == *found); std::cout << "test_find_item: OK" << std::endl; } class Item { public: Item(int number) : _number(number) {} bool is_even() const { return _number % 2 == 0; } bool is_greater(int other) const { return _number > other; } int number() const { return _number; } private: int _number; }; void test_objects() { std::vector<Item> items; for (int i = 1; i < 10; ++i) items.push_back(Item(i)); std::vector<Item> even = copy_items_if<Item>(items, &Item::is_even); assert(even.size() == 4); assert(even[1].number() == 4); std::vector<Item> greater_than_3 = copy_items_if<Item>(items, boost::bind(&Item::is_greater, _1, 3)); assert(greater_than_3.size() == 6); assert(greater_than_3[1].number() == 5); std::vector<Item> only_7 = copy_items_if<Item>(items, boost::bind(&Item::number, _1) == 7); assert(only_7.size() == 1); assert(only_7[0].number() == 7); std::cout << "test_objects: OK" << std::endl; } int main() { test_item_exists(); test_remove_items_if(); test_copy_items_if(); test_find_item(); test_objects(); return 0; } <|endoftext|>
<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include "SkirtBrim.h" #include "support.h" namespace cura { void generateSkirtBrim(SliceDataStorage& storage, int start_distance, unsigned int count, int minLength, bool outside_only) { if (count == 0) return; bool externalOnly = (start_distance > 0); // whether to include holes or not const int primary_extruder = storage.getSettingAsIndex("adhesion_extruder_nr"); const int primary_extruder_skirt_brim_line_width = storage.meshgroup->getExtruderTrain(primary_extruder)->getSettingInMicrons("skirt_brim_line_width"); Polygons& skirt_brim_primary_extruder = storage.skirt_brim[primary_extruder]; bool is_skirt = count == 1 && start_distance > 0; Polygons first_layer_outline; const int layer_nr = 0; if (is_skirt) { const bool include_helper_parts = true; first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, externalOnly); first_layer_outline = first_layer_outline.approxConvexHull(); } else { // don't add brim _around_ support, but underneath it by removing support where there's brim const bool include_helper_parts = false; first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, externalOnly); first_layer_outline.add(storage.primeTower.ground_poly); // don't remove parts of the prime tower, but make a brim for it if (outside_only) { first_layer_outline = first_layer_outline.getOutsidePolygons(); } } Polygons outer_skirt_brim_line_primary_extruder; for (unsigned int skirt_brim_number = 0; skirt_brim_number < count; skirt_brim_number++) { const int offsetDistance = start_distance + primary_extruder_skirt_brim_line_width * skirt_brim_number + primary_extruder_skirt_brim_line_width / 2; outer_skirt_brim_line_primary_extruder = first_layer_outline.offset(offsetDistance, ClipperLib::jtRound); //Remove small inner skirt and brim holes. Holes have a negative area, remove anything smaller then 100x extrusion "area" for (unsigned int n = 0; n < outer_skirt_brim_line_primary_extruder.size(); n++) { double area = outer_skirt_brim_line_primary_extruder[n].area(); if (area < 0 && area > -primary_extruder_skirt_brim_line_width * primary_extruder_skirt_brim_line_width * 100) { outer_skirt_brim_line_primary_extruder.remove(n--); } } skirt_brim_primary_extruder.add(outer_skirt_brim_line_primary_extruder); int length = skirt_brim_primary_extruder.polygonLength(); if (skirt_brim_number + 1 >= count && length > 0 && length < minLength) //Make brim or skirt have more lines when total length is too small. { count++; } } { // process other extruders' brim/skirt (as one brim line around the old brim) int offset_distance = 0; int last_width = primary_extruder_skirt_brim_line_width; for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount(); extruder++) { if (extruder == primary_extruder || !storage.meshgroup->getExtruderTrain(extruder)->getIsUsed()) { continue; } int width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("skirt_brim_line_width"); offset_distance += last_width / 2 + width/2; last_width = width; while (storage.skirt_brim[extruder].polygonLength() < minLength) { storage.skirt_brim[extruder].add(outer_skirt_brim_line_primary_extruder.offset(offset_distance, ClipperLib::jtRound)); offset_distance += width; } } } if (!is_skirt && storage.support.generated) { // remove brim from support for (int extruder_nr = storage.meshgroup->getExtruderCount() - 1; extruder_nr >= 0; extruder_nr--) { Polygons& last_brim = storage.skirt_brim[extruder_nr]; if (last_brim.size() > 0) { int brim_line_width = storage.meshgroup->getExtruderTrain(extruder_nr)->getSettingInMicrons("skirt_brim_line_width"); SupportLayer& support_layer = storage.support.supportLayers[0]; Polygons area_covered_by_brim = last_brim.offset(brim_line_width / 2); support_layer.roofs = support_layer.roofs.difference(area_covered_by_brim); support_layer.supportAreas = support_layer.supportAreas.difference(area_covered_by_brim); break; } } } } }//namespace cura <commit_msg>fix: also generate brim for parts which flly lie inside other parts (CURA-1413)<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */ #include "SkirtBrim.h" #include "support.h" namespace cura { void generateSkirtBrim(SliceDataStorage& storage, int start_distance, unsigned int count, int minLength, bool outside_only) { if (count == 0) return; bool externalOnly = (start_distance > 0); // whether to include holes or not const int primary_extruder = storage.getSettingAsIndex("adhesion_extruder_nr"); const int primary_extruder_skirt_brim_line_width = storage.meshgroup->getExtruderTrain(primary_extruder)->getSettingInMicrons("skirt_brim_line_width"); Polygons& skirt_brim_primary_extruder = storage.skirt_brim[primary_extruder]; bool is_skirt = count == 1 && start_distance > 0; Polygons first_layer_outline; const int layer_nr = 0; if (is_skirt) { const bool include_helper_parts = true; first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, externalOnly); first_layer_outline = first_layer_outline.approxConvexHull(); } else { // don't add brim _around_ support, but underneath it by removing support where there's brim const bool include_helper_parts = false; first_layer_outline = storage.getLayerOutlines(layer_nr, include_helper_parts, externalOnly); first_layer_outline.add(storage.primeTower.ground_poly); // don't remove parts of the prime tower, but make a brim for it if (outside_only) { first_layer_outline = first_layer_outline.removeEmptyHoles(); } } Polygons outer_skirt_brim_line_primary_extruder; for (unsigned int skirt_brim_number = 0; skirt_brim_number < count; skirt_brim_number++) { const int offsetDistance = start_distance + primary_extruder_skirt_brim_line_width * skirt_brim_number + primary_extruder_skirt_brim_line_width / 2; outer_skirt_brim_line_primary_extruder = first_layer_outline.offset(offsetDistance, ClipperLib::jtRound); //Remove small inner skirt and brim holes. Holes have a negative area, remove anything smaller then 100x extrusion "area" for (unsigned int n = 0; n < outer_skirt_brim_line_primary_extruder.size(); n++) { double area = outer_skirt_brim_line_primary_extruder[n].area(); if (area < 0 && area > -primary_extruder_skirt_brim_line_width * primary_extruder_skirt_brim_line_width * 100) { outer_skirt_brim_line_primary_extruder.remove(n--); } } skirt_brim_primary_extruder.add(outer_skirt_brim_line_primary_extruder); int length = skirt_brim_primary_extruder.polygonLength(); if (skirt_brim_number + 1 >= count && length > 0 && length < minLength) //Make brim or skirt have more lines when total length is too small. { count++; } } { // process other extruders' brim/skirt (as one brim line around the old brim) int offset_distance = 0; int last_width = primary_extruder_skirt_brim_line_width; for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount(); extruder++) { if (extruder == primary_extruder || !storage.meshgroup->getExtruderTrain(extruder)->getIsUsed()) { continue; } int width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("skirt_brim_line_width"); offset_distance += last_width / 2 + width/2; last_width = width; while (storage.skirt_brim[extruder].polygonLength() < minLength) { storage.skirt_brim[extruder].add(outer_skirt_brim_line_primary_extruder.offset(offset_distance, ClipperLib::jtRound)); offset_distance += width; } } } if (!is_skirt && storage.support.generated) { // remove brim from support for (int extruder_nr = storage.meshgroup->getExtruderCount() - 1; extruder_nr >= 0; extruder_nr--) { Polygons& last_brim = storage.skirt_brim[extruder_nr]; if (last_brim.size() > 0) { int brim_line_width = storage.meshgroup->getExtruderTrain(extruder_nr)->getSettingInMicrons("skirt_brim_line_width"); SupportLayer& support_layer = storage.support.supportLayers[0]; Polygons area_covered_by_brim = last_brim.offset(brim_line_width / 2); support_layer.roofs = support_layer.roofs.difference(area_covered_by_brim); support_layer.supportAreas = support_layer.supportAreas.difference(area_covered_by_brim); break; } } } } }//namespace cura <|endoftext|>
<commit_before>#include <vector> #include <string> #include <utility> #include <SFML/Graphics.hpp> #include "JsonBox.h" #include "area.hpp" #include "door.hpp" #include "entity.hpp" #include "inventory.hpp" #include "creature.hpp" #include "dialogue.hpp" #include "tile_set.hpp" #include "entity_manager.hpp" #include "tile_map.hpp" #include "treasure_chest.hpp" Area::Area(const std::string& id, const JsonBox::Value& v, EntityManager* mgr) : Entity(id) { this->load(v, mgr); } void Area::load(const JsonBox::Value& v, EntityManager* mgr) { JsonBox::Object o = v.getObject(); // Attach the tileset this->tileset = mgr->getEntity<TileSet>(o["tileset"].getString()); // Create the tilemap if(o.find("tilemap") != o.end()) { JsonBox::Array a = o["tilemap"].getArray(); this->tilemap = TileMap(a, this->tileset); } // Build the dialogue // This is an optional parameter because it will not be saved // when the area is modified if(o.find("dialogue") != o.end()) this->dialogue = Dialogue(o["dialogue"]); // Build the treasure chests if(o.find("chests") != o.end()) { this->chests.clear(); for(auto chest : o["chests"].getArray()) { auto c = chest.getObject(); Inventory inventory = Inventory(c["inventory"], mgr); char facing = c["facing"].getString()[0]; bool open = false; if(c.find("open") != c.end()) open = c["open"].getBoolean(); chests.emplace_back(inventory, static_cast<Direction>(facing), open, 10.0f, mgr->getEntity<TileSet>("tileset_overworld")); chests.back().setPosition(sf::Vector2f(c["x"].getFloat(), c["y"].getFloat())); } } // Build the creature list this->creatures.clear(); for(auto creature : o["creatures"].getArray()) { // Create a new creature instance indentical to the version // in the entity manager Creature c(*mgr->getEntity<Creature>(creature.getString())); this->creatures.push_back(c); } // Attach doors if(o.find("doors") != o.end()) { this->doors.clear(); for(auto door : o["doors"].getArray()) { Door* d = nullptr; // Each door is either an array of the type [id, locked] or // a single id string. if(door.isString()) { d = mgr->getEntity<Door>(door.getString()); } else { d = mgr->getEntity<Door>(door.getArray()[0].getString()); d->locked = door.getArray()[1].getInteger(); } this->doors.push_back(d); } } return; } JsonBox::Object Area::getJson() const { JsonBox::Object o; // We don't need to save the dialogue because it doesn't change // Save the inventory // o["inventory"] = this->items.getJson(); // Save the creatures JsonBox::Array a; for(auto creature : this->creatures) { a.push_back(JsonBox::Value(creature.id)); } o["creatures"] = a; // Save the doors a.clear(); for(auto door : this->doors) { JsonBox::Array d; d.push_back(door->id); d.push_back(door->locked); a.push_back(d); } o["doors"] = a; return o; } <commit_msg>Made "tileset" an optional key when loading an Area<commit_after>#include <vector> #include <string> #include <utility> #include <SFML/Graphics.hpp> #include "JsonBox.h" #include "area.hpp" #include "door.hpp" #include "entity.hpp" #include "inventory.hpp" #include "creature.hpp" #include "dialogue.hpp" #include "tile_set.hpp" #include "entity_manager.hpp" #include "tile_map.hpp" #include "treasure_chest.hpp" Area::Area(const std::string& id, const JsonBox::Value& v, EntityManager* mgr) : Entity(id) { this->load(v, mgr); } void Area::load(const JsonBox::Value& v, EntityManager* mgr) { JsonBox::Object o = v.getObject(); // Attach the tileset if(o.find("tileset") != o.end()) { this->tileset = mgr->getEntity<TileSet>(o["tileset"].getString()); } // Create the tilemap if(o.find("tilemap") != o.end()) { JsonBox::Array a = o["tilemap"].getArray(); this->tilemap = TileMap(a, this->tileset); } // Build the dialogue // This is an optional parameter because it will not be saved // when the area is modified if(o.find("dialogue") != o.end()) this->dialogue = Dialogue(o["dialogue"]); // Build the treasure chests if(o.find("chests") != o.end()) { this->chests.clear(); for(auto chest : o["chests"].getArray()) { auto c = chest.getObject(); Inventory inventory = Inventory(c["inventory"], mgr); char facing = c["facing"].getString()[0]; bool open = false; if(c.find("open") != c.end()) open = c["open"].getBoolean(); chests.emplace_back(inventory, static_cast<Direction>(facing), open, 10.0f, mgr->getEntity<TileSet>("tileset_overworld")); chests.back().setPosition(sf::Vector2f(c["x"].getFloat(), c["y"].getFloat())); } } // Build the creature list this->creatures.clear(); for(auto creature : o["creatures"].getArray()) { // Create a new creature instance indentical to the version // in the entity manager Creature c(*mgr->getEntity<Creature>(creature.getString())); this->creatures.push_back(c); } // Attach doors if(o.find("doors") != o.end()) { this->doors.clear(); for(auto door : o["doors"].getArray()) { Door* d = nullptr; // Each door is either an array of the type [id, locked] or // a single id string. if(door.isString()) { d = mgr->getEntity<Door>(door.getString()); } else { d = mgr->getEntity<Door>(door.getArray()[0].getString()); d->locked = door.getArray()[1].getInteger(); } this->doors.push_back(d); } } return; } JsonBox::Object Area::getJson() const { JsonBox::Object o; // We don't need to save the dialogue because it doesn't change // Save the inventory // o["inventory"] = this->items.getJson(); // Save the creatures JsonBox::Array a; for(auto creature : this->creatures) { a.push_back(JsonBox::Value(creature.id)); } o["creatures"] = a; // Save the doors a.clear(); for(auto door : this->doors) { JsonBox::Array d; d.push_back(door->id); d.push_back(door->locked); a.push_back(d); } o["doors"] = a; return o; } <|endoftext|>
<commit_before>#include "Math/Cartesian3D.h" #include "Math/Math_vectypes.hxx" #include "benchmark/benchmark.h" #include <random> static bool is_aligned(const void *__restrict__ ptr, size_t align) { return (uintptr_t)ptr % align == 0; } static void BM_Cartesian3D_CreateEmpty(benchmark::State &state) { while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c; } BENCHMARK(BM_Cartesian3D_CreateEmpty); template <typename T> static void BM_Cartesian3D_Theta(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Theta(); state.SetComplexityN(state.range(0)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Cartesian3D_Phi(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Phi(); state.SetComplexityN(state.range(0)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Cartesian3D_Mag2(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Mag2(); state.SetComplexityN(state.range(0)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); // Define our main. BENCHMARK_MAIN(); <commit_msg>Revert "Set the complexity state when fitting the asymptotic complexity."<commit_after>#include "Math/Cartesian3D.h" #include "Math/Math_vectypes.hxx" #include "benchmark/benchmark.h" #include <random> static bool is_aligned(const void *__restrict__ ptr, size_t align) { return (uintptr_t)ptr % align == 0; } static void BM_Cartesian3D_CreateEmpty(benchmark::State &state) { while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c; } BENCHMARK(BM_Cartesian3D_CreateEmpty); template <typename T> static void BM_Cartesian3D_Theta(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Theta(); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Cartesian3D_Phi(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Phi(); state.SetComplexityN(state.range(0)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Cartesian3D_Mag2(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Mag2(); state.SetComplexityN(state.range(0)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); // Define our main. BENCHMARK_MAIN(); <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // playexr -- a program that plays back an // OpenEXR image sequence directly from disk. // //----------------------------------------------------------------------------- #include <playExr.h> #include <osDependent.h> #include <IlmThread.h> #include <iostream> #include <exception> #include <vector> #include <string> #include <stdlib.h> #include <string.h> #include <cstring> using namespace std; namespace { void usageMessage (const char argv0[], bool verbose = false) { cerr << "usage: " << argv0 << " " "[options] fileName [firstFrame lastFrame]" << endl; if (verbose) { cerr << "\n" "Plays back a sequence of OpenEXR files. All files must\n" "have the same data window and the same set of channels.\n" "The names of the files are constructed by substituting\n" "the first '%' in fileName with firstFrame, firstFrame+1,\n" "firstFrame+2, ... lastFrame. For example,\n" "\n" " " << argv0 << " image.%.exr 1 100\n" "\n" "plays back image.1.exr, image.2.exr ... image.100.exr.\n" "\n" "Options:\n" "\n" "-t n read the images using n parallel threads\n" "\n" "-f n images will be played back at a rate of n frames\n" " per second (assuming that reading and displaying\n" " an individual image file takes no more than 1/n\n" " seconds).\n" "\n" "-S n images will be displayed at n times their original\n" " width and height. n must be in the range from 0.1\n" " to 2.0.\n" "\n" #if HAVE_CTL_INTERPRETER "-C s CTL transform s is applied to each image before it\n" " is displayed. Option -C can be specified multiple\n" " times to apply a series of transforms to each image.\n" " The transforms are applied in the order in which\n" " they appear on the command line.\n" "\n" "-i On machines where the graphics hardware does not\n" " directly support interpolation between texture map\n" " pixels images with smooth color gradients will\n" " exhibit contouring artifacts. Option -i selects\n" " software-based texture pixel interpolation. This\n" " avoids contouring but may slow down image playback.\n" "\n" #endif "-h prints this message\n" "\n" #if HAVE_CTL_INTERPRETER "CTL transforms:\n" "\n" " If one or more CTL transforms are specified on\n" " the command line (using the -C flag), then those\n" " transforms are applied to the images.\n" " If no CTL transforms are specified on the command\n" " line then an optional look modification transform\n" " is applied, followed by a rendering transform and\n" " a display transform.\n" " The name of the look modification transform is\n" " taken from the lookModTransform attribute in the\n" " header of the first frame of the image sequence.\n" " If the header contains no such attribute, then no\n" " look modification transform is applied. The name\n" " of the rendering transform is taken from the\n" " renderingTransform attribute in the header of the\n" " first frame of the image sequence. If the header\n" " contains no such attribute, then the name of the\n" " rendering transform is \"transform_RRT.\" The\n" " name of the display transform is taken from the\n" " environment variable CTL_DISPLAY_TRANSFORM. If this\n" " environment variable is not set, then the name of\n" " the display transform is \"transform_display_video.\"\n" " The files that contain the CTL code for the\n" " transforms are located using the CTL_MODULE_PATH\n" " environment variable.\n" "\n" #endif "Playback frame rate:\n" "\n" " If the frame rate is not specified on the command\n" " line (using the -f flag), then the frame rate is\n" " determined by the framesPerSecond attribute in the\n" " header of the first frame of the image sequence.\n" " If the header contains no framesPerSecond attribute\n" " then the frame rate is set to 24 frames per second.\n" "\n" "Keyboard commands:\n" "\n" " L or P play forward / pause\n" " H play backward / pause\n" " K step one frame forward\n" " J step one frame backward\n" " > or . increase exposure\n" " < or , decrease exposure\n" #if HAVE_CTL_INTERPRETER " C CTL transforms on/off\n" #endif " O text overlay on/off\n" " F full-screen mode on/off\n" " Q or ESC quit\n" "\n"; cerr << endl; } exit (1); } int exitStatus = 0; void quickexit () { // // Hack to avoid crashes when someone presses the close or 'X' // button in the title bar of our window. Something GLUT does // while shutting down the program does not play well with // multiple threads. Bypassing GLUT's orderly shutdown by // calling _exit immediately avoids crashes. // _exit (exitStatus); } } // namespace int main(int argc, char **argv) { glutInit (&argc, argv); const char *fileNameTemplate = 0; int firstFrame = 1; int lastFrame = 1; int numThreads = 0; float fps = -1; float xyScale = 1; vector<string> transformNames; bool useHwTexInterpolation = true; // // Parse the command line. // if (argc < 2) usageMessage (argv[0], true); int i = 1; int j = 0; while (i < argc) { if (!strcmp (argv[i], "-t")) { // // Set number of threads // if (i > argc - 2) usageMessage (argv[0]); numThreads = strtol (argv[i + 1], 0, 0); if (numThreads < 0) { cerr << "Number of threads cannot be negative." << endl; return 1; } i += 2; } else if (!strcmp (argv[i], "-f")) { // // Set frame rate // if (i > argc - 2) usageMessage (argv[0]); fps = strtod (argv[i + 1], 0); if (fps < 1 || fps > 1000) { cerr << "Playback speed must be between " "1 and 1000 frames per second." << endl; return 1; } i += 2; } else if (!strcmp (argv[i], "-S")) { // // Set image scale factor // if (i > argc - 2) usageMessage (argv[0]); xyScale = strtod (argv[i + 1], 0); if (xyScale < 0.1 || xyScale > 2.0) { cerr << "Scale factor must be between 0.1 and 2.0." << endl; return 1; } i += 2; } else if (!strcmp (argv[i], "-C")) { // // Apply a CTL transform // if (i > argc - 2) usageMessage (argv[0]); transformNames.push_back (argv[i + 1]); i += 2; } else if (!strcmp (argv[i], "-i")) { // // Use software-based texture map interpolation // useHwTexInterpolation = false; i += 1; } else if (!strcmp (argv[i], "-h")) { // // Print help message // usageMessage (argv[0], true); } else { // // Image file name or frame number // switch (j) { case 0: fileNameTemplate = argv[i]; break; case 1: firstFrame = strtol (argv[i], 0, 0); break; case 2: lastFrame = strtol (argv[i], 0, 0); break; default: break; } i += 1; j += 1; } } if (j != 1 && j != 3) usageMessage (argv[0]); if (firstFrame > lastFrame) { cerr << "Frame number of first frame is greater than " "frame number of last frame." << endl; return 1; } // // Make sure that we have threading support. // if (!IlmThread::supportsThreads()) { cerr << "This program requires multi-threading support.\n" << endl; return 1; } // // Play the image sequence. // atexit (quickexit); try { playExr (fileNameTemplate, firstFrame, lastFrame, numThreads, fps, xyScale, transformNames, useHwTexInterpolation); } catch (const exception &e) { cerr << e.what() << endl; exitStatus = 1; } return exitStatus; } <commit_msg>Fix for gcc-4.7<commit_after>/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // playexr -- a program that plays back an // OpenEXR image sequence directly from disk. // //----------------------------------------------------------------------------- #include <playExr.h> #include <osDependent.h> #include <IlmThread.h> #include <iostream> #include <exception> #include <vector> #include <string> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <cstring> using namespace std; namespace { void usageMessage (const char argv0[], bool verbose = false) { cerr << "usage: " << argv0 << " " "[options] fileName [firstFrame lastFrame]" << endl; if (verbose) { cerr << "\n" "Plays back a sequence of OpenEXR files. All files must\n" "have the same data window and the same set of channels.\n" "The names of the files are constructed by substituting\n" "the first '%' in fileName with firstFrame, firstFrame+1,\n" "firstFrame+2, ... lastFrame. For example,\n" "\n" " " << argv0 << " image.%.exr 1 100\n" "\n" "plays back image.1.exr, image.2.exr ... image.100.exr.\n" "\n" "Options:\n" "\n" "-t n read the images using n parallel threads\n" "\n" "-f n images will be played back at a rate of n frames\n" " per second (assuming that reading and displaying\n" " an individual image file takes no more than 1/n\n" " seconds).\n" "\n" "-S n images will be displayed at n times their original\n" " width and height. n must be in the range from 0.1\n" " to 2.0.\n" "\n" #if HAVE_CTL_INTERPRETER "-C s CTL transform s is applied to each image before it\n" " is displayed. Option -C can be specified multiple\n" " times to apply a series of transforms to each image.\n" " The transforms are applied in the order in which\n" " they appear on the command line.\n" "\n" "-i On machines where the graphics hardware does not\n" " directly support interpolation between texture map\n" " pixels images with smooth color gradients will\n" " exhibit contouring artifacts. Option -i selects\n" " software-based texture pixel interpolation. This\n" " avoids contouring but may slow down image playback.\n" "\n" #endif "-h prints this message\n" "\n" #if HAVE_CTL_INTERPRETER "CTL transforms:\n" "\n" " If one or more CTL transforms are specified on\n" " the command line (using the -C flag), then those\n" " transforms are applied to the images.\n" " If no CTL transforms are specified on the command\n" " line then an optional look modification transform\n" " is applied, followed by a rendering transform and\n" " a display transform.\n" " The name of the look modification transform is\n" " taken from the lookModTransform attribute in the\n" " header of the first frame of the image sequence.\n" " If the header contains no such attribute, then no\n" " look modification transform is applied. The name\n" " of the rendering transform is taken from the\n" " renderingTransform attribute in the header of the\n" " first frame of the image sequence. If the header\n" " contains no such attribute, then the name of the\n" " rendering transform is \"transform_RRT.\" The\n" " name of the display transform is taken from the\n" " environment variable CTL_DISPLAY_TRANSFORM. If this\n" " environment variable is not set, then the name of\n" " the display transform is \"transform_display_video.\"\n" " The files that contain the CTL code for the\n" " transforms are located using the CTL_MODULE_PATH\n" " environment variable.\n" "\n" #endif "Playback frame rate:\n" "\n" " If the frame rate is not specified on the command\n" " line (using the -f flag), then the frame rate is\n" " determined by the framesPerSecond attribute in the\n" " header of the first frame of the image sequence.\n" " If the header contains no framesPerSecond attribute\n" " then the frame rate is set to 24 frames per second.\n" "\n" "Keyboard commands:\n" "\n" " L or P play forward / pause\n" " H play backward / pause\n" " K step one frame forward\n" " J step one frame backward\n" " > or . increase exposure\n" " < or , decrease exposure\n" #if HAVE_CTL_INTERPRETER " C CTL transforms on/off\n" #endif " O text overlay on/off\n" " F full-screen mode on/off\n" " Q or ESC quit\n" "\n"; cerr << endl; } exit (1); } int exitStatus = 0; void quickexit () { // // Hack to avoid crashes when someone presses the close or 'X' // button in the title bar of our window. Something GLUT does // while shutting down the program does not play well with // multiple threads. Bypassing GLUT's orderly shutdown by // calling _exit immediately avoids crashes. // _exit (exitStatus); } } // namespace int main(int argc, char **argv) { glutInit (&argc, argv); const char *fileNameTemplate = 0; int firstFrame = 1; int lastFrame = 1; int numThreads = 0; float fps = -1; float xyScale = 1; vector<string> transformNames; bool useHwTexInterpolation = true; // // Parse the command line. // if (argc < 2) usageMessage (argv[0], true); int i = 1; int j = 0; while (i < argc) { if (!strcmp (argv[i], "-t")) { // // Set number of threads // if (i > argc - 2) usageMessage (argv[0]); numThreads = strtol (argv[i + 1], 0, 0); if (numThreads < 0) { cerr << "Number of threads cannot be negative." << endl; return 1; } i += 2; } else if (!strcmp (argv[i], "-f")) { // // Set frame rate // if (i > argc - 2) usageMessage (argv[0]); fps = strtod (argv[i + 1], 0); if (fps < 1 || fps > 1000) { cerr << "Playback speed must be between " "1 and 1000 frames per second." << endl; return 1; } i += 2; } else if (!strcmp (argv[i], "-S")) { // // Set image scale factor // if (i > argc - 2) usageMessage (argv[0]); xyScale = strtod (argv[i + 1], 0); if (xyScale < 0.1 || xyScale > 2.0) { cerr << "Scale factor must be between 0.1 and 2.0." << endl; return 1; } i += 2; } else if (!strcmp (argv[i], "-C")) { // // Apply a CTL transform // if (i > argc - 2) usageMessage (argv[0]); transformNames.push_back (argv[i + 1]); i += 2; } else if (!strcmp (argv[i], "-i")) { // // Use software-based texture map interpolation // useHwTexInterpolation = false; i += 1; } else if (!strcmp (argv[i], "-h")) { // // Print help message // usageMessage (argv[0], true); } else { // // Image file name or frame number // switch (j) { case 0: fileNameTemplate = argv[i]; break; case 1: firstFrame = strtol (argv[i], 0, 0); break; case 2: lastFrame = strtol (argv[i], 0, 0); break; default: break; } i += 1; j += 1; } } if (j != 1 && j != 3) usageMessage (argv[0]); if (firstFrame > lastFrame) { cerr << "Frame number of first frame is greater than " "frame number of last frame." << endl; return 1; } // // Make sure that we have threading support. // if (!IlmThread::supportsThreads()) { cerr << "This program requires multi-threading support.\n" << endl; return 1; } // // Play the image sequence. // atexit (quickexit); try { playExr (fileNameTemplate, firstFrame, lastFrame, numThreads, fps, xyScale, transformNames, useHwTexInterpolation); } catch (const exception &e) { cerr << e.what() << endl; exitStatus = 1; } return exitStatus; } <|endoftext|>
<commit_before>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018-2019 Intel Corporation #ifndef OPENCV_GAPI_UTIL_HPP #define OPENCV_GAPI_UTIL_HPP #include <tuple> // \cond HIDDEN_SYMBOLS // This header file contains some generic utility functions which are // used in other G-API Public API headers. // // PLEASE don't put any stuff here if it is NOT used in public API headers! namespace cv { namespace detail { // Recursive integer sequence type, useful for enumerating elements of // template parameter packs. template<int... I> struct Seq { using next = Seq<I..., sizeof...(I)>; }; template<int Sz> struct MkSeq { using type = typename MkSeq<Sz-1>::type::next; }; template<> struct MkSeq<0>{ using type = Seq<>; }; // Checks if elements of variadic template satisfy the given Predicate. // Implemented via tuple, with an interface to accept plain type lists template<template<class> class, typename, typename...> struct all_satisfy; template<template<class> class F, typename T, typename... Ts> struct all_satisfy<F, std::tuple<T, Ts...> > { static const constexpr bool value = F<T>::value && all_satisfy<F, std::tuple<Ts...> >::value; }; template<template<class> class F, typename T> struct all_satisfy<F, std::tuple<T> > { static const constexpr bool value = F<T>::value; }; template<template<class> class F, typename T, typename... Ts> struct all_satisfy: public all_satisfy<F, std::tuple<T, Ts...> > {}; // Permute given tuple type C with given integer sequence II // Sequence may be less than tuple C size. template<class, class> struct permute_tuple; template<class C, int... IIs> struct permute_tuple<C, Seq<IIs...> > { using type = std::tuple< typename std::tuple_element<IIs, C>::type... >; }; // Given T..., generates a type sequence of sizeof...(T)-1 elements // which is T... without its last element // Implemented via tuple, with an interface to accept plain type lists template<typename T, typename... Ts> struct all_but_last; template<typename T, typename... Ts> struct all_but_last<std::tuple<T, Ts...> > { using C = std::tuple<T, Ts...>; using S = typename MkSeq<std::tuple_size<C>::value - 1>::type; using type = typename permute_tuple<C, S>::type; }; template<typename T, typename... Ts> struct all_but_last: public all_but_last<std::tuple<T, Ts...> > {}; template<typename... Ts> using all_but_last_t = typename all_but_last<Ts...>::type; // NB.: This is here because there's no constexpr std::max in C++11 template<std::size_t S0, std::size_t... SS> struct max_of_t { static constexpr const std::size_t rest = max_of_t<SS...>::value; static constexpr const std::size_t value = rest > S0 ? rest : S0; }; template<std::size_t S> struct max_of_t<S> { static constexpr const std::size_t value = S; }; template <typename...> struct contains : std::false_type{}; template <typename T1, typename T2, typename... Ts> struct contains<T1, T2, Ts...> : std::integral_constant<bool, std::is_same<T1, T2>::value || contains<T1, Ts...>::value> {}; template <typename...> struct all_unique : std::true_type{}; template <typename T1, typename... Ts> struct all_unique<T1, Ts...> : std::integral_constant<bool, !contains<T1, Ts...>::value && all_unique<Ts...>::value> {}; template<typename> struct tuple_wrap_helper; template<typename T> struct tuple_wrap_helper { using type = std::tuple<T>; static type get(T&& obj) { return std::make_tuple(std::move(obj)); } }; template<typename... Objs> struct tuple_wrap_helper<std::tuple<Objs...>> { using type = std::tuple<Objs...>; static type get(std::tuple<Objs...>&& objs) { return std::forward<std::tuple<Objs...>>(objs); } }; } // namespace detail } // namespace cv // \endcond #endif // OPENCV_GAPI_UTIL_HPP <commit_msg>Added overload of contains<> for tuple<commit_after>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018-2019 Intel Corporation #ifndef OPENCV_GAPI_UTIL_HPP #define OPENCV_GAPI_UTIL_HPP #include <tuple> // \cond HIDDEN_SYMBOLS // This header file contains some generic utility functions which are // used in other G-API Public API headers. // // PLEASE don't put any stuff here if it is NOT used in public API headers! namespace cv { namespace detail { // Recursive integer sequence type, useful for enumerating elements of // template parameter packs. template<int... I> struct Seq { using next = Seq<I..., sizeof...(I)>; }; template<int Sz> struct MkSeq { using type = typename MkSeq<Sz-1>::type::next; }; template<> struct MkSeq<0>{ using type = Seq<>; }; // Checks if elements of variadic template satisfy the given Predicate. // Implemented via tuple, with an interface to accept plain type lists template<template<class> class, typename, typename...> struct all_satisfy; template<template<class> class F, typename T, typename... Ts> struct all_satisfy<F, std::tuple<T, Ts...> > { static const constexpr bool value = F<T>::value && all_satisfy<F, std::tuple<Ts...> >::value; }; template<template<class> class F, typename T> struct all_satisfy<F, std::tuple<T> > { static const constexpr bool value = F<T>::value; }; template<template<class> class F, typename T, typename... Ts> struct all_satisfy: public all_satisfy<F, std::tuple<T, Ts...> > {}; // Permute given tuple type C with given integer sequence II // Sequence may be less than tuple C size. template<class, class> struct permute_tuple; template<class C, int... IIs> struct permute_tuple<C, Seq<IIs...> > { using type = std::tuple< typename std::tuple_element<IIs, C>::type... >; }; // Given T..., generates a type sequence of sizeof...(T)-1 elements // which is T... without its last element // Implemented via tuple, with an interface to accept plain type lists template<typename T, typename... Ts> struct all_but_last; template<typename T, typename... Ts> struct all_but_last<std::tuple<T, Ts...> > { using C = std::tuple<T, Ts...>; using S = typename MkSeq<std::tuple_size<C>::value - 1>::type; using type = typename permute_tuple<C, S>::type; }; template<typename T, typename... Ts> struct all_but_last: public all_but_last<std::tuple<T, Ts...> > {}; template<typename... Ts> using all_but_last_t = typename all_but_last<Ts...>::type; // NB.: This is here because there's no constexpr std::max in C++11 template<std::size_t S0, std::size_t... SS> struct max_of_t { static constexpr const std::size_t rest = max_of_t<SS...>::value; static constexpr const std::size_t value = rest > S0 ? rest : S0; }; template<std::size_t S> struct max_of_t<S> { static constexpr const std::size_t value = S; }; template <typename...> struct contains : std::false_type{}; template <typename T1, typename T2, typename... Ts> struct contains<T1, T2, Ts...> : std::integral_constant<bool, std::is_same<T1, T2>::value || contains<T1, Ts...>::value> {}; template<typename T, typename... Types> struct contains<T, std::tuple<Types...>> : std::integral_constant<bool, contains<T, Types...>::value> {}; template <typename...> struct all_unique : std::true_type{}; template <typename T1, typename... Ts> struct all_unique<T1, Ts...> : std::integral_constant<bool, !contains<T1, Ts...>::value && all_unique<Ts...>::value> {}; template<typename> struct tuple_wrap_helper; template<typename T> struct tuple_wrap_helper { using type = std::tuple<T>; static type get(T&& obj) { return std::make_tuple(std::move(obj)); } }; template<typename... Objs> struct tuple_wrap_helper<std::tuple<Objs...>> { using type = std::tuple<Objs...>; static type get(std::tuple<Objs...>&& objs) { return std::forward<std::tuple<Objs...>>(objs); } }; } // namespace detail } // namespace cv // \endcond #endif // OPENCV_GAPI_UTIL_HPP <|endoftext|>
<commit_before>// PropertyTable.cpp //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /* * Copyright (c) 2011-12, Stanford University. All rights reserved. * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //============================================================================ // INCLUDES //============================================================================ #include "PropertyTable.h" using namespace OpenSim; using namespace SimTK; using namespace std; //_____________________________________________________________________________ // Default constructor is inline //_____________________________________________________________________________ // Copy constructor has to clone the source properties. PropertyTable::PropertyTable(const PropertyTable& source) { replaceProperties(source.properties); } //_____________________________________________________________________________ // Destructor must deep-delete the properties since they are owned by the // PropertyTable. PropertyTable::~PropertyTable() { deleteProperties(); } //_____________________________________________________________________________ // Copy assignment has to clone the source properties. PropertyTable& PropertyTable::operator=(const PropertyTable& source) { if (&source != this) replaceProperties(source.properties); return *this; } //_____________________________________________________________________________ // Reinitialize the table to be completely empty. void PropertyTable::clear() { deleteProperties(); } //_____________________________________________________________________________ // Equality operator compares each property with the one at the same position. bool PropertyTable::equals(const PropertyTable& other) const { if (getNumProperties() != other.getNumProperties()) return false; for (int i=0; i < getNumProperties(); ++i) { if (!(getAbstractPropertyByIndex(i) == other.getAbstractPropertyByIndex(i))) return false; } return true; } int PropertyTable::adoptProperty(AbstractProperty* prop) { assert(prop); const int nxtIndex = properties.size(); const std::string& name = prop->getName(); // Unnamed property should have had its Object class name used as its name. assert(!name.empty()); if (hasProperty(name)) throw OpenSim::Exception ("PropertyTable::adoptProperty(): Property " + name + " already in table."); propertyIndex[name] = nxtIndex; properties.push_back(prop); return nxtIndex; } const AbstractProperty& PropertyTable:: getAbstractPropertyByIndex(int index) const { if (!(0 <= index && index < getNumProperties())) throw OpenSim::Exception ("PropertyTable::getAbstractPropertyByIndex(): index " + String(index) + " out of range (" + String(getNumProperties()) + " properties in table)."); return *properties[index]; } AbstractProperty& PropertyTable:: updAbstractPropertyByIndex(int index) { if (!(0 <= index && index < getNumProperties())) throw OpenSim::Exception ("PropertyTable::updAbstractPropertyByIndex(): index " + String(index) + " out of range (" + String(getNumProperties()) + " properties in table)."); return *properties[index]; } const AbstractProperty& PropertyTable:: getAbstractPropertyByName(const std::string& name) const { const AbstractProperty* p = getPropertyPtr(name); if (p == NULL) throw OpenSim::Exception ("PropertyTable::getAbstractPropertyByName(): Property " + name + " not found."); return *p; } AbstractProperty& PropertyTable:: updAbstractPropertyByName(const std::string& name) { AbstractProperty* p = updPropertyPtr(name); if (p == NULL) throw OpenSim::Exception ("PropertyTable::updAbstractPropertyByName(): Property " + name + " not found."); return *p; } // Look up the property by name in the map to find its index // in the property array and return that. If the name isn't there, return -1. // This method is reused in the implementation of any method that // takes a property by name. int PropertyTable::findPropertyIndex(const std::string& name) const { const std::map<std::string, int>::const_iterator it = propertyIndex.find(name); return it == propertyIndex.end() ? -1 : it->second; } // Private method to replace the existing properties with a deep copy of // the source, and update the index map to match. void PropertyTable::replaceProperties (const SimTK::Array_<AbstractProperty*>& source) { deleteProperties(); for (unsigned i=0; i < source.size(); ++i) { properties.push_back(source[i]->clone()); propertyIndex[source[i]->getName()] = i; } } // Private method to delete all the properties and clear the index. void PropertyTable::deleteProperties() { for (unsigned i=0; i < properties.size(); ++i) delete properties[i]; properties.clear(); propertyIndex.clear(); } <commit_msg>Improve the error message issued when a constructProperty() call is omitted. (Tim Dorn ran into this problem.)<commit_after>// PropertyTable.cpp //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /* * Copyright (c) 2011-12, Stanford University. All rights reserved. * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //============================================================================ // INCLUDES //============================================================================ #include "PropertyTable.h" using namespace OpenSim; using namespace SimTK; using namespace std; //_____________________________________________________________________________ // Default constructor is inline //_____________________________________________________________________________ // Copy constructor has to clone the source properties. PropertyTable::PropertyTable(const PropertyTable& source) { replaceProperties(source.properties); } //_____________________________________________________________________________ // Destructor must deep-delete the properties since they are owned by the // PropertyTable. PropertyTable::~PropertyTable() { deleteProperties(); } //_____________________________________________________________________________ // Copy assignment has to clone the source properties. PropertyTable& PropertyTable::operator=(const PropertyTable& source) { if (&source != this) replaceProperties(source.properties); return *this; } //_____________________________________________________________________________ // Reinitialize the table to be completely empty. void PropertyTable::clear() { deleteProperties(); } //_____________________________________________________________________________ // Equality operator compares each property with the one at the same position. bool PropertyTable::equals(const PropertyTable& other) const { if (getNumProperties() != other.getNumProperties()) return false; for (int i=0; i < getNumProperties(); ++i) { if (!(getAbstractPropertyByIndex(i) == other.getAbstractPropertyByIndex(i))) return false; } return true; } int PropertyTable::adoptProperty(AbstractProperty* prop) { assert(prop); const int nxtIndex = properties.size(); const std::string& name = prop->getName(); // Unnamed property should have had its Object class name used as its name. assert(!name.empty()); if (hasProperty(name)) throw OpenSim::Exception ("PropertyTable::adoptProperty(): Property " + name + " already in table."); propertyIndex[name] = nxtIndex; properties.push_back(prop); return nxtIndex; } const AbstractProperty& PropertyTable:: getAbstractPropertyByIndex(int index) const { if (index == SimTK::InvalidIndex) throw OpenSim::Exception ("PropertyTable::getAbstractPropertyByIndex(): uninitialized " "property index -- did you forget a constructProperty() call?"); if (!(0 <= index && index < getNumProperties())) throw OpenSim::Exception ("PropertyTable::getAbstractPropertyByIndex(): index " + String(index) + " out of range (" + String(getNumProperties()) + " properties in table)."); return *properties[index]; } AbstractProperty& PropertyTable:: updAbstractPropertyByIndex(int index) { if (index == SimTK::InvalidIndex) throw OpenSim::Exception ("PropertyTable::updAbstractPropertyByIndex(): uninitialized " "property index -- did you forget a constructProperty() call?"); if (!(0 <= index && index < getNumProperties())) throw OpenSim::Exception ("PropertyTable::updAbstractPropertyByIndex(): index " + String(index) + " out of range (" + String(getNumProperties()) + " properties in table)."); return *properties[index]; } const AbstractProperty& PropertyTable:: getAbstractPropertyByName(const std::string& name) const { const AbstractProperty* p = getPropertyPtr(name); if (p == NULL) throw OpenSim::Exception ("PropertyTable::getAbstractPropertyByName(): Property " + name + " not found."); return *p; } AbstractProperty& PropertyTable:: updAbstractPropertyByName(const std::string& name) { AbstractProperty* p = updPropertyPtr(name); if (p == NULL) throw OpenSim::Exception ("PropertyTable::updAbstractPropertyByName(): Property " + name + " not found."); return *p; } // Look up the property by name in the map to find its index // in the property array and return that. If the name isn't there, return -1. // This method is reused in the implementation of any method that // takes a property by name. int PropertyTable::findPropertyIndex(const std::string& name) const { const std::map<std::string, int>::const_iterator it = propertyIndex.find(name); return it == propertyIndex.end() ? -1 : it->second; } // Private method to replace the existing properties with a deep copy of // the source, and update the index map to match. void PropertyTable::replaceProperties (const SimTK::Array_<AbstractProperty*>& source) { deleteProperties(); for (unsigned i=0; i < source.size(); ++i) { properties.push_back(source[i]->clone()); propertyIndex[source[i]->getName()] = i; } } // Private method to delete all the properties and clear the index. void PropertyTable::deleteProperties() { for (unsigned i=0; i < properties.size(); ++i) delete properties[i]; properties.clear(); propertyIndex.clear(); } <|endoftext|>
<commit_before><commit_msg>Go back to working dir if par compilation fails, this helps debugging (AndreaR)<commit_after>void LoadLibraries(Bool_t useParFiles=kFALSE) { gSystem->Load("libTree.so"); gSystem->Load("libGeom.so"); gSystem->Load("libPhysics.so"); gSystem->Load("libVMC.so"); gSystem->Load("libSTEERBase.so"); gSystem->Load("libESD.so"); gSystem->Load("libAOD.so"); gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libCORRFW.so"); gSystem->Load("libPWG3base.so"); gSystem->Load("libPWG3vertexingHF.so"); if(useParFiles) { setupPar("STEERBase"); setupPar("ESD"); setupPar("AOD"); setupPar("ANALYSIS"); setupPar("ANALYSISalice"); setupPar("CORRFW"); setupPar("PWG3vertexingHF"); } return; } //------------------------------------------------------------------------ Int_t setupPar(const char* pararchivename) { /////////////////// // Setup PAR File// /////////////////// if (pararchivename) { char processline[1024]; TString base = gSystem->BaseName(pararchivename); TString dir = gSystem->DirName(pararchivename); TString ocwd = gSystem->WorkingDirectory(); // Move to dir where the par files are and unpack gSystem->ChangeDirectory(dir.Data()); sprintf(processline,".! tar xvzf %s.par",base.Data()); gROOT->ProcessLine(processline); // Move to par folder gSystem->ChangeDirectory(base.Data()); // check for BUILD.sh and execute if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) { printf("*******************************\n"); printf("*** Building PAR archive ***\n"); printf("*******************************\n"); if (gSystem->Exec("PROOF-INF/BUILD.sh")) { Error("runAnalysis","Cannot Build the PAR Archive! - Abort!"); gSystem->ChangeDirectory(ocwd.Data()); return -1; } } // check for SETUP.C and execute if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) { printf("*******************************\n"); printf("*** Setup PAR archive ***\n"); printf("*******************************\n"); // If dir not empty, set the full include path if (dir.Length()) { sprintf(processline, ".include %s", pararchivename); gROOT->ProcessLine(processline); } gROOT->Macro("PROOF-INF/SETUP.C"); } gSystem->ChangeDirectory(ocwd.Data()); } return 1; }<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <stdlib.h> #include <time.h> using namespace std; //global variables int HEALTH = 100; int WEALTH = 0; string SHIP = "Sloop"; int SHIP_HEALTH = 100; string NAME; vector <string> CREW; //prototypes void game_play(); //clear screen void clear() { // CSI[2J clears screen, CSI[H moves the cursor to top-left corner cout << "\x1B[2J\x1B[H"; } //used first time playing game bool init() { cout << "Ahoy thar! Welcome to the Pirate Game! ARRGH!" << endl; cout << "Would ye like to play? (Y/N) "; string input = ""; while (input != "Y" && input != "N") { cin >> input; } if(input == "N") { return false; } else if(input == "Y") { clear(); cout << "That be the spirit! What be yer name? "; cin >> NAME; return true; } } //main menu void land_menu() { cout << " MENU " << endl; cout << " --------------------------------------" << endl; cout << " | 1. Navigate the Seas |" << endl; cout << " | 2. Build a Crew |" << endl; cout << " | 3. Find a Ship |" << endl; cout << " | 4. Try Yer Luck |" << endl; cout << " | 5. Check Yer Satus |" << endl; cout << " | 6. Save |" << endl; cout << " --------------------------------------" << endl; cout << " | Q to quit the game |" << endl; cout << " --------------------------------------" << endl; } //sea menu void sea_menu() { cout << " Navigate" << endl; cout << " --------------------------------------" << endl; cout << " | 1. Continue sailing |" << endl; cout << " | 2. Return to Land |" << endl; cout << " --------------------------------------" << endl; } //used first time playing game void tutorial_init() { clear(); cout << "It be a pleasure to set sail with ye, " << NAME << "! ARRGH!" << endl << endl; cout << "This be the main menu. Ye can navigate the menu by enterin\' the respective numbers." << endl << endl; land_menu(); cout << endl; cout << "Yer objective be to gain as much wealth as possible before death be yer fate! ARRGH" << endl; cout << "Upgrading yer ships, growin\' yer crew, and tryin\' yer luck can help yer chances while sailin\' the seas." << endl; cout << "Ye will start off with the Sloop as yer vessel, a crew of size 0, a wealth of $0, and a health of 100 points." << endl; cout << "Best of luck to ye!" << endl; cout << "Enter \"START\" to begin the game: "; string input = ""; while (input != "START") { cin >> input; } clear(); } void sail() //1 { int next = 0; int injury = 0; int treasure = 0; sea_menu(); cout << "What woul\' ye like to do, capt\'n " << NAME << "? " << endl; string input = ""; while (input != "1" && input != "2") { cin >> input; } if (input == "1") { next = rand() % 100; if (next < 20) { clear(); cout << "It be smooth sailin\'." << endl; sail(); } else if (next < 30) { clear(); cout << "Ye got battered up by some stormy weather! ARRGH!" << endl; injury = rand() % 3 + 1; //from 1 to 3 cout << "Health -" << injury; HEALTH -= injury; sail(); } else if (next < 45) { clear(); if (CREW.size() > 0) { if (next % 3 == 0) { cout << "Yer crew came down wit\' scurvy! ARRGH!" << endl; injury = rand() % 5 + 5; //from 5 to 10 cout << "Health -" << injury; HEALTH -= injury; } else if (next % 3 == 1) { cout << "Yer crew started a fight on board yer ship! Them scalleywags!" << endl; injury = rand() % 2 + 5; //from 2 to 7 cout << "Health -" << injury; HEALTH -= injury; } else { cout << "Yer crew didn\'t get any shut eye!" << endl; injury = 1; cout << "Health -" << injury; HEALTH -= injury; } } else { clear(); if (next % 3 == 0) { cout << "Ye came down wit\' scurvy! ARRGH!" << endl; injury = rand() % 5 + 5; //from 5 to 10 cout << "Health -" << injury; HEALTH -= injury; } else if (next % 3 == 1) { cout << "Ye got sea sick from some rough tides!" << endl; injury = rand() % 2 + 5; //from 2 to 7 cout << "Health -" << injury; HEALTH -= injury; } else { cout << "Yer couldn\'t get any shut eye!" << endl; injury = 1; cout << "Health -" << injury; HEALTH -= injury; } } sail(); } else if (next < 60) { clear(); cout << "Ye came across some floatin\' treasure!" << endl; if (next % 2 == 0) { treasure = rand() % 10 + 1 + 5; //from 5 to 15 } else { treasure = rand() % 5 + 1; //from 1 to 5 } cout << "Wealth +" << treasure << endl; WEALTH += treasure; sail(); } else if (next < 80) { clear(); cout << "Thar be a small ship up ahead. Would ye like to attack? (Y/N) " << endl; input = ""; cin >> input; while (input != "Y" && input != "N") { cin >> input; } if (input == "Y") { //battle } else if (input == "N") { cout << "Ye let the humble wee vessel be..." << endl; } sail(); } else { clear(); cout << "A military ship is just under the horizon. Would ye like to attack it? (Y/N) " << endl; input = ""; cin >> input; while (input != "Y" && input != "N") { cin >> input; } if (input == "Y") { //battle } else if (input == "N") { if (next % 3 != 0) { cout << "Ye sailed passed their ship unharmed." << endl; } else { cout << "The ship blocked yer path! ARRGH! To battle!" << endl; //battle } } sail(); } } else if (input == "2") { clear(); game_play(); } } void build_crew() //2 { clear(); game_play(); } void ship_yard() //3 { string input = ""; if (WEALTH == 0) { cout << "Ye need some wealth to come to the ship yard!" << endl; cout << "Try settin\' sail first." << endl; cout << "(Type C to Continue) : "; cin >> input; while (input != "C") { cin >> input; } clear(); game_play(); } else { //do stuff } } void try_luck() //4 { string input = ""; if (WEALTH == 0) { cout << "Ye need some wealth to come to the ship yard!" << endl; cout << "Try settin\' sail first." << endl; cout << "(Type C to Continue) : "; cin >> input; while (input != "C") { cin >> input; } clear(); game_play(); } else { //do stuff } } void status() //5 { clear(); cout << "Status of " << NAME << ": " << endl; cout << endl; cout << "Health: " << HEALTH << endl; cout << "Wealth: " << WEALTH << endl; cout << endl; cout << "Ship: " << SHIP << endl; cout << "Ship Health: " << SHIP_HEALTH << endl; cout << "Crew size: " << CREW.size() << endl; if (CREW.size() > 0) { cout << "Crew members: " << endl; for (int i = 0; i < CREW.size(); i++) { cout << " " << CREW.at(i) << endl; } } cout << endl; cout << "(Type C to Continue) : "; string input = ""; while (input != "C") { cin >> input; } clear(); game_play(); } void save() //6 { clear(); cout << "This feature is not yet implemented" << endl; cout << "(Type C to Continue) : "; string input = ""; while (input != "C") { cin >> input; } clear(); game_play(); } void game_play() { land_menu(); string input = ""; while (input != "1" && input != "2" && input != "3" && input != "4" && input != "5" && input != "6" && input != "Q") { cin >> input; } if (input == "Q") { return; } else if (input == "1") { clear(); sail(); } else if (input == "2") { clear(); build_crew(); } else if (input == "3") { clear(); ship_yard(); } else if (input == "4") { clear(); try_luck(); } else if (input == "5") { clear(); status(); } else if (input == "6") { clear(); save(); } } int main() { clear(); srand(time(NULL)); if (init()) { tutorial_init(); game_play(); } clear(); cout << "Till we set sail again, " << NAME << "!" << endl; return 0; } <commit_msg>added ships<commit_after>#include <iostream> #include <vector> #include <stdlib.h> #include <time.h> using namespace std; //global variables int HEALTH = 100; int WEALTH = 0; string SHIP = "Sloop"; int SHIP_HEALTH = 100; string NAME; vector <string> CREW; //prototypes void game_play(); //clear screen void clear() { // CSI[2J clears screen, CSI[H moves the cursor to top-left corner cout << "\x1B[2J\x1B[H"; } //used first time playing game bool init() { cout << "Ahoy thar! Welcome to the Pirate Game! ARRGH!" << endl; cout << "Would ye like to play? (Y/N) "; string input = ""; while (input != "Y" && input != "N") { cin >> input; } if(input == "N") { return false; } else if(input == "Y") { clear(); cout << "That be the spirit! What be yer name? "; cin >> NAME; return true; } } //main menu void land_menu() { cout << " MENU " << endl; cout << " --------------------------------------" << endl; cout << " | 1. Navigate the Seas |" << endl; cout << " | 2. Build a Crew |" << endl; cout << " | 3. Find a Ship |" << endl; cout << " | 4. Try Yer Luck |" << endl; cout << " | 5. Check Yer Satus |" << endl; cout << " | 6. Save |" << endl; cout << " --------------------------------------" << endl; cout << " | Q to quit the game |" << endl; cout << " --------------------------------------" << endl; } //sea menu void sea_menu() { cout << " Navigate" << endl; cout << " --------------------------------------" << endl; cout << " | 1. Continue sailing |" << endl; cout << " | 2. Return to Land |" << endl; cout << " --------------------------------------" << endl; } //used first time playing game void tutorial_init() { clear(); cout << "It be a pleasure to set sail with ye, " << NAME << "! ARRGH!" << endl << endl; cout << "This be the main menu. Ye can navigate the menu by enterin\' the respective numbers." << endl << endl; land_menu(); cout << endl; cout << "Yer objective be to gain as much wealth as possible before death be yer fate! ARRGH" << endl; cout << "Upgrading yer ships, growin\' yer crew, and tryin\' yer luck can help yer chances while sailin\' the seas." << endl; cout << endl; cout << "Ye will start off with the Sloop as yer vessel, a crew of size 0, a wealth of $0, and a health of 100 points." << endl; cout << "Best of luck to ye!" << endl; cout << "Enter \"START\" to begin the game: "; string input = ""; while (input != "START") { cin >> input; } clear(); } void sail() //1 { int next = 0; int injury = 0; int treasure = 0; sea_menu(); cout << "What woul\' ye like to do, capt\'n " << NAME << "? " << endl; string input = ""; while (input != "1" && input != "2") { cin >> input; } if (input == "1") { next = rand() % 100; if (next < 20) { clear(); cout << "It be smooth sailin\'." << endl; sail(); } else if (next < 30) { clear(); cout << "Ye got battered up by some stormy weather! ARRGH!" << endl; injury = rand() % 3 + 1; //from 1 to 3 cout << "Health -" << injury; HEALTH -= injury; sail(); } else if (next < 45) { clear(); if (CREW.size() > 0) { if (next % 3 == 0) { cout << "Yer crew came down wit\' scurvy! ARRGH!" << endl; injury = rand() % 5 + 5; //from 5 to 10 cout << "Health -" << injury << endl; HEALTH -= injury; } else if (next % 3 == 1) { cout << "Yer crew started a fight on board yer ship! Them scalleywags!" << endl; injury = rand() % 2 + 5; //from 2 to 7 cout << "Health -" << injury << endl; HEALTH -= injury; } else { cout << "Yer crew didn\'t get any shut eye!" << endl; injury = 1; cout << "Health -" << injury << endl; HEALTH -= injury; } } else { clear(); if (next % 3 == 0) { cout << "Ye came down wit\' scurvy! ARRGH!" << endl; injury = rand() % 5 + 5; //from 5 to 10 cout << "Health -" << injury << endl; HEALTH -= injury; } else if (next % 3 == 1) { cout << "Ye got sea sick from some rough tides!" << endl; injury = rand() % 2 + 5; //from 2 to 7 cout << "Health -" << injury << endl; HEALTH -= injury; } else { cout << "Yer couldn\'t get any shut eye!" << endl; injury = 1; cout << "Health -" << injury << endl; HEALTH -= injury; } } sail(); } else if (next < 60) { clear(); cout << "Ye came across some floatin\' treasure!" << endl; if (next % 2 == 0) { treasure = rand() % 10 + 1 + 5; //from 5 to 15 } else { treasure = rand() % 5 + 1; //from 1 to 5 } cout << "Wealth +" << treasure << endl; WEALTH += treasure; sail(); } else if (next < 80) { clear(); cout << "Thar be a small ship up ahead. Would ye like to attack? (Y/N) " << endl; input = ""; cin >> input; while (input != "Y" && input != "N") { cin >> input; } if (input == "Y") { //battle } else if (input == "N") { cout << "Ye let the humble wee vessel be..." << endl; } sail(); } else { clear(); cout << "A military ship is just under the horizon. Would ye like to attack it? (Y/N) " << endl; input = ""; cin >> input; while (input != "Y" && input != "N") { cin >> input; } if (input == "Y") { //battle } else if (input == "N") { if (next % 3 != 0) { cout << "Ye sailed passed their ship unharmed." << endl; } else { cout << "The ship blocked yer path! ARRGH! To battle!" << endl; //battle } } sail(); } } else if (input == "2") { clear(); game_play(); } } void build_crew() //2 { clear(); game_play(); } void ship_yard() //3 { string input = ""; if (WEALTH == 0) { cout << "Ye need some wealth to come to the ship yard!" << endl; cout << "Try settin\' sail first." << endl; cout << "(Type C to Continue) : "; cin >> input; while (input != "C") { cin >> input; } clear(); game_play(); } else { cout << "Ahoy thar! Welcome to the ship yard!" << endl; cout << "Woul\' ye like to purchase one o\' me ships?" << endl; cout << endl; cout << "1. Pinnace.....................$150" << endl; cout << " Health: 120 Crew cap: 10 Attack level: 15" << endl; cout << endl; cout << "2. Lugger......................$160" << endl; cout << " Health: 110 Crew cap: 12 Attack level: 18" << endl; cout << endl; cout << "3. Corvette....................$220" << endl; cout << " Health: 180 Crew cap: 20 Attack level: 30" << endl; cout << endl; cout << "4. Schooner....................$275" << endl; cout << " Health: 200 Crew cap: 20 Attack level: 33" << endl; cout << endl; cout << "5. Collier.....................$400" << endl; cout << " Health: 250 Crew cap: 30 Attack level: 45" << endl; cout << endl; cout << "6. Galleon.....................$650" << endl; cout << " Health: 375 Crew cap: 75 Attack level: 65" << endl; cout << endl; cout << "7. Barque......................$1000" << endl; cout << " Health: 500 Crew cap: 100 Attack level: 90" << endl; cout << endl; cout << "8. Clipper.....................$2,250" << endl; cout << " Health: 700 Crew cap: 150 Attack level: 110" << endl; cout << endl; cout << "9. Frigate.....................$4,500" << endl; cout << " Health: 1000 Crew cap: 250 Attack level: 150" << endl; cout << endl; cout << "10. Man O\' War.................$5,000" << endl; cout << " Health: 1200 Crew cap: 200 Attack level: 135" << endl; cout << endl; cout << "11. Ship of the Line............$6,000" << endl; cout << " Health: 1100 Crew cap: 300 Attack level: 145" << endl; cout << endl; cout << "12. The Armada's Brig...........$15,000" << endl; cout << " Health: 1500 Crew cap: 450 Attack level: 200" << endl; cout << endl; cout << "13. Royal Navy's Frigate........$20,000" << endl; cout << " Health: 1500 Crew cap: 500 Attack level: 200" << endl; cout << endl; cout << "14. The Black Pearl.............$100,000" << endl; cout << " Health: 2000 Crew cap: 750 Attack level: 300" << endl; cout << endl; cout << "15. The Flying Dutchman.........$500,000" << endl; cout << " Health: 3000 Crew cap: 1000 Attack level: 400" << endl; cout << endl; cin >> input; while (input != "1" && input != "2" && input != "1" && input != "4" && input != "5" && input != "6" && input != "7" && input != "8" && input != "9" && input != "10" && input != "11" && input != "12" && input != "13" && input != "14" && input != "15") { cin >> input; } } game_play(); } void try_luck() //4 { string input = ""; if (WEALTH == 0) { cout << "Ye need some wealth to come to the ship yard!" << endl; cout << "Try settin\' sail first." << endl; cout << "(Type C to Continue) : "; cin >> input; while (input != "C") { cin >> input; } clear(); game_play(); } else { //do stuff } game_play(); } void status() //5 { clear(); cout << "Status of " << NAME << ": " << endl; cout << endl; cout << "Health: " << HEALTH << endl; cout << "Wealth: " << WEALTH << endl; cout << endl; cout << "Ship: " << SHIP << endl; cout << "Ship Health: " << SHIP_HEALTH << endl; cout << "Crew size: " << CREW.size() << endl; if (CREW.size() > 0) { cout << "Crew members: " << endl; for (int i = 0; i < CREW.size(); i++) { cout << " " << CREW.at(i) << endl; } } cout << endl; cout << "(Type C to Continue) : "; string input = ""; while (input != "C") { cin >> input; } clear(); game_play(); } void save() //6 { clear(); cout << "This feature is not yet implemented" << endl; cout << "(Type C to Continue) : "; string input = ""; while (input != "C") { cin >> input; } clear(); game_play(); } void game_play() { land_menu(); string input = ""; while (input != "1" && input != "2" && input != "3" && input != "4" && input != "5" && input != "6" && input != "Q") { cin >> input; } if (input == "Q") { return; } else if (input == "1") { clear(); sail(); } else if (input == "2") { clear(); build_crew(); } else if (input == "3") { clear(); ship_yard(); } else if (input == "4") { clear(); try_luck(); } else if (input == "5") { clear(); status(); } else if (input == "6") { clear(); save(); } } int main() { clear(); srand(time(NULL)); if (init()) { tutorial_init(); game_play(); } clear(); cout << "Till we set sail again, " << NAME << "!" << endl; return 0; } <|endoftext|>
<commit_before>#include "game.hpp" #include "main_state.hpp" #include "entity_creator.hpp" Game::~Game() { SDL_DestroyRenderer(m_render); SDL_DestroyWindow(m_window); Mix_Quit(); IMG_Quit(); SDL_Quit(); } int Game::init() { if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } int width = 1200; int height = 800; m_window = SDL_CreateWindow("Hello World!", 100, 100, width, height, SDL_WINDOW_SHOWN); if (m_window == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (m_render == nullptr) { SDL_DestroyWindow(m_window); std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } m_res_manager.load_surface("Player","res/character.png",m_render); SDL_RenderSetLogicalSize(m_render, width, height); entityx::Entity entity = m_ex.entities.create(); entity.assign<Interactable>(); entity.assign<Position>(); m_states.push({"main", std::make_unique<MainState>(this)}); m_states.top().second->init(); return 0; } void Game::mainloop() { int current_time = SDL_GetTicks(); double dt = (current_time - m_last_frame_time) / 1000.0; m_last_frame_time = current_time; m_states.top().second->update(dt); } SDL_Renderer *Game::get_renderer() { return m_render; } SDL_Window *Game::get_window() { return m_window; } ResourceManager &Game::get_res_manager() { return m_res_manager; } bool Game::is_running() { return m_running; } void Game::shutdown() { m_running = false; } const SDL_Rect &Game::get_worldsize() const { return m_worldsize; } <commit_msg>Style<commit_after>#include "game.hpp" #include "main_state.hpp" #include "entity_creator.hpp" Game::~Game() { SDL_DestroyRenderer(m_render); SDL_DestroyWindow(m_window); Mix_Quit(); IMG_Quit(); SDL_Quit(); } int Game::init() { if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } int width = 1200; int height = 800; m_window = SDL_CreateWindow("Hello World!", 100, 100, width, height, SDL_WINDOW_SHOWN); if (m_window == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (m_render == nullptr) { SDL_DestroyWindow(m_window); std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } m_res_manager.load_surface("Player","res/character.png",m_render); SDL_RenderSetLogicalSize(m_render, width, height); entityx::Entity entity = m_ex.entities.create(); entity.assign<Interactable>(); entity.assign<Position>(); m_states.push({"main", std::make_unique<MainState>(this)}); m_states.top().second->init(); return 0; } void Game::mainloop() { int current_time = SDL_GetTicks(); double dt = (current_time - m_last_frame_time) / 1000.0; m_last_frame_time = current_time; m_states.top().second->update(dt); } SDL_Renderer *Game::get_renderer() { return m_render; } SDL_Window *Game::get_window() { return m_window; } ResourceManager &Game::get_res_manager() { return m_res_manager; } bool Game::is_running() { return m_running; } void Game::shutdown() { m_running = false; } const SDL_Rect &Game::get_worldsize() const { return m_worldsize; } <|endoftext|>
<commit_before>#include "TokenList.h" TokenListIterator::TokenListIterator(list<Token*>::iterator begin, list<Token*>::iterator end) { it = begin; this->begin = begin; this->end = --end; it--; } void TokenListIterator::toEnd () { it = end; } Token* TokenListIterator::previous () { return *--it; } Token* TokenListIterator::next () { return *++it; } Token* TokenListIterator::peek () { Token* ret; it++; ret = *it; it--; return ret; } bool TokenListIterator::hasNext () { return (it != end); } bool TokenListIterator::hasPrevious () { return (it != begin); } TokenList::~TokenList() { while (!empty()) delete pop(); } void TokenList::push (Token* token) { tokens.push_back(token); } Token* TokenList::pop () { Token* token = tokens.back(); tokens.pop_back(); return token; } void TokenList::unshift (Token* token) { tokens.push_front(token); } Token* TokenList::shift () { Token* token = tokens.front(); tokens.pop_front(); return token; } bool TokenList::empty () { return tokens.empty(); } int TokenList::size() { return tokens.size(); } bool TokenList::equals(TokenList* list) { TokenListIterator* it1, * it2; if (list->size() != size()) return false; it1 = iterator(); it2 = list->iterator(); while (it1->hasNext() && it2->hasNext()) { if (!it1->next()->equals(it2->next())) { delete it1; delete it2; return false; } } return true; } Token* TokenList::back() { return tokens.back(); } Token* TokenList::front() { return tokens.front(); } TokenListIterator* TokenList::iterator() { return new TokenListIterator(tokens.begin(), tokens.end()); } TokenListIterator* TokenList::reverseIterator () { TokenListIterator* it = new TokenListIterator(tokens.begin(), tokens.end()); it->toEnd(); return it; } void TokenList::push(TokenList* list) { TokenListIterator* it = list->iterator(); while (it->hasNext()) push(it->next()->clone()); delete it; } void TokenList::unshift(TokenList* list) { TokenListIterator* it = list->reverseIterator(); while (it->hasNext()) unshift(it->next()->clone()); delete it; } TokenList* TokenList::clone() { TokenList* newtokens = new TokenList(); list<Token*>::iterator it; for (it = tokens.begin(); it != tokens.end(); it++) { newtokens->push((*it)->clone()); } return newtokens; } string* TokenList::toString() { string* str = new string(); list<Token*>::iterator it; for (it = tokens.begin(); it != tokens.end(); it++) { str->append((*it)->str); } return str; } <commit_msg>Fixed the TokenList::unshift() and TokenListIterator::toEnd() functions.<commit_after>#include "TokenList.h" TokenListIterator::TokenListIterator(list<Token*>::iterator begin, list<Token*>::iterator end) { it = begin; this->begin = begin; this->end = --end; it--; } void TokenListIterator::toEnd () { it = end; it++; } Token* TokenListIterator::previous () { return *--it; } Token* TokenListIterator::next () { return *++it; } Token* TokenListIterator::peek () { Token* ret; it++; ret = *it; it--; return ret; } bool TokenListIterator::hasNext () { return (it != end); } bool TokenListIterator::hasPrevious () { return (it != begin); } TokenList::~TokenList() { while (!empty()) delete pop(); } void TokenList::push (Token* token) { tokens.push_back(token); } Token* TokenList::pop () { Token* token = tokens.back(); tokens.pop_back(); return token; } void TokenList::unshift (Token* token) { tokens.push_front(token); } Token* TokenList::shift () { Token* token = tokens.front(); tokens.pop_front(); return token; } bool TokenList::empty () { return tokens.empty(); } int TokenList::size() { return tokens.size(); } bool TokenList::equals(TokenList* list) { TokenListIterator* it1, * it2; if (list->size() != size()) return false; it1 = iterator(); it2 = list->iterator(); while (it1->hasNext() && it2->hasNext()) { if (!it1->next()->equals(it2->next())) { delete it1; delete it2; return false; } } return true; } Token* TokenList::back() { return tokens.back(); } Token* TokenList::front() { return tokens.front(); } TokenListIterator* TokenList::iterator() { return new TokenListIterator(tokens.begin(), tokens.end()); } TokenListIterator* TokenList::reverseIterator () { TokenListIterator* it = new TokenListIterator(tokens.begin(), tokens.end()); it->toEnd(); return it; } void TokenList::push(TokenList* list) { TokenListIterator* it = list->iterator(); while (it->hasNext()) push(it->next()->clone()); delete it; } void TokenList::unshift(TokenList* list) { TokenListIterator* it = list->reverseIterator(); while (it->hasPrevious()) unshift(it->previous()->clone()); delete it; } TokenList* TokenList::clone() { TokenList* newtokens = new TokenList(); list<Token*>::iterator it; for (it = tokens.begin(); it != tokens.end(); it++) { newtokens->push((*it)->clone()); } return newtokens; } string* TokenList::toString() { string* str = new string(); list<Token*>::iterator it; for (it = tokens.begin(); it != tokens.end(); it++) { str->append((*it)->str); } return str; } <|endoftext|>
<commit_before>#include <cpr/cpr.h> #include <fstream> #include <regex> #include <tw/reader.h> #include <utils.h> #include "permissions.h" #include "TwitchBot.h" #include "version.h" static const char *TWITCH_SERV = "irc.twitch.tv"; static const char *TWITCH_PORT = "80"; static std::string urltitle(const std::string &resp); TwitchBot::TwitchBot(const std::string &nick, const std::string &channel, const std::string &password, const std::string &token, ConfigReader *cfgr) : m_connected(false), m_nick(nick), m_channelName(channel), m_token(token), m_client(TWITCH_SERV, TWITCH_PORT), m_cmdHandler(nick, channel.substr(1), token, &m_mod, &m_parser, &m_event, &m_giveaway, cfgr), m_cfgr(cfgr), m_event(cfgr), m_giveaway(channel.substr(1), time(nullptr), cfgr), m_mod(&m_parser, cfgr) { if ((m_connected = m_client.cconnect())) { /* send required IRC data: PASS, NICK, USER */ sendData("PASS " + password); sendData("NICK " + nick); sendData("USER " + nick); /* enable tags in PRIVMSGs */ sendData("CAP REQ :twitch.tv/tags"); /* join channel */ sendData("JOIN " + channel); m_tick = std::thread(&TwitchBot::tick, this); /* create giveaway checking event */ m_event.add("checkgiveaway", 10, time(nullptr)); /* read the subscriber messages */ parseSubMsg(m_subMsg, "submessage"); parseSubMsg(m_resubMsg, "resubmessage"); } } TwitchBot::~TwitchBot() { m_client.cdisconnect(); } bool TwitchBot::isConnected() const { return m_connected; } /* disconnect: disconnect from Twitch server */ void TwitchBot::disconnect() { m_client.cdisconnect(); m_connected = false; m_tick.join(); } /* serverLoop: continously receive and process data */ void TwitchBot::serverLoop() { std::string msg; /* continously receive data from server */ while (true) { if (m_client.cread(msg) <= 0) { std::cerr << "No data received. Exiting." << std::endl; disconnect(); break; } std::cout << "[RECV] " << msg << std::endl; processData(msg); if (!m_connected) break; } } /* sendData: format data and write to client */ bool TwitchBot::sendData(const std::string &data) { /* format string by adding CRLF */ std::string formatted = data + (utils::endsWith(data, "\r\n") ? "" : "\r\n"); /* send formatted data */ int32_t bytes = m_client.cwrite(formatted); std::cout << (bytes > 0 ? "[SENT] " : "Failed to send: ") << formatted << std::endl; /* return true iff data was sent succesfully */ return bytes > 0; } /* sendMsg: send a PRIVMSG to the connected channel */ bool TwitchBot::sendMsg(const std::string &msg) { return sendData("PRIVMSG " + m_channelName + " :" + msg); } /* sendPong: send an IRC PONG */ bool TwitchBot::sendPong(const std::string &ping) { /* first six chars are "PING :", server name starts after */ return sendData("PONG " + ping.substr(6)); } /* processData: send data to designated function */ void TwitchBot::processData(const std::string &data) { if (data.find("Error logging in") != std::string::npos || data.find("Login unsuccessful") != std::string::npos) { disconnect(); std::cerr << "\nCould not log in to Twitch IRC.\nMake sure " << utils::configdir() << utils::config("config") << " is configured correctly." << std::endl; std::cin.get(); } else if (utils::startsWith(data, "PING")) { sendPong(data); } else if (data.find("PRIVMSG") != std::string::npos) { processPRIVMSG(data); } } /* processPRIVMSG: parse a chat message and perform relevant actions */ bool TwitchBot::processPRIVMSG(const std::string &PRIVMSG) { /* regex to extract all necessary data from message */ static const std::regex privmsgRegex("subscriber=(\\d).*user-type=(.*) " ":(\\w+)!\\3@\\3.* PRIVMSG (#\\w+) :(.+)"); static const std::regex subRegex(":twitchnotify.* PRIVMSG (#\\w+) " ":(.+) (?:just subscribed!|subscribed for (\\d+) " "months)"); std::smatch match; if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, privmsgRegex)) { const std::string type = match[2].str(); const std::string nick = match[3].str(); const std::string channel = match[4].str(); const std::string msg = match[5].str(); /* confirm message is from current channel */ if (channel != m_channelName) return false; /* set user privileges */ perm_t p; P_RESET(p); if (nick == channel.substr(1) || nick == "brainsoldier") P_STOWN(p); if (!type.empty()) P_STMOD(p); if (match[1].str() == "1") P_STSUB(p); /* check if the message contains a URL */ m_parser.parse(msg); /* check if message is valid */ if (P_ISREG(p) && m_mod.active() && moderate(nick, msg)) return true; /* all chat commands start with $ */ if (utils::startsWith(msg, "$") && msg.length() > 1) { std::string output = m_cmdHandler.processCommand( nick, msg.substr(1), p); if (!output.empty()) sendMsg(output); return true; } /* count */ if (m_cmdHandler.isCounting() && utils::startsWith(msg, "+") && msg.length() > 1) { m_cmdHandler.count(nick, msg.substr(1)); return true; } /* link information */ if (m_parser.wasModified()) { URLParser::URL *url = m_parser.getLast(); /* print info about twitter statuses */ if (url->twitter && !url->tweetID.empty()) { tw::Reader twr(&m_auth); if (twr.read(url->tweetID)) { sendMsg(twr.result()); return true; } else { std::cout << "Could not read tweet" << std::endl; return false; } } /* get the title of the url otherwise */ cpr::Response resp = cpr::Get(cpr::Url(url->full), cpr::Header{{ "Connection", "close" }}); std::string title; std::string s = url->subdomain + url->domain; if (!(title = urltitle(resp.text)).empty()) { sendMsg("[URL] " + title + " (at " + s + ")"); return true; } return false; } /* check for responses */ std::string output = m_cmdHandler.processResponse(msg); if (!output.empty()) sendMsg("@" + nick + ", " + output); return true; } else if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, subRegex)) { std::string nick, fmt, len; nick = match[2].str(); if (match[3].str().empty()) { fmt = m_subMsg; len = "1"; } else { fmt = m_resubMsg; len = match[3].str(); } std::cout << formatSubMsg(fmt, nick, len) << std::endl; /* sendMsg(formatSubMsg(fmt, nick, len)); */ return true; } else { std::cerr << "Could not extract data" << std::endl; return false; } return false; } /* moderate: check if message is valid; penalize nick if not */ bool TwitchBot::moderate(const std::string &nick, const std::string &msg) { std::string reason; if (!m_mod.isValidMsg(msg, nick, reason)) { uint8_t offenses = m_mod.getOffenses(nick); static const std::string warnings[5] = { "first", "second", "third", "fourth", "FINAL" }; std::string warning; if (offenses < 6) { /* timeout for 2^(offenses - 1) minutes */ uint16_t t = 60 * (uint16_t)pow(2, offenses - 1); sendMsg("/timeout " + nick + " " + std::to_string(t)); warning = warnings[offenses - 1] + " warning"; } else { sendMsg("/ban " + nick); warning = "Permanently banned"; } sendMsg(nick + " - " + reason + " (" + warning + ")"); return true; } return false; } /* tick: repeatedly check variables and perform actions if conditions met */ void TwitchBot::tick() { /* check every second */ while (m_connected) { for (std::vector<std::string>::size_type i = 0; i < m_event.messages()->size(); ++i) { if (m_event.ready("msg" + std::to_string(i))) { if (m_event.messagesActive()) sendMsg(((*m_event.messages())[i]).first); m_event.setUsed("msg" + std::to_string(i)); break; } } if (m_giveaway.active() && m_event.ready("checkgiveaway")) { if (m_giveaway.checkConditions(time(nullptr))) sendMsg(m_giveaway.giveaway()); m_event.setUsed("checkgiveaway"); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } /* parseSubMsg: read which from m_cfgr into tgt and verify validity */ void TwitchBot::parseSubMsg(std::string &tgt, const std::string &which) { static const std::string fmt_c = "%Ncmn"; size_t ind; std::string fmt, err; char c; ind = -1; fmt = m_cfgr->get(which); while ((ind = fmt.find('%', ind + 1)) != std::string::npos) { if (ind == fmt.length() - 1) { err = "unexpected end of line after '%'"; break; } c = fmt[ind + 1]; if (fmt_c.find(c) == std::string::npos) { err = "invalid format character -- "; err += c; break; } if (c == '%') ++ind; } if (!err.empty()) { std::cerr << m_cfgr->path() << ": " << which << ": " << err << std::endl; std::cin.get(); fmt = ""; } tgt = fmt; } /* formatSubMsg: replace placeholders in format string with data */ std::string TwitchBot::formatSubMsg(const std::string &format, const std::string &n, const std::string &m) { size_t ind; std::string out, ins; char c; ind = 0; out = format; while ((ind = out.find('%', ind)) != std::string::npos) { c = out[ind + 1]; out.erase(ind, 2); switch (c) { case '%': ins = "%"; break; case 'N': ins = "@" + n + ","; break; case 'c': ins = m_channelName.substr(1); break; case 'm': ins = m; break; case 'n': ins = n; break; default: break; } out.insert(ind, ins); ind += ins.length(); } return out; } /* urltitle: extract webpage title from html */ static std::string urltitle(const std::string &resp) { size_t start; if ((start = resp.find("<title>")) != std::string::npos) { std::string title; for (start += 7; resp[start] != '<'; ++start) title += resp[start] == '\n' ? ' ' : resp[start]; return title; } return ""; } <commit_msg>Formatted sub and resub messages<commit_after>#include <cpr/cpr.h> #include <fstream> #include <regex> #include <tw/reader.h> #include <utils.h> #include "permissions.h" #include "TwitchBot.h" #include "version.h" static const char *TWITCH_SERV = "irc.twitch.tv"; static const char *TWITCH_PORT = "80"; static std::string urltitle(const std::string &resp); TwitchBot::TwitchBot(const std::string &nick, const std::string &channel, const std::string &password, const std::string &token, ConfigReader *cfgr) : m_connected(false), m_nick(nick), m_channelName(channel), m_token(token), m_client(TWITCH_SERV, TWITCH_PORT), m_cmdHandler(nick, channel.substr(1), token, &m_mod, &m_parser, &m_event, &m_giveaway, cfgr), m_cfgr(cfgr), m_event(cfgr), m_giveaway(channel.substr(1), time(nullptr), cfgr), m_mod(&m_parser, cfgr) { if ((m_connected = m_client.cconnect())) { /* send required IRC data: PASS, NICK, USER */ sendData("PASS " + password); sendData("NICK " + nick); sendData("USER " + nick); /* enable tags in PRIVMSGs */ sendData("CAP REQ :twitch.tv/tags"); /* join channel */ sendData("JOIN " + channel); m_tick = std::thread(&TwitchBot::tick, this); /* create giveaway checking event */ m_event.add("checkgiveaway", 10, time(nullptr)); /* read the subscriber messages */ parseSubMsg(m_subMsg, "submessage"); parseSubMsg(m_resubMsg, "resubmessage"); } } TwitchBot::~TwitchBot() { m_client.cdisconnect(); } bool TwitchBot::isConnected() const { return m_connected; } /* disconnect: disconnect from Twitch server */ void TwitchBot::disconnect() { m_client.cdisconnect(); m_connected = false; m_tick.join(); } /* serverLoop: continously receive and process data */ void TwitchBot::serverLoop() { std::string msg; /* continously receive data from server */ while (true) { if (m_client.cread(msg) <= 0) { std::cerr << "No data received. Exiting." << std::endl; disconnect(); break; } std::cout << "[RECV] " << msg << std::endl; processData(msg); if (!m_connected) break; } } /* sendData: format data and write to client */ bool TwitchBot::sendData(const std::string &data) { /* format string by adding CRLF */ std::string formatted = data + (utils::endsWith(data, "\r\n") ? "" : "\r\n"); /* send formatted data */ int32_t bytes = m_client.cwrite(formatted); std::cout << (bytes > 0 ? "[SENT] " : "Failed to send: ") << formatted << std::endl; /* return true iff data was sent succesfully */ return bytes > 0; } /* sendMsg: send a PRIVMSG to the connected channel */ bool TwitchBot::sendMsg(const std::string &msg) { return sendData("PRIVMSG " + m_channelName + " :" + msg); } /* sendPong: send an IRC PONG */ bool TwitchBot::sendPong(const std::string &ping) { /* first six chars are "PING :", server name starts after */ return sendData("PONG " + ping.substr(6)); } /* processData: send data to designated function */ void TwitchBot::processData(const std::string &data) { if (data.find("Error logging in") != std::string::npos || data.find("Login unsuccessful") != std::string::npos) { disconnect(); std::cerr << "\nCould not log in to Twitch IRC.\nMake sure " << utils::configdir() << utils::config("config") << " is configured correctly." << std::endl; std::cin.get(); } else if (utils::startsWith(data, "PING")) { sendPong(data); } else if (data.find("PRIVMSG") != std::string::npos) { processPRIVMSG(data); } } /* processPRIVMSG: parse a chat message and perform relevant actions */ bool TwitchBot::processPRIVMSG(const std::string &PRIVMSG) { /* regex to extract all necessary data from message */ static const std::regex privmsgRegex("subscriber=(\\d).*user-type=(.*) " ":(\\w+)!\\3@\\3.* PRIVMSG (#\\w+) :(.+)"); static const std::regex subRegex(":twitchnotify.* PRIVMSG (#\\w+) " ":(.+) (?:just subscribed!|subscribed for (\\d+) " "months)"); std::smatch match; if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, privmsgRegex)) { const std::string type = match[2].str(); const std::string nick = match[3].str(); const std::string channel = match[4].str(); const std::string msg = match[5].str(); /* confirm message is from current channel */ if (channel != m_channelName) return false; /* set user privileges */ perm_t p; P_RESET(p); if (nick == channel.substr(1) || nick == "brainsoldier") P_STOWN(p); if (!type.empty()) P_STMOD(p); if (match[1].str() == "1") P_STSUB(p); /* check if the message contains a URL */ m_parser.parse(msg); /* check if message is valid */ if (P_ISREG(p) && m_mod.active() && moderate(nick, msg)) return true; /* all chat commands start with $ */ if (utils::startsWith(msg, "$") && msg.length() > 1) { std::string output = m_cmdHandler.processCommand( nick, msg.substr(1), p); if (!output.empty()) sendMsg(output); return true; } /* count */ if (m_cmdHandler.isCounting() && utils::startsWith(msg, "+") && msg.length() > 1) { m_cmdHandler.count(nick, msg.substr(1)); return true; } /* link information */ if (m_parser.wasModified()) { URLParser::URL *url = m_parser.getLast(); /* print info about twitter statuses */ if (url->twitter && !url->tweetID.empty()) { tw::Reader twr(&m_auth); if (twr.read(url->tweetID)) { sendMsg(twr.result()); return true; } else { std::cout << "Could not read tweet" << std::endl; return false; } } /* get the title of the url otherwise */ cpr::Response resp = cpr::Get(cpr::Url(url->full), cpr::Header{{ "Connection", "close" }}); std::string title; std::string s = url->subdomain + url->domain; if (!(title = urltitle(resp.text)).empty()) { sendMsg("[URL] " + title + " (at " + s + ")"); return true; } return false; } /* check for responses */ std::string output = m_cmdHandler.processResponse(msg); if (!output.empty()) sendMsg("@" + nick + ", " + output); return true; } else if (std::regex_search(PRIVMSG.begin(), PRIVMSG.end(), match, subRegex)) { std::string nick, fmt, len; nick = match[2].str(); if (match[3].str().empty()) { fmt = m_subMsg; len = "1"; } else { fmt = m_resubMsg; len = match[3].str(); } if (!fmt.empty()) sendMsg(formatSubMsg(fmt, nick, len)); return true; } else { std::cerr << "Could not extract data" << std::endl; return false; } return false; } /* moderate: check if message is valid; penalize nick if not */ bool TwitchBot::moderate(const std::string &nick, const std::string &msg) { std::string reason; if (!m_mod.isValidMsg(msg, nick, reason)) { uint8_t offenses = m_mod.getOffenses(nick); static const std::string warnings[5] = { "first", "second", "third", "fourth", "FINAL" }; std::string warning; if (offenses < 6) { /* timeout for 2^(offenses - 1) minutes */ uint16_t t = 60 * (uint16_t)pow(2, offenses - 1); sendMsg("/timeout " + nick + " " + std::to_string(t)); warning = warnings[offenses - 1] + " warning"; } else { sendMsg("/ban " + nick); warning = "Permanently banned"; } sendMsg(nick + " - " + reason + " (" + warning + ")"); return true; } return false; } /* tick: repeatedly check variables and perform actions if conditions met */ void TwitchBot::tick() { /* check every second */ while (m_connected) { for (std::vector<std::string>::size_type i = 0; i < m_event.messages()->size(); ++i) { if (m_event.ready("msg" + std::to_string(i))) { if (m_event.messagesActive()) sendMsg(((*m_event.messages())[i]).first); m_event.setUsed("msg" + std::to_string(i)); break; } } if (m_giveaway.active() && m_event.ready("checkgiveaway")) { if (m_giveaway.checkConditions(time(nullptr))) sendMsg(m_giveaway.giveaway()); m_event.setUsed("checkgiveaway"); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } /* parseSubMsg: read which from m_cfgr into tgt and verify validity */ void TwitchBot::parseSubMsg(std::string &tgt, const std::string &which) { static const std::string fmt_c = "%Ncmn"; size_t ind; std::string fmt, err; char c; ind = -1; fmt = m_cfgr->get(which); while ((ind = fmt.find('%', ind + 1)) != std::string::npos) { if (ind == fmt.length() - 1) { err = "unexpected end of line after '%'"; break; } c = fmt[ind + 1]; if (fmt_c.find(c) == std::string::npos) { err = "invalid format character -- "; err += c; break; } if (c == '%') ++ind; } if (!err.empty()) { std::cerr << m_cfgr->path() << ": " << which << ": " << err << std::endl; std::cin.get(); fmt = ""; } tgt = fmt; } /* formatSubMsg: replace placeholders in format string with data */ std::string TwitchBot::formatSubMsg(const std::string &format, const std::string &n, const std::string &m) { size_t ind; std::string out, ins; char c; ind = 0; out = format; while ((ind = out.find('%', ind)) != std::string::npos) { c = out[ind + 1]; out.erase(ind, 2); switch (c) { case '%': ins = "%"; break; case 'N': ins = "@" + n + ","; break; case 'c': ins = m_channelName.substr(1); break; case 'm': ins = m; break; case 'n': ins = n; break; default: break; } out.insert(ind, ins); ind += ins.length(); } return out; } /* urltitle: extract webpage title from html */ static std::string urltitle(const std::string &resp) { size_t start; if ((start = resp.find("<title>")) != std::string::npos) { std::string title; for (start += 7; resp[start] != '<'; ++start) title += resp[start] == '\n' ? ' ' : resp[start]; return title; } return ""; } <|endoftext|>
<commit_before> #include <cmath> #include "beam.h" Beam::Beam(int channel, int base_note, int color) : channel(channel), base_note(base_note), color(color) { } void Beam::draw_bg() { ofPushStyle(); ofFill(); ofSetHexColor(color); ofDrawRectangle(0, 0, 1, 1); ofPopStyle(); } void Beam::draw(vector<Hand> hands) { if(hands.size() > 0) { ofPushStyle(); ofFill(); ofSetHexColor(0xAAAAAA); ofDrawRectangle(0, 0, 1, 1); ofPopStyle(); } } void Beam::update(vector<Hand> hands, ofxMidiOut& midi_out) { BeamRegion regions[SCALE_SIZE]; float max_bend = 0.0; //sort hands into their respective regions for(Hand& hand : hands) { size_t r = hand_to_region(hand); //mark that there is a hand in this region regions[r].status = true; //fastest hand dominates if(hand.speed() > regions[r].hand.speed()) regions[r].hand = hand; if(hand.vel.x > max_bend) max_bend = (hand.vel.x < 0) ? 0 : hand.vel.x; } midi_out.sendPitchBend(channel, 0x2000 + (0x8000 * max_bend)); //check the current region status against the previous status, //to determine whether to send note ON or OFF for(size_t r = 0; r < SCALE_SIZE; r++) { int note = region_to_note(r); int vel = speed_to_midi_velocity(regions[r].hand.speed()); //if the hand is new if(regions[r].status && !previous_regions[r].status) { //NOTE ON ofLog() << "ON " << note << " : " << vel; midi_out.sendNoteOn(channel, note, vel); } else if(!regions[r].status && previous_regions[r].status) { //a hand just LEFT a region //NOTE OFF ofLog() << "OFF " << note << " : " << vel; midi_out.sendNoteOff(channel, note, 64); } //walk the buffers previous_regions[r] = regions[r]; } } size_t Beam::hand_to_region(Hand& hand) { size_t r = floor(ofLerp(0, SCALE_SIZE, hand.pos.y)); return max((size_t) 0, min(r, SCALE_SIZE - 1)); } int Beam::region_to_note(size_t region) { return base_note + midi_scale[region]; } size_t Beam::speed_to_midi_velocity(float speed) { return midi_velocities[0]; //TODO } <commit_msg>increased bend range<commit_after> #include <cmath> #include "beam.h" Beam::Beam(int channel, int base_note, int color) : channel(channel), base_note(base_note), color(color) { } void Beam::draw_bg() { ofPushStyle(); ofFill(); ofSetHexColor(color); ofDrawRectangle(0, 0, 1, 1); ofPopStyle(); } void Beam::draw(vector<Hand> hands) { if(hands.size() > 0) { ofPushStyle(); ofFill(); ofSetHexColor(0xAAAAAA); ofDrawRectangle(0, 0, 1, 1); ofPopStyle(); } } void Beam::update(vector<Hand> hands, ofxMidiOut& midi_out) { BeamRegion regions[SCALE_SIZE]; float max_bend = 0.0; //sort hands into their respective regions for(Hand& hand : hands) { size_t r = hand_to_region(hand); //mark that there is a hand in this region regions[r].status = true; //fastest hand dominates if(hand.speed() > regions[r].hand.speed()) regions[r].hand = hand; if(hand.vel.x > max_bend) max_bend = (hand.vel.x < 0) ? 0 : hand.vel.x; } midi_out.sendPitchBend(channel, 0x2000 + (0x8800 * max_bend)); //check the current region status against the previous status, //to determine whether to send note ON or OFF for(size_t r = 0; r < SCALE_SIZE; r++) { int note = region_to_note(r); int vel = speed_to_midi_velocity(regions[r].hand.speed()); //if the hand is new if(regions[r].status && !previous_regions[r].status) { //NOTE ON ofLog() << "ON " << note << " : " << vel; midi_out.sendNoteOn(channel, note, vel); } else if(!regions[r].status && previous_regions[r].status) { //a hand just LEFT a region //NOTE OFF ofLog() << "OFF " << note << " : " << vel; midi_out.sendNoteOff(channel, note, 64); } //walk the buffers previous_regions[r] = regions[r]; } } size_t Beam::hand_to_region(Hand& hand) { size_t r = floor(ofLerp(0, SCALE_SIZE, hand.pos.y)); return max((size_t) 0, min(r, SCALE_SIZE - 1)); } int Beam::region_to_note(size_t region) { return base_note + midi_scale[region]; } size_t Beam::speed_to_midi_velocity(float speed) { return midi_velocities[0]; //TODO } <|endoftext|>
<commit_before>#include "PLC_LSH.h" #include "SymmIsotropicElasticityTensor.h" template<> InputParameters validParams<PLC_LSH>() { InputParameters params = validParams<SolidModel>(); // Power-law creep material parameters params.addRequiredParam<Real>("coefficient", "Leading coefficent in power-law equation"); params.addRequiredParam<Real>("n_exponent", "Exponent on effective stress in power-law equation"); params.addParam<Real>("m_exponent", 0.0, "Exponent on time in power-law equation"); params.addRequiredParam<Real>("activation_energy", "Activation energy"); params.addParam<Real>("gas_constant", 8.3143, "Universal gas constant"); // Linear strain hardening parameters params.addRequiredParam<Real>("yield_stress", "The point at which plastic strain begins accumulating"); params.addRequiredParam<Real>("hardening_constant", "Hardening slope"); // Sub-Newton Iteration control parameters params.addParam<unsigned int>("max_its", 30, "Maximum number of sub-newton iterations"); params.addParam<bool>("output_iteration_info", false, "Set true to output sub-newton iteration information"); params.addParam<Real>("relative_tolerance", 1e-5, "Relative convergence tolerance for sub-newtion iteration"); params.addParam<Real>("absolute_tolerance", 1e-20, "Absolute convergence tolerance for sub-newtion iteration"); params.addParam<PostprocessorName>("output", "", "The reporting postprocessor to use for the max_iterations value."); // Control of combined plasticity-creep iterarion params.addParam<Real>("absolute_stress_tolerance", 1e-5, "Convergence tolerance for combined plasticity-creep stress iteration"); return params; } PLC_LSH::PLC_LSH( const std::string & name, InputParameters parameters ) :SolidModel( name, parameters ), _coefficient(parameters.get<Real>("coefficient")), _n_exponent(parameters.get<Real>("n_exponent")), _m_exponent(parameters.get<Real>("m_exponent")), _activation_energy(parameters.get<Real>("activation_energy")), _gas_constant(parameters.get<Real>("gas_constant")), _yield_stress(parameters.get<Real>("yield_stress")), _hardening_constant(parameters.get<Real>("hardening_constant")), _max_its(parameters.get<unsigned int>("max_its")), _output_iteration_info(getParam<bool>("output_iteration_info")), _relative_tolerance(parameters.get<Real>("relative_tolerance")), _absolute_tolerance(parameters.get<Real>("absolute_tolerance")), _absolute_stress_tolerance(parameters.get<Real>("absolute_stress_tolerance")), _creep_strain(declareProperty<SymmTensor>("creep_strain")), _creep_strain_old(declarePropertyOld<SymmTensor>("creep_strain")), _plastic_strain(declareProperty<SymmTensor>("plastic_strain")), _plastic_strain_old(declarePropertyOld<SymmTensor>("plastic_strain")), _hardening_variable(declareProperty<Real>("hardening_variable")), _hardening_variable_old(declarePropertyOld<Real>("hardening_variable")), _output( getParam<PostprocessorName>("output") != "" ? &getPostprocessorValue("output") : NULL ) { } void PLC_LSH::initQpStatefulProperties() { _hardening_variable[_qp] = _hardening_variable_old[_qp] = 0; SolidModel::initQpStatefulProperties(); } void PLC_LSH::computeStress() { // Given the stretching, compute the stress increment and add it to the old stress. Also update the creep strain // stress = stressOld + stressIncrement // creep_strain = creep_strainOld + creep_strainIncrement // // // This is more work than needs to be done. The strain and stress tensors are symmetric, and so we are carrying // a third more memory than is required. We are also running a 9x9 * 9x1 matrix-vector multiply when at most // a 6x6 * 6x1 matrix vector multiply is needed. For the most common case, isotropic elasticity, only two // constants are needed and a matrix vector multiply can be avoided entirely. // if(_t_step == 0) return; if (_output_iteration_info == true) { std::cout << std::endl << "iteration output for combined creep-plasticity solve:" << " time=" <<_t << " temperature=" << _temperature[_qp] << " int_pt=" << _qp << std::endl; } // compute trial stress SymmTensor stress_new( *elasticityTensor() * _strain_increment ); stress_new += _stress_old; SymmTensor creep_strain_increment; SymmTensor plastic_strain_increment; SymmTensor elastic_strain_increment; SymmTensor stress_new_last( stress_new ); Real delS(_absolute_stress_tolerance+1); Real first_delS(delS); unsigned int counter(0); while(counter < _max_its && delS > _absolute_stress_tolerance && (delS/first_delS) > _relative_tolerance) { elastic_strain_increment = _strain_increment; elastic_strain_increment -= plastic_strain_increment; stress_new = *elasticityTensor() * elastic_strain_increment; stress_new += _stress_old; computeCreep( creep_strain_increment, stress_new ); // now use stress_new to calculate a new effective_trial_stress and determine if // yield has occured and if so, calculate the corresponding plastic strain computeLSH( creep_strain_increment, plastic_strain_increment, stress_new ); elastic_strain_increment = _strain_increment; elastic_strain_increment -= plastic_strain_increment; elastic_strain_increment -= creep_strain_increment; // now check convergence SymmTensor deltaS(stress_new_last - stress_new); delS = std::sqrt(deltaS.doubleContraction(deltaS)); if(counter==0) first_delS = delS; stress_new_last = stress_new; if (_output_iteration_info == true) { std::cout << "stress_it=" << counter << " rel_delS=" << delS/first_delS << " rel_tol=" << _relative_tolerance << " abs_delS=" << delS << " abs_tol=" << _absolute_stress_tolerance << std::endl; } if(counter == _max_its) { mooseError("Max stress iteration hit during plasticity-creep solve!"); } counter++; } _strain_increment = elastic_strain_increment; _stress[_qp] = stress_new; } void PLC_LSH::computeCreep( SymmTensor & creep_strain_increment, SymmTensor & stress_new ) { creep_strain_increment.zero(); // compute deviatoric trial stress SymmTensor dev_trial_stress(stress_new); dev_trial_stress.addDiag( -dev_trial_stress.trace()/3.0 ); // compute effective trial stress Real dts_squared = dev_trial_stress.doubleContraction(dev_trial_stress); Real effective_trial_stress = std::sqrt(1.5 * dts_squared); // Use Newton sub-iteration to determine effective creep strain increment Real exponential(1); SymmTensor stress_last(_stress_old); SymmTensor stress_next; Real del_p(0); unsigned int it(0); Real creep_residual(10); Real norm_creep_residual = 10; Real first_norm_creep_residual = 10; while(it < _max_its && norm_creep_residual > _absolute_tolerance && (norm_creep_residual/first_norm_creep_residual) > _relative_tolerance) { if (_has_temp) { exponential = std::exp(-_activation_energy/(_gas_constant *_temperature[_qp])); } Real phi = _coefficient*std::pow(effective_trial_stress - 3.*_shear_modulus*del_p, _n_exponent)* exponential*std::pow(_t,_m_exponent); Real dphi_ddelp = -3.*_coefficient*_shear_modulus*_n_exponent* std::pow(effective_trial_stress-3.*_shear_modulus*del_p, _n_exponent-1.)*exponential*std::pow(_t,_m_exponent); creep_residual = phi - del_p/_dt; norm_creep_residual = std::abs(creep_residual); if(it==0) first_norm_creep_residual = norm_creep_residual; del_p = del_p + (creep_residual / (1/_dt - dphi_ddelp)); if (_output_iteration_info == true) { std::cout << "crp_it=" << it << " trl_strs=" << effective_trial_stress << " phi=" << phi << " dphi=" << dphi_ddelp << " del_p=" << del_p << " rel_res=" << norm_creep_residual/first_norm_creep_residual << " rel_tol=" << _relative_tolerance << " abs_res=" << norm_creep_residual << " abs_tol=" << _absolute_tolerance << std::endl; } it++; } if(it == _max_its && (norm_creep_residual/first_norm_creep_residual) > _relative_tolerance && norm_creep_residual > _absolute_tolerance) { mooseError("Max sub-newton iteration hit during creep solve!"); } // compute creep and elastic strain increments (avoid potential divide by zero - how should this be done)? if (effective_trial_stress < 0.01) { effective_trial_stress = 0.01; } SymmTensor creep_strain_sub_increment( dev_trial_stress ); creep_strain_sub_increment *= (1.5*del_p/effective_trial_stress); SymmTensor elastic_strain_increment(_strain_increment); elastic_strain_increment -= creep_strain_sub_increment; // compute stress increment stress_next = *elasticityTensor() * elastic_strain_increment; // update stress and creep strain stress_next += stress_last; stress_last = stress_next; creep_strain_increment += creep_strain_sub_increment; _creep_strain[_qp] = creep_strain_increment; _creep_strain[_qp] += _creep_strain_old[_qp]; stress_new = stress_next; } void PLC_LSH::computeLSH( const SymmTensor & creep_strain_increment, SymmTensor & plastic_strain_increment, SymmTensor & stress_new ) { // compute deviatoric trial stress SymmTensor dev_trial_stress_p(stress_new); dev_trial_stress_p.addDiag( -stress_new.trace()/3.0 ); // effective trial stress Real dts_squared_p = dev_trial_stress_p.doubleContraction(dev_trial_stress_p); Real effective_trial_stress_p = std::sqrt(1.5 * dts_squared_p); // determine if yield condition is satisfied Real yield_condition = effective_trial_stress_p - _hardening_variable_old[_qp] - _yield_stress; _hardening_variable[_qp] = _hardening_variable_old[_qp]; _plastic_strain[_qp] = _plastic_strain_old[_qp]; if (yield_condition > 0.) //then use newton iteration to determine effective plastic strain increment { unsigned int jt = 0; Real plastic_residual = 10; Real norm_plas_residual = 10; Real first_norm_plas_residual = 10; Real scalar_plastic_strain_increment = 0; while(jt < _max_its && norm_plas_residual > _absolute_tolerance && (norm_plas_residual/first_norm_plas_residual) > _relative_tolerance) { plastic_residual = effective_trial_stress_p - (3. * _shear_modulus * scalar_plastic_strain_increment) - _hardening_variable[_qp] - _yield_stress; norm_plas_residual = std::abs(plastic_residual); if(jt==0) first_norm_plas_residual = norm_plas_residual; scalar_plastic_strain_increment = scalar_plastic_strain_increment + ((plastic_residual) / (3. * _shear_modulus + _hardening_constant)); _hardening_variable[_qp] = _hardening_variable_old[_qp] + (_hardening_constant * scalar_plastic_strain_increment); if (_output_iteration_info == true) { std::cout << "pls_it=" << jt << " trl_strs=" << effective_trial_stress_p << " del_p=" << scalar_plastic_strain_increment << " harden=" <<_hardening_variable[_qp] << " rel_res=" << norm_plas_residual/first_norm_plas_residual << " rel_tol=" << _relative_tolerance << " abs_res=" << norm_plas_residual << " abs_tol=" << _absolute_tolerance << std::endl; } jt++; } if(jt == _max_its && (norm_plas_residual/first_norm_plas_residual) > _relative_tolerance && norm_plas_residual > _absolute_tolerance) { mooseError("Max sub-newton iteration hit during plasticity increment solve!"); } if (effective_trial_stress_p < 0.01) effective_trial_stress_p = 0.01; plastic_strain_increment = dev_trial_stress_p; plastic_strain_increment *= (1.5*scalar_plastic_strain_increment/effective_trial_stress_p); SymmTensor elastic_strain_increment(_strain_increment); elastic_strain_increment -= plastic_strain_increment; elastic_strain_increment -= creep_strain_increment; // compute stress increment stress_new = *elasticityTensor() * elastic_strain_increment; // update stress and plastic strain stress_new += _stress_old; _plastic_strain[_qp] += plastic_strain_increment; }//end of if statement } <commit_msg>Cleanup<commit_after>#include "PLC_LSH.h" #include "SymmIsotropicElasticityTensor.h" template<> InputParameters validParams<PLC_LSH>() { InputParameters params = validParams<SolidModel>(); // Power-law creep material parameters params.addRequiredParam<Real>("coefficient", "Leading coefficent in power-law equation"); params.addRequiredParam<Real>("n_exponent", "Exponent on effective stress in power-law equation"); params.addParam<Real>("m_exponent", 0.0, "Exponent on time in power-law equation"); params.addRequiredParam<Real>("activation_energy", "Activation energy"); params.addParam<Real>("gas_constant", 8.3143, "Universal gas constant"); // Linear strain hardening parameters params.addRequiredParam<Real>("yield_stress", "The point at which plastic strain begins accumulating"); params.addRequiredParam<Real>("hardening_constant", "Hardening slope"); // Sub-Newton Iteration control parameters params.addParam<unsigned int>("max_its", 30, "Maximum number of sub-newton iterations"); params.addParam<bool>("output_iteration_info", false, "Set true to output sub-newton iteration information"); params.addParam<Real>("relative_tolerance", 1e-5, "Relative convergence tolerance for sub-newtion iteration"); params.addParam<Real>("absolute_tolerance", 1e-20, "Absolute convergence tolerance for sub-newtion iteration"); params.addParam<PostprocessorName>("output", "", "The reporting postprocessor to use for the max_iterations value."); // Control of combined plasticity-creep iterarion params.addParam<Real>("absolute_stress_tolerance", 1e-5, "Convergence tolerance for combined plasticity-creep stress iteration"); return params; } PLC_LSH::PLC_LSH( const std::string & name, InputParameters parameters ) :SolidModel( name, parameters ), _coefficient(parameters.get<Real>("coefficient")), _n_exponent(parameters.get<Real>("n_exponent")), _m_exponent(parameters.get<Real>("m_exponent")), _activation_energy(parameters.get<Real>("activation_energy")), _gas_constant(parameters.get<Real>("gas_constant")), _yield_stress(parameters.get<Real>("yield_stress")), _hardening_constant(parameters.get<Real>("hardening_constant")), _max_its(parameters.get<unsigned int>("max_its")), _output_iteration_info(getParam<bool>("output_iteration_info")), _relative_tolerance(parameters.get<Real>("relative_tolerance")), _absolute_tolerance(parameters.get<Real>("absolute_tolerance")), _absolute_stress_tolerance(parameters.get<Real>("absolute_stress_tolerance")), _creep_strain(declareProperty<SymmTensor>("creep_strain")), _creep_strain_old(declarePropertyOld<SymmTensor>("creep_strain")), _plastic_strain(declareProperty<SymmTensor>("plastic_strain")), _plastic_strain_old(declarePropertyOld<SymmTensor>("plastic_strain")), _hardening_variable(declareProperty<Real>("hardening_variable")), _hardening_variable_old(declarePropertyOld<Real>("hardening_variable")), _output( getParam<PostprocessorName>("output") != "" ? &getPostprocessorValue("output") : NULL ) { } void PLC_LSH::initQpStatefulProperties() { _hardening_variable[_qp] = _hardening_variable_old[_qp] = 0; SolidModel::initQpStatefulProperties(); } void PLC_LSH::computeStress() { // Given the stretching, compute the stress increment and add it to the old stress. Also update the creep strain // stress = stressOld + stressIncrement // creep_strain = creep_strainOld + creep_strainIncrement // // // This is more work than needs to be done. The strain and stress tensors are symmetric, and so we are carrying // a third more memory than is required. We are also running a 9x9 * 9x1 matrix-vector multiply when at most // a 6x6 * 6x1 matrix vector multiply is needed. For the most common case, isotropic elasticity, only two // constants are needed and a matrix vector multiply can be avoided entirely. // if(_t_step == 0) return; if (_output_iteration_info == true) { std::cout << std::endl << "iteration output for combined creep-plasticity solve:" << " time=" <<_t << " temperature=" << _temperature[_qp] << " int_pt=" << _qp << std::endl; } // compute trial stress SymmTensor stress_new( *elasticityTensor() * _strain_increment ); stress_new += _stress_old; SymmTensor creep_strain_increment; SymmTensor plastic_strain_increment; SymmTensor elastic_strain_increment; SymmTensor stress_new_last( stress_new ); Real delS(_absolute_stress_tolerance+1); Real first_delS(delS); unsigned int counter(0); while(counter < _max_its && delS > _absolute_stress_tolerance && (delS/first_delS) > _relative_tolerance) { elastic_strain_increment = _strain_increment; elastic_strain_increment -= plastic_strain_increment; stress_new = *elasticityTensor() * elastic_strain_increment; stress_new += _stress_old; computeCreep( creep_strain_increment, stress_new ); // now use stress_new to calculate a new effective_trial_stress and determine if // yield has occured and if so, calculate the corresponding plastic strain computeLSH( creep_strain_increment, plastic_strain_increment, stress_new ); elastic_strain_increment = _strain_increment; elastic_strain_increment -= plastic_strain_increment; elastic_strain_increment -= creep_strain_increment; // now check convergence SymmTensor deltaS(stress_new_last - stress_new); delS = std::sqrt(deltaS.doubleContraction(deltaS)); if(counter==0) first_delS = delS; stress_new_last = stress_new; if (_output_iteration_info == true) { std::cout << "stress_it=" << counter << " rel_delS=" << delS/first_delS << " rel_tol=" << _relative_tolerance << " abs_delS=" << delS << " abs_tol=" << _absolute_stress_tolerance << std::endl; } ++counter; } if(counter == _max_its && delS > _absolute_stress_tolerance && (delS/first_delS) > _relative_tolerance) { mooseError("Max stress iteration hit during plasticity-creep solve!"); } _strain_increment = elastic_strain_increment; _stress[_qp] = stress_new; } void PLC_LSH::computeCreep( SymmTensor & creep_strain_increment, SymmTensor & stress_new ) { // compute deviatoric trial stress SymmTensor dev_trial_stress(stress_new); dev_trial_stress.addDiag( -dev_trial_stress.trace()/3.0 ); // compute effective trial stress Real dts_squared = dev_trial_stress.doubleContraction(dev_trial_stress); Real effective_trial_stress = std::sqrt(1.5 * dts_squared); // Use Newton sub-iteration to determine effective creep strain increment Real exponential(1); if (_has_temp) { exponential = std::exp(-_activation_energy/(_gas_constant *_temperature[_qp])); } Real expTime = std::pow(_t, _m_exponent); Real del_p = 0; unsigned int it = 0; Real creep_residual = 10; Real norm_creep_residual = 10; Real first_norm_creep_residual = 10; while(it < _max_its && norm_creep_residual > _absolute_tolerance && (norm_creep_residual/first_norm_creep_residual) > _relative_tolerance) { Real phi = _coefficient*std::pow(effective_trial_stress - 3*_shear_modulus*del_p, _n_exponent)* exponential*expTime; Real dphi_ddelp = -3*_coefficient*_shear_modulus*_n_exponent* std::pow(effective_trial_stress-3*_shear_modulus*del_p, _n_exponent-1)*exponential*expTime; creep_residual = phi - del_p/_dt; norm_creep_residual = std::abs(creep_residual); if (it == 0) { first_norm_creep_residual = norm_creep_residual; } del_p = del_p + (creep_residual / (1/_dt - dphi_ddelp)); if (_output_iteration_info == true) { std::cout << "crp_it=" << it << " trl_strs=" << effective_trial_stress << " phi=" << phi << " dphi=" << dphi_ddelp << " del_p=" << del_p << " rel_res=" << norm_creep_residual/first_norm_creep_residual << " rel_tol=" << _relative_tolerance << " abs_res=" << norm_creep_residual << " abs_tol=" << _absolute_tolerance << std::endl; } ++it; } if(it == _max_its && norm_creep_residual > _absolute_tolerance && (norm_creep_residual/first_norm_creep_residual) > _relative_tolerance) { mooseError("Max sub-newton iteration hit during creep solve!"); } // compute creep and elastic strain increments (avoid potential divide by zero - how should this be done)? if (effective_trial_stress < 0.01) { effective_trial_stress = 0.01; } creep_strain_increment = dev_trial_stress; creep_strain_increment *= (1.5*del_p/effective_trial_stress); SymmTensor elastic_strain_increment(_strain_increment); elastic_strain_increment -= creep_strain_increment; // compute stress increment stress_new = *elasticityTensor() * elastic_strain_increment; // update stress and creep strain stress_new += _stress_old; _creep_strain[_qp] = creep_strain_increment; _creep_strain[_qp] += _creep_strain_old[_qp]; } void PLC_LSH::computeLSH( const SymmTensor & creep_strain_increment, SymmTensor & plastic_strain_increment, SymmTensor & stress_new ) { // compute deviatoric trial stress SymmTensor dev_trial_stress_p(stress_new); dev_trial_stress_p.addDiag( -stress_new.trace()/3 ); // effective trial stress Real dts_squared_p = dev_trial_stress_p.doubleContraction(dev_trial_stress_p); Real effective_trial_stress_p = std::sqrt(1.5 * dts_squared_p); // determine if yield condition is satisfied Real yield_condition = effective_trial_stress_p - _hardening_variable_old[_qp] - _yield_stress; _hardening_variable[_qp] = _hardening_variable_old[_qp]; _plastic_strain[_qp] = _plastic_strain_old[_qp]; if (yield_condition > 0.) //then use newton iteration to determine effective plastic strain increment { unsigned int jt = 0; Real plastic_residual = 10; Real norm_plas_residual = 10; Real first_norm_plas_residual = 10; Real scalar_plastic_strain_increment = 0; while(jt < _max_its && norm_plas_residual > _absolute_tolerance && (norm_plas_residual/first_norm_plas_residual) > _relative_tolerance) { plastic_residual = effective_trial_stress_p - (3. * _shear_modulus * scalar_plastic_strain_increment) - _hardening_variable[_qp] - _yield_stress; norm_plas_residual = std::abs(plastic_residual); if(jt==0) first_norm_plas_residual = norm_plas_residual; scalar_plastic_strain_increment = scalar_plastic_strain_increment + ((plastic_residual) / (3. * _shear_modulus + _hardening_constant)); _hardening_variable[_qp] = _hardening_variable_old[_qp] + (_hardening_constant * scalar_plastic_strain_increment); if (_output_iteration_info == true) { std::cout << "pls_it=" << jt << " trl_strs=" << effective_trial_stress_p << " del_p=" << scalar_plastic_strain_increment << " harden=" <<_hardening_variable[_qp] << " rel_res=" << norm_plas_residual/first_norm_plas_residual << " rel_tol=" << _relative_tolerance << " abs_res=" << norm_plas_residual << " abs_tol=" << _absolute_tolerance << std::endl; } jt++; } if(jt == _max_its && (norm_plas_residual/first_norm_plas_residual) > _relative_tolerance && norm_plas_residual > _absolute_tolerance) { mooseError("Max sub-newton iteration hit during plasticity increment solve!"); } if (effective_trial_stress_p < 0.01) effective_trial_stress_p = 0.01; plastic_strain_increment = dev_trial_stress_p; plastic_strain_increment *= (1.5*scalar_plastic_strain_increment/effective_trial_stress_p); SymmTensor elastic_strain_increment(_strain_increment); elastic_strain_increment -= plastic_strain_increment; elastic_strain_increment -= creep_strain_increment; // compute stress increment stress_new = *elasticityTensor() * elastic_strain_increment; // update stress and plastic strain stress_new += _stress_old; _plastic_strain[_qp] += plastic_strain_increment; }//end of if statement } <|endoftext|>
<commit_before>#include <string> #include "nbind/api.h" #include "control.h" #include "ui.h" class UiCheckbox : public UiControl { DEFINE_EVENT(onToggled) public: UiCheckbox(std::string text); UiCheckbox(); DEFINE_CONTROL_METHODS() void setText(std::string text); std::string getText(); void setChecked(bool checked); bool getChecked(); ~UiCheckbox(); void onDestroy(uiControl *control) override; }; void UiCheckbox::onDestroy(uiControl *control){ /* freeing event callbacks to allow JS to garbage collect this class when there are no references to it left in JS code. */ DISPOSE_EVENT(onToggled)} UiCheckbox::~UiCheckbox() { printf("UiCheckbox %p destroyed with wrapper %p.\n", getHandle(), this); } IMPLEMENT_EVENT(UiCheckbox, uiCheckbox, onToggled, uiCheckboxOnToggled) UiCheckbox::UiCheckbox(std::string text) : UiControl(uiControl(uiNewCheckbox(text.c_str()))) {} UiCheckbox::UiCheckbox() : UiControl(uiControl(uiNewCheckbox(""))) {} INHERITS_CONTROL_METHODS(UiCheckbox) void UiCheckbox::setText(std::string text) { uiCheckboxSetText(uiCheckbox(getHandle()), text.c_str()); } std::string UiCheckbox::getText() { char *char_ptr = uiCheckboxText(uiCheckbox(getHandle())); std::string s(char_ptr); uiFreeText(char_ptr); return s; } void UiCheckbox::setChecked(bool checked) { uiCheckboxSetChecked(uiCheckbox(getHandle()), checked); if (onToggledCallback != NULL) { (*onToggledCallback)(); } } bool UiCheckbox::getChecked() { return uiCheckboxChecked(uiCheckbox(getHandle())); } NBIND_CLASS(UiCheckbox) { construct<std::string>(); construct<>(); DECLARE_CHILD_CONTROL_METHODS() getset(getChecked, setChecked); getset(getText, setText); method(getChecked); method(setChecked); method(getText); method(setText); method(onToggled); } <commit_msg>Fixed events leak -> UiCheckbox<commit_after>#include <string> #include "nbind/api.h" #include "control.h" #include "ui.h" class UiCheckbox : public UiControl { DEFINE_EVENT(onToggled) public: UiCheckbox(std::string text); UiCheckbox(); DEFINE_CONTROL_METHODS() void setText(std::string text); std::string getText(); void setChecked(bool checked); bool getChecked(); ~UiCheckbox(); void onDestroy(uiControl *control) override; }; void UiCheckbox::onDestroy(uiControl *control) { /* freeing event callbacks to allow JS to garbage collect this class when there are no references to it left in JS code. */ DISPOSE_EVENT(onToggled); } UiCheckbox::~UiCheckbox() { printf("UiCheckbox %p destroyed with wrapper %p.\n", getHandle(), this); } IMPLEMENT_EVENT(UiCheckbox, uiCheckbox, onToggled, uiCheckboxOnToggled) UiCheckbox::UiCheckbox(std::string text) : UiControl(uiControl(uiNewCheckbox(text.c_str()))) {} UiCheckbox::UiCheckbox() : UiControl(uiControl(uiNewCheckbox(""))) {} INHERITS_CONTROL_METHODS(UiCheckbox) void UiCheckbox::setText(std::string text) { uiCheckboxSetText(uiCheckbox(getHandle()), text.c_str()); } std::string UiCheckbox::getText() { char *char_ptr = uiCheckboxText(uiCheckbox(getHandle())); std::string s(char_ptr); uiFreeText(char_ptr); return s; } void UiCheckbox::setChecked(bool checked) { uiCheckboxSetChecked(uiCheckbox(getHandle()), checked); if (onToggledCallback != NULL) { (*onToggledCallback)(); } } bool UiCheckbox::getChecked() { return uiCheckboxChecked(uiCheckbox(getHandle())); } NBIND_CLASS(UiCheckbox) { construct<std::string>(); construct<>(); DECLARE_CHILD_CONTROL_METHODS() getset(getChecked, setChecked); getset(getText, setText); method(getChecked); method(setChecked); method(getText); method(setText); method(onToggled); } <|endoftext|>
<commit_before>// I2C interface // (c) Koheron // See also https://www.kernel.org/doc/Documentation/spi/spidev #ifndef __DRIVERS_LIB_I2C_DEV_HPP__ #define __DRIVERS_LIB_I2C_DEV_HPP__ #include <cstdio> #include <cstdint> #include <cassert> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/types.h> #include <linux/i2c-dev.h> #include <unordered_map> #include <string> #include <memory> #include <array> #include <vector> #include <atomic> #include <thread> #include <mutex> #include <context_base.hpp> class I2cDev { public: I2cDev(ContextBase& ctx_, std::string devname_); ~I2cDev() { if (fd >= 0) close(fd); } bool is_ok() {return fd >= 0;} /// Write data to I2C driver /// addr: Addresse of the driver to write to /// buffer: Pointer to the data to send /// len: Number of elements on the buffer array template<int32_t addr, typename T> int write(const T *buffer, int32_t len) { // Lock to avoid another process to change // the driver address while writing std::lock_guard<std::mutex> lock(mutex); if (! is_ok()) return -1; if (set_address<addr>() < 0) return -1; return ::write(fd, buffer, static_cast<uint32_t>(len) * sizeof(T)); } template<int32_t addr, typename T, size_t N> int write(const std::array<T, N>& buff) { return write<addr>(buff.data(), buff.size()); } template<int32_t addr, typename T> int write(const std::vector<T>& buff) { return write<addr>(buff.data(), buff.size()); } // Receive data from I2C driver template<int32_t addr> int recv(uint8_t *buffer, size_t n_bytes) { // Lock to avoid another process to change // the driver address while reading std::lock_guard<std::mutex> lock(mutex); if (! is_ok()) return -1; if (set_address<addr>() < 0) return -1; int bytes_rcv = 0; int64_t bytes_read = 0; while (bytes_read < n_bytes) { bytes_rcv = read(fd, buffer + bytes_read, n_bytes - bytes_read); if (bytes_rcv == 0) { return 0; } if (bytes_rcv < 0) { return -1; } bytes_read += bytes_rcv; } assert(bytes_read == n_bytes); return bytes_read; } template<int32_t addr, typename T, size_t N> int recv(std::array<T, N>& data) { return recv<addr>(reinterpret_cast<uint8_t*>(data.data()), N * sizeof(T)); } template<int32_t addr, typename T> int recv(std::vector<T>& data) { return recv<addr>(reinterpret_cast<uint8_t*>(data.data()), data.size() * sizeof(T)); } private: ContextBase& ctx; std::string devname; int fd = -1; std::atomic<int32_t> last_addr{-1}; std::mutex mutex; int init(); template<int32_t addr> int set_address() { constexpr int32_t largest_i2c_addr = 127; // 7 bits long address static_assert(addr <= largest_i2c_addr, "Invalid I2C address"); if (addr != last_addr) { if (ioctl(fd, I2C_SLAVE_FORCE, addr) < 0) { return -1; } last_addr = addr; } return 0; } friend class I2cManager; }; class I2cManager { public: I2cManager(ContextBase& ctx_); int init(); bool has_device(const std::string& devname) const; auto& get(const std::string& devname) { if (! has_device(devname)) { // This is critical since explicit driver request cannot be honored return *empty_i2cdev; } i2c_drivers[devname]->init(); return *i2c_drivers[devname]; } private: ContextBase& ctx; std::unordered_map<std::string, std::unique_ptr<I2cDev>> i2c_drivers; std::unique_ptr<I2cDev> empty_i2cdev; }; #endif // __DRIVERS_LIB_I2C_DEV_HPP__<commit_msg>do not use template for address in i2c api<commit_after>// I2C interface // (c) Koheron // See also https://www.kernel.org/doc/Documentation/spi/spidev #ifndef __DRIVERS_LIB_I2C_DEV_HPP__ #define __DRIVERS_LIB_I2C_DEV_HPP__ #include <cstdio> #include <cstdint> #include <cassert> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/types.h> #include <linux/i2c-dev.h> #include <unordered_map> #include <string> #include <memory> #include <array> #include <vector> #include <atomic> #include <thread> #include <mutex> #include <context_base.hpp> class I2cDev { public: I2cDev(ContextBase& ctx_, std::string devname_); ~I2cDev() { if (fd >= 0) { close(fd); } } bool is_ok() {return fd >= 0;} /// Write data to I2C driver /// addr: Address of the driver to write to /// buffer: Pointer to the data to send /// len: Number of elements on the buffer array template<typename T> int write(int32_t addr, const T *buffer, int32_t len) { // Lock to avoid another process to change // the driver address while writing std::lock_guard<std::mutex> lock(mutex); if (! is_ok()) { return -1; } if (set_address(addr) < 0) { return -1; } return ::write(fd, buffer, static_cast<uint32_t>(len) * sizeof(T)); } template<typename T, size_t N> int write(int32_t addr, const std::array<T, N>& buff) { return write(addr, buff.data(), buff.size()); } template<typename T> int write(int32_t addr, const std::vector<T>& buff) { return write(addr, buff.data(), buff.size()); } // Receive data from I2C driver int recv(int32_t addr, uint8_t *buffer, size_t n_bytes) { // Lock to avoid another process to change // the driver address while reading std::lock_guard<std::mutex> lock(mutex); if (! is_ok()) return -1; if (set_address(addr) < 0) return -1; int bytes_rcv = 0; int64_t bytes_read = 0; while (bytes_read < n_bytes) { bytes_rcv = read(fd, buffer + bytes_read, n_bytes - bytes_read); if (bytes_rcv == 0) { return 0; } if (bytes_rcv < 0) { return -1; } bytes_read += bytes_rcv; } assert(bytes_read == n_bytes); return bytes_read; } template<typename T, size_t N> int recv(int32_t addr, std::array<T, N>& data) { return recv(addr, reinterpret_cast<uint8_t*>(data.data()), N * sizeof(T)); } template<typename T> int recv(int32_t addr, std::vector<T>& data) { return recv(addr, reinterpret_cast<uint8_t*>(data.data()), data.size() * sizeof(T)); } private: ContextBase& ctx; std::string devname; int fd = -1; std::atomic<int32_t> last_addr{-1}; std::mutex mutex; int init(); int set_address(int32_t addr) { constexpr int32_t largest_i2c_addr = 127; // 7 bits long address if (addr < 0 || addr > largest_i2c_addr) { return -1; } if (addr != last_addr) { if (ioctl(fd, I2C_SLAVE_FORCE, addr) < 0) { return -1; } last_addr = addr; } return 0; } friend class I2cManager; }; class I2cManager { public: I2cManager(ContextBase& ctx_); int init(); bool has_device(const std::string& devname) const; auto& get(const std::string& devname) { if (! has_device(devname)) { // This is critical since explicit driver request cannot be honored return *empty_i2cdev; } i2c_drivers[devname]->init(); return *i2c_drivers[devname]; } private: ContextBase& ctx; std::unordered_map<std::string, std::unique_ptr<I2cDev>> i2c_drivers; std::unique_ptr<I2cDev> empty_i2cdev; }; #endif // __DRIVERS_LIB_I2C_DEV_HPP__<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/native_library.h" #include "base/path_service.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_egl_api_implementation.h" #include "ui/gl/gl_gl_api_implementation.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_osmesa_api_implementation.h" namespace gfx { namespace { void GL_BINDING_CALL MarshalClearDepthToClearDepthf(GLclampd depth) { glClearDepthf(static_cast<GLclampf>(depth)); } void GL_BINDING_CALL MarshalDepthRangeToDepthRangef(GLclampd z_near, GLclampd z_far) { glDepthRangef(static_cast<GLclampf>(z_near), static_cast<GLclampf>(z_far)); } base::NativeLibrary LoadLibrary(const base::FilePath& filename) { std::string error; base::NativeLibrary library = base::LoadNativeLibrary(filename, &error); if (!library) { DVLOG(1) << "Failed to load " << filename.MaybeAsASCII() << ": " << error; return NULL; } return library; } base::NativeLibrary LoadLibrary(const char* filename) { return LoadLibrary(base::FilePath(filename)); } } // namespace void GetAllowedGLImplementations(std::vector<GLImplementation>* impls) { impls->push_back(kGLImplementationEGLGLES2); } bool InitializeGLBindings(GLImplementation implementation) { // Prevent reinitialization with a different implementation. Once the gpu // unit tests have initialized with kGLImplementationMock, we don't want to // later switch to another GL implementation. if (GetGLImplementation() != kGLImplementationNone) return true; switch (implementation) { case kGLImplementationEGLGLES2: { base::NativeLibrary gles_library = LoadLibrary("libGLESv2.so"); if (!gles_library) return false; base::NativeLibrary egl_library = LoadLibrary("libEGL.so"); if (!egl_library) { base::UnloadNativeLibrary(gles_library); return false; } GLGetProcAddressProc get_proc_address = reinterpret_cast<GLGetProcAddressProc>( base::GetFunctionPointerFromNativeLibrary( egl_library, "eglGetProcAddress")); if (!get_proc_address) { LOG(ERROR) << "eglGetProcAddress not found."; base::UnloadNativeLibrary(egl_library); base::UnloadNativeLibrary(gles_library); return false; } SetGLGetProcAddressProc(get_proc_address); AddGLNativeLibrary(egl_library); AddGLNativeLibrary(gles_library); SetGLImplementation(kGLImplementationEGLGLES2); InitializeGLBindingsGL(); InitializeGLBindingsEGL(); // These two functions take single precision float rather than double // precision float parameters in GLES. ::gfx::g_driver_gl.fn.glClearDepthFn = MarshalClearDepthToClearDepthf; ::gfx::g_driver_gl.fn.glDepthRangeFn = MarshalDepthRangeToDepthRangef; break; } case kGLImplementationMockGL: { SetGLGetProcAddressProc(GetMockGLProcAddress); SetGLImplementation(kGLImplementationMockGL); InitializeGLBindingsGL(); break; } default: NOTIMPLEMENTED() << "InitializeGLBindings on Android"; return false; } return true; } bool InitializeGLExtensionBindings(GLImplementation implementation, GLContext* context) { switch (implementation) { case kGLImplementationEGLGLES2: InitializeGLExtensionBindingsGL(context); InitializeGLExtensionBindingsEGL(context); break; case kGLImplementationMockGL: InitializeGLExtensionBindingsGL(context); break; default: return false; } return true; } void InitializeDebugGLBindings() { } void ClearGLBindings() { ClearGLBindingsEGL(); ClearGLBindingsGL(); SetGLImplementation(kGLImplementationNone); UnloadGLNativeLibraries(); } bool GetGLWindowSystemBindingInfo(GLWindowSystemBindingInfo* info) { switch (GetGLImplementation()) { case kGLImplementationEGLGLES2: return GetGLWindowSystemBindingInfoEGL(info); default: return false; } return false; } } // namespace gfx <commit_msg>Add initialization of debug GL bindings on Android<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/native_library.h" #include "base/path_service.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_egl_api_implementation.h" #include "ui/gl/gl_gl_api_implementation.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_osmesa_api_implementation.h" namespace gfx { namespace { void GL_BINDING_CALL MarshalClearDepthToClearDepthf(GLclampd depth) { glClearDepthf(static_cast<GLclampf>(depth)); } void GL_BINDING_CALL MarshalDepthRangeToDepthRangef(GLclampd z_near, GLclampd z_far) { glDepthRangef(static_cast<GLclampf>(z_near), static_cast<GLclampf>(z_far)); } base::NativeLibrary LoadLibrary(const base::FilePath& filename) { std::string error; base::NativeLibrary library = base::LoadNativeLibrary(filename, &error); if (!library) { DVLOG(1) << "Failed to load " << filename.MaybeAsASCII() << ": " << error; return NULL; } return library; } base::NativeLibrary LoadLibrary(const char* filename) { return LoadLibrary(base::FilePath(filename)); } } // namespace void GetAllowedGLImplementations(std::vector<GLImplementation>* impls) { impls->push_back(kGLImplementationEGLGLES2); } bool InitializeGLBindings(GLImplementation implementation) { // Prevent reinitialization with a different implementation. Once the gpu // unit tests have initialized with kGLImplementationMock, we don't want to // later switch to another GL implementation. if (GetGLImplementation() != kGLImplementationNone) return true; switch (implementation) { case kGLImplementationEGLGLES2: { base::NativeLibrary gles_library = LoadLibrary("libGLESv2.so"); if (!gles_library) return false; base::NativeLibrary egl_library = LoadLibrary("libEGL.so"); if (!egl_library) { base::UnloadNativeLibrary(gles_library); return false; } GLGetProcAddressProc get_proc_address = reinterpret_cast<GLGetProcAddressProc>( base::GetFunctionPointerFromNativeLibrary( egl_library, "eglGetProcAddress")); if (!get_proc_address) { LOG(ERROR) << "eglGetProcAddress not found."; base::UnloadNativeLibrary(egl_library); base::UnloadNativeLibrary(gles_library); return false; } SetGLGetProcAddressProc(get_proc_address); AddGLNativeLibrary(egl_library); AddGLNativeLibrary(gles_library); SetGLImplementation(kGLImplementationEGLGLES2); InitializeGLBindingsGL(); InitializeGLBindingsEGL(); // These two functions take single precision float rather than double // precision float parameters in GLES. ::gfx::g_driver_gl.fn.glClearDepthFn = MarshalClearDepthToClearDepthf; ::gfx::g_driver_gl.fn.glDepthRangeFn = MarshalDepthRangeToDepthRangef; break; } case kGLImplementationMockGL: { SetGLGetProcAddressProc(GetMockGLProcAddress); SetGLImplementation(kGLImplementationMockGL); InitializeGLBindingsGL(); break; } default: NOTIMPLEMENTED() << "InitializeGLBindings on Android"; return false; } return true; } bool InitializeGLExtensionBindings(GLImplementation implementation, GLContext* context) { switch (implementation) { case kGLImplementationEGLGLES2: InitializeGLExtensionBindingsGL(context); InitializeGLExtensionBindingsEGL(context); break; case kGLImplementationMockGL: InitializeGLExtensionBindingsGL(context); break; default: return false; } return true; } void InitializeDebugGLBindings() { InitializeDebugGLBindingsEGL(); InitializeDebugGLBindingsGL(); } void ClearGLBindings() { ClearGLBindingsEGL(); ClearGLBindingsGL(); SetGLImplementation(kGLImplementationNone); UnloadGLNativeLibraries(); } bool GetGLWindowSystemBindingInfo(GLWindowSystemBindingInfo* info) { switch (GetGLImplementation()) { case kGLImplementationEGLGLES2: return GetGLWindowSystemBindingInfoEGL(info); default: return false; } return false; } } // namespace gfx <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filtopt.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:43:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef PCH #include "core_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <tools/debug.hxx> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/uno/Sequence.hxx> #include "filtopt.hxx" #include "miscuno.hxx" using namespace utl; using namespace rtl; using namespace com::sun::star::uno; //------------------------------------------------------------------ #define CFGPATH_FILTER "Office.Calc/Filter/Import" #define SCFILTOPT_COLSCALE 0 #define SCFILTOPT_ROWSCALE 1 #define SCFILTOPT_WK3 2 #define SCFILTOPT_COUNT 3 Sequence<OUString> ScFilterOptions::GetPropertyNames() { static const char* aPropNames[] = { "MS_Excel/ColScale", // SCFILTOPT_COLSCALE "MS_Excel/RowScale", // SCFILTOPT_ROWSCALE "Lotus123/WK3" // SCFILTOPT_WK3 }; Sequence<OUString> aNames(SCFILTOPT_COUNT); OUString* pNames = aNames.getArray(); for(int i = 0; i < SCFILTOPT_COUNT; i++) pNames[i] = OUString::createFromAscii(aPropNames[i]); return aNames; } ScFilterOptions::ScFilterOptions() : ConfigItem( OUString::createFromAscii( CFGPATH_FILTER ) ), bWK3Flag( FALSE ), fExcelColScale( 0 ), fExcelRowScale( 0 ) { Sequence<OUString> aNames = GetPropertyNames(); Sequence<Any> aValues = GetProperties(aNames); // EnableNotification(aNames); const Any* pValues = aValues.getConstArray(); DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed") if(aValues.getLength() == aNames.getLength()) { for(int nProp = 0; nProp < aNames.getLength(); nProp++) { DBG_ASSERT(pValues[nProp].hasValue(), "property value missing") if(pValues[nProp].hasValue()) { switch(nProp) { case SCFILTOPT_COLSCALE: pValues[nProp] >>= fExcelColScale; break; case SCFILTOPT_ROWSCALE: pValues[nProp] >>= fExcelRowScale; break; case SCFILTOPT_WK3: bWK3Flag = ScUnoHelpFunctions::GetBoolFromAny( pValues[nProp] ); break; } } } } } void ScFilterOptions::Commit() { // options are never modified from office DBG_ERROR("trying to commit changed ScFilterOptions?"); } void ScFilterOptions::Notify( const Sequence<rtl::OUString>& aPropertyNames ) { DBG_ERROR("properties have been changed") } <commit_msg>INTEGRATION: CWS pchfix01 (1.3.216); FILE MERGED 2006/07/12 10:01:42 kaib 1.3.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filtopt.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-07-21 11:29:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------ #include <tools/debug.hxx> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/uno/Sequence.hxx> #include "filtopt.hxx" #include "miscuno.hxx" using namespace utl; using namespace rtl; using namespace com::sun::star::uno; //------------------------------------------------------------------ #define CFGPATH_FILTER "Office.Calc/Filter/Import" #define SCFILTOPT_COLSCALE 0 #define SCFILTOPT_ROWSCALE 1 #define SCFILTOPT_WK3 2 #define SCFILTOPT_COUNT 3 Sequence<OUString> ScFilterOptions::GetPropertyNames() { static const char* aPropNames[] = { "MS_Excel/ColScale", // SCFILTOPT_COLSCALE "MS_Excel/RowScale", // SCFILTOPT_ROWSCALE "Lotus123/WK3" // SCFILTOPT_WK3 }; Sequence<OUString> aNames(SCFILTOPT_COUNT); OUString* pNames = aNames.getArray(); for(int i = 0; i < SCFILTOPT_COUNT; i++) pNames[i] = OUString::createFromAscii(aPropNames[i]); return aNames; } ScFilterOptions::ScFilterOptions() : ConfigItem( OUString::createFromAscii( CFGPATH_FILTER ) ), bWK3Flag( FALSE ), fExcelColScale( 0 ), fExcelRowScale( 0 ) { Sequence<OUString> aNames = GetPropertyNames(); Sequence<Any> aValues = GetProperties(aNames); // EnableNotification(aNames); const Any* pValues = aValues.getConstArray(); DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed") if(aValues.getLength() == aNames.getLength()) { for(int nProp = 0; nProp < aNames.getLength(); nProp++) { DBG_ASSERT(pValues[nProp].hasValue(), "property value missing") if(pValues[nProp].hasValue()) { switch(nProp) { case SCFILTOPT_COLSCALE: pValues[nProp] >>= fExcelColScale; break; case SCFILTOPT_ROWSCALE: pValues[nProp] >>= fExcelRowScale; break; case SCFILTOPT_WK3: bWK3Flag = ScUnoHelpFunctions::GetBoolFromAny( pValues[nProp] ); break; } } } } } void ScFilterOptions::Commit() { // options are never modified from office DBG_ERROR("trying to commit changed ScFilterOptions?"); } void ScFilterOptions::Notify( const Sequence<rtl::OUString>& aPropertyNames ) { DBG_ERROR("properties have been changed") } <|endoftext|>
<commit_before>#include <iostream> #include "eval.hpp" #include "bitboards.hpp" #include "other.hpp" #define INF (1000000) #define TURN_BONUS (10) #define PIECE_VALUE (100) #define MOBILITY_VALUE (10) const int PST[49] = { 30, 20, 10, 10, 10, 20, 30, 20, 10, 10, 5, 10, 10, 20, 10, 10, 5, 0, 5, 10, 10, 10, 5, 0, 0, 0, 5, 10, 10, 10, 5, 0, 5, 10, 10, 20, 10, 10, 5, 10, 10, 20, 30, 20, 10, 10, 10, 20, 30 }; void splitEval(const Position& pos) { int numFriendly = popcountll(pos.pieces[PIECE::CROSS]); int numUnfriendly = popcountll(pos.pieces[PIECE::NOUGHT]); std::cout << "Num friendly: " << numFriendly << std::endl; std::cout << "Num unfriendly: " << numUnfriendly << std::endl; } int eval(const Position& pos) { int numFriendly = popcountll(pos.pieces[PIECE::CROSS]); int numUnfriendly = popcountll(pos.pieces[PIECE::NOUGHT]); int ourMobility = 0; int theirMobility = 0; /* // Win condition if(numFriendly == 0 || numUnfriendly == 0) if((pieces[PIECE::CROSS] | pieces[PIECE::NOUGHT] | blockers) == U64_BOARD) { int score = 0; if(numFriendly > numUnfriendly) { score = INF; } else if(numFriendly < numUnfriendly) { score = -INF; } if(turn == SIDE::CROSS) { return score; } else { return -score; } } */ int ourPST = 0; int theirPST = 0; /* uint64_t copy = pos.pieces[PIECE::CROSS]; while(copy) { int sq = lsb(copy); ourPST += PST[sq]; copy &= copy - 1; } copy = pos.pieces[PIECE::NOUGHT]; while(copy) { int sq = lsb(copy); theirPST += PST[sq]; copy &= copy - 1; } */ int score = TURN_BONUS*(pos.turn == SIDE::CROSS ? 1 : -1) + PIECE_VALUE*numFriendly - PIECE_VALUE*numUnfriendly + MOBILITY_VALUE*ourMobility - MOBILITY_VALUE*theirMobility + ourPST - theirPST; if(pos.turn == SIDE::CROSS) { return score; } else { return -score; } }<commit_msg>Enable eval PST<commit_after>#include <iostream> #include "eval.hpp" #include "bitboards.hpp" #include "other.hpp" #define INF (1000000) #define TURN_BONUS (10) #define PIECE_VALUE (100) #define MOBILITY_VALUE (10) const int PST[49] = { 30, 20, 10, 10, 10, 20, 30, 20, 10, 10, 5, 10, 10, 20, 10, 10, 5, 0, 5, 10, 10, 10, 5, 0, 0, 0, 5, 10, 10, 10, 5, 0, 5, 10, 10, 20, 10, 10, 5, 10, 10, 20, 30, 20, 10, 10, 10, 20, 30 }; void splitEval(const Position& pos) { int numFriendly = popcountll(pos.pieces[PIECE::CROSS]); int numUnfriendly = popcountll(pos.pieces[PIECE::NOUGHT]); std::cout << "Num friendly: " << numFriendly << std::endl; std::cout << "Num unfriendly: " << numUnfriendly << std::endl; } int eval(const Position& pos) { int numFriendly = popcountll(pos.pieces[PIECE::CROSS]); int numUnfriendly = popcountll(pos.pieces[PIECE::NOUGHT]); int ourMobility = 0; int theirMobility = 0; /* // Win condition if(numFriendly == 0 || numUnfriendly == 0) if((pieces[PIECE::CROSS] | pieces[PIECE::NOUGHT] | blockers) == U64_BOARD) { int score = 0; if(numFriendly > numUnfriendly) { score = INF; } else if(numFriendly < numUnfriendly) { score = -INF; } if(turn == SIDE::CROSS) { return score; } else { return -score; } } */ int ourPST = 0; int theirPST = 0; uint64_t copy = pos.pieces[PIECE::CROSS]; while(copy) { int sq = lsb(copy); ourPST += PST[sq]; copy &= copy - 1; } copy = pos.pieces[PIECE::NOUGHT]; while(copy) { int sq = lsb(copy); theirPST += PST[sq]; copy &= copy - 1; } int score = TURN_BONUS*(pos.turn == SIDE::CROSS ? 1 : -1) + PIECE_VALUE*numFriendly - PIECE_VALUE*numUnfriendly + MOBILITY_VALUE*ourMobility - MOBILITY_VALUE*theirMobility + ourPST - theirPST; if(pos.turn == SIDE::CROSS) { return score; } else { return -score; } }<|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rechead.cxx,v $ * $Revision: 1.6.32.2 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include <tools/debug.hxx> #include "rechead.hxx" #include "scerrors.hxx" // STATIC DATA ----------------------------------------------------------- // ======================================================================= ScMultipleReadHeader::ScMultipleReadHeader(SvStream& rNewStream) : rStream( rNewStream ) { sal_uInt32 nDataSize; rStream >> nDataSize; ULONG nDataPos = rStream.Tell(); nTotalEnd = nDataPos + nDataSize; nEntryEnd = nTotalEnd; rStream.SeekRel(nDataSize); USHORT nID; rStream >> nID; if (nID != SCID_SIZES) { DBG_ERROR("SCID_SIZES nicht gefunden"); if ( rStream.GetError() == SVSTREAM_OK ) rStream.SetError( SVSTREAM_FILEFORMAT_ERROR ); // alles auf 0, damit BytesLeft() wenigstens abbricht pBuf = NULL; pMemStream = NULL; nEntryEnd = nDataPos; } else { sal_uInt32 nSizeTableLen; rStream >> nSizeTableLen; pBuf = new BYTE[nSizeTableLen]; rStream.Read( pBuf, nSizeTableLen ); pMemStream = new SvMemoryStream( (char*)pBuf, nSizeTableLen, STREAM_READ ); } nEndPos = rStream.Tell(); rStream.Seek( nDataPos ); } ScMultipleReadHeader::~ScMultipleReadHeader() { if ( pMemStream && pMemStream->Tell() != pMemStream->GetSize() ) { DBG_ERRORFILE( "Sizes nicht vollstaendig gelesen" ); if ( rStream.GetError() == SVSTREAM_OK ) rStream.SetError( SCWARN_IMPORT_INFOLOST ); } delete pMemStream; delete[] pBuf; rStream.Seek(nEndPos); } void ScMultipleReadHeader::EndEntry() { ULONG nPos = rStream.Tell(); DBG_ASSERT( nPos <= nEntryEnd, "zuviel gelesen" ); if ( nPos != nEntryEnd ) { if ( rStream.GetError() == SVSTREAM_OK ) rStream.SetError( SCWARN_IMPORT_INFOLOST ); rStream.Seek( nEntryEnd ); // Rest ueberspringen } nEntryEnd = nTotalEnd; // den ganzen Rest, wenn kein StartEntry kommt } void ScMultipleReadHeader::StartEntry() { ULONG nPos = rStream.Tell(); sal_uInt32 nEntrySize; (*pMemStream) >> nEntrySize; nEntryEnd = nPos + nEntrySize; DBG_ASSERT( nEntryEnd <= nTotalEnd, "zuviele Eintraege gelesen" ); } ULONG ScMultipleReadHeader::BytesLeft() const { ULONG nReadEnd = rStream.Tell(); if (nReadEnd <= nEntryEnd) return nEntryEnd-nReadEnd; DBG_ERROR("Fehler bei ScMultipleReadHeader::BytesLeft"); return 0; } // ----------------------------------------------------------------------- ScMultipleWriteHeader::ScMultipleWriteHeader(SvStream& rNewStream, sal_uInt32 nDefault) : rStream( rNewStream ), aMemStream( 4096, 4096 ) { nDataSize = nDefault; rStream << nDataSize; nDataPos = rStream.Tell(); nEntryStart = nDataPos; } ScMultipleWriteHeader::~ScMultipleWriteHeader() { ULONG nDataEnd = rStream.Tell(); rStream << (USHORT) SCID_SIZES; rStream << static_cast<sal_uInt32>(aMemStream.Tell()); rStream.Write( aMemStream.GetData(), aMemStream.Tell() ); if ( nDataEnd - nDataPos != nDataSize ) // Default getroffen? { nDataSize = nDataEnd - nDataPos; ULONG nPos = rStream.Tell(); rStream.Seek(nDataPos-sizeof(sal_uInt32)); rStream << nDataSize; // Groesse am Anfang eintragen rStream.Seek(nPos); } } void ScMultipleWriteHeader::EndEntry() { ULONG nPos = rStream.Tell(); aMemStream << static_cast<sal_uInt32>(nPos - nEntryStart); } void ScMultipleWriteHeader::StartEntry() { ULONG nPos = rStream.Tell(); nEntryStart = nPos; } <commit_msg>#i105745#: tools/stream.hxx: API change: make SvMemoryStream::GetSize() private introduce new public SvMemoryStream::GetEndOfData()<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rechead.cxx,v $ * $Revision: 1.6.32.2 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE --------------------------------------------------------------- #include <tools/debug.hxx> #include "rechead.hxx" #include "scerrors.hxx" // STATIC DATA ----------------------------------------------------------- // ======================================================================= ScMultipleReadHeader::ScMultipleReadHeader(SvStream& rNewStream) : rStream( rNewStream ) { sal_uInt32 nDataSize; rStream >> nDataSize; ULONG nDataPos = rStream.Tell(); nTotalEnd = nDataPos + nDataSize; nEntryEnd = nTotalEnd; rStream.SeekRel(nDataSize); USHORT nID; rStream >> nID; if (nID != SCID_SIZES) { DBG_ERROR("SCID_SIZES nicht gefunden"); if ( rStream.GetError() == SVSTREAM_OK ) rStream.SetError( SVSTREAM_FILEFORMAT_ERROR ); // alles auf 0, damit BytesLeft() wenigstens abbricht pBuf = NULL; pMemStream = NULL; nEntryEnd = nDataPos; } else { sal_uInt32 nSizeTableLen; rStream >> nSizeTableLen; pBuf = new BYTE[nSizeTableLen]; rStream.Read( pBuf, nSizeTableLen ); pMemStream = new SvMemoryStream( (char*)pBuf, nSizeTableLen, STREAM_READ ); } nEndPos = rStream.Tell(); rStream.Seek( nDataPos ); } ScMultipleReadHeader::~ScMultipleReadHeader() { if ( pMemStream && pMemStream->Tell() != pMemStream->GetEndOfData() ) { DBG_ERRORFILE( "Sizes nicht vollstaendig gelesen" ); if ( rStream.GetError() == SVSTREAM_OK ) rStream.SetError( SCWARN_IMPORT_INFOLOST ); } delete pMemStream; delete[] pBuf; rStream.Seek(nEndPos); } void ScMultipleReadHeader::EndEntry() { ULONG nPos = rStream.Tell(); DBG_ASSERT( nPos <= nEntryEnd, "zuviel gelesen" ); if ( nPos != nEntryEnd ) { if ( rStream.GetError() == SVSTREAM_OK ) rStream.SetError( SCWARN_IMPORT_INFOLOST ); rStream.Seek( nEntryEnd ); // Rest ueberspringen } nEntryEnd = nTotalEnd; // den ganzen Rest, wenn kein StartEntry kommt } void ScMultipleReadHeader::StartEntry() { ULONG nPos = rStream.Tell(); sal_uInt32 nEntrySize; (*pMemStream) >> nEntrySize; nEntryEnd = nPos + nEntrySize; DBG_ASSERT( nEntryEnd <= nTotalEnd, "zuviele Eintraege gelesen" ); } ULONG ScMultipleReadHeader::BytesLeft() const { ULONG nReadEnd = rStream.Tell(); if (nReadEnd <= nEntryEnd) return nEntryEnd-nReadEnd; DBG_ERROR("Fehler bei ScMultipleReadHeader::BytesLeft"); return 0; } // ----------------------------------------------------------------------- ScMultipleWriteHeader::ScMultipleWriteHeader(SvStream& rNewStream, sal_uInt32 nDefault) : rStream( rNewStream ), aMemStream( 4096, 4096 ) { nDataSize = nDefault; rStream << nDataSize; nDataPos = rStream.Tell(); nEntryStart = nDataPos; } ScMultipleWriteHeader::~ScMultipleWriteHeader() { ULONG nDataEnd = rStream.Tell(); rStream << (USHORT) SCID_SIZES; rStream << static_cast<sal_uInt32>(aMemStream.Tell()); rStream.Write( aMemStream.GetData(), aMemStream.Tell() ); if ( nDataEnd - nDataPos != nDataSize ) // Default getroffen? { nDataSize = nDataEnd - nDataPos; ULONG nPos = rStream.Tell(); rStream.Seek(nDataPos-sizeof(sal_uInt32)); rStream << nDataSize; // Groesse am Anfang eintragen rStream.Seek(nPos); } } void ScMultipleWriteHeader::EndEntry() { ULONG nPos = rStream.Tell(); aMemStream << static_cast<sal_uInt32>(nPos - nEntryStart); } void ScMultipleWriteHeader::StartEntry() { ULONG nPos = rStream.Tell(); nEntryStart = nPos; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formel.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-07-10 13:52:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FORMEL_HXX #define _FORMEL_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _TOKSTACK_HXX #include "tokstack.hxx" #endif #ifndef _ROOT_HXX #include "root.hxx" #endif #ifndef SC_SCGLOB_HXX #include <global.hxx> #endif #ifndef SC_COMPILER_HXX #include <compiler.hxx> #endif // ----- forwards -------------------------------------------------------- class XclImpStream; class ScTokenArray; class ScFormulaCell; struct SingleRefData; struct ComplRefData; //------------------------------------------------------------------------ enum ConvErr { ConvOK = 0, ConvErrNi, // nicht implemntierter/unbekannter Opcode aufgetreten ConvErrNoMem, // Fehler beim Speicheranfordern ConvErrExternal,// Add-Ins aus Excel werden nicht umgesetzt ConvErrCount // Nicht alle Bytes der Formel 'erwischt' }; enum FORMULA_TYPE { FT_CellFormula, FT_RangeName, FT_SharedFormula }; //--------------------------------------------------------- class ScRangeList - class _ScRangeList : protected List { private: protected: public: virtual ~_ScRangeList(); inline void Append( const ScRange& rRange ); inline void Append( ScRange* pRange ); inline void Append( const SingleRefData& rSRD ); inline void Append( const ComplRefData& rCRD ); List::Count; inline BOOL HasRanges( void ) const; inline const ScRange* First( void ); inline const ScRange* Next( void ); }; inline void _ScRangeList::Append( const ScRange& r ) { List::Insert( new ScRange( r ), LIST_APPEND ); } inline void _ScRangeList::Append( ScRange* p ) { List::Insert( p, LIST_APPEND ); } inline BOOL _ScRangeList::HasRanges( void ) const { return Count() > 0; } inline const ScRange* _ScRangeList::First( void ) { return ( const ScRange* ) List::First(); } inline const ScRange* _ScRangeList::Next( void ) { return ( const ScRange* ) List::Next(); } inline void _ScRangeList::Append( const SingleRefData& r ) { List::Insert( new ScRange( r.nCol, r.nRow, r.nTab ), LIST_APPEND ); } inline void _ScRangeList::Append( const ComplRefData& r ) { List::Insert( new ScRange( r.Ref1.nCol, r.Ref1.nRow, r.Ref1.nTab, r.Ref2.nCol, r.Ref2.nRow, r.Ref2.nTab ), LIST_APPEND ); } //----------------------------------------------------- class ScRangeListTabs - class _ScRangeListTabs { private: protected: BOOL bHasRanges; _ScRangeList** ppTabLists; _ScRangeList* pAct; UINT16 nAct; public: _ScRangeListTabs( void ); virtual ~_ScRangeListTabs(); void Append( SingleRefData aSRD, const BOOL bLimit = TRUE ); void Append( ComplRefData aCRD, const BOOL bLimit = TRUE ); inline BOOL HasRanges( void ) const; const ScRange* First( const UINT16 nTab = 0 ); const ScRange* Next( void ); // const ScRange* NextContinue( void ); inline const _ScRangeList* GetActList( void ) const; }; inline BOOL _ScRangeListTabs::HasRanges( void ) const { return bHasRanges; } inline const _ScRangeList* _ScRangeListTabs::GetActList( void ) const { return pAct; } class ConverterBase { protected: ConvErr eStatus; TokenPool aPool; // User Token + Predefined Token TokenStack aStack; sal_Char* pBuffer; // Universal-Puffer UINT16 nBufferSize; // ...und seine Groesse ScAddress aEingPos; ConverterBase( UINT16 nNewBuffer ); virtual ~ConverterBase(); void Reset(); public: inline SCCOL GetEingabeCol( void ) const { return aEingPos.Col(); } inline SCROW GetEingabeRow( void ) const { return aEingPos.Row(); } inline SCTAB GetEingabeTab( void ) const { return aEingPos.Tab(); } inline ScAddress GetEingPos( void ) const { return aEingPos; } }; class ExcelConverterBase : public ConverterBase { protected: ExcelConverterBase( UINT16 nNewBuffer ); virtual ~ExcelConverterBase(); public: void Reset(); void Reset( ScAddress aEingPos ); virtual ConvErr Convert( const ScTokenArray*& rpErg, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula ) = 0; virtual ConvErr Convert( _ScRangeListTabs&, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula ) = 0; }; class LotusConverterBase : public ConverterBase { protected: SvStream& aIn; INT32 nBytesLeft; inline void Ignore( const long nSeekRel ); inline void Read( sal_Char& nByte ); inline void Read( BYTE& nByte ); inline void Read( UINT16& nUINT16 ); inline void Read( INT16& nINT16 ); inline void Read( double& fDouble ); inline void Read( UINT32& nUINT32 ); LotusConverterBase( SvStream& rStr, UINT16 nNewBuffer ); virtual ~LotusConverterBase(); public: void Reset( INT32 nLen ); void Reset( INT32 nLen, ScAddress aEingPos ); void Reset( ScAddress aEingPos ); virtual ConvErr Convert( const ScTokenArray*& rpErg, INT32& nRest, const FORMULA_TYPE eFT = FT_CellFormula ) = 0; }; inline void LotusConverterBase::Ignore( const long nSeekRel ) { aIn.SeekRel( nSeekRel ); nBytesLeft -= nSeekRel; } inline void LotusConverterBase::Read( sal_Char& nByte ) { aIn >> nByte; nBytesLeft--; } inline void LotusConverterBase::Read( BYTE& nByte ) { aIn >> nByte; nBytesLeft--; } inline void LotusConverterBase::Read( UINT16& nUINT16 ) { aIn >> nUINT16; nBytesLeft -= 2; } inline void LotusConverterBase::Read( INT16& nINT16 ) { aIn >> nINT16; nBytesLeft -= 2; } inline void LotusConverterBase::Read( double& fDouble ) { aIn >> fDouble; nBytesLeft -= 8; } inline void LotusConverterBase::Read( UINT32& nUINT32 ) { aIn >> nUINT32; nBytesLeft -= 4; } #endif <commit_msg>INTEGRATION: CWS calcwarnings (1.8.116); FILE MERGED 2006/12/15 12:47:04 nn 1.8.116.4: #i69284# warning-free: access control for using 2006/12/14 14:01:19 dr 1.8.116.3: #i69284# remove compiler warnings for unxsols4 2006/12/12 16:42:48 dr 1.8.116.2: #i69284# remove compiler warnings for unxlngi6 2006/12/01 14:42:05 dr 1.8.116.1: #i69284# remove compiler warnings for wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: formel.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:33:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FORMEL_HXX #define _FORMEL_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _TOKSTACK_HXX #include "tokstack.hxx" #endif #ifndef _ROOT_HXX #include "root.hxx" #endif #ifndef SC_SCGLOB_HXX #include <global.hxx> #endif #ifndef SC_COMPILER_HXX #include <compiler.hxx> #endif // ----- forwards -------------------------------------------------------- class XclImpStream; class ScTokenArray; class ScFormulaCell; struct SingleRefData; struct ComplRefData; //------------------------------------------------------------------------ enum ConvErr { ConvOK = 0, ConvErrNi, // nicht implemntierter/unbekannter Opcode aufgetreten ConvErrNoMem, // Fehler beim Speicheranfordern ConvErrExternal,// Add-Ins aus Excel werden nicht umgesetzt ConvErrCount // Nicht alle Bytes der Formel 'erwischt' }; enum FORMULA_TYPE { FT_CellFormula, FT_RangeName, FT_SharedFormula }; //--------------------------------------------------------- class ScRangeList - class _ScRangeList : protected List { private: protected: public: virtual ~_ScRangeList(); inline void Append( const ScRange& rRange ); inline void Append( ScRange* pRange ); inline void Append( const SingleRefData& rSRD ); inline void Append( const ComplRefData& rCRD ); using List::Count; inline BOOL HasRanges( void ) const; inline const ScRange* First( void ); inline const ScRange* Next( void ); }; inline void _ScRangeList::Append( const ScRange& r ) { List::Insert( new ScRange( r ), LIST_APPEND ); } inline void _ScRangeList::Append( ScRange* p ) { List::Insert( p, LIST_APPEND ); } inline BOOL _ScRangeList::HasRanges( void ) const { return Count() > 0; } inline const ScRange* _ScRangeList::First( void ) { return ( const ScRange* ) List::First(); } inline const ScRange* _ScRangeList::Next( void ) { return ( const ScRange* ) List::Next(); } inline void _ScRangeList::Append( const SingleRefData& r ) { List::Insert( new ScRange( r.nCol, r.nRow, r.nTab ), LIST_APPEND ); } inline void _ScRangeList::Append( const ComplRefData& r ) { List::Insert( new ScRange( r.Ref1.nCol, r.Ref1.nRow, r.Ref1.nTab, r.Ref2.nCol, r.Ref2.nRow, r.Ref2.nTab ), LIST_APPEND ); } //----------------------------------------------------- class ScRangeListTabs - class _ScRangeListTabs { private: protected: BOOL bHasRanges; _ScRangeList** ppTabLists; _ScRangeList* pAct; UINT16 nAct; public: _ScRangeListTabs( void ); virtual ~_ScRangeListTabs(); void Append( SingleRefData aSRD, const BOOL bLimit = TRUE ); void Append( ComplRefData aCRD, const BOOL bLimit = TRUE ); inline BOOL HasRanges( void ) const; const ScRange* First( const UINT16 nTab = 0 ); const ScRange* Next( void ); // const ScRange* NextContinue( void ); inline const _ScRangeList* GetActList( void ) const; }; inline BOOL _ScRangeListTabs::HasRanges( void ) const { return bHasRanges; } inline const _ScRangeList* _ScRangeListTabs::GetActList( void ) const { return pAct; } class ConverterBase { protected: TokenPool aPool; // User Token + Predefined Token TokenStack aStack; ScAddress aEingPos; ConvErr eStatus; sal_Char* pBuffer; // Universal-Puffer UINT16 nBufferSize; // ...und seine Groesse ConverterBase( UINT16 nNewBuffer ); virtual ~ConverterBase(); void Reset(); public: inline SCCOL GetEingabeCol( void ) const { return aEingPos.Col(); } inline SCROW GetEingabeRow( void ) const { return aEingPos.Row(); } inline SCTAB GetEingabeTab( void ) const { return aEingPos.Tab(); } inline ScAddress GetEingPos( void ) const { return aEingPos; } }; class ExcelConverterBase : public ConverterBase { protected: ExcelConverterBase( UINT16 nNewBuffer ); virtual ~ExcelConverterBase(); public: void Reset(); void Reset( const ScAddress& rEingPos ); virtual ConvErr Convert( const ScTokenArray*& rpErg, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula ) = 0; virtual ConvErr Convert( _ScRangeListTabs&, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula ) = 0; }; class LotusConverterBase : public ConverterBase { protected: SvStream& aIn; INT32 nBytesLeft; inline void Ignore( const long nSeekRel ); inline void Read( sal_Char& nByte ); inline void Read( BYTE& nByte ); inline void Read( UINT16& nUINT16 ); inline void Read( INT16& nINT16 ); inline void Read( double& fDouble ); inline void Read( UINT32& nUINT32 ); LotusConverterBase( SvStream& rStr, UINT16 nNewBuffer ); virtual ~LotusConverterBase(); public: void Reset( INT32 nLen ); void Reset( INT32 nLen, const ScAddress& rEingPos ); void Reset( const ScAddress& rEingPos ); virtual ConvErr Convert( const ScTokenArray*& rpErg, INT32& nRest, const FORMULA_TYPE eFT = FT_CellFormula ) = 0; protected: using ConverterBase::Reset; }; inline void LotusConverterBase::Ignore( const long nSeekRel ) { aIn.SeekRel( nSeekRel ); nBytesLeft -= nSeekRel; } inline void LotusConverterBase::Read( sal_Char& nByte ) { aIn >> nByte; nBytesLeft--; } inline void LotusConverterBase::Read( BYTE& nByte ) { aIn >> nByte; nBytesLeft--; } inline void LotusConverterBase::Read( UINT16& nUINT16 ) { aIn >> nUINT16; nBytesLeft -= 2; } inline void LotusConverterBase::Read( INT16& nINT16 ) { aIn >> nINT16; nBytesLeft -= 2; } inline void LotusConverterBase::Read( double& fDouble ) { aIn >> fDouble; nBytesLeft -= 8; } inline void LotusConverterBase::Read( UINT32& nUINT32 ) { aIn >> nUINT32; nBytesLeft -= 4; } #endif <|endoftext|>
<commit_before>/* * Copyright 2007-2013 The OpenMx Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <sys/types.h> #include <errno.h> #include <R.h> #include <Rinternals.h> #include <Rdefines.h> #include <R_ext/Rdynload.h> #include <R_ext/BLAS.h> #include <R_ext/Lapack.h> #include "omxDefines.h" #include "types.h" #include "glue.h" #include "omxOpenmpWrap.h" #include "omxState.h" #include "omxMatrix.h" #include "omxAlgebra.h" #include "omxFitFunction.h" #include "omxExpectation.h" #include "omxNPSOLSpecific.h" #include "omxImportFrontendState.h" #include "omxExportBackendState.h" #include "Compute.h" #include "dmvnorm.h" #include "npsolswitch.h" static SEXP has_NPSOL() { return ScalarLogical(HAS_NPSOL); } static R_CallMethodDef callMethods[] = { {"backend", (DL_FUNC) omxBackend, 11}, {"callAlgebra", (DL_FUNC) omxCallAlgebra, 3}, {"findIdenticalRowsData", (DL_FUNC) findIdenticalRowsData, 5}, {"Dmvnorm_wrapper", (DL_FUNC) dmvnorm_wrapper, 3}, {"hasNPSOL_wrapper", (DL_FUNC) has_NPSOL, 0}, {NULL, NULL, 0} }; #ifdef __cplusplus extern "C" { #endif void R_init_OpenMx(DllInfo *info) { R_registerRoutines(info, NULL, callMethods, NULL, NULL); // There is no code that will change behavior whether openmp // is set for nested or not. I'm just keeping this in case it // makes a difference with older versions of openmp. 2012-12-24 JNP #if defined(_OPENMP) && _OPENMP <= 200505 omp_set_nested(0); #endif } void R_unload_OpenMx(DllInfo *) { // keep this stub in case we need it } #ifdef __cplusplus } #endif void string_to_try_error( const std::string& str ) { error("%s", str.c_str()); } void exception_to_try_error( const std::exception& ex ) { string_to_try_error(ex.what()); } SEXP asR(MxRList *out) { // detect duplicate keys TODO SEXP names, ans; int len = out->size(); PROTECT(names = allocVector(STRSXP, len)); PROTECT(ans = allocVector(VECSXP, len)); for (int lx=0; lx < len; ++lx) { SET_STRING_ELT(names, lx, (*out)[lx].first); SET_VECTOR_ELT(ans, lx, (*out)[lx].second); } namesgets(ans, names); return ans; } /* Main functions */ SEXP omxCallAlgebra2(SEXP matList, SEXP algNum, SEXP) { omxManageProtectInsanity protectManager; if(OMX_DEBUG) { mxLog("-----------------------------------------------------------------------");} if(OMX_DEBUG) { mxLog("Explicit call to algebra %d.", INTEGER(algNum)[0]);} int j,k,l; omxMatrix* algebra; int algebraNum = INTEGER(algNum)[0]; SEXP ans, nextMat; char output[MAX_STRING_LEN]; FitContext::setRFitFunction(NULL); Global = new omxGlobal; globalState = new omxState; omxInitState(globalState); if(OMX_DEBUG) { mxLog("Created state object at %p.", globalState);} /* Retrieve All Matrices From the MatList */ if(OMX_DEBUG) { mxLog("Processing %d matrix(ces).", length(matList));} omxMatrix *args[length(matList)]; for(k = 0; k < length(matList); k++) { PROTECT(nextMat = VECTOR_ELT(matList, k)); // This is the matrix + populations args[k] = omxNewMatrixFromRPrimitive(nextMat, globalState, 1, - k - 1); globalState->matrixList.push_back(args[k]); if(OMX_DEBUG) { mxLog("Matrix initialized at %p = (%d x %d).", globalState->matrixList[k], globalState->matrixList[k]->rows, globalState->matrixList[k]->cols); } } algebra = omxNewAlgebraFromOperatorAndArgs(algebraNum, args, length(matList), globalState); if(algebra==NULL) { error(globalState->statusMsg); } if(OMX_DEBUG) {mxLog("Completed Algebras and Matrices. Beginning Initial Compute.");} omxStateNextEvaluation(globalState); omxRecompute(algebra); PROTECT(ans = allocMatrix(REALSXP, algebra->rows, algebra->cols)); for(l = 0; l < algebra->rows; l++) for(j = 0; j < algebra->cols; j++) REAL(ans)[j * algebra->rows + l] = omxMatrixElement(algebra, l, j); if(OMX_DEBUG) { mxLog("All Algebras complete."); } output[0] = 0; if (isErrorRaised(globalState)) { strncpy(output, globalState->statusMsg, MAX_STRING_LEN); } omxFreeAllMatrixData(algebra); omxFreeState(globalState); delete Global; if(output[0]) error(output); return ans; } SEXP omxCallAlgebra(SEXP matList, SEXP algNum, SEXP options) { try { return omxCallAlgebra2(matList, algNum, options); } catch( std::exception& __ex__ ) { exception_to_try_error( __ex__ ); } catch(...) { string_to_try_error( "c++ exception (unknown reason)" ); } } static void friendlyStringToLogical(const char *key, const char *str, int *out) { int understood = FALSE; int newVal; if (matchCaseInsensitive(str, "Yes")) { understood = TRUE; newVal = 1; } else if (matchCaseInsensitive(str, "No")) { understood = TRUE; newVal = 0; } else if (isdigit(str[0]) && (atoi(str) == 1 || atoi(str) == 0)) { understood = TRUE; newVal = atoi(str); } if (!understood) { warning("Expecting 'Yes' or 'No' for '%s' but got '%s', ignoring", key, str); return; } if(OMX_DEBUG) { mxLog("%s=%d", key, newVal); } *out = newVal; } static void readOpts(SEXP options, int *ciMaxIterations, int *numThreads, int *analyticGradients) { char optionCharArray[250] = ""; // For setting options int numOptions = length(options); SEXP optionNames; PROTECT(optionNames = GET_NAMES(options)); for(int i = 0; i < numOptions; i++) { const char *nextOptionName = CHAR(STRING_ELT(optionNames, i)); const char *nextOptionValue = STRING_VALUE(VECTOR_ELT(options, i)); if (matchCaseInsensitive(nextOptionName, "CI Max Iterations")) { int newvalue = atoi(nextOptionValue); if (newvalue > 0) *ciMaxIterations = newvalue; } else if(matchCaseInsensitive(nextOptionName, "Analytic Gradients")) { friendlyStringToLogical(nextOptionName, nextOptionValue, analyticGradients); } else if(matchCaseInsensitive(nextOptionName, "Number of Threads")) { *numThreads = atoi(nextOptionValue); if (*numThreads < 1) { warning("Computation will be too slow with %d threads; using 1 thread instead", *numThreads); *numThreads = 1; } } else { // ignore } } UNPROTECT(1); // optionNames } SEXP omxBackend2(SEXP computeIndex, SEXP constraints, SEXP matList, SEXP varList, SEXP algList, SEXP expectList, SEXP computeList, SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options) { SEXP nextLoc; /* Sanity Check and Parse Inputs */ /* TODO: Need to find a way to account for nullness in these. For now, all checking is done on the front-end. */ // if(!isVector(matList)) error ("matList must be a list"); // if(!isVector(algList)) error ("algList must be a list"); omxManageProtectInsanity protectManager; FitContext::setRFitFunction(NULL); Global = new omxGlobal; /* Create new omxState for current state storage and initialize it. */ globalState = new omxState; omxInitState(globalState); if(OMX_DEBUG) { mxLog("Created state object at %p.", globalState);} Global->ciMaxIterations = 5; Global->numThreads = 1; Global->analyticGradients = 0; Global->numChildren = 0; readOpts(options, &Global->ciMaxIterations, &Global->numThreads, &Global->analyticGradients); #if HAS_NPSOL omxSetNPSOLOpts(options); #endif omxProcessMxDataEntities(data); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxMatrixEntities(matList); if (isErrorRaised(globalState)) error(globalState->statusMsg); std::vector<double> startingValues; omxProcessFreeVarList(varList, &startingValues); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxExpectationEntities(expectList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxAlgebraEntities(algList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxFitFunction(algList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxComputeEntities(computeList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxCompleteMxExpectationEntities(); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxCompleteMxFitFunction(algList); if (isErrorRaised(globalState)) error(globalState->statusMsg); // This is the chance to check for matrix // conformability, etc. Any errors encountered should // be reported using R's error() function, not // omxRaiseErrorf. omxInitialMatrixAlgebraCompute(); omxResetStatus(globalState); for(size_t index = 0; index < globalState->matrixList.size(); index++) { omxMarkDirty(globalState->matrixList[index]); } for(size_t index = 0; index < globalState->algebraList.size(); index++) { omxMarkDirty(globalState->algebraList[index]); } // maybe require a Compute object? TODO omxCompute *topCompute = NULL; if (!isNull(computeIndex)) { int ox = INTEGER(computeIndex)[0]; topCompute = Global->computeList[ox]; } /* Process Matrix and Algebra Population Function */ /* Each matrix is a list containing a matrix and the other matrices/algebras that are populated into it at each iteration. The first element is already processed, above. The rest of the list will be processed here. */ for(int j = 0; j < length(matList); j++) { PROTECT(nextLoc = VECTOR_ELT(matList, j)); // This is the matrix + populations omxProcessMatrixPopulationList(globalState->matrixList[j], nextLoc); } omxProcessConstraints(constraints); omxProcessConfidenceIntervals(intervalList); omxProcessCheckpointOptions(checkpointList); for (size_t vg=0; vg < Global->freeGroup.size(); ++vg) { Global->freeGroup[vg]->cacheDependencies(); } FitContext fc(startingValues); if (topCompute && !isErrorRaised(globalState)) { // switch varGroup, if necessary TODO topCompute->compute(&fc); } SEXP evaluations; PROTECT(evaluations = NEW_NUMERIC(2)); REAL(evaluations)[0] = globalState->computeCount; if (topCompute && !isErrorRaised(globalState) && globalState->stale) { fc.copyParamToModel(globalState); } MxRList result; omxExportResults(globalState, &result); REAL(evaluations)[1] = globalState->computeCount; double optStatus = NA_REAL; if (topCompute && !isErrorRaised(globalState)) { topCompute->reportResults(&fc, &result); optStatus = topCompute->getOptimizerStatus(); } MxRList backwardCompatStatus; backwardCompatStatus.push_back(std::make_pair(mkChar("code"), ScalarReal(optStatus))); backwardCompatStatus.push_back(std::make_pair(mkChar("status"), ScalarInteger(-isErrorRaised(globalState)))); if (isErrorRaised(globalState)) { SEXP msg; PROTECT(msg = allocVector(STRSXP, 1)); SET_STRING_ELT(msg, 0, mkChar(globalState->statusMsg)); result.push_back(std::make_pair(mkChar("error"), msg)); backwardCompatStatus.push_back(std::make_pair(mkChar("statusMsg"), msg)); } result.push_back(std::make_pair(mkChar("status"), asR(&backwardCompatStatus))); result.push_back(std::make_pair(mkChar("evaluations"), evaluations)); omxFreeState(globalState); delete Global; return asR(&result); } SEXP omxBackend(SEXP computeIndex, SEXP constraints, SEXP matList, SEXP varList, SEXP algList, SEXP expectList, SEXP computeList, SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options) { try { return omxBackend2(computeIndex, constraints, matList, varList, algList, expectList, computeList, data, intervalList, checkpointList, options); } catch( std::exception& __ex__ ) { exception_to_try_error( __ex__ ); } catch(...) { string_to_try_error( "c++ exception (unknown reason)" ); } } <commit_msg>Deadcode<commit_after>/* * Copyright 2007-2013 The OpenMx Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <sys/types.h> #include <errno.h> #include <R.h> #include <Rinternals.h> #include <Rdefines.h> #include <R_ext/Rdynload.h> #include <R_ext/BLAS.h> #include <R_ext/Lapack.h> #include "omxDefines.h" #include "types.h" #include "glue.h" #include "omxOpenmpWrap.h" #include "omxState.h" #include "omxMatrix.h" #include "omxAlgebra.h" #include "omxFitFunction.h" #include "omxExpectation.h" #include "omxNPSOLSpecific.h" #include "omxImportFrontendState.h" #include "omxExportBackendState.h" #include "Compute.h" #include "dmvnorm.h" #include "npsolswitch.h" static SEXP has_NPSOL() { return ScalarLogical(HAS_NPSOL); } static R_CallMethodDef callMethods[] = { {"backend", (DL_FUNC) omxBackend, 11}, {"callAlgebra", (DL_FUNC) omxCallAlgebra, 3}, {"findIdenticalRowsData", (DL_FUNC) findIdenticalRowsData, 5}, {"Dmvnorm_wrapper", (DL_FUNC) dmvnorm_wrapper, 3}, {"hasNPSOL_wrapper", (DL_FUNC) has_NPSOL, 0}, {NULL, NULL, 0} }; #ifdef __cplusplus extern "C" { #endif void R_init_OpenMx(DllInfo *info) { R_registerRoutines(info, NULL, callMethods, NULL, NULL); // There is no code that will change behavior whether openmp // is set for nested or not. I'm just keeping this in case it // makes a difference with older versions of openmp. 2012-12-24 JNP #if defined(_OPENMP) && _OPENMP <= 200505 omp_set_nested(0); #endif } void R_unload_OpenMx(DllInfo *) { // keep this stub in case we need it } #ifdef __cplusplus } #endif void string_to_try_error( const std::string& str ) { error("%s", str.c_str()); } void exception_to_try_error( const std::exception& ex ) { string_to_try_error(ex.what()); } SEXP asR(MxRList *out) { // detect duplicate keys TODO SEXP names, ans; int len = out->size(); PROTECT(names = allocVector(STRSXP, len)); PROTECT(ans = allocVector(VECSXP, len)); for (int lx=0; lx < len; ++lx) { SET_STRING_ELT(names, lx, (*out)[lx].first); SET_VECTOR_ELT(ans, lx, (*out)[lx].second); } namesgets(ans, names); return ans; } /* Main functions */ SEXP omxCallAlgebra2(SEXP matList, SEXP algNum, SEXP) { omxManageProtectInsanity protectManager; if(OMX_DEBUG) { mxLog("-----------------------------------------------------------------------");} if(OMX_DEBUG) { mxLog("Explicit call to algebra %d.", INTEGER(algNum)[0]);} int j,k,l; omxMatrix* algebra; int algebraNum = INTEGER(algNum)[0]; SEXP ans, nextMat; char output[MAX_STRING_LEN]; FitContext::setRFitFunction(NULL); Global = new omxGlobal; globalState = new omxState; omxInitState(globalState); if(OMX_DEBUG) { mxLog("Created state object at %p.", globalState);} /* Retrieve All Matrices From the MatList */ if(OMX_DEBUG) { mxLog("Processing %d matrix(ces).", length(matList));} omxMatrix *args[length(matList)]; for(k = 0; k < length(matList); k++) { PROTECT(nextMat = VECTOR_ELT(matList, k)); // This is the matrix + populations args[k] = omxNewMatrixFromRPrimitive(nextMat, globalState, 1, - k - 1); globalState->matrixList.push_back(args[k]); if(OMX_DEBUG) { mxLog("Matrix initialized at %p = (%d x %d).", globalState->matrixList[k], globalState->matrixList[k]->rows, globalState->matrixList[k]->cols); } } algebra = omxNewAlgebraFromOperatorAndArgs(algebraNum, args, length(matList), globalState); if(algebra==NULL) { error(globalState->statusMsg); } if(OMX_DEBUG) {mxLog("Completed Algebras and Matrices. Beginning Initial Compute.");} omxStateNextEvaluation(globalState); omxRecompute(algebra); PROTECT(ans = allocMatrix(REALSXP, algebra->rows, algebra->cols)); for(l = 0; l < algebra->rows; l++) for(j = 0; j < algebra->cols; j++) REAL(ans)[j * algebra->rows + l] = omxMatrixElement(algebra, l, j); if(OMX_DEBUG) { mxLog("All Algebras complete."); } output[0] = 0; if (isErrorRaised(globalState)) { strncpy(output, globalState->statusMsg, MAX_STRING_LEN); } omxFreeAllMatrixData(algebra); omxFreeState(globalState); delete Global; if(output[0]) error(output); return ans; } SEXP omxCallAlgebra(SEXP matList, SEXP algNum, SEXP options) { try { return omxCallAlgebra2(matList, algNum, options); } catch( std::exception& __ex__ ) { exception_to_try_error( __ex__ ); } catch(...) { string_to_try_error( "c++ exception (unknown reason)" ); } } static void friendlyStringToLogical(const char *key, const char *str, int *out) { int understood = FALSE; int newVal; if (matchCaseInsensitive(str, "Yes")) { understood = TRUE; newVal = 1; } else if (matchCaseInsensitive(str, "No")) { understood = TRUE; newVal = 0; } else if (isdigit(str[0]) && (atoi(str) == 1 || atoi(str) == 0)) { understood = TRUE; newVal = atoi(str); } if (!understood) { warning("Expecting 'Yes' or 'No' for '%s' but got '%s', ignoring", key, str); return; } if(OMX_DEBUG) { mxLog("%s=%d", key, newVal); } *out = newVal; } static void readOpts(SEXP options, int *ciMaxIterations, int *numThreads, int *analyticGradients) { int numOptions = length(options); SEXP optionNames; PROTECT(optionNames = GET_NAMES(options)); for(int i = 0; i < numOptions; i++) { const char *nextOptionName = CHAR(STRING_ELT(optionNames, i)); const char *nextOptionValue = STRING_VALUE(VECTOR_ELT(options, i)); if (matchCaseInsensitive(nextOptionName, "CI Max Iterations")) { int newvalue = atoi(nextOptionValue); if (newvalue > 0) *ciMaxIterations = newvalue; } else if(matchCaseInsensitive(nextOptionName, "Analytic Gradients")) { friendlyStringToLogical(nextOptionName, nextOptionValue, analyticGradients); } else if(matchCaseInsensitive(nextOptionName, "Number of Threads")) { *numThreads = atoi(nextOptionValue); if (*numThreads < 1) { warning("Computation will be too slow with %d threads; using 1 thread instead", *numThreads); *numThreads = 1; } } else { // ignore } } UNPROTECT(1); // optionNames } SEXP omxBackend2(SEXP computeIndex, SEXP constraints, SEXP matList, SEXP varList, SEXP algList, SEXP expectList, SEXP computeList, SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options) { SEXP nextLoc; /* Sanity Check and Parse Inputs */ /* TODO: Need to find a way to account for nullness in these. For now, all checking is done on the front-end. */ // if(!isVector(matList)) error ("matList must be a list"); // if(!isVector(algList)) error ("algList must be a list"); omxManageProtectInsanity protectManager; FitContext::setRFitFunction(NULL); Global = new omxGlobal; /* Create new omxState for current state storage and initialize it. */ globalState = new omxState; omxInitState(globalState); if(OMX_DEBUG) { mxLog("Created state object at %p.", globalState);} Global->ciMaxIterations = 5; Global->numThreads = 1; Global->analyticGradients = 0; Global->numChildren = 0; readOpts(options, &Global->ciMaxIterations, &Global->numThreads, &Global->analyticGradients); #if HAS_NPSOL omxSetNPSOLOpts(options); #endif omxProcessMxDataEntities(data); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxMatrixEntities(matList); if (isErrorRaised(globalState)) error(globalState->statusMsg); std::vector<double> startingValues; omxProcessFreeVarList(varList, &startingValues); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxExpectationEntities(expectList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxAlgebraEntities(algList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxFitFunction(algList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxProcessMxComputeEntities(computeList); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxCompleteMxExpectationEntities(); if (isErrorRaised(globalState)) error(globalState->statusMsg); omxCompleteMxFitFunction(algList); if (isErrorRaised(globalState)) error(globalState->statusMsg); // This is the chance to check for matrix // conformability, etc. Any errors encountered should // be reported using R's error() function, not // omxRaiseErrorf. omxInitialMatrixAlgebraCompute(); omxResetStatus(globalState); for(size_t index = 0; index < globalState->matrixList.size(); index++) { omxMarkDirty(globalState->matrixList[index]); } for(size_t index = 0; index < globalState->algebraList.size(); index++) { omxMarkDirty(globalState->algebraList[index]); } // maybe require a Compute object? TODO omxCompute *topCompute = NULL; if (!isNull(computeIndex)) { int ox = INTEGER(computeIndex)[0]; topCompute = Global->computeList[ox]; } /* Process Matrix and Algebra Population Function */ /* Each matrix is a list containing a matrix and the other matrices/algebras that are populated into it at each iteration. The first element is already processed, above. The rest of the list will be processed here. */ for(int j = 0; j < length(matList); j++) { PROTECT(nextLoc = VECTOR_ELT(matList, j)); // This is the matrix + populations omxProcessMatrixPopulationList(globalState->matrixList[j], nextLoc); } omxProcessConstraints(constraints); omxProcessConfidenceIntervals(intervalList); omxProcessCheckpointOptions(checkpointList); for (size_t vg=0; vg < Global->freeGroup.size(); ++vg) { Global->freeGroup[vg]->cacheDependencies(); } FitContext fc(startingValues); if (topCompute && !isErrorRaised(globalState)) { // switch varGroup, if necessary TODO topCompute->compute(&fc); } SEXP evaluations; PROTECT(evaluations = NEW_NUMERIC(2)); REAL(evaluations)[0] = globalState->computeCount; if (topCompute && !isErrorRaised(globalState) && globalState->stale) { fc.copyParamToModel(globalState); } MxRList result; omxExportResults(globalState, &result); REAL(evaluations)[1] = globalState->computeCount; double optStatus = NA_REAL; if (topCompute && !isErrorRaised(globalState)) { topCompute->reportResults(&fc, &result); optStatus = topCompute->getOptimizerStatus(); } MxRList backwardCompatStatus; backwardCompatStatus.push_back(std::make_pair(mkChar("code"), ScalarReal(optStatus))); backwardCompatStatus.push_back(std::make_pair(mkChar("status"), ScalarInteger(-isErrorRaised(globalState)))); if (isErrorRaised(globalState)) { SEXP msg; PROTECT(msg = allocVector(STRSXP, 1)); SET_STRING_ELT(msg, 0, mkChar(globalState->statusMsg)); result.push_back(std::make_pair(mkChar("error"), msg)); backwardCompatStatus.push_back(std::make_pair(mkChar("statusMsg"), msg)); } result.push_back(std::make_pair(mkChar("status"), asR(&backwardCompatStatus))); result.push_back(std::make_pair(mkChar("evaluations"), evaluations)); omxFreeState(globalState); delete Global; return asR(&result); } SEXP omxBackend(SEXP computeIndex, SEXP constraints, SEXP matList, SEXP varList, SEXP algList, SEXP expectList, SEXP computeList, SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options) { try { return omxBackend2(computeIndex, constraints, matList, varList, algList, expectList, computeList, data, intervalList, checkpointList, options); } catch( std::exception& __ex__ ) { exception_to_try_error( __ex__ ); } catch(...) { string_to_try_error( "c++ exception (unknown reason)" ); } } <|endoftext|>
<commit_before>#include "../test.h" #include <rxcpp/operators/rx-take.hpp> #include <rxcpp/operators/rx-observe_on.hpp> const int static_onnextcalls = 100000; SCENARIO("range observed on new_thread", "[hide][range][observe_on_debug][observe_on][long][perf]"){ const int& onnextcalls = static_onnextcalls; GIVEN("a range"){ WHEN("multicasting a million ints"){ using namespace std::chrono; typedef steady_clock clock; auto el = rx::observe_on_new_thread(); for (int n = 0; n < 10; n++) { std::atomic_bool disposed; std::atomic_bool done; auto c = std::make_shared<int>(0); rx::composite_subscription cs; cs.add([&](){ if (!done) {abort();} disposed = true; }); auto start = clock::now(); rxs::range<int>(1) .take(onnextcalls) .observe_on(el) .as_blocking() .subscribe( cs, [c](int){ ++(*c); }, [&](){ done = true; }); auto expected = onnextcalls; REQUIRE(*c == expected); auto finish = clock::now(); auto msElapsed = duration_cast<milliseconds>(finish-start); std::cout << "range -> observe_on new_thread : " << (*c) << " on_next calls, " << msElapsed.count() << "ms elapsed, int-per-second " << *c / (msElapsed.count() / 1000.0) << std::endl; } } } } SCENARIO("observe_on", "[observe][observe_on]"){ GIVEN("a source"){ auto sc = rxsc::make_test(); auto so = rx::synchronize_in_one_worker(sc); auto w = sc.create_worker(); const rxsc::test::messages<int> on; auto xs = sc.make_hot_observable({ on.next(150, 1), on.next(210, 2), on.next(240, 3), on.completed(300) }); WHEN("subscribe_on is specified"){ auto res = w.start( [so, xs]() { return xs .observe_on(so); } ); THEN("the output contains items sent while subscribed"){ auto required = rxu::to_vector({ on.next(211, 2), on.next(241, 3), on.completed(301) }); auto actual = res.get_observer().messages(); REQUIRE(required == actual); } THEN("there was 1 subscription/unsubscription to the source"){ auto required = rxu::to_vector({ on.subscribe(200, 300) }); auto actual = xs.subscriptions(); REQUIRE(required == actual); } } } } SCENARIO("stream observe_on", "[observe][observe_on]"){ GIVEN("a source"){ auto sc = rxsc::make_test(); auto so = rx::synchronize_in_one_worker(sc); auto w = sc.create_worker(); const rxsc::test::messages<int> on; auto xs = sc.make_hot_observable({ on.next(150, 1), on.next(210, 2), on.next(240, 3), on.completed(300) }); WHEN("observe_on is specified"){ auto res = w.start( [so, xs]() { return xs | rxo::observe_on(so); } ); THEN("the output contains items sent while subscribed"){ auto required = rxu::to_vector({ on.next(211, 2), on.next(241, 3), on.completed(301) }); auto actual = res.get_observer().messages(); REQUIRE(required == actual); } THEN("there was 1 subscription/unsubscription to the source"){ auto required = rxu::to_vector({ on.subscribe(200, 300) }); auto actual = xs.subscriptions(); REQUIRE(required == actual); } } } }<commit_msg>adding test for nocompare observe_on (#448)<commit_after>#include "../test.h" #include <rxcpp/operators/rx-take.hpp> #include <rxcpp/operators/rx-map.hpp> #include <rxcpp/operators/rx-observe_on.hpp> const int static_onnextcalls = 100000; SCENARIO("range observed on new_thread", "[hide][range][observe_on_debug][observe_on][long][perf]"){ const int& onnextcalls = static_onnextcalls; GIVEN("a range"){ WHEN("multicasting a million ints"){ using namespace std::chrono; typedef steady_clock clock; auto el = rx::observe_on_new_thread(); for (int n = 0; n < 10; n++) { std::atomic_bool disposed; std::atomic_bool done; auto c = std::make_shared<int>(0); rx::composite_subscription cs; cs.add([&](){ if (!done) {abort();} disposed = true; }); auto start = clock::now(); rxs::range<int>(1) .take(onnextcalls) .observe_on(el) .as_blocking() .subscribe( cs, [c](int){ ++(*c); }, [&](){ done = true; }); auto expected = onnextcalls; REQUIRE(*c == expected); auto finish = clock::now(); auto msElapsed = duration_cast<milliseconds>(finish-start); std::cout << "range -> observe_on new_thread : " << (*c) << " on_next calls, " << msElapsed.count() << "ms elapsed, int-per-second " << *c / (msElapsed.count() / 1000.0) << std::endl; } } } } SCENARIO("observe_on", "[observe][observe_on]"){ GIVEN("a source"){ auto sc = rxsc::make_test(); auto so = rx::synchronize_in_one_worker(sc); auto w = sc.create_worker(); const rxsc::test::messages<int> on; auto xs = sc.make_hot_observable({ on.next(150, 1), on.next(210, 2), on.next(240, 3), on.completed(300) }); WHEN("subscribe_on is specified"){ auto res = w.start( [so, xs]() { return xs .observe_on(so); } ); THEN("the output contains items sent while subscribed"){ auto required = rxu::to_vector({ on.next(211, 2), on.next(241, 3), on.completed(301) }); auto actual = res.get_observer().messages(); REQUIRE(required == actual); } THEN("there was 1 subscription/unsubscription to the source"){ auto required = rxu::to_vector({ on.subscribe(200, 300) }); auto actual = xs.subscriptions(); REQUIRE(required == actual); } } } } SCENARIO("stream observe_on", "[observe][observe_on]"){ GIVEN("a source"){ auto sc = rxsc::make_test(); auto so = rx::synchronize_in_one_worker(sc); auto w = sc.create_worker(); const rxsc::test::messages<int> on; auto xs = sc.make_hot_observable({ on.next(150, 1), on.next(210, 2), on.next(240, 3), on.completed(300) }); WHEN("observe_on is specified"){ auto res = w.start( [so, xs]() { return xs | rxo::observe_on(so); } ); THEN("the output contains items sent while subscribed"){ auto required = rxu::to_vector({ on.next(211, 2), on.next(241, 3), on.completed(301) }); auto actual = res.get_observer().messages(); REQUIRE(required == actual); } THEN("there was 1 subscription/unsubscription to the source"){ auto required = rxu::to_vector({ on.subscribe(200, 300) }); auto actual = xs.subscriptions(); REQUIRE(required == actual); } } } } class nocompare { public: int v; }; SCENARIO("observe_on no-comparison", "[observe][observe_on]"){ GIVEN("a source"){ auto sc = rxsc::make_test(); auto so = rx::observe_on_one_worker(sc); auto w = sc.create_worker(); const rxsc::test::messages<nocompare> in; const rxsc::test::messages<int> out; auto xs = sc.make_hot_observable({ in.next(150, nocompare{1}), in.next(210, nocompare{2}), in.next(240, nocompare{3}), in.completed(300) }); WHEN("observe_on is specified"){ auto res = w.start( [so, xs]() { return xs | rxo::observe_on(so) | rxo::map([](nocompare v){ return v.v; }) | rxo::as_dynamic(); } ); THEN("the output contains items sent while subscribed"){ auto required = rxu::to_vector({ out.next(211, 2), out.next(241, 3), out.completed(301) }); auto actual = res.get_observer().messages(); REQUIRE(required == actual); } THEN("there was 1 subscription/unsubscription to the source"){ auto required = rxu::to_vector({ out.subscribe(200, 300) }); auto actual = xs.subscriptions(); REQUIRE(required == actual); } } } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/monitor/monitor_buffer.h" #include <string> #include "gtest/gtest.h" #include "modules/common/monitor/monitor.h" namespace apollo { namespace common { namespace monitor { class MonitorBufferTest : public ::testing::Test { protected: void SetUp() override { buffer_ = new MonitorBuffer(nullptr); } void TearDown() override { delete buffer_; } MonitorBuffer *buffer_ = nullptr; }; TEST_F(MonitorBufferTest, PrintLog) { FLAGS_logtostderr = true; FLAGS_v = 4; { testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_TRUE(testing::internal::GetCapturedStderr().empty()); } { buffer_->INFO("INFO_msg"); testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_NE(std::string::npos, testing::internal::GetCapturedStderr().find("INFO_msg")); } { buffer_->ERROR("ERROR_msg"); testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_NE(std::string::npos, testing::internal::GetCapturedStderr().find("ERROR_msg")); } { buffer_->WARN("WARN_msg"); testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_NE(std::string::npos, testing::internal::GetCapturedStderr().find("WARN_msg")); } { buffer_->FATAL("FATAL_msg"); EXPECT_DEATH(buffer_->PrintLog(), ""); } } TEST_F(MonitorBufferTest, RegisterMacro) { { buffer_->INFO("Info"); EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); const auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::INFO, item.first); EXPECT_EQ("Info", item.second); } { buffer_->ERROR("Error"); EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(2, buffer_->monitor_msg_items_.size()); const auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("Error", item.second); } } TEST_F(MonitorBufferTest, AddMonitorMsgItem) { buffer_->AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError"); EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); const auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("TestError", item.second); } TEST_F(MonitorBufferTest, Operator) { buffer_->ERROR() << "Hi"; EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("Hi", item.second); (*buffer_) << " How" << " are" << " you"; EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("Hi How are you", item.second); buffer_->INFO() << 3 << "pieces"; EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_); ASSERT_EQ(2, buffer_->monitor_msg_items_.size()); item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::INFO, item.first); EXPECT_EQ("3pieces", item.second); const char *fake_input = nullptr; EXPECT_TRUE(&(buffer_->INFO() << fake_input) == buffer_); } } // namespace monitor } // namespace common } // namespace apollo <commit_msg>security: fix security report problem.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/monitor/monitor_buffer.h" #include <string> #include "gtest/gtest.h" #include "modules/common/monitor/monitor.h" namespace apollo { namespace common { namespace monitor { class MonitorBufferTest : public ::testing::Test { protected: void SetUp() override { buffer_ = new MonitorBuffer(nullptr); } void TearDown() override { delete buffer_; } MonitorBuffer *buffer_ = nullptr; }; TEST_F(MonitorBufferTest, PrintLog) { FLAGS_logtostderr = true; FLAGS_v = 4; { testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_TRUE(testing::internal::GetCapturedStderr().empty()); } { buffer_->INFO("INFO_msg"); testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_NE(std::string::npos, testing::internal::GetCapturedStderr().find("INFO_msg")); } { buffer_->ERROR("ERROR_msg"); testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_NE(std::string::npos, testing::internal::GetCapturedStderr().find("ERROR_msg")); } { buffer_->WARN("WARN_msg"); testing::internal::CaptureStderr(); buffer_->PrintLog(); EXPECT_NE(std::string::npos, testing::internal::GetCapturedStderr().find("WARN_msg")); } { buffer_->FATAL("FATAL_msg"); EXPECT_DEATH(buffer_->PrintLog(), ""); } } TEST_F(MonitorBufferTest, RegisterMacro) { { buffer_->INFO("Info"); EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); const auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::INFO, item.first); EXPECT_EQ("Info", item.second); } { buffer_->ERROR("Error"); EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(2, buffer_->monitor_msg_items_.size()); const auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("Error", item.second); } } TEST_F(MonitorBufferTest, AddMonitorMsgItem) { buffer_->AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError"); EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); const auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("TestError", item.second); } TEST_F(MonitorBufferTest, Operator) { buffer_->ERROR() << "Hi"; EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); auto &item = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("Hi", item.second); (*buffer_) << " How" << " are" << " you"; EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_); ASSERT_EQ(1, buffer_->monitor_msg_items_.size()); EXPECT_EQ(MonitorMessageItem::ERROR, item.first); EXPECT_EQ("Hi How are you", item.second); buffer_->INFO() << 3 << "pieces"; EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_); ASSERT_EQ(2, buffer_->monitor_msg_items_.size()); auto item2 = buffer_->monitor_msg_items_.back(); EXPECT_EQ(MonitorMessageItem::INFO, item2.first); EXPECT_EQ("3pieces", item2.second); const char *fake_input = nullptr; EXPECT_TRUE(&(buffer_->INFO() << fake_input) == buffer_); } } // namespace monitor } // namespace common } // namespace apollo <|endoftext|>
<commit_before>#include "from_json.h" #include <unordered_map> #include <stack> #include <asdf_multiplat/utilities/utilities.h> using namespace asdf; using namespace asdf::util; namespace tired_of_build_issues { std::string read_text_file(std::string const& filepath) { //if(!is_file(filepath)) //{ // //throw file_open_exception(filepath); // EXPLODE("C'est une probleme"); //} std::string outputstring; std::ifstream ifs(filepath, std::ifstream::in); ifs.exceptions( std::ios::failbit ); // ASSERT(ifs.good(), "Error loading text file %s", filepath.c_str()); if(!ifs.good()) { //throw file_open_exception(filepath); EXPLODE("C'est une probleme"); } ifs.seekg(0, std::ios::end); //seek to the end to get the size the output string should be outputstring.reserve(size_t(ifs.tellg())); //reserve necessary memory up front ifs.seekg(0, std::ios::beg); //seek back to the start outputstring.assign((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); ifs.close(); return outputstring; } } // custom hash function for std::path so that I can use it as // a key in unordered_map namespace std { template<> struct hash<stdfs::path> { size_t operator()(const stdfs::path &p) const { return std::hash<std::string>()(canonical(p).string()); } }; } namespace plantgen { // global stack used for resolving relative filepaths // when including other json files as node properties / values // I should probably devise a better method of doing this, since // I don't think this will handle more than one level of inclusion // if the JSON files are not all in the same directory //FIXME make this not global std::stack<stdfs::path> include_dir_stack; std::unordered_map<stdfs::path, pregen_node_t> include_cache; bool str_eq(char const* a, char const* b) { return strcmp(a, b) == 0; } std::vector<std::string> value_string_list_from_json_array(cJSON* json_array) { ASSERT(json_array, ""); ASSERT(json_array->type == cJSON_Array, "json_array is not actually a JSON array"); std::vector<std::string> values; cJSON* j = json_array->child; while(j) { ASSERT(j->type == cJSON_String, "Expected a JSON string"); values.emplace_back(j->valuestring); j = j->next; } return values; } multi_value_t multi_value_from_json(cJSON* json) { ASSERT(str_eq(json->child->string, "Multi"), "Expected a \"Multi\" json_obj"); ASSERT(json->child->type == cJSON_Number, "JSON Value of \"Multi\" should be an integer"); multi_value_t v; v.num_to_pick = json->child->valueint; v.values = std::move(value_string_list_from_json_array(json->child->next)); return v; } range_value_t range_value_from_json(cJSON* json) { ASSERT(str_eq(json->string, "Range"), "Expected a \"Range\" json_obj"); return value_string_list_from_json_array(json); } weighted_value_t value_type_from_json(cJSON* json) { if(json->type == cJSON_String) { return std::string(json->valuestring); } else if(!json->child) { EXPLODE("invalid value object %s", json->string); return null_value_t(); } else if(str_eq(json->child->string, "Multi")) { return multi_value_from_json(json); } else if(str_eq(json->child->string, "Range")) { return range_value_from_json(json->child); } else { EXPLODE("unrecognized value object %s", json->child->string); return weighted_value_t(null_value_t()); } } pregen_node_t node_from_json(cJSON* json_node) { pregen_node_t node; node.name = std::string(CJSON_STR(json_node, Name)); cJSON* cur_child = json_node->child; while(cur_child) { if(str_eq(cur_child->string, "Properties")) { cJSON* property_json = cur_child->child; while(property_json) { node.add_child(node_from_json(property_json)); property_json = property_json->next; } } else if(str_eq(cur_child->string, "Values")) { cJSON* value_json = cur_child->child; while(value_json) { // if the value is a node, load it differently // since we can't return a node as part of the variant //if the value is an object starting with a child named "Name", it's a node if(value_json->type == cJSON_Object && value_json->child && str_eq(value_json->child->string, "Name")) { node.value_nodes.push_back(std::move(node_from_json(value_json))); } else { node.values.push_back(std::move(value_type_from_json(value_json))); } value_json = value_json->next; } } else if(str_eq(cur_child->string, "Include")) { ASSERT(cur_child->type == cJSON_String, "Include filepath must be a string"); stdfs::path relpath(cur_child->valuestring); auto parent_path = include_dir_stack.top().parent_path(); stdfs::path fullpath = parent_path / relpath; try{ auto included_node = node_from_json(fullpath); if(included_node.name == node.name) { node.merge_with(std::move(included_node)); } else { node.add_child(std::move(included_node)); } } catch(file_not_found_exception const&) { throw include_exception{include_dir_stack.top(), fullpath}; } } else if(str_eq(cur_child->string, "Weight")) { if(cur_child->type != cJSON_Number) throw json_type_exception(include_dir_stack.top(), cur_child, cJSON_Number); node.weight = cur_child->valueint; } else { // LOG("Unrecognized tag '%s' in node '%s'", cur_child->string, json_node->string); } cur_child = cur_child->next; } return node; } pregen_node_t node_from_json(stdfs::path const& filepath) { if(!stdfs::is_regular_file(filepath)) throw file_not_found_exception{filepath}; auto canonical_path = stdfs::canonical(filepath); auto cached_node_entry = include_cache.find(canonical_path); if(cached_node_entry != include_cache.end()) { return cached_node_entry->second; } else { //std::string json_str = asdf::util::read_text_file(filepath); std::string json_str = tired_of_build_issues::read_text_file(canonical_path.string()); cJSON* json_root = cJSON_Parse(json_str.c_str()); if(!json_root) { throw json_parse_exception(filepath, cJSON_GetErrorPtr()); } include_dir_stack.push(canonical_path); auto node = node_from_json(json_root); cJSON_Delete(json_root); include_dir_stack.pop(); include_cache.insert({canonical_path, node}); return node; } } generated_node_t generate_node_from_json(stdfs::path const& filepath) { auto node = node_from_json(filepath); return generate_node(node); } }<commit_msg>refactoring the parsing of values from json and adding code to read weight from strings (ex: '%20 ValueName' gives a weight of 20 to a value named 'ValueName')<commit_after>#include "from_json.h" #include <unordered_map> #include <stack> #include <asdf_multiplat/utilities/utilities.h> using namespace asdf; using namespace asdf::util; namespace tired_of_build_issues { std::string read_text_file(std::string const& filepath) { //if(!is_file(filepath)) //{ // //throw file_open_exception(filepath); // EXPLODE("C'est une probleme"); //} std::string outputstring; std::ifstream ifs(filepath, std::ifstream::in); ifs.exceptions( std::ios::failbit ); // ASSERT(ifs.good(), "Error loading text file %s", filepath.c_str()); if(!ifs.good()) { //throw file_open_exception(filepath); EXPLODE("C'est une probleme"); } ifs.seekg(0, std::ios::end); //seek to the end to get the size the output string should be outputstring.reserve(size_t(ifs.tellg())); //reserve necessary memory up front ifs.seekg(0, std::ios::beg); //seek back to the start outputstring.assign((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); ifs.close(); return outputstring; } } // custom hash function for std::path so that I can use it as // a key in unordered_map namespace std { template<> struct hash<stdfs::path> { size_t operator()(const stdfs::path &p) const { return std::hash<std::string>()(canonical(p).string()); } }; } namespace plantgen { // global stack used for resolving relative filepaths // when including other json files as node properties / values // I should probably devise a better method of doing this, since // I don't think this will handle more than one level of inclusion // if the JSON files are not all in the same directory //FIXME make this not global std::stack<stdfs::path> include_dir_stack; std::unordered_map<stdfs::path, pregen_node_t> include_cache; bool str_eq(char const* a, char const* b) { return strcmp(a, b) == 0; } std::vector<std::string> value_string_list_from_json_array(cJSON* json_array) { ASSERT(json_array, ""); ASSERT(json_array->type == cJSON_Array, "json_array is not actually a JSON array"); std::vector<std::string> values; cJSON* j = json_array->child; while(j) { ASSERT(j->type == cJSON_String, "Expected a JSON string"); values.emplace_back(j->valuestring); j = j->next; } return values; } multi_value_t multi_value_from_json(cJSON* json) { ASSERT(str_eq(json->child->string, "Multi"), "Expected a \"Multi\" json_obj"); ASSERT(json->child->type == cJSON_Number, "JSON Value of \"Multi\" should be an integer"); multi_value_t v; v.num_to_pick = json->child->valueint; v.values = std::move(value_string_list_from_json_array(json->child->next)); return v; } range_value_t range_value_from_json(cJSON* json) { ASSERT(str_eq(json->string, "Range"), "Expected a \"Range\" json_obj"); return value_string_list_from_json_array(json); } weighted_value_t value_from_string(std::string const& value_string) { weighted_value_t v = value_string; if(value_string[0] == '%') { auto space_pos = value_string.find_first_of(' '); if(space_pos > 1) { v = value_string.substr(space_pos, std::string::npos); v.weight = std::stoi(value_string.substr(1, space_pos)); } else { //TODO: better error message std::cout << "Invalid Weight Specifier for \"" << value_string << "\"\n"; } } return v; } weighted_value_t value_type_from_json(cJSON* json) { if(json->type == cJSON_String) { return value_from_string(std::string(json->valuestring)); } else if(!json->child) { EXPLODE("invalid value object %s", json->string); return null_value_t(); } else if(str_eq(json->child->string, "Multi")) { return multi_value_from_json(json); } else if(str_eq(json->child->string, "Range")) { return range_value_from_json(json->child); } else { EXPLODE("unrecognized value object %s", json->child->string); return weighted_value_t(null_value_t()); } } int weight_from_string(std::string const& weight_str) { if(weight_str[0] == '%') { auto space_pos = weight_str.find_first_of(' '); if(space_pos > 1) { return std::stoi(weight_str.substr(1, space_pos)); } else { //TODO: better error message std::cout << "Invalid Weight Specifier for \"" << weight_str << "\"\n"; } } return -1; } pregen_node_t node_from_json(cJSON* json_node) { pregen_node_t node; node.name = std::string(CJSON_STR(json_node, Name)); cJSON* cur_child = json_node->child; while(cur_child) { if(str_eq(cur_child->string, "Properties")) { cJSON* property_json = cur_child->child; while(property_json) { node.add_child(node_from_json(property_json)); property_json = property_json->next; } } else if(str_eq(cur_child->string, "Values")) { cJSON* value_json = cur_child->child; while(value_json) { // if the value is a node, load it differently // since we can't return a node as part of the variant //if the value is an object starting with a child named "Name", it's a node if(value_json->type == cJSON_Object && value_json->child && str_eq(value_json->child->string, "Name")) { node.value_nodes.push_back(std::move(node_from_json(value_json))); } else { node.values.push_back(std::move(value_type_from_json(value_json))); } value_json = value_json->next; } } else if(str_eq(cur_child->string, "Include")) { ASSERT(cur_child->type == cJSON_String, "Include filepath must be a string"); stdfs::path relpath(cur_child->valuestring); auto parent_path = include_dir_stack.top().parent_path(); stdfs::path fullpath = parent_path / relpath; try{ auto included_node = node_from_json(fullpath); if(included_node.name == node.name) { node.merge_with(std::move(included_node)); } else { node.add_child(std::move(included_node)); } } catch(file_not_found_exception const&) { throw include_exception{include_dir_stack.top(), fullpath}; } } else if(str_eq(cur_child->string, "Weight")) { switch(cur_child->type) { case cJSON_Number: node.weight = cur_child->valueint; break; case cJSON_String: { int weight = weight_from_string(std::string(cur_child->valuestring)); if(weight >= 0) node.weight = weight; else std::cout << "Invalid Weight Specifier for \"" << node.name << "\"\n"; break; } default: throw json_type_exception(include_dir_stack.top(), cur_child, cur_child->type); } } else { // LOG("Unrecognized tag '%s' in node '%s'", cur_child->string, json_node->string); } cur_child = cur_child->next; } return node; } pregen_node_t node_from_json(stdfs::path const& filepath) { if(!stdfs::is_regular_file(filepath)) throw file_not_found_exception{filepath}; auto canonical_path = stdfs::canonical(filepath); auto cached_node_entry = include_cache.find(canonical_path); if(cached_node_entry != include_cache.end()) { return cached_node_entry->second; } else { //std::string json_str = asdf::util::read_text_file(filepath); std::string json_str = tired_of_build_issues::read_text_file(canonical_path.string()); cJSON* json_root = cJSON_Parse(json_str.c_str()); if(!json_root) { throw json_parse_exception(filepath, cJSON_GetErrorPtr()); } include_dir_stack.push(canonical_path); auto node = node_from_json(json_root); cJSON_Delete(json_root); include_dir_stack.pop(); include_cache.insert({canonical_path, node}); return node; } } generated_node_t generate_node_from_json(stdfs::path const& filepath) { auto node = node_from_json(filepath); return generate_node(node); } }<|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/_assert.h> #include <bm/bm_sim/logger.h> #include <bm/bm_sim/options_parse.h> #include <bm/PI/pi.h> #include <PI/frontends/proto/device_mgr.h> #include <PI/frontends/proto/logging.h> #include <PI/proto/pi_server.h> #include <PI/pi.h> #include <PI/target/pi_imp.h> #include <grpc++/grpc++.h> #include <p4/bm/dataplane_interface.grpc.pb.h> #include <map> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include "simple_switch.h" #include "switch_runner.h" #ifdef WITH_SYSREPO #include "switch_sysrepo.h" #endif // WITH_SYSREPO #ifdef WITH_THRIFT #include <bm/SimpleSwitch.h> #include <bm/bm_runtime/bm_runtime.h> namespace sswitch_runtime { shared_ptr<SimpleSwitchIf> get_handler(SimpleSwitch *sw); } // namespace sswitch_runtime #endif // WITH_THRIFT namespace sswitch_grpc { using pi::fe::proto::DeviceMgr; namespace { using grpc::ServerContext; using grpc::Status; using grpc::StatusCode; using ServerReaderWriter = grpc::ServerReaderWriter< p4::bm::PacketStreamResponse, p4::bm::PacketStreamRequest>; class DataplaneInterfaceServiceImpl : public p4::bm::DataplaneInterface::Service, public bm::DevMgrIface { public: explicit DataplaneInterfaceServiceImpl(bm::device_id_t device_id) : device_id(device_id) { p_monitor = bm::PortMonitorIface::make_passive(device_id); } private: using Lock = std::lock_guard<std::mutex>; Status PacketStream(ServerContext *context, ServerReaderWriter *stream) override { { Lock lock(mutex); if (!started) return Status(StatusCode::UNAVAILABLE, "not ready"); if (active) { return Status(StatusCode::RESOURCE_EXHAUSTED, "only one client authorized at a time"); } active = true; this->context = context; this->stream = stream; } p4::bm::PacketStreamRequest request; while (this->stream->Read(&request)) { if (request.device_id() != device_id) { continue; } const auto &packet = request.packet(); if (packet.empty()) continue; if (!pkt_handler) continue; pkt_handler(request.port(), packet.data(), packet.size(), pkt_cookie); } auto &runner = sswitch_grpc::SimpleSwitchGrpcRunner::get_instance(); runner.block_until_all_packets_processed(); Lock lock(mutex); active = false; return Status::OK; } Status SetPortOperStatus( ServerContext *context, const p4::bm::SetPortOperStatusRequest *request, p4::bm::SetPortOperStatusResponse *response) override { (void) context; (void) response; Lock lock(mutex); if (request->device_id() != device_id) return Status(StatusCode::INVALID_ARGUMENT, "Invalid device id"); if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_DOWN) ports_oper_status[request->port()] = false; else if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_UP) ports_oper_status[request->port()] = true; else return Status(StatusCode::INVALID_ARGUMENT, "Invalid oper status"); return Status::OK; } ReturnCode port_add_(const std::string &iface_name, port_t port_num, const PortExtras &port_extras) override { _BM_UNUSED(iface_name); _BM_UNUSED(port_num); _BM_UNUSED(port_extras); return ReturnCode::SUCCESS; } ReturnCode port_remove_(port_t port_num) override { _BM_UNUSED(port_num); return ReturnCode::SUCCESS; } void transmit_fn_(int port_num, const char *buffer, int len) override { p4::bm::PacketStreamResponse response; response.set_device_id(device_id); response.set_port(port_num); response.set_packet(buffer, len); Lock lock(mutex); if (active) stream->Write(response); } void start_() override { Lock lock(mutex); started = true; } ReturnCode set_packet_handler_(const PacketHandler &handler, void *cookie) override { pkt_handler = handler; pkt_cookie = cookie; return ReturnCode::SUCCESS; } bool port_is_up_(port_t port) const override { Lock lock(mutex); auto status_it = ports_oper_status.find(port); return (status_it == ports_oper_status.end()) ? true : status_it->second; } std::map<port_t, PortInfo> get_port_info_() const override { return {}; } bm::device_id_t device_id; // protects the shared state (active) and prevents concurrent Write calls by // different threads mutable std::mutex mutex{}; bool started{false}; bool active{false}; ServerContext *context{nullptr}; ServerReaderWriter *stream{nullptr}; PacketHandler pkt_handler{}; void *pkt_cookie{nullptr}; std::unordered_map<port_t, bool> ports_oper_status{}; }; } // namespace SimpleSwitchGrpcRunner::SimpleSwitchGrpcRunner(int max_port, bool enable_swap, std::string grpc_server_addr, int cpu_port, std::string dp_grpc_server_addr) : simple_switch(new SimpleSwitch(max_port, enable_swap)), grpc_server_addr(grpc_server_addr), cpu_port(cpu_port), dp_grpc_server_addr(dp_grpc_server_addr), dp_grpc_server(nullptr) { DeviceMgr::init(256); } int SimpleSwitchGrpcRunner::init_and_start(const bm::OptionsParser &parser) { std::unique_ptr<bm::DevMgrIface> my_dev_mgr = nullptr; if (!dp_grpc_server_addr.empty()) { auto service = new DataplaneInterfaceServiceImpl(parser.device_id); grpc::ServerBuilder builder; builder.SetSyncServerOption( grpc::ServerBuilder::SyncServerOption::NUM_CQS, 1); builder.SetSyncServerOption( grpc::ServerBuilder::SyncServerOption::MIN_POLLERS, 1); builder.SetSyncServerOption( grpc::ServerBuilder::SyncServerOption::MAX_POLLERS, 1); builder.AddListeningPort(dp_grpc_server_addr, grpc::InsecureServerCredentials(), &dp_grpc_server_port); builder.RegisterService(service); dp_grpc_server = builder.BuildAndStart(); my_dev_mgr.reset(service); } #ifdef WITH_SYSREPO sysrepo_driver = std::unique_ptr<SysrepoDriver>(new SysrepoDriver( parser.device_id, simple_switch.get())); #endif // WITH_SYSREPO // Even when using gNMI to manage ports, it is convenient to be able to use // the --interface / -i command-line option. However we have to "intercept" // the options before the call to DevMgr::port_add, otherwise we would try to // add the ports twice (once when calling Switch::init_from_options_parser and // once when we are notified by sysrepo of the YANG datastore change). // We therefore save the interface list provided on the command-line and we // call SysrepoDriver::add_iface at the end of this method after we start the // sysrepo subscriber. const bm::OptionsParser *parser_ptr; #ifdef WITH_SYSREPO auto new_parser = parser; auto &interfaces = new_parser.ifaces; auto saved_interfaces = interfaces; interfaces.clear(); parser_ptr = &new_parser; #else parser_ptr = &parser; #endif // WITH_SYSREPO int status = simple_switch->init_from_options_parser( *parser_ptr, nullptr, std::move(my_dev_mgr)); if (status != 0) return status; // PortMonitor saves the CB by reference so we cannot use this code; it seems // that at this stage we do not need the CB any way. // using PortStatus = bm::DevMgrIface::PortStatus; // auto port_cb = std::bind(&SimpleSwitchGrpcRunner::port_status_cb, this, // std::placeholders::_1, std::placeholders::_2); // simple_switch->register_status_cb(PortStatus::PORT_ADDED, port_cb); // simple_switch->register_status_cb(PortStatus::PORT_REMOVED, port_cb); // check if CPU port number is also used by --interface // TODO(antonin): ports added dynamically? if (cpu_port >= 0) { if (parser.ifaces.find(cpu_port) != parser.ifaces.end()) { bm::Logger::get()->error("Cpu port {} is used as a data port", cpu_port); return 1; } } if (cpu_port >= 0) { auto transmit_fn = [this](int port_num, const char *buf, int len) { if (port_num == cpu_port) { BMLOG_DEBUG("Transmitting packet-in"); auto status = pi_packetin_receive( simple_switch->get_device_id(), buf, static_cast<size_t>(len)); if (status != PI_STATUS_SUCCESS) bm::Logger::get()->error("Error when transmitting packet-in"); } else { simple_switch->transmit_fn(port_num, buf, len); } }; simple_switch->set_transmit_fn(transmit_fn); } bm::pi::register_switch(simple_switch.get(), cpu_port); { using pi::fe::proto::LogWriterIface; using pi::fe::proto::LoggerConfig; class P4RuntimeLogger : public LogWriterIface { void write(Severity severity, const char *msg) override { auto severity_map = [&severity]() { namespace spdL = spdlog::level; switch (severity) { case Severity::TRACE : return spdL::trace; case Severity::DEBUG: return spdL::debug; case Severity::INFO: return spdL::info; case Severity::WARN: return spdL::warn; case Severity::ERROR: return spdL::err; case Severity::CRITICAL: return spdL::critical; } return spdL::off; }; // TODO(antonin): use a separate logger with a separate name bm::Logger::get()->log(severity_map(), "[P4Runtime] {}", msg); } }; LoggerConfig::set_writer(std::make_shared<P4RuntimeLogger>()); } PIGrpcServerRunAddr(grpc_server_addr.c_str()); #ifdef WITH_SYSREPO if (!sysrepo_driver->start()) return 1; for (const auto &p : saved_interfaces) sysrepo_driver->add_iface(p.first, p.second); #endif // WITH_SYSREPO #ifdef WITH_THRIFT int thrift_port = simple_switch->get_runtime_port(); bm_runtime::start_server(simple_switch.get(), thrift_port); using ::sswitch_runtime::SimpleSwitchIf; using ::sswitch_runtime::SimpleSwitchProcessor; bm_runtime::add_service<SimpleSwitchIf, SimpleSwitchProcessor>( "simple_switch", sswitch_runtime::get_handler(simple_switch.get())); #endif // WITH_THRIFT simple_switch->start_and_return(); return 0; } void SimpleSwitchGrpcRunner::wait() { PIGrpcServerWait(); } void SimpleSwitchGrpcRunner::shutdown() { if (!dp_grpc_server_addr.empty()) dp_grpc_server->Shutdown(); PIGrpcServerShutdown(); } void SimpleSwitchGrpcRunner::mirroring_mapping_add(int mirror_id, int egress_port) { simple_switch->mirroring_mapping_add(mirror_id, egress_port); } void SimpleSwitchGrpcRunner::block_until_all_packets_processed() { simple_switch->block_until_no_more_packets(); } SimpleSwitchGrpcRunner::~SimpleSwitchGrpcRunner() { PIGrpcServerCleanup(); DeviceMgr::destroy(); } void SimpleSwitchGrpcRunner::port_status_cb( bm::DevMgrIface::port_t port, const bm::DevMgrIface::PortStatus status) { _BM_UNUSED(port); _BM_UNUSED(status); } } // namespace sswitch_grpc <commit_msg>Minor style fix. Made parameter names in declaration and definition c… (#547)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas (antonin@barefootnetworks.com) * */ #include <bm/bm_sim/_assert.h> #include <bm/bm_sim/logger.h> #include <bm/bm_sim/options_parse.h> #include <bm/PI/pi.h> #include <PI/frontends/proto/device_mgr.h> #include <PI/frontends/proto/logging.h> #include <PI/proto/pi_server.h> #include <PI/pi.h> #include <PI/target/pi_imp.h> #include <grpc++/grpc++.h> #include <p4/bm/dataplane_interface.grpc.pb.h> #include <map> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include "simple_switch.h" #include "switch_runner.h" #ifdef WITH_SYSREPO #include "switch_sysrepo.h" #endif // WITH_SYSREPO #ifdef WITH_THRIFT #include <bm/SimpleSwitch.h> #include <bm/bm_runtime/bm_runtime.h> namespace sswitch_runtime { shared_ptr<SimpleSwitchIf> get_handler(SimpleSwitch *sw); } // namespace sswitch_runtime #endif // WITH_THRIFT namespace sswitch_grpc { using pi::fe::proto::DeviceMgr; namespace { using grpc::ServerContext; using grpc::Status; using grpc::StatusCode; using ServerReaderWriter = grpc::ServerReaderWriter< p4::bm::PacketStreamResponse, p4::bm::PacketStreamRequest>; class DataplaneInterfaceServiceImpl : public p4::bm::DataplaneInterface::Service, public bm::DevMgrIface { public: explicit DataplaneInterfaceServiceImpl(bm::device_id_t device_id) : device_id(device_id) { p_monitor = bm::PortMonitorIface::make_passive(device_id); } private: using Lock = std::lock_guard<std::mutex>; Status PacketStream(ServerContext *context, ServerReaderWriter *stream) override { { Lock lock(mutex); if (!started) return Status(StatusCode::UNAVAILABLE, "not ready"); if (active) { return Status(StatusCode::RESOURCE_EXHAUSTED, "only one client authorized at a time"); } active = true; this->context = context; this->stream = stream; } p4::bm::PacketStreamRequest request; while (this->stream->Read(&request)) { if (request.device_id() != device_id) { continue; } const auto &packet = request.packet(); if (packet.empty()) continue; if (!pkt_handler) continue; pkt_handler(request.port(), packet.data(), packet.size(), pkt_cookie); } auto &runner = sswitch_grpc::SimpleSwitchGrpcRunner::get_instance(); runner.block_until_all_packets_processed(); Lock lock(mutex); active = false; return Status::OK; } Status SetPortOperStatus( ServerContext *context, const p4::bm::SetPortOperStatusRequest *request, p4::bm::SetPortOperStatusResponse *response) override { (void) context; (void) response; Lock lock(mutex); if (request->device_id() != device_id) return Status(StatusCode::INVALID_ARGUMENT, "Invalid device id"); if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_DOWN) ports_oper_status[request->port()] = false; else if (request->oper_status() == p4::bm::PortOperStatus::OPER_STATUS_UP) ports_oper_status[request->port()] = true; else return Status(StatusCode::INVALID_ARGUMENT, "Invalid oper status"); return Status::OK; } ReturnCode port_add_(const std::string &iface_name, port_t port_num, const PortExtras &port_extras) override { _BM_UNUSED(iface_name); _BM_UNUSED(port_num); _BM_UNUSED(port_extras); return ReturnCode::SUCCESS; } ReturnCode port_remove_(port_t port_num) override { _BM_UNUSED(port_num); return ReturnCode::SUCCESS; } void transmit_fn_(int port_num, const char *buffer, int len) override { p4::bm::PacketStreamResponse response; response.set_device_id(device_id); response.set_port(port_num); response.set_packet(buffer, len); Lock lock(mutex); if (active) stream->Write(response); } void start_() override { Lock lock(mutex); started = true; } ReturnCode set_packet_handler_(const PacketHandler &handler, void *cookie) override { pkt_handler = handler; pkt_cookie = cookie; return ReturnCode::SUCCESS; } bool port_is_up_(port_t port) const override { Lock lock(mutex); auto status_it = ports_oper_status.find(port); return (status_it == ports_oper_status.end()) ? true : status_it->second; } std::map<port_t, PortInfo> get_port_info_() const override { return {}; } bm::device_id_t device_id; // protects the shared state (active) and prevents concurrent Write calls by // different threads mutable std::mutex mutex{}; bool started{false}; bool active{false}; ServerContext *context{nullptr}; ServerReaderWriter *stream{nullptr}; PacketHandler pkt_handler{}; void *pkt_cookie{nullptr}; std::unordered_map<port_t, bool> ports_oper_status{}; }; } // namespace SimpleSwitchGrpcRunner::SimpleSwitchGrpcRunner(int max_port, bool enable_swap, std::string grpc_server_addr, int cpu_port, std::string dp_grpc_server_addr) : simple_switch(new SimpleSwitch(max_port, enable_swap)), grpc_server_addr(grpc_server_addr), cpu_port(cpu_port), dp_grpc_server_addr(dp_grpc_server_addr), dp_grpc_server(nullptr) { DeviceMgr::init(256); } int SimpleSwitchGrpcRunner::init_and_start(const bm::OptionsParser &parser) { std::unique_ptr<bm::DevMgrIface> my_dev_mgr = nullptr; if (!dp_grpc_server_addr.empty()) { auto service = new DataplaneInterfaceServiceImpl(parser.device_id); grpc::ServerBuilder builder; builder.SetSyncServerOption( grpc::ServerBuilder::SyncServerOption::NUM_CQS, 1); builder.SetSyncServerOption( grpc::ServerBuilder::SyncServerOption::MIN_POLLERS, 1); builder.SetSyncServerOption( grpc::ServerBuilder::SyncServerOption::MAX_POLLERS, 1); builder.AddListeningPort(dp_grpc_server_addr, grpc::InsecureServerCredentials(), &dp_grpc_server_port); builder.RegisterService(service); dp_grpc_server = builder.BuildAndStart(); my_dev_mgr.reset(service); } #ifdef WITH_SYSREPO sysrepo_driver = std::unique_ptr<SysrepoDriver>(new SysrepoDriver( parser.device_id, simple_switch.get())); #endif // WITH_SYSREPO // Even when using gNMI to manage ports, it is convenient to be able to use // the --interface / -i command-line option. However we have to "intercept" // the options before the call to DevMgr::port_add, otherwise we would try to // add the ports twice (once when calling Switch::init_from_options_parser and // once when we are notified by sysrepo of the YANG datastore change). // We therefore save the interface list provided on the command-line and we // call SysrepoDriver::add_iface at the end of this method after we start the // sysrepo subscriber. const bm::OptionsParser *parser_ptr; #ifdef WITH_SYSREPO auto new_parser = parser; auto &interfaces = new_parser.ifaces; auto saved_interfaces = interfaces; interfaces.clear(); parser_ptr = &new_parser; #else parser_ptr = &parser; #endif // WITH_SYSREPO int status = simple_switch->init_from_options_parser( *parser_ptr, nullptr, std::move(my_dev_mgr)); if (status != 0) return status; // PortMonitor saves the CB by reference so we cannot use this code; it seems // that at this stage we do not need the CB any way. // using PortStatus = bm::DevMgrIface::PortStatus; // auto port_cb = std::bind(&SimpleSwitchGrpcRunner::port_status_cb, this, // std::placeholders::_1, std::placeholders::_2); // simple_switch->register_status_cb(PortStatus::PORT_ADDED, port_cb); // simple_switch->register_status_cb(PortStatus::PORT_REMOVED, port_cb); // check if CPU port number is also used by --interface // TODO(antonin): ports added dynamically? if (cpu_port >= 0) { if (parser.ifaces.find(cpu_port) != parser.ifaces.end()) { bm::Logger::get()->error("Cpu port {} is used as a data port", cpu_port); return 1; } } if (cpu_port >= 0) { auto transmit_fn = [this](int port_num, const char *buf, int len) { if (port_num == cpu_port) { BMLOG_DEBUG("Transmitting packet-in"); auto status = pi_packetin_receive( simple_switch->get_device_id(), buf, static_cast<size_t>(len)); if (status != PI_STATUS_SUCCESS) bm::Logger::get()->error("Error when transmitting packet-in"); } else { simple_switch->transmit_fn(port_num, buf, len); } }; simple_switch->set_transmit_fn(transmit_fn); } bm::pi::register_switch(simple_switch.get(), cpu_port); { using pi::fe::proto::LogWriterIface; using pi::fe::proto::LoggerConfig; class P4RuntimeLogger : public LogWriterIface { void write(Severity severity, const char *msg) override { auto severity_map = [&severity]() { namespace spdL = spdlog::level; switch (severity) { case Severity::TRACE : return spdL::trace; case Severity::DEBUG: return spdL::debug; case Severity::INFO: return spdL::info; case Severity::WARN: return spdL::warn; case Severity::ERROR: return spdL::err; case Severity::CRITICAL: return spdL::critical; } return spdL::off; }; // TODO(antonin): use a separate logger with a separate name bm::Logger::get()->log(severity_map(), "[P4Runtime] {}", msg); } }; LoggerConfig::set_writer(std::make_shared<P4RuntimeLogger>()); } PIGrpcServerRunAddr(grpc_server_addr.c_str()); #ifdef WITH_SYSREPO if (!sysrepo_driver->start()) return 1; for (const auto &p : saved_interfaces) sysrepo_driver->add_iface(p.first, p.second); #endif // WITH_SYSREPO #ifdef WITH_THRIFT int thrift_port = simple_switch->get_runtime_port(); bm_runtime::start_server(simple_switch.get(), thrift_port); using ::sswitch_runtime::SimpleSwitchIf; using ::sswitch_runtime::SimpleSwitchProcessor; bm_runtime::add_service<SimpleSwitchIf, SimpleSwitchProcessor>( "simple_switch", sswitch_runtime::get_handler(simple_switch.get())); #endif // WITH_THRIFT simple_switch->start_and_return(); return 0; } void SimpleSwitchGrpcRunner::wait() { PIGrpcServerWait(); } void SimpleSwitchGrpcRunner::shutdown() { if (!dp_grpc_server_addr.empty()) dp_grpc_server->Shutdown(); PIGrpcServerShutdown(); } void SimpleSwitchGrpcRunner::mirroring_mapping_add(int mirror_id, int egress_port) { simple_switch->mirroring_mapping_add(mirror_id, egress_port); } void SimpleSwitchGrpcRunner::block_until_all_packets_processed() { simple_switch->block_until_no_more_packets(); } SimpleSwitchGrpcRunner::~SimpleSwitchGrpcRunner() { PIGrpcServerCleanup(); DeviceMgr::destroy(); } void SimpleSwitchGrpcRunner::port_status_cb(bm::DevMgrIface::port_t port, const bm::DevMgrIface::PortStatus port_status) { _BM_UNUSED(port); _BM_UNUSED(port_status); } } // namespace sswitch_grpc <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <assert.h> #include <memcached/engine.h> #include "ep_engine.h" /** * Helper function to avoid typing in the long cast all over the place * @param handle pointer to the engine * @return the engine as a class */ static inline EventuallyPersistentEngine* getHandle(ENGINE_HANDLE* handle) { return reinterpret_cast<EventuallyPersistentEngine*>(handle); } // The Engine API specifies C linkage for the functions.. extern "C" { static const char* EvpGetInfo(ENGINE_HANDLE* handle) { (void)handle; return "EP engine v0.1"; } static ENGINE_ERROR_CODE EvpInitialize(ENGINE_HANDLE* handle, const char* config_str) { return getHandle(handle)->initialize(config_str); } static void EvpDestroy(ENGINE_HANDLE* handle) { getHandle(handle)->destroy(); } static ENGINE_ERROR_CODE EvpItemAllocate(ENGINE_HANDLE* handle, const void* cookie, item **item, const void* key, const size_t nkey, const size_t nbytes, const int flags, const rel_time_t exptime) { return getHandle(handle)->itemAllocate(cookie, item, key, nkey, nbytes, flags, exptime); } static ENGINE_ERROR_CODE EvpItemDelete(ENGINE_HANDLE* handle, const void* cookie, item* item) { return getHandle(handle)->itemDelete(cookie, item); } static void EvpItemRelease(ENGINE_HANDLE* handle, const void *cookie, item* item) { getHandle(handle)->itemRelease(cookie, item); } static ENGINE_ERROR_CODE EvpGet(ENGINE_HANDLE* handle, const void* cookie, item** item, const void* key, const int nkey) { return getHandle(handle)->get(cookie, item, key, nkey); } static ENGINE_ERROR_CODE EvpGetStats(ENGINE_HANDLE* handle, const void* cookie, const char* stat_key, int nkey, ADD_STAT add_stat) { return getHandle(handle)->getStats(cookie, stat_key, nkey, add_stat); } static ENGINE_ERROR_CODE EvpStore(ENGINE_HANDLE* handle, const void *cookie, item* item, uint64_t *cas, ENGINE_STORE_OPERATION operation) { return getHandle(handle)->store(cookie, item, cas, operation); } static ENGINE_ERROR_CODE EvpArithmetic(ENGINE_HANDLE* handle, const void* cookie, const void* key, const int nkey, const bool increment, const bool create, const uint64_t delta, const uint64_t initial, const rel_time_t exptime, uint64_t *cas, uint64_t *result) { (void)handle; (void)cookie; (void)key; (void)nkey; (void)increment; (void)create; (void)delta; (void)initial; (void)exptime; (void)cas; (void)result; return ENGINE_ENOTSUP; } static ENGINE_ERROR_CODE EvpFlush(ENGINE_HANDLE* handle, const void* cookie, time_t when) { return getHandle(handle)->flush(cookie, when); } static void EvpResetStats(ENGINE_HANDLE* handle, const void *cookie) { (void)cookie; return getHandle(handle)->resetStats(); } static protocol_binary_response_status stopFlusher(EventuallyPersistentEngine *e, const char **msg) { return e->stopFlusher(msg); } static protocol_binary_response_status startFlusher(EventuallyPersistentEngine *e, const char **msg) { return e->startFlusher(msg); } static ENGINE_ERROR_CODE EvpUnknownCommand(ENGINE_HANDLE* handle, const void* cookie, protocol_binary_request_header *request, ADD_RESPONSE response) { (void)handle; (void)cookie; (void)request; bool handled = true; protocol_binary_response_status res = PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND; const char *msg; EventuallyPersistentEngine *h = getHandle(handle); switch (request->request.opcode) { case CMD_STOP_PERSISTENCE: res = stopFlusher(h, &msg); break; case CMD_START_PERSISTENCE: res = startFlusher(h, &msg); break; default: /* unknown command */ handled = false; break; } if (handled) { size_t msg_size = msg ? strlen(msg) : 0; response(msg, static_cast<uint16_t>(msg_size), NULL, 0, NULL, 0, PROTOCOL_BINARY_RAW_BYTES, static_cast<uint16_t>(res), 0, cookie); } else { response(NULL, 0, NULL, 0, NULL, 0, PROTOCOL_BINARY_RAW_BYTES, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, 0, cookie); } return ENGINE_SUCCESS; } static uint64_t EvpItemGetCas(const item *item) { (void)item; return 0; } static void EvpItemSetCas(item *item, uint64_t cas) { (void)item; (void)cas; // empty } static const char *EvpItemGetKey(const item *it) { return static_cast<const Item*>(it)->key.c_str(); } static char *EvpItemGetData(const item *it) { return static_cast<const Item*>(it)->data; } static uint8_t EvpItemGetClsid(const item *item) { (void)item; return 0; } struct observer_walker_item EvpTapWalker(ENGINE_HANDLE* handle, const void *cookie) { return getHandle(handle)->walkTapQueue(cookie); } TAP_WALKER EvpGetTapWalker(ENGINE_HANDLE* handle, const void* cookie) { getHandle(handle)->createTapQueue(cookie); return EvpTapWalker; } /** * The only public interface to the eventually persistance engine. * Allocate a new instance and initialize it * @param interface the highest interface the server supports (we only support * interface 1) * @param get_server_api callback function to get the server exported API * functions * @param handle Where to return the new instance * @return ENGINE_SUCCESS on success */ ENGINE_ERROR_CODE create_instance(uint64_t interface, GET_SERVER_API get_server_api, ENGINE_HANDLE **handle) { SERVER_HANDLE_V1 *api; api = static_cast<SERVER_HANDLE_V1 *>(get_server_api(1)); if (interface != 1 || api == NULL) { return ENGINE_ENOTSUP; } EventuallyPersistentEngine *engine; engine = new struct EventuallyPersistentEngine(api); if (engine == NULL) { return ENGINE_ENOMEM; } ep_current_time = api->get_current_time; *handle = reinterpret_cast<ENGINE_HANDLE*> (engine); return ENGINE_SUCCESS; } void *loadDataseThread(void*arg) { EventuallyPersistentEngine::loadDatabase(static_cast<EventuallyPersistentEngine*>(arg)); return NULL; } } // C linkage EventuallyPersistentEngine::EventuallyPersistentEngine(SERVER_HANDLE_V1 *sApi) : dbname("/tmp/test.db"), warmup(true), warmupComplete(false), sqliteDb(NULL), epstore(NULL) { interface.interface = 1; ENGINE_HANDLE_V1::get_info = EvpGetInfo; ENGINE_HANDLE_V1::initialize = EvpInitialize; ENGINE_HANDLE_V1::destroy = EvpDestroy; ENGINE_HANDLE_V1::allocate = EvpItemAllocate; ENGINE_HANDLE_V1::remove = EvpItemDelete; ENGINE_HANDLE_V1::release = EvpItemRelease; ENGINE_HANDLE_V1::get = EvpGet; ENGINE_HANDLE_V1::get_stats = EvpGetStats; ENGINE_HANDLE_V1::reset_stats = EvpResetStats; ENGINE_HANDLE_V1::store = EvpStore; ENGINE_HANDLE_V1::arithmetic = EvpArithmetic; ENGINE_HANDLE_V1::flush = EvpFlush; ENGINE_HANDLE_V1::unknown_command = EvpUnknownCommand; ENGINE_HANDLE_V1::get_tap_walker = EvpGetTapWalker; ENGINE_HANDLE_V1::item_get_cas = EvpItemGetCas; ENGINE_HANDLE_V1::item_set_cas = EvpItemSetCas; ENGINE_HANDLE_V1::item_get_key = EvpItemGetKey; ENGINE_HANDLE_V1::item_get_data = EvpItemGetData; ENGINE_HANDLE_V1::item_get_clsid = EvpItemGetClsid; serverApi = *sApi; } void EventuallyPersistentEngine::loadDatabase(void) { pthread_t tid; if (pthread_create(&tid, NULL, loadDataseThread, this) != 0) { throw std::runtime_error("Error creating thread to load database"); } pthread_detach(tid); } <commit_msg>Initialize get_stats_struct<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <assert.h> #include <memcached/engine.h> #include "ep_engine.h" /** * Helper function to avoid typing in the long cast all over the place * @param handle pointer to the engine * @return the engine as a class */ static inline EventuallyPersistentEngine* getHandle(ENGINE_HANDLE* handle) { return reinterpret_cast<EventuallyPersistentEngine*>(handle); } // The Engine API specifies C linkage for the functions.. extern "C" { static const char* EvpGetInfo(ENGINE_HANDLE* handle) { (void)handle; return "EP engine v0.1"; } static ENGINE_ERROR_CODE EvpInitialize(ENGINE_HANDLE* handle, const char* config_str) { return getHandle(handle)->initialize(config_str); } static void EvpDestroy(ENGINE_HANDLE* handle) { getHandle(handle)->destroy(); } static ENGINE_ERROR_CODE EvpItemAllocate(ENGINE_HANDLE* handle, const void* cookie, item **item, const void* key, const size_t nkey, const size_t nbytes, const int flags, const rel_time_t exptime) { return getHandle(handle)->itemAllocate(cookie, item, key, nkey, nbytes, flags, exptime); } static ENGINE_ERROR_CODE EvpItemDelete(ENGINE_HANDLE* handle, const void* cookie, item* item) { return getHandle(handle)->itemDelete(cookie, item); } static void EvpItemRelease(ENGINE_HANDLE* handle, const void *cookie, item* item) { getHandle(handle)->itemRelease(cookie, item); } static ENGINE_ERROR_CODE EvpGet(ENGINE_HANDLE* handle, const void* cookie, item** item, const void* key, const int nkey) { return getHandle(handle)->get(cookie, item, key, nkey); } static ENGINE_ERROR_CODE EvpGetStats(ENGINE_HANDLE* handle, const void* cookie, const char* stat_key, int nkey, ADD_STAT add_stat) { return getHandle(handle)->getStats(cookie, stat_key, nkey, add_stat); } static ENGINE_ERROR_CODE EvpStore(ENGINE_HANDLE* handle, const void *cookie, item* item, uint64_t *cas, ENGINE_STORE_OPERATION operation) { return getHandle(handle)->store(cookie, item, cas, operation); } static ENGINE_ERROR_CODE EvpArithmetic(ENGINE_HANDLE* handle, const void* cookie, const void* key, const int nkey, const bool increment, const bool create, const uint64_t delta, const uint64_t initial, const rel_time_t exptime, uint64_t *cas, uint64_t *result) { (void)handle; (void)cookie; (void)key; (void)nkey; (void)increment; (void)create; (void)delta; (void)initial; (void)exptime; (void)cas; (void)result; return ENGINE_ENOTSUP; } static ENGINE_ERROR_CODE EvpFlush(ENGINE_HANDLE* handle, const void* cookie, time_t when) { return getHandle(handle)->flush(cookie, when); } static void EvpResetStats(ENGINE_HANDLE* handle, const void *cookie) { (void)cookie; return getHandle(handle)->resetStats(); } static protocol_binary_response_status stopFlusher(EventuallyPersistentEngine *e, const char **msg) { return e->stopFlusher(msg); } static protocol_binary_response_status startFlusher(EventuallyPersistentEngine *e, const char **msg) { return e->startFlusher(msg); } static ENGINE_ERROR_CODE EvpUnknownCommand(ENGINE_HANDLE* handle, const void* cookie, protocol_binary_request_header *request, ADD_RESPONSE response) { (void)handle; (void)cookie; (void)request; bool handled = true; protocol_binary_response_status res = PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND; const char *msg; EventuallyPersistentEngine *h = getHandle(handle); switch (request->request.opcode) { case CMD_STOP_PERSISTENCE: res = stopFlusher(h, &msg); break; case CMD_START_PERSISTENCE: res = startFlusher(h, &msg); break; default: /* unknown command */ handled = false; break; } if (handled) { size_t msg_size = msg ? strlen(msg) : 0; response(msg, static_cast<uint16_t>(msg_size), NULL, 0, NULL, 0, PROTOCOL_BINARY_RAW_BYTES, static_cast<uint16_t>(res), 0, cookie); } else { response(NULL, 0, NULL, 0, NULL, 0, PROTOCOL_BINARY_RAW_BYTES, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, 0, cookie); } return ENGINE_SUCCESS; } static uint64_t EvpItemGetCas(const item *item) { (void)item; return 0; } static void EvpItemSetCas(item *item, uint64_t cas) { (void)item; (void)cas; // empty } static const char *EvpItemGetKey(const item *it) { return static_cast<const Item*>(it)->key.c_str(); } static char *EvpItemGetData(const item *it) { return static_cast<const Item*>(it)->data; } static uint8_t EvpItemGetClsid(const item *item) { (void)item; return 0; } struct observer_walker_item EvpTapWalker(ENGINE_HANDLE* handle, const void *cookie) { return getHandle(handle)->walkTapQueue(cookie); } TAP_WALKER EvpGetTapWalker(ENGINE_HANDLE* handle, const void* cookie) { getHandle(handle)->createTapQueue(cookie); return EvpTapWalker; } /** * The only public interface to the eventually persistance engine. * Allocate a new instance and initialize it * @param interface the highest interface the server supports (we only support * interface 1) * @param get_server_api callback function to get the server exported API * functions * @param handle Where to return the new instance * @return ENGINE_SUCCESS on success */ ENGINE_ERROR_CODE create_instance(uint64_t interface, GET_SERVER_API get_server_api, ENGINE_HANDLE **handle) { SERVER_HANDLE_V1 *api; api = static_cast<SERVER_HANDLE_V1 *>(get_server_api(1)); if (interface != 1 || api == NULL) { return ENGINE_ENOTSUP; } EventuallyPersistentEngine *engine; engine = new struct EventuallyPersistentEngine(api); if (engine == NULL) { return ENGINE_ENOMEM; } ep_current_time = api->get_current_time; *handle = reinterpret_cast<ENGINE_HANDLE*> (engine); return ENGINE_SUCCESS; } void *loadDataseThread(void*arg) { EventuallyPersistentEngine::loadDatabase(static_cast<EventuallyPersistentEngine*>(arg)); return NULL; } } // C linkage EventuallyPersistentEngine::EventuallyPersistentEngine(SERVER_HANDLE_V1 *sApi) : dbname("/tmp/test.db"), warmup(true), warmupComplete(false), sqliteDb(NULL), epstore(NULL) { interface.interface = 1; ENGINE_HANDLE_V1::get_info = EvpGetInfo; ENGINE_HANDLE_V1::initialize = EvpInitialize; ENGINE_HANDLE_V1::destroy = EvpDestroy; ENGINE_HANDLE_V1::allocate = EvpItemAllocate; ENGINE_HANDLE_V1::remove = EvpItemDelete; ENGINE_HANDLE_V1::release = EvpItemRelease; ENGINE_HANDLE_V1::get = EvpGet; ENGINE_HANDLE_V1::get_stats = EvpGetStats; ENGINE_HANDLE_V1::reset_stats = EvpResetStats; ENGINE_HANDLE_V1::store = EvpStore; ENGINE_HANDLE_V1::arithmetic = EvpArithmetic; ENGINE_HANDLE_V1::flush = EvpFlush; ENGINE_HANDLE_V1::unknown_command = EvpUnknownCommand; ENGINE_HANDLE_V1::get_tap_walker = EvpGetTapWalker; ENGINE_HANDLE_V1::item_get_cas = EvpItemGetCas; ENGINE_HANDLE_V1::item_set_cas = EvpItemSetCas; ENGINE_HANDLE_V1::item_get_key = EvpItemGetKey; ENGINE_HANDLE_V1::item_get_data = EvpItemGetData; ENGINE_HANDLE_V1::item_get_clsid = EvpItemGetClsid; ENGINE_HANDLE_V1::get_stats_struct = NULL; serverApi = *sApi; } void EventuallyPersistentEngine::loadDatabase(void) { pthread_t tid; if (pthread_create(&tid, NULL, loadDataseThread, this) != 0) { throw std::runtime_error("Error creating thread to load database"); } pthread_detach(tid); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // INTERNAL USE ONLY: Do NOT use for any other purpose. // #include "qsoundeffect_qaudio_p.h" #include <QtCore/qcoreapplication.h> #include <QtCore/qthread.h> #include <QtCore/qmutex.h> #include <QtCore/qwaitcondition.h> #include <QtCore/qiodevice.h> //#include <QDebug> //#define QT_QAUDIO_DEBUG 1 QT_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSampleCache, sampleCache) QSoundEffectPrivate::QSoundEffectPrivate(QObject* parent): QObject(parent), d(new PrivateSoundSource(this)) { } QSoundEffectPrivate::~QSoundEffectPrivate() { } void QSoundEffectPrivate::release() { stop(); if (d->m_audioOutput) { d->m_audioOutput->stop(); d->m_audioOutput->deleteLater(); d->m_sample->release(); } delete d; this->deleteLater(); } QStringList QSoundEffectPrivate::supportedMimeTypes() { // Only return supported mime types if we have a audio device available const QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput); if (devices.size() <= 0) return QStringList(); return QStringList() << QLatin1String("audio/x-wav") << QLatin1String("audio/wav") << QLatin1String("audio/wave") << QLatin1String("audio/x-pn-wav"); } QUrl QSoundEffectPrivate::source() const { return d->m_url; } void QSoundEffectPrivate::setSource(const QUrl &url) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setSource current=" << d->m_url << ", to=" << url; #endif Q_ASSERT(d->m_url != url); stop(); d->m_url = url; d->m_sampleReady = false; if (url.isEmpty()) { setStatus(QSoundEffect::Null); return; } if (!url.isValid()) { setStatus(QSoundEffect::Error); return; } if (d->m_sample) { if (!d->m_sampleReady) { disconnect(d->m_sample, SIGNAL(error()), d, SLOT(decoderError())); disconnect(d->m_sample, SIGNAL(ready()), d, SLOT(sampleReady())); } d->m_sample->release(); d->m_sample = 0; } setStatus(QSoundEffect::Loading); d->m_sample = sampleCache()->requestSample(url); connect(d->m_sample, SIGNAL(error()), d, SLOT(decoderError())); connect(d->m_sample, SIGNAL(ready()), d, SLOT(sampleReady())); switch (d->m_sample->state()) { case QSample::Ready: d->sampleReady(); break; case QSample::Error: d->decoderError(); break; default: break; } } int QSoundEffectPrivate::loopCount() const { return d->m_loopCount; } int QSoundEffectPrivate::loopsRemaining() const { return d->m_runningCount; } void QSoundEffectPrivate::setLoopCount(int loopCount) { #ifdef QT_QAUDIO_DEBUG qDebug() << "setLoopCount " << loopCount; #endif if (loopCount == 0) loopCount = 1; d->m_loopCount = loopCount; d->m_runningCount = loopCount; } int QSoundEffectPrivate::volume() const { if (d->m_audioOutput && !d->m_muted) return d->m_audioOutput->volume()*100.0f; return d->m_volume; } void QSoundEffectPrivate::setVolume(int volume) { d->m_volume = volume; if (d->m_audioOutput && !d->m_muted) d->m_audioOutput->setVolume(volume/100.0f); emit volumeChanged(); } bool QSoundEffectPrivate::isMuted() const { return d->m_muted; } void QSoundEffectPrivate::setMuted(bool muted) { if (muted && d->m_audioOutput) d->m_audioOutput->setVolume(0); else if (!muted && d->m_audioOutput && d->m_muted) d->m_audioOutput->setVolume(d->m_volume/100.0f); d->m_muted = muted; emit mutedChanged(); } bool QSoundEffectPrivate::isLoaded() const { return d->m_status == QSoundEffect::Ready; } bool QSoundEffectPrivate::isPlaying() const { return d->m_playing; } QSoundEffect::Status QSoundEffectPrivate::status() const { return d->m_status; } void QSoundEffectPrivate::play() { d->m_offset = 0; d->m_runningCount = d->m_loopCount; #ifdef QT_QAUDIO_DEBUG qDebug() << this << "play"; #endif if (d->m_status == QSoundEffect::Null || d->m_status == QSoundEffect::Error) { setStatus(QSoundEffect::Null); return; } if (d->m_audioOutput && d->m_audioOutput->state() == QAudio::StoppedState && d->m_sampleReady) d->m_audioOutput->start(d); setPlaying(true); } void QSoundEffectPrivate::stop() { if (!d->m_playing) return; #ifdef QT_QAUDIO_DEBUG qDebug() << "stop()"; #endif d->m_offset = 0; setPlaying(false); if (d->m_audioOutput) d->m_audioOutput->stop(); } void QSoundEffectPrivate::setStatus(QSoundEffect::Status status) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setStatus" << status; #endif if (d->m_status == status) return; bool oldLoaded = isLoaded(); d->m_status = status; emit statusChanged(); if (oldLoaded != isLoaded()) emit loadedChanged(); } void QSoundEffectPrivate::setPlaying(bool playing) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setPlaying(" << playing << ")"; #endif if (d->m_playing == playing) return; d->m_playing = playing; emit playingChanged(); } void QSoundEffectPrivate::setLoopsRemaining(int loopsRemaining) { if (!d->m_runningCount && loopsRemaining) return; #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setLoopsRemaining " << loopsRemaining; #endif d->m_runningCount = loopsRemaining; emit loopsRemainingChanged(); } /* Categories are ignored */ QString QSoundEffectPrivate::category() const { return d->m_category; } void QSoundEffectPrivate::setCategory(const QString &category) { if (d->m_category != category && !d->m_playing) { d->m_category = category; emit categoryChanged(); } } PrivateSoundSource::PrivateSoundSource(QSoundEffectPrivate* s): m_loopCount(1), m_runningCount(0), m_playing(false), m_status(QSoundEffect::Null), m_audioOutput(0), m_sample(0), m_muted(false), m_volume(100), m_sampleReady(false), m_offset(0) { soundeffect = s; m_category = QLatin1String("game"); open(QIODevice::ReadOnly); } void PrivateSoundSource::sampleReady() { if (m_status == QSoundEffect::Error) return; #ifdef QT_QAUDIO_DEBUG qDebug() << this << "sampleReady "<<m_playing; #endif disconnect(m_sample, SIGNAL(error()), this, SLOT(decoderError())); disconnect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady())); if (!m_audioOutput) { m_audioOutput = new QAudioOutput(m_sample->format()); connect(m_audioOutput,SIGNAL(stateChanged(QAudio::State)), this, SLOT(stateChanged(QAudio::State))); if (!m_muted) m_audioOutput->setVolume(m_volume/100.0f); else m_audioOutput->setVolume(0); } m_sampleReady = true; soundeffect->setStatus(QSoundEffect::Ready); if (m_playing) m_audioOutput->start(this); } void PrivateSoundSource::decoderError() { qWarning("QSoundEffect(qaudio): Error decoding source"); disconnect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady())); disconnect(m_sample, SIGNAL(error()), this, SLOT(decoderError())); m_playing = false; soundeffect->setStatus(QSoundEffect::Error); } void PrivateSoundSource::stateChanged(QAudio::State state) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "stateChanged " << state; #endif if (state == QAudio::IdleState && m_runningCount == 0) emit soundeffect->stop(); } qint64 PrivateSoundSource::readData( char* data, qint64 len) { if (m_runningCount > 0 && m_playing) { if (m_sample->state() != QSample::Ready) return 0; qint64 bytesWritten = 0; const int periodSize = m_audioOutput->periodSize(); const int sampleSize = m_sample->data().size(); const char* sampleData = m_sample->data().constData(); // Some systems can have large buffers we only need a max of three int periodsFree = qMin(3, (int)(m_audioOutput->bytesFree()/periodSize)); int dataOffset = 0; #ifdef QT_QAUDIO_DEBUG qDebug() << "bytesFree=" << m_audioOutput->bytesFree() << ", can fit " << periodsFree << " periodSize() chunks"; #endif while ((periodsFree > 0) && (bytesWritten + periodSize <= len)) { if (sampleSize - m_offset >= periodSize) { // We can fit a whole period of data memcpy(data + dataOffset, sampleData + m_offset, periodSize); m_offset += periodSize; dataOffset += periodSize; bytesWritten += periodSize; #ifdef QT_QAUDIO_DEBUG qDebug() << "WHOLE PERIOD: bytesWritten=" << bytesWritten << ", offset=" << m_offset << ", filesize=" << sampleSize; #endif } else { // We are at end of sound, first write what is left of current sound memcpy(data + dataOffset, sampleData + m_offset, sampleSize - m_offset); bytesWritten += sampleSize - m_offset; int wrapLen = periodSize - (sampleSize - m_offset); #ifdef QT_QAUDIO_DEBUG qDebug() << "END OF SOUND: bytesWritten=" << bytesWritten << ", offset=" << m_offset << ", part1=" << (sampleSize-m_offset); #endif dataOffset += (sampleSize - m_offset); m_offset = 0; if (m_runningCount > 0 || m_runningCount == QSoundEffect::Infinite) { // There are still more loops of this sound to play, append the start of sound to make up full period memcpy(data + dataOffset, sampleData + m_offset, wrapLen); m_offset += wrapLen; dataOffset += wrapLen; bytesWritten += wrapLen; #ifdef QT_QAUDIO_DEBUG qDebug() << "APPEND START FOR FULL PERIOD: bytesWritten=" << bytesWritten << ", offset=" << m_offset << ", part2=" << wrapLen; qDebug() << "part1 + part2 should be a period " << periodSize; #endif if (m_runningCount != QSoundEffect::Infinite) soundeffect->setLoopsRemaining(m_runningCount-1); } } if (m_runningCount == 0) break; periodsFree--; } return bytesWritten; } return 0; } qint64 PrivateSoundSource::writeData(const char* data, qint64 len) { Q_UNUSED(data) Q_UNUSED(len) return 0; } QT_END_NAMESPACE #include "moc_qsoundeffect_qaudio_p.cpp" <commit_msg>Don't add the beginning of the file to the end of the last period<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // INTERNAL USE ONLY: Do NOT use for any other purpose. // #include "qsoundeffect_qaudio_p.h" #include <QtCore/qcoreapplication.h> #include <QtCore/qthread.h> #include <QtCore/qmutex.h> #include <QtCore/qwaitcondition.h> #include <QtCore/qiodevice.h> //#include <QDebug> //#define QT_QAUDIO_DEBUG 1 QT_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSampleCache, sampleCache) QSoundEffectPrivate::QSoundEffectPrivate(QObject* parent): QObject(parent), d(new PrivateSoundSource(this)) { } QSoundEffectPrivate::~QSoundEffectPrivate() { } void QSoundEffectPrivate::release() { stop(); if (d->m_audioOutput) { d->m_audioOutput->stop(); d->m_audioOutput->deleteLater(); d->m_sample->release(); } delete d; this->deleteLater(); } QStringList QSoundEffectPrivate::supportedMimeTypes() { // Only return supported mime types if we have a audio device available const QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput); if (devices.size() <= 0) return QStringList(); return QStringList() << QLatin1String("audio/x-wav") << QLatin1String("audio/wav") << QLatin1String("audio/wave") << QLatin1String("audio/x-pn-wav"); } QUrl QSoundEffectPrivate::source() const { return d->m_url; } void QSoundEffectPrivate::setSource(const QUrl &url) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setSource current=" << d->m_url << ", to=" << url; #endif Q_ASSERT(d->m_url != url); stop(); d->m_url = url; d->m_sampleReady = false; if (url.isEmpty()) { setStatus(QSoundEffect::Null); return; } if (!url.isValid()) { setStatus(QSoundEffect::Error); return; } if (d->m_sample) { if (!d->m_sampleReady) { disconnect(d->m_sample, SIGNAL(error()), d, SLOT(decoderError())); disconnect(d->m_sample, SIGNAL(ready()), d, SLOT(sampleReady())); } d->m_sample->release(); d->m_sample = 0; } setStatus(QSoundEffect::Loading); d->m_sample = sampleCache()->requestSample(url); connect(d->m_sample, SIGNAL(error()), d, SLOT(decoderError())); connect(d->m_sample, SIGNAL(ready()), d, SLOT(sampleReady())); switch (d->m_sample->state()) { case QSample::Ready: d->sampleReady(); break; case QSample::Error: d->decoderError(); break; default: break; } } int QSoundEffectPrivate::loopCount() const { return d->m_loopCount; } int QSoundEffectPrivate::loopsRemaining() const { return d->m_runningCount; } void QSoundEffectPrivate::setLoopCount(int loopCount) { #ifdef QT_QAUDIO_DEBUG qDebug() << "setLoopCount " << loopCount; #endif if (loopCount == 0) loopCount = 1; d->m_loopCount = loopCount; d->m_runningCount = loopCount; } int QSoundEffectPrivate::volume() const { if (d->m_audioOutput && !d->m_muted) return d->m_audioOutput->volume()*100.0f; return d->m_volume; } void QSoundEffectPrivate::setVolume(int volume) { d->m_volume = volume; if (d->m_audioOutput && !d->m_muted) d->m_audioOutput->setVolume(volume/100.0f); emit volumeChanged(); } bool QSoundEffectPrivate::isMuted() const { return d->m_muted; } void QSoundEffectPrivate::setMuted(bool muted) { if (muted && d->m_audioOutput) d->m_audioOutput->setVolume(0); else if (!muted && d->m_audioOutput && d->m_muted) d->m_audioOutput->setVolume(d->m_volume/100.0f); d->m_muted = muted; emit mutedChanged(); } bool QSoundEffectPrivate::isLoaded() const { return d->m_status == QSoundEffect::Ready; } bool QSoundEffectPrivate::isPlaying() const { return d->m_playing; } QSoundEffect::Status QSoundEffectPrivate::status() const { return d->m_status; } void QSoundEffectPrivate::play() { d->m_offset = 0; d->m_runningCount = d->m_loopCount; #ifdef QT_QAUDIO_DEBUG qDebug() << this << "play"; #endif if (d->m_status == QSoundEffect::Null || d->m_status == QSoundEffect::Error) { setStatus(QSoundEffect::Null); return; } if (d->m_audioOutput && d->m_audioOutput->state() == QAudio::StoppedState && d->m_sampleReady) d->m_audioOutput->start(d); setPlaying(true); } void QSoundEffectPrivate::stop() { if (!d->m_playing) return; #ifdef QT_QAUDIO_DEBUG qDebug() << "stop()"; #endif d->m_offset = 0; setPlaying(false); if (d->m_audioOutput) d->m_audioOutput->stop(); } void QSoundEffectPrivate::setStatus(QSoundEffect::Status status) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setStatus" << status; #endif if (d->m_status == status) return; bool oldLoaded = isLoaded(); d->m_status = status; emit statusChanged(); if (oldLoaded != isLoaded()) emit loadedChanged(); } void QSoundEffectPrivate::setPlaying(bool playing) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setPlaying(" << playing << ")"; #endif if (d->m_playing == playing) return; d->m_playing = playing; emit playingChanged(); } void QSoundEffectPrivate::setLoopsRemaining(int loopsRemaining) { if (!d->m_runningCount && loopsRemaining) return; #ifdef QT_QAUDIO_DEBUG qDebug() << this << "setLoopsRemaining " << loopsRemaining; #endif d->m_runningCount = loopsRemaining; emit loopsRemainingChanged(); } /* Categories are ignored */ QString QSoundEffectPrivate::category() const { return d->m_category; } void QSoundEffectPrivate::setCategory(const QString &category) { if (d->m_category != category && !d->m_playing) { d->m_category = category; emit categoryChanged(); } } PrivateSoundSource::PrivateSoundSource(QSoundEffectPrivate* s): m_loopCount(1), m_runningCount(0), m_playing(false), m_status(QSoundEffect::Null), m_audioOutput(0), m_sample(0), m_muted(false), m_volume(100), m_sampleReady(false), m_offset(0) { soundeffect = s; m_category = QLatin1String("game"); open(QIODevice::ReadOnly); } void PrivateSoundSource::sampleReady() { if (m_status == QSoundEffect::Error) return; #ifdef QT_QAUDIO_DEBUG qDebug() << this << "sampleReady "<<m_playing; #endif disconnect(m_sample, SIGNAL(error()), this, SLOT(decoderError())); disconnect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady())); if (!m_audioOutput) { m_audioOutput = new QAudioOutput(m_sample->format()); connect(m_audioOutput,SIGNAL(stateChanged(QAudio::State)), this, SLOT(stateChanged(QAudio::State))); if (!m_muted) m_audioOutput->setVolume(m_volume/100.0f); else m_audioOutput->setVolume(0); } m_sampleReady = true; soundeffect->setStatus(QSoundEffect::Ready); if (m_playing) m_audioOutput->start(this); } void PrivateSoundSource::decoderError() { qWarning("QSoundEffect(qaudio): Error decoding source"); disconnect(m_sample, SIGNAL(ready()), this, SLOT(sampleReady())); disconnect(m_sample, SIGNAL(error()), this, SLOT(decoderError())); m_playing = false; soundeffect->setStatus(QSoundEffect::Error); } void PrivateSoundSource::stateChanged(QAudio::State state) { #ifdef QT_QAUDIO_DEBUG qDebug() << this << "stateChanged " << state; #endif if (state == QAudio::IdleState && m_runningCount == 0) emit soundeffect->stop(); } qint64 PrivateSoundSource::readData( char* data, qint64 len) { if (m_runningCount > 0 && m_playing) { if (m_sample->state() != QSample::Ready) return 0; qint64 bytesWritten = 0; const int periodSize = m_audioOutput->periodSize(); const int sampleSize = m_sample->data().size(); const char* sampleData = m_sample->data().constData(); // Some systems can have large buffers we only need a max of three int periodsFree = qMin(3, (int)(m_audioOutput->bytesFree()/periodSize)); int dataOffset = 0; #ifdef QT_QAUDIO_DEBUG qDebug() << "bytesFree=" << m_audioOutput->bytesFree() << ", can fit " << periodsFree << " periodSize() chunks"; #endif while ((periodsFree > 0) && (bytesWritten + periodSize <= len)) { if (sampleSize - m_offset >= periodSize) { // We can fit a whole period of data memcpy(data + dataOffset, sampleData + m_offset, periodSize); m_offset += periodSize; dataOffset += periodSize; bytesWritten += periodSize; #ifdef QT_QAUDIO_DEBUG qDebug() << "WHOLE PERIOD: bytesWritten=" << bytesWritten << ", offset=" << m_offset << ", filesize=" << sampleSize; #endif } else { // We are at end of sound, first write what is left of current sound memcpy(data + dataOffset, sampleData + m_offset, sampleSize - m_offset); bytesWritten += sampleSize - m_offset; int wrapLen = periodSize - (sampleSize - m_offset); #ifdef QT_QAUDIO_DEBUG qDebug() << "END OF SOUND: bytesWritten=" << bytesWritten << ", offset=" << m_offset << ", part1=" << (sampleSize-m_offset); #endif dataOffset += (sampleSize - m_offset); m_offset = 0; if (m_runningCount > 0 && m_runningCount != QSoundEffect::Infinite) soundeffect->setLoopsRemaining(m_runningCount-1); if (m_runningCount > 0 || m_runningCount == QSoundEffect::Infinite) { // There are still more loops of this sound to play, append the start of sound to make up full period memcpy(data + dataOffset, sampleData + m_offset, wrapLen); m_offset += wrapLen; dataOffset += wrapLen; bytesWritten += wrapLen; #ifdef QT_QAUDIO_DEBUG qDebug() << "APPEND START FOR FULL PERIOD: bytesWritten=" << bytesWritten << ", offset=" << m_offset << ", part2=" << wrapLen; qDebug() << "part1 + part2 should be a period " << periodSize; #endif } } if (m_runningCount == 0) break; periodsFree--; } return bytesWritten; } return 0; } qint64 PrivateSoundSource::writeData(const char* data, qint64 len) { Q_UNUSED(data) Q_UNUSED(len) return 0; } QT_END_NAMESPACE #include "moc_qsoundeffect_qaudio_p.cpp" <|endoftext|>
<commit_before>#include <cfloat> #include <cctype> #include <cmath> #include <cstdlib> #include <sstream> #include "equation.h" float equation::eval(float x, float y, float z){ this->lit_i=this->literals.size()-1; this->var_i=this->variables.size()-1; this->ins_i=this->instructions.size()-1; this->evr_i=this->everything.size()-1; return eval_h(x,y,z); } float equation::eval_h(float x, float y, float z){ if(everything[evr_i] == 'L'){ --evr_i; return literals[lit_i--]; }else if(everything[evr_i] == 'V'){ --evr_i; char k = variables[var_i--]; switch(k){ case 'X': return x; case 'Y': return y; case 'Z': return z; } }else if(everything[evr_i] == 'I'){ --evr_i; int k = instructions[ins_i--]; float a = 0; float b = 0; a = eval_h(x,y,z); if(k < 10){ b = eval_h(x,y,z); } switch(k){ case 1: return add(a,b); case 2: return sub(b,a); //numbers fed in backwards, this corrects that case 3: return mul(a,b); case 4: return div(b,a); //numbers fed in backwards, going to fix that case 5: return pow(b,a); //numbers will be fed in backwards as we get them, so flip around case 11: return sqrt(a); case 12: return exp(a); case 13: return log10(a); case 14: return log(a); case 15: return cos(a); case 16: return sin(a); case 17: return tan(a); case 18: return neg(a); } } return 0; } float* equation::eval(float x, float y, float z, float* vector){ if(isVector){ vector[0] = xyz[0]->eval(x,y,z); vector[1] = xyz[1]->eval(x,y,z); vector[2] = xyz[2]->eval(x,y,z); } return vector; } float inline equation::add(float a, float b){ return a+b; } float inline equation::sub(float a, float b){ return a-b; } float inline equation::mul(float a, float b){ return a*b; } float inline equation::div(float a, float b){ return a/b; } float inline equation::neg(float a){ return -1*a; } equation::equation(){ this->xyz = NULL; //empty } std::string equation_factory::replacer(std::string subject, const std::string& search,const std::string& replace){ size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } equation* equation_factory::vector_equation(std::string eq){ for (size_t i = 0; i < eq.size(); ++i) {//basically, if it's not an equation, don't bother parsing. It's not going to end well. if (eq.at(i) == '\\' || eq.at(i) == ':') return NULL; } std::vector<std::string> eqrs; std::istringstream ss(eq); std::string token; while(std::getline(ss, token, ',')){ eqrs.push_back(token); } std::vector<std::string> all_real; std::string white_space(" "); for(int i = 0; i < eqrs.size(); ++i){ std::string k = replacer(eqrs[i], std::string("<"), white_space); std::string f = replacer(k, std::string(">"), white_space); all_real.push_back(f); } equation* ret = new equation(); ret->isVector = true; ret->xyz = new equation*[3]; ret->xyz[0] = scalar_equation(all_real[0]); ret->xyz[1] = scalar_equation(all_real[1]); ret->xyz[2] = scalar_equation(all_real[2]); return ret; } equation* equation_factory::scalar_equation(std::string eq){ equation* ret = new equation(); ret->isVector = false; //look into shunting-yard algorithm // '(' -> 100, ')' -> 101 std::stack<int> ops; char k = 0; int i = 0; for(i=0; i<eq.size(); ++i){ k = eq[i]; switch(k){ case 'X': ret->everything.push_back('V'); ret->variables.push_back('X'); break; case 'Y': ret->everything.push_back('V'); ret->variables.push_back('Y'); break; case 'Z': ret->everything.push_back('V'); ret->variables.push_back('Z'); break; case '+': case '-': case '*': case '/': case '^': case '(': case ')': case 's': case 't': case 'c': case 'l': case 'e': case '~':{ int skip = handle_instruction(&ops, ret, k, eq, i); i += skip; break; } case ' '://deliberately ignore whitespaces case '\n': case '\t': break; } if(num_part(k)){ std::string build; while(num_part(k)){ build += k; k = eq[++i]; } i--; //went too far, the end condition on the loop will move formward, so we are moving this back one. float num = (float)atof(build.c_str()); ret->everything.push_back('L'); ret->literals.push_back(num); } } while(ops.size() > 0){ ret->everything.push_back('I'); ret->instructions.push_back(ops.top()); ops.pop(); } return ret; } bool equation_factory::num_part(char a){ switch(a){ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': case '-': case '.': return true; } return false; } int equation_factory::handle_instruction(std::stack<int> *ops, equation *eqr, char k, std::string q, int i){ int opk = get_num_for_inst(k,q,i); int last = 0; if(ops->size() > 0) last = ops->top(); while(ops->size() > 0 && should_pop(last, opk)){ eqr->everything.push_back('I'); eqr->instructions.push_back(last); ops->pop(); last = (ops->size() > 0) ? ops->top() : 0; } if(opk == 101) ops->pop(); //')' if(opk != 101) ops->push(opk); if(k == 's'){ if(q[i+1] == 'i') return 2; if(q[i+1] == 'q') return 3; } if(k == 'l'){ if(q[i+1] == 'n') return 1; if(q[i+1] == 'o') return 2; } if(k == 'c') return 2; if(k == 't') return 2; if(k == 'e') return 1; return 0; } bool equation_factory::should_pop(int a, int b){ if(a == 0) return false; //the null op if(a == 18) return true; //'~'(negate) if(b == 101){ //')' if(a == 100) return false; //'(' else return true; } if(b == 1 || b == 2){ // '+', '-' if(a == 100) return false; //'(' return true; } if(b == 3 || b == 4){ // '*','/' switch(a){ case 1: //'+' case 2: //'-' case 100://'(' return false; } return true; } if(b == 5){ // '^' switch(a){ case 5: case 1: case 2: case 3: case 4: case 100: return false; } return true; } if(b > 10) return false; } int equation_factory::get_num_for_inst(char k, std::string q, int i){ switch(k){ case '+': return 1; case '-': return 2; case '*': return 3; case '/': return 4; case '^': return 5; case '(': return 100; case ')': return 101; case '~': return 18; case 'e': return 12; case 's': if(q[i+1] == 'i') return 16; if(q[i+1] == 'q') return 11; case 'c': return 15; case 't': return 17; case 'l': if(q[i+1] == 'n') return 14; if(q[i+1] == 'o') return 13; } } equation_factory::equation_factory(){ } <commit_msg>equation engine now case-insensitive<commit_after>#include <cfloat> #include <cctype> #include <cmath> #include <cstdlib> #include <sstream> #include "equation.h" float equation::eval(float x, float y, float z){ this->lit_i=this->literals.size()-1; this->var_i=this->variables.size()-1; this->ins_i=this->instructions.size()-1; this->evr_i=this->everything.size()-1; return eval_h(x,y,z); } float equation::eval_h(float x, float y, float z){ if(everything[evr_i] == 'L'){ --evr_i; return literals[lit_i--]; }else if(everything[evr_i] == 'V'){ --evr_i; char k = variables[var_i--]; switch(k){ case 'X': return x; case 'Y': return y; case 'Z': return z; } }else if(everything[evr_i] == 'I'){ --evr_i; int k = instructions[ins_i--]; float a = 0; float b = 0; a = eval_h(x,y,z); if(k < 10){ b = eval_h(x,y,z); } switch(k){ case 1: return add(a,b); case 2: return sub(b,a); //numbers fed in backwards, this corrects that case 3: return mul(a,b); case 4: return div(b,a); //numbers fed in backwards, going to fix that case 5: return pow(b,a); //numbers will be fed in backwards as we get them, so flip around case 11: return sqrt(a); case 12: return exp(a); case 13: return log10(a); case 14: return log(a); case 15: return cos(a); case 16: return sin(a); case 17: return tan(a); case 18: return neg(a); } } return 0; } float* equation::eval(float x, float y, float z, float* vector){ if(isVector){ vector[0] = xyz[0]->eval(x,y,z); vector[1] = xyz[1]->eval(x,y,z); vector[2] = xyz[2]->eval(x,y,z); } return vector; } float inline equation::add(float a, float b){ return a+b; } float inline equation::sub(float a, float b){ return a-b; } float inline equation::mul(float a, float b){ return a*b; } float inline equation::div(float a, float b){ return a/b; } float inline equation::neg(float a){ return -1*a; } equation::equation(){ this->xyz = NULL; //empty } std::string equation_factory::replacer(std::string subject, const std::string& search,const std::string& replace){ size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } equation* equation_factory::vector_equation(std::string eq){ for (size_t i = 0; i < eq.size(); ++i) {//basically, if it's not an equation, don't bother parsing. It's not going to end well. if (eq.at(i) == '\\' || eq.at(i) == ':') return NULL; } std::vector<std::string> eqrs; std::istringstream ss(eq); std::string token; while(std::getline(ss, token, ',')){ eqrs.push_back(token); } std::vector<std::string> all_real; std::string white_space(" "); for(int i = 0; i < eqrs.size(); ++i){ std::string k = replacer(eqrs[i], std::string("<"), white_space); std::string f = replacer(k, std::string(">"), white_space); all_real.push_back(f); } equation* ret = new equation(); ret->isVector = true; ret->xyz = new equation*[3]; ret->xyz[0] = scalar_equation(all_real[0]); ret->xyz[1] = scalar_equation(all_real[1]); ret->xyz[2] = scalar_equation(all_real[2]); return ret; } equation* equation_factory::scalar_equation(std::string eq){ equation* ret = new equation(); ret->isVector = false; //look into shunting-yard algorithm // '(' -> 100, ')' -> 101 std::stack<int> ops; char k = 0; int i = 0; for(i=0; i<eq.size(); ++i){ k = eq[i]; switch(k){ case 'x': case 'X': ret->everything.push_back('V'); ret->variables.push_back('X'); break; case 'y': case 'Y': ret->everything.push_back('V'); ret->variables.push_back('Y'); break; case 'z': case 'Z': ret->everything.push_back('V'); ret->variables.push_back('Z'); break; case '+': case '-': case '*': case '/': case '^': case '(': case ')': case 'S': case 's': case 'T': case 't': case 'C': case 'c': case 'L': case 'l': case 'E': case 'e': case '~':{ int skip = handle_instruction(&ops, ret, k, eq, i); i += skip; break; } case ' '://deliberately ignore whitespaces case '\n': case '\t': break; } if(num_part(k)){ std::string build; while(num_part(k)){ build += k; k = eq[++i]; } i--; //went too far, the end condition on the loop will move formward, so we are moving this back one. float num = (float)atof(build.c_str()); ret->everything.push_back('L'); ret->literals.push_back(num); } } while(ops.size() > 0){ ret->everything.push_back('I'); ret->instructions.push_back(ops.top()); ops.pop(); } return ret; } bool equation_factory::num_part(char a){ switch(a){ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': case '-': case '.': return true; } return false; } int equation_factory::handle_instruction(std::stack<int> *ops, equation *eqr, char k, std::string q, int i){ int opk = get_num_for_inst(k,q,i); int last = 0; if(ops->size() > 0) last = ops->top(); while(ops->size() > 0 && should_pop(last, opk)){ eqr->everything.push_back('I'); eqr->instructions.push_back(last); ops->pop(); last = (ops->size() > 0) ? ops->top() : 0; } if(opk == 101) ops->pop(); //')' if(opk != 101) ops->push(opk); if(k == 's' || k == 'S'){ if(q[i+1] == 'i' || q[i + 1] == 'I') return 2; if(q[i+1] == 'q' || q[i + 1] == 'Q') return 3; } if(k == 'l' || k == 'L'){ if(q[i+1] == 'n' || q[i + 1] == 'N') return 1; if(q[i+1] == 'o' || q[i + 1] == 'O') return 2; } if(k == 'c' || k == 'C') return 2; if(k == 't' || k == 'T') return 2; if(k == 'e' || k == 'E') return 1; return 0; } bool equation_factory::should_pop(int a, int b){ if(a == 0) return false; //the null op if(a == 18) return true; //'~'(negate) if(b == 101){ //')' if(a == 100) return false; //'(' else return true; } if(b == 1 || b == 2){ // '+', '-' if(a == 100) return false; //'(' return true; } if(b == 3 || b == 4){ // '*','/' switch(a){ case 1: //'+' case 2: //'-' case 100://'(' return false; } return true; } if(b == 5){ // '^' switch(a){ case 5: case 1: case 2: case 3: case 4: case 100: return false; } return true; } if(b > 10) return false; } int equation_factory::get_num_for_inst(char k, std::string q, int i){ switch(k){ case '+': return 1; case '-': return 2; case '*': return 3; case '/': return 4; case '^': return 5; case '(': return 100; case ')': return 101; case '~': return 18; case 'E': case 'e': return 12; case 'S': case 's': if(q[i+1] == 'i' || q[i + 1] == 'I') return 16; if(q[i+1] == 'q' || q[i + 1] == 'Q') return 11; case 'C': case 'c': return 15; case 'T': case 't': return 17; case 'L': case 'l': if(q[i+1] == 'n' || q[i + 1] == 'N') return 14; if(q[i+1] == 'o' || q[i + 1] == 'O') return 13; } } equation_factory::equation_factory(){ } <|endoftext|>
<commit_before>#include <sge/actionmgr.hpp> using namespace std; namespace sge { void ActionManager::register_keyboard_action(string const &name, SDL_Keycode key) { a_keyboard[name].push_back(key); } void ActionManager::register_mouse_action(string const &name, Uint8 button) { a_mouse[name].push_back(button); } void ActionManager::register_joystick_action(string const &name, Uint8 button) { a_joystick[name].push_back(button); } bool ActionManager::is_action_pressed(string const &name) const { return a_active.at(name); } bool ActionManager::is_action_released(string const &name) const { return !a_active.at(name); } bool ActionManager::event_handler(SDL_Event *event) { switch (event->type) { case SDL_CONTROLLERBUTTONDOWN: for (auto it = a_joystick.begin(); it != a_joystick.end(); it++) { string action = it->first; vector<Uint8> button = it->second; for (auto it = button.begin(); it != button.end(); it++) { if (*it == event->cbutton.button) { a_active[action] = true; break; } } } break; case SDL_CONTROLLERBUTTONUP: for (auto it = a_joystick.begin(); it != a_joystick.end(); it++) { string action = it->first; vector<Uint8> button = it->second; for (auto it = button.begin(); it != button.end(); it++) { if (*it == event->cbutton.button) { a_active[action] = false; break; } } } break; case SDL_KEYDOWN: for (auto it = a_keyboard.begin(); it != a_keyboard.end(); it++) { string action = it->first; vector<SDL_Keycode> key = it->second; for (auto it = key.begin(); it != key.end(); it++) { if (*it == event->key.keysym.sym) { a_active[action] = true; break; } } } break; case SDL_KEYUP: for (auto it = a_keyboard.begin(); it != a_keyboard.end(); it++) { string action = it->first; vector<SDL_Keycode> key = it->second; for (auto it = key.begin(); it != key.end(); it++) { if (*it == event->key.keysym.sym) { a_active[action] = false; break; } } } break; case SDL_MOUSEBUTTONDOWN: for (auto it = a_mouse.begin(); it != a_mouse.end(); it++) { string action = it->first; vector<Uint8> button = it->second; for (auto it = button.begin(); it != button.end(); it++) { if (*it == event->button.button) { a_active[action] = true; break; } } } break; case SDL_MOUSEBUTTONUP: for (auto it = a_mouse.begin(); it != a_mouse.end(); it++) { string action = it->first; vector<Uint8> button = it->second; for (auto it = button.begin(); it != button.end(); it++) { if (*it == event->button.button) { a_active[action] = false; break; } } } break; default: break; } return true; } } <commit_msg>Remove C++98-style loops<commit_after>#include <sge/actionmgr.hpp> using namespace std; namespace sge { void ActionManager::register_keyboard_action(string const &name, SDL_Keycode key) { a_keyboard[name].push_back(key); } void ActionManager::register_mouse_action(string const &name, Uint8 button) { a_mouse[name].push_back(button); } void ActionManager::register_joystick_action(string const &name, Uint8 button) { a_joystick[name].push_back(button); } bool ActionManager::is_action_pressed(string const &name) const { return a_active.at(name); } bool ActionManager::is_action_released(string const &name) const { return !a_active.at(name); } bool ActionManager::event_handler(SDL_Event *event) { switch (event->type) { case SDL_CONTROLLERBUTTONDOWN: for (auto &joy : a_joystick) { string action = joy.first; vector<Uint8> button = joy.second; for (auto b : button) { if (b == event->cbutton.button) { a_active[action] = true; break; } } } break; case SDL_CONTROLLERBUTTONUP: for (auto &joy : a_joystick) { string action = joy.first; vector<Uint8> button = joy.second; for (auto &b : button) { if (b == event->cbutton.button) { a_active[action] = false; break; } } } break; case SDL_KEYDOWN: for (auto &kbd : a_keyboard) { string action = kbd.first; vector<SDL_Keycode> keys = kbd.second; for (auto &key : keys) { if (key == event->key.keysym.sym) { a_active[action] = true; break; } } } break; case SDL_KEYUP: for (auto &kbd : a_keyboard) { string action = kbd.first; vector<SDL_Keycode> keys = kbd.second; for (auto &key : keys) { if (key == event->key.keysym.sym) { a_active[action] = false; break; } } } break; case SDL_MOUSEBUTTONDOWN: for (auto &mouse : a_mouse) { string action = mouse.first; vector<Uint8> button = mouse.second; for (auto &b : button) { if (b == event->button.button) { a_active[action] = true; break; } } } break; case SDL_MOUSEBUTTONUP: for (auto &mouse : a_mouse) { string action = mouse.first; vector<Uint8> button = mouse.second; for (auto &b : button) { if (b == event->button.button) { a_active[action] = false; break; } } } break; default: break; } return true; } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/smoothing_spline/spline_1d_constraint.h" #include "glog/logging.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(Spline1dConstraint, add_boundary) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); std::vector<double> x_coord = {0.0, 0.5, 1.0}; std::vector<double> lower_bound = {1.0, 1.0, 1.0}; std::vector<double> upper_bound = {5.0, 5.0, 5.0}; constraint.AddBoundary(x_coord, lower_bound, upper_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6); ref_mat << 1, 0, 0, 0, 0, 0, 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0, -1, -0.5, -0.25, -0.125, -0.0625, -0.03125, -1, -1, -1, -1, -1, -1; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1); ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0)); } } TEST(Spline1dConstraint, add_derivative_boundary) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); std::vector<double> x_coord = {0.0, 0.5, 1.0}; std::vector<double> lower_bound = {1.0, 1.0, 1.0}; std::vector<double> upper_bound = {5.0, 5.0, 5.0}; constraint.AddDerivativeBoundary(x_coord, lower_bound, upper_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6); ref_mat << 0, 1, 0, 0, 0, 0, 0, 1, 1, 0.75, 0.5, 0.3125, 0, 1, 2, 3, 4, 5, 0, -1, -0, -0, -0, -0, 0, -1, -1, -0.75, -0.5, -0.3125, 0, -1, -2, -3, -4, -5; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1); ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0)); } } TEST(Spline1dConstraint, add_second_derivative_boundary) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); std::vector<double> x_coord = {0.0, 0.5, 1.0}; std::vector<double> lower_bound = {1.0, 1.0, 1.0}; std::vector<double> upper_bound = {5.0, 5.0, 5.0}; constraint.AddSecondDerivativeBoundary(x_coord, lower_bound, upper_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6); ref_mat << 0, 0, 2, 0, 0, 0, 0, 0, 2, 3, 3, 2.5, 0, 0, 2, 6, 12, 20, 0, 0, -2, -0, -0, -0, 0, 0, -2, -3, -3, -2.5, 0, 0, -2, -6, -12, -20; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1); ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0)); } } TEST(Spline1dConstraint, add_smooth_constraint_01) { std::vector<double> x_knots = {0.0, 1.0, 2.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 12); ref_mat << 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } TEST(Spline1dConstraint, add_smooth_constraint_02) { std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(2, 18); // clang-format off ref_mat << 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } TEST(Spline1dConstraint, add_derivative_smooth_constraint) { std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0}; int32_t spline_order = 4; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddDerivativeSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); std::cout << mat << std::endl; // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 12); ref_mat << 1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } } // namespace planning } // namespace apollo <commit_msg>Planning: added 1st/2nd/3rd derivative continuity constraints in spline1d<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/smoothing_spline/spline_1d_constraint.h" #include "glog/logging.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(Spline1dConstraint, add_boundary) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); std::vector<double> x_coord = {0.0, 0.5, 1.0}; std::vector<double> lower_bound = {1.0, 1.0, 1.0}; std::vector<double> upper_bound = {5.0, 5.0, 5.0}; constraint.AddBoundary(x_coord, lower_bound, upper_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6); ref_mat << 1, 0, 0, 0, 0, 0, 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0, -1, -0.5, -0.25, -0.125, -0.0625, -0.03125, -1, -1, -1, -1, -1, -1; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1); ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0)); } } TEST(Spline1dConstraint, add_derivative_boundary) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); std::vector<double> x_coord = {0.0, 0.5, 1.0}; std::vector<double> lower_bound = {1.0, 1.0, 1.0}; std::vector<double> upper_bound = {5.0, 5.0, 5.0}; constraint.AddDerivativeBoundary(x_coord, lower_bound, upper_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6); ref_mat << 0, 1, 0, 0, 0, 0, 0, 1, 1, 0.75, 0.5, 0.3125, 0, 1, 2, 3, 4, 5, 0, -1, -0, -0, -0, -0, 0, -1, -1, -0.75, -0.5, -0.3125, 0, -1, -2, -3, -4, -5; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1); ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0)); } } TEST(Spline1dConstraint, add_second_derivative_boundary) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); std::vector<double> x_coord = {0.0, 0.5, 1.0}; std::vector<double> lower_bound = {1.0, 1.0, 1.0}; std::vector<double> upper_bound = {5.0, 5.0, 5.0}; constraint.AddSecondDerivativeBoundary(x_coord, lower_bound, upper_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 6); ref_mat << 0, 0, 2, 0, 0, 0, 0, 0, 2, 3, 3, 2.5, 0, 0, 2, 6, 12, 20, 0, 0, -2, -0, -0, -0, 0, 0, -2, -3, -3, -2.5, 0, 0, -2, -6, -12, -20; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(6, 1); ref_boundary << 1.0, 1.0, 1.0, -5.0, -5.0, -5.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), ref_boundary(i, 0)); } } TEST(Spline1dConstraint, add_smooth_constraint_01) { std::vector<double> x_knots = {0.0, 1.0, 2.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 12); ref_mat << 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } TEST(Spline1dConstraint, add_smooth_constraint_02) { std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0}; int32_t spline_order = 6; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(2, 18); // clang-format off ref_mat << 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } TEST(Spline1dConstraint, add_derivative_smooth_constraint) { std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0}; int32_t spline_order = 4; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddDerivativeSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); std::cout << mat << std::endl; // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 12); ref_mat << 1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } TEST(Spline1dConstraint, add_second_derivative_smooth_constraint) { std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0}; int32_t spline_order = 4; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddSecondDerivativeSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); std::cout << mat << std::endl; // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(6, 12); ref_mat << 1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0, 0, 0, 2, 6, 0, 0, -2, -0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, -1, -0, -0, -0, 0, 0, 0, 0, 0, 1, 2, 3, 0, -1, -0, -0, 0, 0, 0, 0, 0, 0, 2, 6, 0, 0, -2, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } TEST(Spline1dConstraint, add_third_derivative_smooth_constraint) { std::vector<double> x_knots = {0.0, 1.0, 2.0, 3.0}; int32_t spline_order = 5; Spline1dConstraint constraint(x_knots, spline_order); constraint.AddThirdDerivativeSmoothConstraint(); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); std::cout << mat << std::endl; // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(8, 15); ref_mat << 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, -1, -0, -0, -0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 12, 0, 0, -2, -0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 24, 0, 0, 0, -6, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, -1, -0, -0, -0, -0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, -1, -0, -0, -0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 12, 0, 0, -2, -0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 24, 0, 0, 0, -6, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_DOUBLE_EQ(mat(i, j), ref_mat(i, j)); } } for (int i = 0; i < boundary.rows(); ++i) { EXPECT_DOUBLE_EQ(boundary(i, 0), 0.0); } } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* * File: rigResection_test.cpp * Author: sgaspari * * Created on January 2, 2016, 11:38 PM */ #include "rigResection.hpp" #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> #include <openMVG/geometry/pose3.hpp> #include "testing/testing.h" #include <vector> #include <math.h> #include <chrono> #include <random> using namespace openMVG; Mat3 generateRotation(double x, double y, double z) { //std::cout << "generateRotation" << std::endl; Mat3 R1 = Mat3::Identity(); R1(1,1) = cos(x); R1(1,2) = -sin(x); R1(2,1) = -R1(1,2); R1(2,2) = R1(1,1); Mat3 R2 = Mat3::Identity(); R2(0,0) = cos(y); R2(0,2) = sin(y); R2(2,0) = -R2(0,2); R2(2,2) = R2(0,0); Mat3 R3 = Mat3::Identity(); R3(0,0) = cos(z); R3(0,1) = -sin(z); R3(1,0) =-R3(0,1); R3(1,1) = R3(0,0); return R3 * R2 * R1; } Mat3 generateRotation(const Vec3 &angles) { return generateRotation(angles(0), angles(1), angles(2)); } Mat3 generateRandomRotation(const Vec3 &maxAngles = Vec3::Constant(2*M_PI)) { const Vec3 angles = Vec3::Random().cwiseProduct(maxAngles); // std::cout << "generateRandomRotation" << std::endl; return generateRotation(angles); } Vec3 generateRandomTranslation(double maxNorm) { // std::cout << "generateRandomTranslation" << std::endl; Vec3 translation = Vec3::Random(); return maxNorm * (translation / translation.norm()); } Vec3 generateRandomPoint(double thetaMin, double thetaMax, double depthMax, double depthMin) { // variables contains the spherical parameters (r, theta, phi) for the point to generate its // spherical coordinatrs Vec3 variables = Vec3::Random(); variables(0) = (variables(0)+1)/2; // put the random in [0,1] variables(1) = (variables(1)+1)/2; // put the random in [0,1] // get random value for r const double &r = variables(0) = depthMin*variables(0) + (1-variables(0))*depthMax; // get random value for theta const double &theta = variables(1) = thetaMin*variables(1) + (1-variables(1))*thetaMax; // get random value for phi const double &phi = variables(2) = M_PI*variables(2); return Vec3(r*std::sin(theta)*std::cos(phi), r*std::sin(theta)*std::sin(phi), r*std::cos(theta)); } Mat3X generateRandomPoints(std::size_t numPts, double thetaMin, double thetaMax, double depthMax, double depthMin) { Mat3X points = Mat(3, numPts); for(std::size_t i = 0; i < numPts; ++i) { points.col(i) = generateRandomPoint(thetaMin, thetaMax, depthMax, depthMin); } return points; } geometry::Pose3 generateRandomPose(const Vec3 &maxAngles = Vec3::Constant(2*M_PI), double maxNorm = 1) { // std::cout << "generateRandomPose" << std::endl; return geometry::Pose3(generateRandomRotation(maxAngles), generateRandomTranslation(maxNorm)); } TEST(rigResection, simpleNoNoiseNoOutliers) { const std::size_t numCameras = 3; const std::size_t numPoints = 10; const std::size_t numTrials = 10; const double threshold = 1e-3; for(std::size_t trial = 0; trial < numTrials; ++trial) { // generate random pose for the rig const geometry::Pose3 rigPoseGT = generateRandomPose(Vec3::Constant(M_PI/10), 5); // generate random 3D points const double thetaMin = 0; const double thetaMax = M_PI/3; const double depthMax = 50; const double depthMin = 10; const Mat3X pointsGT = generateRandomPoints(numPoints, thetaMin, thetaMax, depthMax, depthMin); // apply random rig pose to points const Mat3X points = rigPoseGT(pointsGT); // generate numCameras random poses and intrinsics std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > vec_queryIntrinsics; std::vector<geometry::Pose3 > vec_subPoses; // std::cout << "points" << points << std::endl; std::cout << "rigPoseGT\n" << rigPoseGT.rotation() << "\n" << rigPoseGT.center()<< std::endl; for(std::size_t cam = 0; cam < numCameras; ++cam) { // first camera is in I 0 if(cam != 0) vec_subPoses.push_back(generateRandomPose(Vec3::Constant(M_PI/10), 1.5)); // let's keep it simple vec_queryIntrinsics.push_back(cameras::Pinhole_Intrinsic_Radial_K3(640, 480, 500, 320, 240)); } assert(vec_subPoses.size() == numCameras-1); // for(std::size_t i = 0; i < vec_subPoses.size(); ++i) // std::cout << "vec_subPoses\n" << vec_subPoses[i].rotation() << "\n" << vec_subPoses[i].center()<< std::endl;; // for each camera generate the features (if 3D point is "in front" of the camera) std::vector<Mat3X> vec_pts3d; vec_pts3d.reserve(numCameras); std::vector<Mat2X> vec_pts2d; vec_pts2d.reserve(numCameras); for(std::size_t cam = 0; cam < numCameras; ++cam) { Mat3X localPts; if(cam != 0) localPts = vec_subPoses[cam-1](points); else localPts = points; // count the number of points in front of the camera const std::size_t validPoints = (localPts.row(2).array() > 0.0).count(); Mat3X pts3d = Mat(3, validPoints); Mat2X pts2d = Mat(2, validPoints); // for each 3D point std::size_t idx = 0; for(std::size_t i = 0; i < numPoints; ++i) { // if it is in front of the camera if(localPts(2,i) > 0) { // project it Vec2 feat = vec_queryIntrinsics[cam].project(geometry::Pose3(), localPts.col(i)); // add the 3d and 2d point pts3d.col(idx) = pointsGT.col(i); pts2d.col(idx) = feat; ++idx; } else { std::cout << localPts.col(i) << std::endl; } } assert(idx == validPoints); // std::cout << "Cam " << cam << std::endl; // std::cout << "pts3d\n" << pts3d << std::endl; // std::cout << "pts2d\n" << pts2d << std::endl; // // auto residuals = vec_queryIntrinsics[cam].residuals(geometry::Pose3(), localPts, pts2d); // auto sqrErrors = (residuals.cwiseProduct(residuals)).colwise().sum(); // // std::cout << "residuals\n" << sqrErrors << std::endl; // if(cam!=0) // residuals = vec_queryIntrinsics[cam].residuals(vec_subPoses[cam-1], points, pts2d); // else // residuals = vec_queryIntrinsics[cam].residuals(geometry::Pose3(), points, pts2d); // // auto sqrErrors2 = (residuals.cwiseProduct(residuals)).colwise().sum(); // // std::cout << "residuals2\n" << sqrErrors2 << std::endl; vec_pts3d.push_back(pts3d); vec_pts2d.push_back(pts2d); } // call the GPNP std::vector<std::vector<std::size_t> > inliers; geometry::Pose3 rigPose; EXPECT_TRUE(localization::rigResection(vec_pts2d, vec_pts3d, vec_queryIntrinsics, vec_subPoses, rigPose, inliers)); std::cout << "rigPose\n" << rigPose.rotation() << "\n" << rigPose.center()<< std::endl; // check result for the pose const Mat3 &rot = rigPose.rotation(); const Mat3 &rotGT = rigPoseGT.rotation(); for(std::size_t i = 0; i < 3; ++i) { for(std::size_t j = 0; j < 3; ++j) { EXPECT_NEAR(rotGT(i,j), rot(i,j), threshold); } } const Vec3 &center = rigPose.center(); const Vec3 &centerGT = rigPoseGT.center(); for(std::size_t i = 0; i < 3; ++i) { EXPECT_NEAR(center(i), centerGT(i), threshold); } // check inliers EXPECT_TRUE(inliers.size() == numCameras); for(std::size_t i = 0; i < numCameras; ++i) { EXPECT_TRUE(inliers[i].size() == numPoints); } // check reprojection errors for(std::size_t cam = 0; cam < numCameras; ++cam) { const std::size_t numPts = vec_pts2d[cam].cols(); const cameras::Pinhole_Intrinsic_Radial_K3 &currCamera = vec_queryIntrinsics[cam]; Mat2X residuals; if(cam!=0) residuals = currCamera.residuals(vec_subPoses[cam-1]*rigPose, vec_pts3d[cam], vec_pts2d[cam]); else residuals = currCamera.residuals(geometry::Pose3()*rigPose, vec_pts3d[cam], vec_pts2d[cam]); auto sqrErrors = (residuals.cwiseProduct(residuals)).colwise().sum(); for(std::size_t j = 0; j < numPts; ++j) { EXPECT_TRUE(sqrErrors(j) <= threshold); } } } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */ <commit_msg>[localization] Refactoring unity test for rigResection<commit_after>/* * File: rigResection_test.cpp * Author: sgaspari * * Created on January 2, 2016, 11:38 PM */ #include "rigResection.hpp" #include <openMVG/cameras/Camera_Pinhole_Radial.hpp> #include <openMVG/geometry/pose3.hpp> #include "testing/testing.h" #include <vector> #include <math.h> #include <chrono> #include <random> #include <random> using namespace openMVG; Mat3 generateRotation(double x, double y, double z) { //std::cout << "generateRotation" << std::endl; Mat3 R1 = Mat3::Identity(); R1(1,1) = cos(x); R1(1,2) = -sin(x); R1(2,1) = -R1(1,2); R1(2,2) = R1(1,1); Mat3 R2 = Mat3::Identity(); R2(0,0) = cos(y); R2(0,2) = sin(y); R2(2,0) = -R2(0,2); R2(2,2) = R2(0,0); Mat3 R3 = Mat3::Identity(); R3(0,0) = cos(z); R3(0,1) = -sin(z); R3(1,0) =-R3(0,1); R3(1,1) = R3(0,0); return R3 * R2 * R1; } Mat3 generateRotation(const Vec3 &angles) { return generateRotation(angles(0), angles(1), angles(2)); } Mat3 generateRandomRotation(const Vec3 &maxAngles = Vec3::Constant(2*M_PI)) { const Vec3 angles = Vec3::Random().cwiseProduct(maxAngles); // std::cout << "generateRandomRotation" << std::endl; return generateRotation(angles); } Vec3 generateRandomTranslation(double maxNorm) { // std::cout << "generateRandomTranslation" << std::endl; Vec3 translation = Vec3::Random(); return maxNorm * (translation / translation.norm()); } Vec3 generateRandomPoint(double thetaMin, double thetaMax, double depthMax, double depthMin) { // variables contains the spherical parameters (r, theta, phi) for the point to generate its // spherical coordinatrs Vec3 variables = Vec3::Random(); variables(0) = (variables(0)+1)/2; // put the random in [0,1] variables(1) = (variables(1)+1)/2; // put the random in [0,1] // get random value for r const double &r = variables(0) = depthMin*variables(0) + (1-variables(0))*depthMax; // get random value for theta const double &theta = variables(1) = thetaMin*variables(1) + (1-variables(1))*thetaMax; // get random value for phi const double &phi = variables(2) = M_PI*variables(2); return Vec3(r*std::sin(theta)*std::cos(phi), r*std::sin(theta)*std::sin(phi), r*std::cos(theta)); } Mat3X generateRandomPoints(std::size_t numPts, double thetaMin, double thetaMax, double depthMax, double depthMin) { Mat3X points = Mat(3, numPts); for(std::size_t i = 0; i < numPts; ++i) { points.col(i) = generateRandomPoint(thetaMin, thetaMax, depthMax, depthMin); } return points; } geometry::Pose3 generateRandomPose(const Vec3 &maxAngles = Vec3::Constant(2*M_PI), double maxNorm = 1) { // std::cout << "generateRandomPose" << std::endl; return geometry::Pose3(generateRandomRotation(maxAngles), generateRandomTranslation(maxNorm)); } void generateRandomExperiment(std::size_t numCameras, std::size_t numPoints, double outliersPercentage, double noise, geometry::Pose3 &rigPoseGT, Mat3X &pointsGT, std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > &vec_queryIntrinsics, std::vector<geometry::Pose3 > &vec_subPoses, std::vector<Mat3X> &vec_pts3d, std::vector<Mat2X> &vec_pts2d) { // generate random pose for the rig rigPoseGT = generateRandomPose(Vec3::Constant(M_PI/10), 5); // generate random 3D points const double thetaMin = 0; const double thetaMax = M_PI/3; const double depthMax = 50; const double depthMin = 10; pointsGT = generateRandomPoints(numPoints, thetaMin, thetaMax, depthMax, depthMin); // apply random rig pose to points const Mat3X points = rigPoseGT(pointsGT); std::cout << "rigPoseGT\n" << rigPoseGT.rotation() << "\n" << rigPoseGT.center()<< std::endl; // generate numCameras random poses and intrinsics for(std::size_t cam = 0; cam < numCameras; ++cam) { // first camera is in I 0 if(cam != 0) vec_subPoses.push_back(generateRandomPose(Vec3::Constant(M_PI/10), 1.5)); // let's keep it simple vec_queryIntrinsics.push_back(cameras::Pinhole_Intrinsic_Radial_K3(640, 480, 500, 320, 240)); } assert(vec_subPoses.size() == numCameras-1); // for(std::size_t i = 0; i < vec_subPoses.size(); ++i) // std::cout << "vec_subPoses\n" << vec_subPoses[i].rotation() << "\n" << vec_subPoses[i].center()<< std::endl;; // for each camera generate the features (if 3D point is "in front" of the camera) vec_pts3d.reserve(numCameras); vec_pts2d.reserve(numCameras); const std::size_t numOutliers = (std::size_t)numPoints*outliersPercentage; for(std::size_t cam = 0; cam < numCameras; ++cam) { Mat3X localPts; if(cam != 0) localPts = vec_subPoses[cam-1](points); else localPts = points; // count the number of points in front of the camera // ie take the 3rd coordinate and check it is > 0 const std::size_t validPoints = (localPts.row(2).array() > 0.0).count(); Mat3X pts3d = Mat(3, validPoints + numOutliers); Mat2X pts2d = Mat(2, validPoints + numOutliers); // for each 3D point std::size_t idx = 0; for(std::size_t i = 0; i < numPoints; ++i) { // if it is in front of the camera if(localPts(2,i) > 0) { // project it Vec2 feat = vec_queryIntrinsics[cam].project(geometry::Pose3(), localPts.col(i)); if(noise > 0.0) { feat = feat + noise*Vec2::Random(); } // add the 3d and 2d point pts3d.col(idx) = pointsGT.col(i); pts2d.col(idx) = feat; ++idx; } } assert(idx == validPoints); if(numOutliers) { //add some other random associations for(std::size_t i = 0; i < numOutliers; ++i) { pts3d.col(idx) = 10*Vec3::Random(); pts2d.col(idx) = 100*Vec2::Random(); ++idx; } } // std::cout << "Cam " << cam << std::endl; // std::cout << "pts2d\n" << pts2d << std::endl; // std::cout << "pts3d\n" << pts3d << std::endl; // std::cout << "pts3dTRA\n" << localPts << std::endl; // // auto residuals = vec_queryIntrinsics[cam].residuals(geometry::Pose3(), localPts, pts2d); // auto sqrErrors = (residuals.cwiseProduct(residuals)).colwise().sum(); // // std::cout << "residuals\n" << sqrErrors << std::endl; // if(cam!=0) // residuals = vec_queryIntrinsics[cam].residuals(vec_subPoses[cam-1], points, pts2d); // else // residuals = vec_queryIntrinsics[cam].residuals(geometry::Pose3(), points, pts2d); // // auto sqrErrors2 = (residuals.cwiseProduct(residuals)).colwise().sum(); // // std::cout << "residuals2\n" << sqrErrors2 << std::endl; vec_pts3d.push_back(pts3d); vec_pts2d.push_back(pts2d); } } TEST(rigResection, simpleNoNoiseNoOutliers) { const std::size_t numCameras = 3; const std::size_t numPoints = 10; const std::size_t numTrials = 10; const double threshold = 1e-3; for(std::size_t trial = 0; trial < numTrials; ++trial) { // generate random pose for the rig geometry::Pose3 rigPoseGT; std::vector<cameras::Pinhole_Intrinsic_Radial_K3 > vec_queryIntrinsics; std::vector<geometry::Pose3 > vec_subPoses; std::vector<Mat3X> vec_pts3d; std::vector<Mat2X> vec_pts2d; Mat3X pointsGT; generateRandomExperiment(numCameras, numPoints, 0, 0, rigPoseGT, pointsGT, vec_queryIntrinsics, vec_subPoses, vec_pts3d, vec_pts2d); // call the GPNP std::vector<std::vector<std::size_t> > inliers; geometry::Pose3 rigPose; EXPECT_TRUE(localization::rigResection(vec_pts2d, vec_pts3d, vec_queryIntrinsics, vec_subPoses, rigPose, inliers)); std::cout << "rigPose\n" << rigPose.rotation() << "\n" << rigPose.center()<< std::endl; // check result for the pose const Mat3 &rot = rigPose.rotation(); const Mat3 &rotGT = rigPoseGT.rotation(); for(std::size_t i = 0; i < 3; ++i) { for(std::size_t j = 0; j < 3; ++j) { EXPECT_NEAR(rotGT(i,j), rot(i,j), threshold); } } const Vec3 &center = rigPose.center(); const Vec3 &centerGT = rigPoseGT.center(); for(std::size_t i = 0; i < 3; ++i) { EXPECT_NEAR(center(i), centerGT(i), threshold); } // check inliers EXPECT_TRUE(inliers.size() == numCameras); for(std::size_t i = 0; i < numCameras; ++i) { EXPECT_TRUE(inliers[i].size() == numPoints); } // check reprojection errors for(std::size_t cam = 0; cam < numCameras; ++cam) { const std::size_t numPts = vec_pts2d[cam].cols(); const cameras::Pinhole_Intrinsic_Radial_K3 &currCamera = vec_queryIntrinsics[cam]; Mat2X residuals; if(cam!=0) residuals = currCamera.residuals(vec_subPoses[cam-1]*rigPose, vec_pts3d[cam], vec_pts2d[cam]); else residuals = currCamera.residuals(geometry::Pose3()*rigPose, vec_pts3d[cam], vec_pts2d[cam]); auto sqrErrors = (residuals.cwiseProduct(residuals)).colwise().sum(); for(std::size_t j = 0; j < numPts; ++j) { EXPECT_TRUE(sqrErrors(j) <= threshold); } } } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */ <|endoftext|>
<commit_before>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #ifdef TORRENT_WINDOWS #include <windows.h> #elif defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #else #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN #include <malloc.h> // memalign #endif #ifdef TORRENT_DEBUG_BUFFERS #include <sys/mman.h> #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif #if defined TORRENT_DEBUG_BUFFERS && (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) void print_backtrace(char* out, int len); #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #endif #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)VirtualAlloc(0, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif #ifdef TORRENT_WINDOWS VirtualFree(block, 0, MEM_RELEASE); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif } } <commit_msg>fixed bug in buffer debug code in allocator<commit_after>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/allocator.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #ifdef TORRENT_WINDOWS #include <windows.h> #elif defined TORRENT_BEOS #include <kernel/OS.h> #include <stdlib.h> // malloc/free #else #include <stdlib.h> // valloc/free #include <unistd.h> // _SC_PAGESIZE #endif #if TORRENT_USE_MEMALIGN || TORRENT_USE_POSIX_MEMALIGN #include <malloc.h> // memalign #endif #ifdef TORRENT_DEBUG_BUFFERS #include <sys/mman.h> #include "libtorrent/size_type.hpp" struct alloc_header { libtorrent::size_type size; int magic; char stack[3072]; }; #endif #if defined TORRENT_DEBUG_BUFFERS && (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) void print_backtrace(char* out, int len); #endif namespace libtorrent { int page_size() { static int s = 0; if (s != 0) return s; #ifdef TORRENT_WINDOWS SYSTEM_INFO si; GetSystemInfo(&si); s = si.dwPageSize; #elif defined TORRENT_BEOS s = B_PAGE_SIZE; #else s = sysconf(_SC_PAGESIZE); #endif // assume the page size is 4 kiB if we // fail to query it if (s <= 0) s = 4096; return s; } char* page_aligned_allocator::malloc(size_type bytes) { #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); int num_pages = (bytes + (page-1)) / page + 2; char* ret = (char*)valloc(num_pages * page); // make the two surrounding pages non-readable and -writable alloc_header* h = (alloc_header*)ret; h->size = bytes; h->magic = 0x1337; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif mprotect(ret, page, PROT_READ); mprotect(ret + (num_pages-1) * page, page, PROT_READ); // fprintf(stderr, "malloc: %p head: %p tail: %p size: %d\n", ret + page, ret, ret + page + bytes, int(bytes)); return ret + page; #endif #if TORRENT_USE_POSIX_MEMALIGN void* ret; if (posix_memalign(&ret, page_size(), bytes) != 0) ret = 0; return (char*)ret; #elif TORRENT_USE_MEMALIGN return (char*)memalign(page_size(), bytes); #elif defined TORRENT_WINDOWS return (char*)VirtualAlloc(0, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #elif defined TORRENT_BEOS void* ret = 0; area_id id = create_area("", &ret, B_ANY_ADDRESS , (bytes + page_size() - 1) & (page_size()-1), B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (id < B_OK) return 0; return (char*)ret; #else return (char*)valloc(bytes); #endif } void page_aligned_allocator::free(char* const block) { #ifdef TORRENT_DEBUG_BUFFERS int page = page_size(); // make the two surrounding pages non-readable and -writable mprotect(block - page, page, PROT_READ | PROT_WRITE); alloc_header* h = (alloc_header*)(block - page); int num_pages = (h->size + (page-1)) / page + 2; TORRENT_ASSERT(h->magic == 0x1337); mprotect(block + (num_pages-2) * page, page, PROT_READ | PROT_WRITE); // fprintf(stderr, "free: %p head: %p tail: %p size: %d\n", block, block - page, block + h->size, int(h->size)); h->magic = 0; #if defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) print_backtrace(h->stack, sizeof(h->stack)); #endif ::free(block - page); return; #endif #ifdef TORRENT_WINDOWS VirtualFree(block, 0, MEM_RELEASE); #elif defined TORRENT_BEOS area_id id = area_for(block); if (id < B_OK) return; delete_area(id); #else ::free(block); #endif } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "completionwidget.h" #include "completionsupport.h" #include "icompletioncollector.h" #include <texteditor/itexteditable.h> #include <utils/qtcassert.h> #include <QtCore/QEvent> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtGui/QKeyEvent> #include <QtGui/QVBoxLayout> #include <limits.h> using namespace TextEditor; using namespace TextEditor::Internal; #define NUMBER_OF_VISIBLE_ITEMS 10 namespace TextEditor { namespace Internal { class AutoCompletionModel : public QAbstractListModel { public: AutoCompletionModel(QObject *parent); inline const CompletionItem &itemAt(const QModelIndex &index) const { return m_items.at(index.row()); } void setItems(const QList<CompletionItem> &items); int rowCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; private: QList<CompletionItem> m_items; }; } // namespace Internal } // namespace TextEditor AutoCompletionModel::AutoCompletionModel(QObject *parent) : QAbstractListModel(parent) { } void AutoCompletionModel::setItems(const QList<CompletionItem> &items) { m_items = items; reset(); } int AutoCompletionModel::rowCount(const QModelIndex &) const { return m_items.count(); } QVariant AutoCompletionModel::data(const QModelIndex &index, int role) const { if (index.row() >= m_items.count()) return QVariant(); if (role == Qt::DisplayRole) { return itemAt(index).text; } else if (role == Qt::DecorationRole) { return itemAt(index).icon; } else if (role == Qt::ToolTipRole) { return itemAt(index).details; } return QVariant(); } CompletionWidget::CompletionWidget(CompletionSupport *support, ITextEditable *editor) : QFrame(0, Qt::Popup), m_support(support), m_editor(editor) { // We disable the frame on this list view and use a QFrame around it instead. // This improves the look with QGTKStyle. #ifndef Q_WS_MAC setFrameStyle(frameStyle()); #endif setObjectName(QLatin1String("m_popupFrame")); setAttribute(Qt::WA_DeleteOnClose); setMinimumSize(1, 1); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); m_completionListView = new CompletionListView(support, editor, this); layout->addWidget(m_completionListView); setFocusProxy(m_completionListView); connect(m_completionListView, SIGNAL(itemSelected(TextEditor::CompletionItem)), this, SIGNAL(itemSelected(TextEditor::CompletionItem))); connect(m_completionListView, SIGNAL(completionListClosed()), this, SIGNAL(completionListClosed())); connect(m_completionListView, SIGNAL(activated(QModelIndex)), SLOT(closeList(QModelIndex))); } CompletionWidget::~CompletionWidget() { } void CompletionWidget::setQuickFix(bool quickFix) { m_completionListView->setQuickFix(quickFix); } void CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionitems) { m_completionListView->setCompletionItems(completionitems); } void CompletionWidget::closeList(const QModelIndex &index) { m_completionListView->closeList(index); close(); } void CompletionWidget::showCompletions(int startPos) { updatePositionAndSize(startPos); show(); setFocus(); } void CompletionWidget::updatePositionAndSize(int startPos) { // Determine size by calculating the space of the visible items QAbstractItemModel *model = m_completionListView->model(); int visibleItems = model->rowCount(); if (visibleItems > NUMBER_OF_VISIBLE_ITEMS) visibleItems = NUMBER_OF_VISIBLE_ITEMS; const QStyleOptionViewItem &option = m_completionListView->viewOptions(); QSize shint; for (int i = 0; i < visibleItems; ++i) { QSize tmp = m_completionListView->itemDelegate()->sizeHint(option, model->index(i, 0)); if (shint.width() < tmp.width()) shint = tmp; } const int fw = frameWidth(); const int width = shint.width() + fw * 2 + 30; const int height = shint.height() * visibleItems + fw * 2; // Determine the position, keeping the popup on the screen const QRect cursorRect = m_editor->cursorRect(startPos); const QDesktopWidget *desktop = QApplication::desktop(); QWidget *editorWidget = m_editor->widget(); #ifdef Q_WS_MAC const QRect screen = desktop->availableGeometry(desktop->screenNumber(editorWidget)); #else const QRect screen = desktop->screenGeometry(desktop->screenNumber(editorWidget)); #endif QPoint pos = cursorRect.bottomLeft(); pos.rx() -= 16 + fw; // Space for the icons if (pos.y() + height > screen.bottom()) pos.setY(cursorRect.top() - height); if (pos.x() + width > screen.right()) pos.setX(screen.right() - width); setGeometry(pos.x(), pos.y(), width, height); } CompletionListView::CompletionListView(CompletionSupport *support, ITextEditable *editor, CompletionWidget *completionWidget) : QListView(completionWidget), m_blockFocusOut(false), m_quickFix(false), m_editor(editor), m_editorWidget(editor->widget()), m_completionWidget(completionWidget), m_model(new AutoCompletionModel(this)), m_support(support) { QTC_ASSERT(m_editorWidget, return); setAttribute(Qt::WA_MacShowFocusRect, false); setUniformItemSizes(true); setSelectionBehavior(QAbstractItemView::SelectItems); setSelectionMode(QAbstractItemView::SingleSelection); setFrameStyle(QFrame::NoFrame); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMinimumSize(1, 1); setModel(m_model); } CompletionListView::~CompletionListView() { } bool CompletionListView::event(QEvent *e) { if (m_blockFocusOut) return QListView::event(e); bool forwardKeys = true; if (e->type() == QEvent::FocusOut) { QModelIndex index; #if defined(Q_OS_DARWIN) && ! defined(QT_MAC_USE_COCOA) QFocusEvent *fe = static_cast<QFocusEvent *>(e); if (fe->reason() == Qt::OtherFocusReason) { // Qt/carbon workaround // focus out is received before the key press event. index = currentIndex(); } #endif m_completionWidget->closeList(index); return true; } else if (e->type() == QEvent::ShortcutOverride) { QKeyEvent *ke = static_cast<QKeyEvent *>(e); switch (ke->key()) { case Qt::Key_N: case Qt::Key_P: // select next/previous completion if (ke->modifiers() == Qt::ControlModifier) { e->accept(); int change = (ke->key() == Qt::Key_N) ? 1 : -1; int nrows = model()->rowCount(); int row = currentIndex().row(); int newRow = (row + change + nrows) % nrows; if (newRow == row + change || !ke->isAutoRepeat()) setCurrentIndex(m_model->index(newRow)); return true; } } } else if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(e); switch (ke->key()) { case Qt::Key_N: case Qt::Key_P: // select next/previous completion - so don't pass on to editor if (ke->modifiers() == Qt::ControlModifier) forwardKeys = false; break; case Qt::Key_Escape: m_completionWidget->closeList(); return true; case Qt::Key_Right: case Qt::Key_Left: break; case Qt::Key_Tab: case Qt::Key_Return: //independently from style, accept current entry if return is pressed if (qApp->focusWidget() == this) m_completionWidget->closeList(currentIndex()); return true; case Qt::Key_Up: if (!ke->isAutoRepeat() && currentIndex().row() == 0) { setCurrentIndex(model()->index(model()->rowCount()-1, 0)); return true; } forwardKeys = false; break; case Qt::Key_Down: if (!ke->isAutoRepeat() && currentIndex().row() == model()->rowCount()-1) { setCurrentIndex(model()->index(0, 0)); return true; } forwardKeys = false; break; case Qt::Key_Enter: case Qt::Key_PageDown: case Qt::Key_PageUp: forwardKeys = false; break; default: // if a key is forwarded, completion widget is re-opened and selected item is reset to first, // so only forward keys that insert text and refine the completed item forwardKeys = !ke->text().isEmpty(); break; } if (forwardKeys && ! m_quickFix) { m_blockFocusOut = true; QApplication::sendEvent(m_editorWidget, e); m_blockFocusOut = false; // Have the completion support update the list of items m_support->autoComplete(m_editor, false); return true; } } return QListView::event(e); } void CompletionListView::keyboardSearch(const QString &search) { Q_UNUSED(search) } void CompletionListView::setQuickFix(bool quickFix) { m_quickFix = quickFix; } void CompletionListView::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems) { m_model->setItems(completionItems); // Select the first of the most relevant completion items int relevance = INT_MIN; int mostRelevantIndex = 0; for (int i = 0; i < completionItems.size(); ++i) { const CompletionItem &item = completionItems.at(i); if (item.relevance > relevance) { relevance = item.relevance; mostRelevantIndex = i; } } setCurrentIndex(m_model->index(mostRelevantIndex)); } void CompletionListView::closeList(const QModelIndex &index) { m_blockFocusOut = true; if (index.isValid()) emit itemSelected(m_model->itemAt(index)); emit completionListClosed(); m_blockFocusOut = false; } <commit_msg>Fixed the border of the completion widget<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "completionwidget.h" #include "completionsupport.h" #include "icompletioncollector.h" #include <texteditor/itexteditable.h> #include <utils/qtcassert.h> #include <QtCore/QEvent> #include <QtGui/QApplication> #include <QtGui/QDesktopWidget> #include <QtGui/QKeyEvent> #include <QtGui/QVBoxLayout> #include <limits.h> using namespace TextEditor; using namespace TextEditor::Internal; #define NUMBER_OF_VISIBLE_ITEMS 10 namespace TextEditor { namespace Internal { class AutoCompletionModel : public QAbstractListModel { public: AutoCompletionModel(QObject *parent); inline const CompletionItem &itemAt(const QModelIndex &index) const { return m_items.at(index.row()); } void setItems(const QList<CompletionItem> &items); int rowCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; private: QList<CompletionItem> m_items; }; } // namespace Internal } // namespace TextEditor AutoCompletionModel::AutoCompletionModel(QObject *parent) : QAbstractListModel(parent) { } void AutoCompletionModel::setItems(const QList<CompletionItem> &items) { m_items = items; reset(); } int AutoCompletionModel::rowCount(const QModelIndex &) const { return m_items.count(); } QVariant AutoCompletionModel::data(const QModelIndex &index, int role) const { if (index.row() >= m_items.count()) return QVariant(); if (role == Qt::DisplayRole) { return itemAt(index).text; } else if (role == Qt::DecorationRole) { return itemAt(index).icon; } else if (role == Qt::ToolTipRole) { return itemAt(index).details; } return QVariant(); } CompletionWidget::CompletionWidget(CompletionSupport *support, ITextEditable *editor) : QFrame(0, Qt::Popup), m_support(support), m_editor(editor), m_completionListView(new CompletionListView(support, editor, this)) { // We disable the frame on this list view and use a QFrame around it instead. // This improves the look with QGTKStyle. #ifndef Q_WS_MAC setFrameStyle(m_completionListView->frameStyle()); #endif m_completionListView->setFrameStyle(QFrame::NoFrame); setObjectName(QLatin1String("m_popupFrame")); setAttribute(Qt::WA_DeleteOnClose); setMinimumSize(1, 1); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->addWidget(m_completionListView); setFocusProxy(m_completionListView); connect(m_completionListView, SIGNAL(itemSelected(TextEditor::CompletionItem)), this, SIGNAL(itemSelected(TextEditor::CompletionItem))); connect(m_completionListView, SIGNAL(completionListClosed()), this, SIGNAL(completionListClosed())); connect(m_completionListView, SIGNAL(activated(QModelIndex)), SLOT(closeList(QModelIndex))); } CompletionWidget::~CompletionWidget() { } void CompletionWidget::setQuickFix(bool quickFix) { m_completionListView->setQuickFix(quickFix); } void CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionitems) { m_completionListView->setCompletionItems(completionitems); } void CompletionWidget::closeList(const QModelIndex &index) { m_completionListView->closeList(index); close(); } void CompletionWidget::showCompletions(int startPos) { updatePositionAndSize(startPos); show(); setFocus(); } void CompletionWidget::updatePositionAndSize(int startPos) { // Determine size by calculating the space of the visible items QAbstractItemModel *model = m_completionListView->model(); int visibleItems = model->rowCount(); if (visibleItems > NUMBER_OF_VISIBLE_ITEMS) visibleItems = NUMBER_OF_VISIBLE_ITEMS; const QStyleOptionViewItem &option = m_completionListView->viewOptions(); QSize shint; for (int i = 0; i < visibleItems; ++i) { QSize tmp = m_completionListView->itemDelegate()->sizeHint(option, model->index(i, 0)); if (shint.width() < tmp.width()) shint = tmp; } const int fw = frameWidth(); const int width = shint.width() + fw * 2 + 30; const int height = shint.height() * visibleItems + fw * 2; // Determine the position, keeping the popup on the screen const QRect cursorRect = m_editor->cursorRect(startPos); const QDesktopWidget *desktop = QApplication::desktop(); QWidget *editorWidget = m_editor->widget(); #ifdef Q_WS_MAC const QRect screen = desktop->availableGeometry(desktop->screenNumber(editorWidget)); #else const QRect screen = desktop->screenGeometry(desktop->screenNumber(editorWidget)); #endif QPoint pos = cursorRect.bottomLeft(); pos.rx() -= 16 + fw; // Space for the icons if (pos.y() + height > screen.bottom()) pos.setY(cursorRect.top() - height); if (pos.x() + width > screen.right()) pos.setX(screen.right() - width); setGeometry(pos.x(), pos.y(), width, height); } CompletionListView::CompletionListView(CompletionSupport *support, ITextEditable *editor, CompletionWidget *completionWidget) : QListView(completionWidget), m_blockFocusOut(false), m_quickFix(false), m_editor(editor), m_editorWidget(editor->widget()), m_completionWidget(completionWidget), m_model(new AutoCompletionModel(this)), m_support(support) { QTC_ASSERT(m_editorWidget, return); setAttribute(Qt::WA_MacShowFocusRect, false); setUniformItemSizes(true); setSelectionBehavior(QAbstractItemView::SelectItems); setSelectionMode(QAbstractItemView::SingleSelection); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setMinimumSize(1, 1); setModel(m_model); } CompletionListView::~CompletionListView() { } bool CompletionListView::event(QEvent *e) { if (m_blockFocusOut) return QListView::event(e); bool forwardKeys = true; if (e->type() == QEvent::FocusOut) { QModelIndex index; #if defined(Q_OS_DARWIN) && ! defined(QT_MAC_USE_COCOA) QFocusEvent *fe = static_cast<QFocusEvent *>(e); if (fe->reason() == Qt::OtherFocusReason) { // Qt/carbon workaround // focus out is received before the key press event. index = currentIndex(); } #endif m_completionWidget->closeList(index); return true; } else if (e->type() == QEvent::ShortcutOverride) { QKeyEvent *ke = static_cast<QKeyEvent *>(e); switch (ke->key()) { case Qt::Key_N: case Qt::Key_P: // select next/previous completion if (ke->modifiers() == Qt::ControlModifier) { e->accept(); int change = (ke->key() == Qt::Key_N) ? 1 : -1; int nrows = model()->rowCount(); int row = currentIndex().row(); int newRow = (row + change + nrows) % nrows; if (newRow == row + change || !ke->isAutoRepeat()) setCurrentIndex(m_model->index(newRow)); return true; } } } else if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(e); switch (ke->key()) { case Qt::Key_N: case Qt::Key_P: // select next/previous completion - so don't pass on to editor if (ke->modifiers() == Qt::ControlModifier) forwardKeys = false; break; case Qt::Key_Escape: m_completionWidget->closeList(); return true; case Qt::Key_Right: case Qt::Key_Left: break; case Qt::Key_Tab: case Qt::Key_Return: //independently from style, accept current entry if return is pressed if (qApp->focusWidget() == this) m_completionWidget->closeList(currentIndex()); return true; case Qt::Key_Up: if (!ke->isAutoRepeat() && currentIndex().row() == 0) { setCurrentIndex(model()->index(model()->rowCount()-1, 0)); return true; } forwardKeys = false; break; case Qt::Key_Down: if (!ke->isAutoRepeat() && currentIndex().row() == model()->rowCount()-1) { setCurrentIndex(model()->index(0, 0)); return true; } forwardKeys = false; break; case Qt::Key_Enter: case Qt::Key_PageDown: case Qt::Key_PageUp: forwardKeys = false; break; default: // if a key is forwarded, completion widget is re-opened and selected item is reset to first, // so only forward keys that insert text and refine the completed item forwardKeys = !ke->text().isEmpty(); break; } if (forwardKeys && ! m_quickFix) { m_blockFocusOut = true; QApplication::sendEvent(m_editorWidget, e); m_blockFocusOut = false; // Have the completion support update the list of items m_support->autoComplete(m_editor, false); return true; } } return QListView::event(e); } void CompletionListView::keyboardSearch(const QString &search) { Q_UNUSED(search) } void CompletionListView::setQuickFix(bool quickFix) { m_quickFix = quickFix; } void CompletionListView::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems) { m_model->setItems(completionItems); // Select the first of the most relevant completion items int relevance = INT_MIN; int mostRelevantIndex = 0; for (int i = 0; i < completionItems.size(); ++i) { const CompletionItem &item = completionItems.at(i); if (item.relevance > relevance) { relevance = item.relevance; mostRelevantIndex = i; } } setCurrentIndex(m_model->index(mostRelevantIndex)); } void CompletionListView::closeList(const QModelIndex &index) { m_blockFocusOut = true; if (index.isValid()) emit itemSelected(m_model->itemAt(index)); emit completionListClosed(); m_blockFocusOut = false; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <SimpleITKTestHarness.h> #include <SimpleITK.h> #include <stdint.h> #include <memory> namespace { class IterationUpdate : public itk::simple::Command { public: IterationUpdate( const itk::simple::ImageRegistrationMethod &m) : m_Method(m) {} virtual void Execute( ) { // use sitk's output operator for std::vector etc.. using itk::simple::operator<<; // stash the stream state std::ios state(NULL); state.copyfmt(std::cout); std::cout << std::fixed << std::setfill(' ') << std::setprecision( 5 ); std::cout << std::setw(3) << m_Method.GetOptimizerIteration(); std::cout << " = " << std::setw(10) << m_Method.GetMetricValue(); std::cout << " : " << m_Method.GetOptimizerPosition() << std::endl; std::cout.copyfmt(state); } private: const itk::simple::ImageRegistrationMethod &m_Method; }; } // // // TEST(Registration,ImageRegistrationMethod_Basic) { // This test is to perform some basic coverage of methods. namespace sitk = itk::simple; sitk::ImageRegistrationMethod registration; std::cout << registration.ToString(); } // // Fixture based tests // namespace sitk = itk::simple; class sitkRegistrationMethodTest : public ::testing::Test { public: sitk::Image MakeDualGaussianBlobs(const std::vector<double> &pt0, const std::vector<double> &pt1, const std::vector<unsigned int> &size) { sitk::GaussianImageSource source1; source1.SetMean(pt0); source1.SetScale(1.0); std::vector<double> sigma; for(unsigned int i = 0; i < size.size(); ++i) { sigma.push_back(size[i]/10.0); } source1.SetSigma(sigma); source1.SetSize(size); source1.SetOutputPixelType(sitk::sitkFloat32); sitk::GaussianImageSource source2; source2.SetMean(pt1); source2.SetScale(-1.0); source2.SetSigma(sigma); source2.SetSize(size); source2.SetOutputPixelType(sitk::sitkFloat32); return sitk::Add(source1.Execute(), source2.Execute()); } protected: virtual void SetUp() { fixedBlobs = MakeDualGaussianBlobs(v2(64,64), v2(192,192), std::vector<unsigned int>(2,256)); movingBlobs = MakeDualGaussianBlobs(v2(54,74), v2(192,192), std::vector<unsigned int>(2,256)); } // virtual void TearDown() {} sitk::Image fixedBlobs; sitk::Image movingBlobs; }; TEST_F(sitkRegistrationMethodTest, Metric_Evaluate) { sitk::Image fixed = fixedBlobs; sitk::Image moving = fixedBlobs; sitk::ImageRegistrationMethod R; R.SetInitialTransform(sitk::Transform(fixed.GetDimension(),sitk::sitkIdentity)); EXPECT_NEAR(-1.5299437083119216, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsCorrelation(); EXPECT_NEAR(-1.0, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsJointHistogramMutualInformation( 20, 1.5); EXPECT_NEAR(-0.52624100016564002, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsMeanSquares(); EXPECT_NEAR(0.0, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsMattesMutualInformation(); EXPECT_NEAR(-1.5299437083119216, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsMeanSquares(); // test that the transforms are used R.SetInitialTransform(sitk::TranslationTransform(fixed.GetDimension(),v2(5,-7))); EXPECT_NEAR(0.0036468516797954148, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMovingInitialTransform(sitk::TranslationTransform(fixed.GetDimension(),v2(-5,7))); EXPECT_NEAR(0.0, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetFixedInitialTransform(sitk::TranslationTransform(fixed.GetDimension(),v2(-5,7))); EXPECT_NEAR(0.0036468516797954148, R.MetricEvaluate(fixed,moving), 1e-10 ); sitk::ImageRegistrationMethod R2; R2.SetInitialTransform(sitk::Transform(fixed.GetDimension(),sitk::sitkIdentity)); R2.SetMetricAsMeanSquares(); R2.SetMetricFixedMask(sitk::Greater(fixedBlobs,0)); EXPECT_NEAR(0.0091550861657971119,R2.MetricEvaluate(fixedBlobs,movingBlobs), 1e-10); sitk::ImageRegistrationMethod R3; R3.SetInitialTransform(sitk::Transform(fixed.GetDimension(),sitk::sitkIdentity)); R3.SetMetricAsMeanSquares(); R3.SetMetricMovingMask(sitk::Less(movingBlobs,0)); EXPECT_NEAR(3.34e-09 ,R3.MetricEvaluate(fixedBlobs,movingBlobs), 1e-10); } TEST_F(sitkRegistrationMethodTest, Transform_InPlaceOn) { // This test is to check the inplace operation of the initial // transform sitk::ImageRegistrationMethod R; EXPECT_TRUE(R.GetInitialTransformInPlace()); sitk::Image fixed = fixedBlobs; sitk::Image moving = fixedBlobs; double minStep=1e-4; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance = 1e-10; R.SetOptimizerAsRegularStepGradientDescent(1.0, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixed.GetDimension()); tx.SetOffset(v2(1.1,-2.2)); R.SetInitialTransform(tx,false); EXPECT_TRUE(!R.GetInitialTransformInPlace()); R.SetMetricAsMeanSquares(); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); // expect input not to be modified EXPECT_EQ(v2(1.1,-2.2), tx.GetParameters()); // optimize in place this time R.SetInitialTransform(tx,true); EXPECT_TRUE(R.GetInitialTransformInPlace()); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); // expect input to have been modified EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), tx.GetParameters(), 1e-4); // set with const method, with inplace constant const sitk::Transform &ctx = sitk::TranslationTransform(fixed.GetDimension(),v2(0.1,-0.2)); R.SetInitialTransform(ctx); EXPECT_TRUE(R.GetInitialTransformInPlace()); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); // expect input not to be modified EXPECT_EQ(v2(0.1,-0.2), ctx.GetParameters()); } TEST_F(sitkRegistrationMethodTest, Transform_Initial) { // This test is to check the initial transforms sitk::ImageRegistrationMethod R; sitk::Image fixed = fixedBlobs; sitk::Image moving = fixedBlobs; double minStep=1e-4; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance = 1e-10; R.SetOptimizerAsRegularStepGradientDescent(1.0, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixed.GetDimension()); sitk::TranslationTransform txMoving(fixed.GetDimension()); sitk::TranslationTransform txFixed(fixed.GetDimension()); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(txFixed); R.SetMetricAsMeanSquares(); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); txMoving.SetOffset(v2(0.0,3.0)); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(txFixed); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,-3.0), outTx.GetParameters(), 1e-4); txMoving.SetOffset(v2(0.0,3.0)); txFixed.SetOffset(v2(0.0,2.0)); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(txFixed); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,-1.0), outTx.GetParameters(), 1e-4); EXPECT_EQ(R.GetMovingInitialTransform().GetParameters(), v2(0.0,3.0)); EXPECT_EQ(R.GetFixedInitialTransform().GetParameters(), v2(0.0,2.0)); // test some expected exception cases R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(sitk::TranslationTransform(3)); R.SetFixedInitialTransform(txFixed); EXPECT_THROW(R.Execute(fixed,moving), sitk::GenericException); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(sitk::TranslationTransform(3)); EXPECT_THROW(R.Execute(fixed,moving), sitk::GenericException); } TEST_F(sitkRegistrationMethodTest, Mask_Test0) { // This test is to check some excpetional cases for using masks sitk::ImageRegistrationMethod R; R.SetOptimizerAsGradientDescent(1.0, 100); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixedBlobs.GetDimension()); R.SetInitialTransform(tx); // wrong dimension should produce error R.SetMetricFixedMask(sitk::Image(100,100,100,sitk::sitkUInt8)); EXPECT_THROW(R.Execute(fixedBlobs,movingBlobs), sitk::GenericException); R.SetMetricFixedMask(sitk::Image()); // wrong dimension should produce error R.SetMetricMovingMask(sitk::Image(100,100,100,sitk::sitkUInt8)); EXPECT_THROW(R.Execute(fixedBlobs,movingBlobs), sitk::GenericException); } TEST_F(sitkRegistrationMethodTest, Mask_Test1) { // This test is to check that the metric masks have the correct // effect. sitk::ImageRegistrationMethod R; double learningRate=2.0; double minStep=1e-7; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance=1e-8; R.SetOptimizerAsRegularStepGradientDescent(learningRate, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance ); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixedBlobs.GetDimension()); R.SetInitialTransform(tx); R.SetMetricAsCorrelation(); R.SetMetricFixedMask(sitk::Cast(sitk::Greater(fixedBlobs,0),sitk::sitkFloat32)); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixedBlobs,movingBlobs); EXPECT_VECTOR_DOUBLE_NEAR(v2(-10,10), outTx.GetParameters(), 1e-4); } TEST_F(sitkRegistrationMethodTest, Mask_Test2) { // This test is to check that the metric masks have the correct // effect. sitk::ImageRegistrationMethod R; double learningRate=1.0; double minStep=1e-7; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance=1e-8; R.SetOptimizerAsRegularStepGradientDescent(learningRate, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance ); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixedBlobs.GetDimension()); tx.SetOffset(v2(120,99)); R.SetInitialTransform(tx); R.SetMetricAsCorrelation(); R.SetMetricFixedMask(sitk::Greater(fixedBlobs,0)); R.SetMetricMovingMask(sitk::Less(movingBlobs,0)); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixedBlobs,movingBlobs); EXPECT_VECTOR_DOUBLE_NEAR(v2(128.0,128.0), outTx.GetParameters(), 1e-3); } <commit_msg>Adjusting tolerance for results on the dashboard<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <SimpleITKTestHarness.h> #include <SimpleITK.h> #include <stdint.h> #include <memory> namespace { class IterationUpdate : public itk::simple::Command { public: IterationUpdate( const itk::simple::ImageRegistrationMethod &m) : m_Method(m) {} virtual void Execute( ) { // use sitk's output operator for std::vector etc.. using itk::simple::operator<<; // stash the stream state std::ios state(NULL); state.copyfmt(std::cout); std::cout << std::fixed << std::setfill(' ') << std::setprecision( 5 ); std::cout << std::setw(3) << m_Method.GetOptimizerIteration(); std::cout << " = " << std::setw(10) << m_Method.GetMetricValue(); std::cout << " : " << m_Method.GetOptimizerPosition() << std::endl; std::cout.copyfmt(state); } private: const itk::simple::ImageRegistrationMethod &m_Method; }; } // // // TEST(Registration,ImageRegistrationMethod_Basic) { // This test is to perform some basic coverage of methods. namespace sitk = itk::simple; sitk::ImageRegistrationMethod registration; std::cout << registration.ToString(); } // // Fixture based tests // namespace sitk = itk::simple; class sitkRegistrationMethodTest : public ::testing::Test { public: sitk::Image MakeDualGaussianBlobs(const std::vector<double> &pt0, const std::vector<double> &pt1, const std::vector<unsigned int> &size) { sitk::GaussianImageSource source1; source1.SetMean(pt0); source1.SetScale(1.0); std::vector<double> sigma; for(unsigned int i = 0; i < size.size(); ++i) { sigma.push_back(size[i]/10.0); } source1.SetSigma(sigma); source1.SetSize(size); source1.SetOutputPixelType(sitk::sitkFloat32); sitk::GaussianImageSource source2; source2.SetMean(pt1); source2.SetScale(-1.0); source2.SetSigma(sigma); source2.SetSize(size); source2.SetOutputPixelType(sitk::sitkFloat32); return sitk::Add(source1.Execute(), source2.Execute()); } protected: virtual void SetUp() { fixedBlobs = MakeDualGaussianBlobs(v2(64,64), v2(192,192), std::vector<unsigned int>(2,256)); movingBlobs = MakeDualGaussianBlobs(v2(54,74), v2(192,192), std::vector<unsigned int>(2,256)); } // virtual void TearDown() {} sitk::Image fixedBlobs; sitk::Image movingBlobs; }; TEST_F(sitkRegistrationMethodTest, Metric_Evaluate) { sitk::Image fixed = fixedBlobs; sitk::Image moving = fixedBlobs; sitk::ImageRegistrationMethod R; R.SetInitialTransform(sitk::Transform(fixed.GetDimension(),sitk::sitkIdentity)); EXPECT_NEAR(-1.5299437083119216, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsCorrelation(); EXPECT_NEAR(-1.0, R.MetricEvaluate(fixed,moving), 1e-10 ); // tolerance adjusted for i386, why is it so much more? R.SetMetricAsJointHistogramMutualInformation( 20, 1.5); EXPECT_NEAR(-0.52624100016564002, R.MetricEvaluate(fixed,moving), 2e-6 ); R.SetMetricAsMeanSquares(); EXPECT_NEAR(0.0, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsMattesMutualInformation(); EXPECT_NEAR(-1.5299437083119216, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMetricAsMeanSquares(); // test that the transforms are used R.SetInitialTransform(sitk::TranslationTransform(fixed.GetDimension(),v2(5,-7))); EXPECT_NEAR(0.0036468516797954148, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetMovingInitialTransform(sitk::TranslationTransform(fixed.GetDimension(),v2(-5,7))); EXPECT_NEAR(0.0, R.MetricEvaluate(fixed,moving), 1e-10 ); R.SetFixedInitialTransform(sitk::TranslationTransform(fixed.GetDimension(),v2(-5,7))); EXPECT_NEAR(0.0036468516797954148, R.MetricEvaluate(fixed,moving), 1e-10 ); sitk::ImageRegistrationMethod R2; R2.SetInitialTransform(sitk::Transform(fixed.GetDimension(),sitk::sitkIdentity)); R2.SetMetricAsMeanSquares(); R2.SetMetricFixedMask(sitk::Greater(fixedBlobs,0)); EXPECT_NEAR(0.0091550861657971119,R2.MetricEvaluate(fixedBlobs,movingBlobs), 1e-10); sitk::ImageRegistrationMethod R3; R3.SetInitialTransform(sitk::Transform(fixed.GetDimension(),sitk::sitkIdentity)); R3.SetMetricAsMeanSquares(); R3.SetMetricMovingMask(sitk::Less(movingBlobs,0)); EXPECT_NEAR(3.34e-09 ,R3.MetricEvaluate(fixedBlobs,movingBlobs), 1e-10); } TEST_F(sitkRegistrationMethodTest, Transform_InPlaceOn) { // This test is to check the inplace operation of the initial // transform sitk::ImageRegistrationMethod R; EXPECT_TRUE(R.GetInitialTransformInPlace()); sitk::Image fixed = fixedBlobs; sitk::Image moving = fixedBlobs; double minStep=1e-4; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance = 1e-10; R.SetOptimizerAsRegularStepGradientDescent(1.0, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixed.GetDimension()); tx.SetOffset(v2(1.1,-2.2)); R.SetInitialTransform(tx,false); EXPECT_TRUE(!R.GetInitialTransformInPlace()); R.SetMetricAsMeanSquares(); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); // expect input not to be modified EXPECT_EQ(v2(1.1,-2.2), tx.GetParameters()); // optimize in place this time R.SetInitialTransform(tx,true); EXPECT_TRUE(R.GetInitialTransformInPlace()); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); // expect input to have been modified EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), tx.GetParameters(), 1e-4); // set with const method, with inplace constant const sitk::Transform &ctx = sitk::TranslationTransform(fixed.GetDimension(),v2(0.1,-0.2)); R.SetInitialTransform(ctx); EXPECT_TRUE(R.GetInitialTransformInPlace()); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); // expect input not to be modified EXPECT_EQ(v2(0.1,-0.2), ctx.GetParameters()); } TEST_F(sitkRegistrationMethodTest, Transform_Initial) { // This test is to check the initial transforms sitk::ImageRegistrationMethod R; sitk::Image fixed = fixedBlobs; sitk::Image moving = fixedBlobs; double minStep=1e-4; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance = 1e-10; R.SetOptimizerAsRegularStepGradientDescent(1.0, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixed.GetDimension()); sitk::TranslationTransform txMoving(fixed.GetDimension()); sitk::TranslationTransform txFixed(fixed.GetDimension()); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(txFixed); R.SetMetricAsMeanSquares(); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,0.0), outTx.GetParameters(), 1e-4); txMoving.SetOffset(v2(0.0,3.0)); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(txFixed); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,-3.0), outTx.GetParameters(), 1e-4); txMoving.SetOffset(v2(0.0,3.0)); txFixed.SetOffset(v2(0.0,2.0)); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(txFixed); outTx = R.Execute(fixed,moving); EXPECT_VECTOR_DOUBLE_NEAR(v2(0.0,-1.0), outTx.GetParameters(), 1e-4); EXPECT_EQ(R.GetMovingInitialTransform().GetParameters(), v2(0.0,3.0)); EXPECT_EQ(R.GetFixedInitialTransform().GetParameters(), v2(0.0,2.0)); // test some expected exception cases R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(sitk::TranslationTransform(3)); R.SetFixedInitialTransform(txFixed); EXPECT_THROW(R.Execute(fixed,moving), sitk::GenericException); R.SetInitialTransform(tx,false); R.SetMovingInitialTransform(txMoving); R.SetFixedInitialTransform(sitk::TranslationTransform(3)); EXPECT_THROW(R.Execute(fixed,moving), sitk::GenericException); } TEST_F(sitkRegistrationMethodTest, Mask_Test0) { // This test is to check some excpetional cases for using masks sitk::ImageRegistrationMethod R; R.SetOptimizerAsGradientDescent(1.0, 100); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixedBlobs.GetDimension()); R.SetInitialTransform(tx); // wrong dimension should produce error R.SetMetricFixedMask(sitk::Image(100,100,100,sitk::sitkUInt8)); EXPECT_THROW(R.Execute(fixedBlobs,movingBlobs), sitk::GenericException); R.SetMetricFixedMask(sitk::Image()); // wrong dimension should produce error R.SetMetricMovingMask(sitk::Image(100,100,100,sitk::sitkUInt8)); EXPECT_THROW(R.Execute(fixedBlobs,movingBlobs), sitk::GenericException); } TEST_F(sitkRegistrationMethodTest, Mask_Test1) { // This test is to check that the metric masks have the correct // effect. sitk::ImageRegistrationMethod R; double learningRate=2.0; double minStep=1e-7; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance=1e-8; R.SetOptimizerAsRegularStepGradientDescent(learningRate, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance ); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixedBlobs.GetDimension()); R.SetInitialTransform(tx); R.SetMetricAsCorrelation(); R.SetMetricFixedMask(sitk::Cast(sitk::Greater(fixedBlobs,0),sitk::sitkFloat32)); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixedBlobs,movingBlobs); EXPECT_VECTOR_DOUBLE_NEAR(v2(-10,10), outTx.GetParameters(), 1e-4); } TEST_F(sitkRegistrationMethodTest, Mask_Test2) { // This test is to check that the metric masks have the correct // effect. sitk::ImageRegistrationMethod R; double learningRate=1.0; double minStep=1e-7; unsigned int numberOfIterations=100; double relaxationFactor=0.5; double gradientMagnitudeTolerance=1e-8; R.SetOptimizerAsRegularStepGradientDescent(learningRate, minStep, numberOfIterations, relaxationFactor, gradientMagnitudeTolerance ); R.SetInterpolator(sitk::sitkLinear); sitk::TranslationTransform tx(fixedBlobs.GetDimension()); tx.SetOffset(v2(120,99)); R.SetInitialTransform(tx); R.SetMetricAsCorrelation(); R.SetMetricFixedMask(sitk::Greater(fixedBlobs,0)); R.SetMetricMovingMask(sitk::Less(movingBlobs,0)); IterationUpdate cmd(R); R.AddCommand(sitk::sitkIterationEvent, cmd); sitk::Transform outTx = R.Execute(fixedBlobs,movingBlobs); EXPECT_VECTOR_DOUBLE_NEAR(v2(128.0,128.0), outTx.GetParameters(), 1e-3); } <|endoftext|>
<commit_before>#include "response.h" #include "request.h" #include <boost/filesystem.hpp> #include <iomanip> #include "compress.h" namespace httpserver { using field = boost::beast::http::field; httpserver::response getCompressResponse(const string& str) { using namespace httpserver; const auto& req = httpserver::request(); httpserver::response resp; boost::string_view encoding = req[field::accept_encoding]; if(encoding.find("gzip") != boost::string_view::npos && str.size()>1450){ resp.body() = compress_gzip(str); resp.set(field::content_encoding, "gzip"); }else if(encoding.find("deflate") != boost::string_view::npos && str.size()>1450){ resp.body() = compress_deflate(str); resp.set(field::content_encoding, "deflate"); }else resp.body() = str; return resp; } void compress_and_send(const string &str) { httpserver::response resp = getCompressResponse(str); send(resp); } void ok(const std::string& content) { compress_and_send(content); } void ok(const string &content, const string &type, bool compress) { response res = getCompressResponse(content); res.set(boost::beast::http::field::content_type, type); send(res); } type_function_resp_default created = [](const std::string& local) { response resp; resp.result(status::created); resp.set("Local", local ); send(resp); }; type_function_resp_default accepted = [](const std::string& content) { response resp; resp.result(status::accepted); resp.body() = content; send(resp); }; type_function_resp_default forbidden = [](const std::string& why) { response res; res.result(boost::beast::http::status::bad_request); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = why; res.keep_alive(false); res.prepare_payload(); send(res); }; type_function_resp_default bad_request = [](const std::string& why) { response res; res.result(boost::beast::http::status::bad_request); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = why; res.keep_alive(false); res.prepare_payload(); send(res); }; type_function_resp_default not_found = [](const std::string& target) { response res; res.result(boost::beast::http::status::not_found); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = "The resource '" + target + "' was not found."; res.keep_alive(false); res.prepare_payload(); send(res); }; type_function_resp_default server_error = [](const std::string& what) { response res; res.result(boost::beast::http::status::internal_server_error); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = "An error occurred: '" + what + "'"; res.prepare_payload(); res.keep_alive(false); send(res); }; type_function_resp_default redirect_to = [](const std::string& url) { response res; res.result(boost::beast::http::status::temporary_redirect); res.set(field::location, url); send(res); }; std::function<void(const std::vector<std::string>&)> invalid_parameters = [](const std::vector<std::string>& parameters) { std::string erro = "Processing parameters: "; erro += parameters[0]; for(int i=1; i<parameters.size(); i++) erro += ", "+parameters[i]; server_error(erro); }; response &operator <<(response& resp, const std::string &str) { resp.body() += str; return resp; } response &operator <<(response&& resp, const std::string &str) { resp.body() += str; return resp; } response &operator <<(response&& resp, const char* str) { resp.body() += str; return resp; } template<class R> void setHeader(R& res, const std::string &filename, const size_t size, std::time_t lastWrite) { std::stringstream ss; ss << std::put_time(std::gmtime(&lastWrite), "%a, %d %b %Y %T GMT"); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, mime_type(filename)); res.set(boost::beast::http::field::last_modified, ss.str()); // res.set(boost::beast::http::field::cache_control, "public"); res.content_length(size); // res.keep_alive(req.keep_alive()); } void send_file(const std::string &filename) { http_session_i* hs = get_http_session(); const auto& req = hs->request(); // Attempt to open the file boost::beast::error_code ec; boost::beast::http::file_body::value_type body; body.open(filename.c_str(), boost::beast::file_mode::scan, ec); // Handle the case where the file doesn't exist if(ec == boost::system::errc::no_such_file_or_directory) return not_found(to_string(req.method()).to_string()+':'+req.target().to_string()); // Handle an unknown error if(ec) return server_error(ec.message()); // Cache the size since we need it after the move auto const size = body.size(); std::time_t lastWrite = boost::filesystem::last_write_time(filename); // Respond to HEAD request if(req.method() == verb::head) { boost::beast::http::response<boost::beast::http::empty_body> res{boost::beast::http::status::ok, req.version()}; setHeader(res, filename, size, lastWrite); return send(std::move(res)); } // Respond to GET request boost::beast::http::response<boost::beast::http::file_body> res{ std::piecewise_construct, std::make_tuple(std::move(body)), std::make_tuple(boost::beast::http::status::ok, req.version())}; setHeader(res, filename, size, lastWrite); return send(std::move(res)); } boost::beast::string_view mime_type(boost::beast::string_view path) { using boost::beast::iequals; auto const ext = [&path] { auto const pos = path.rfind("."); if(pos == boost::beast::string_view::npos) return boost::beast::string_view{}; return path.substr(pos); }(); if(iequals(ext, ".htm")) return "text/html"; if(iequals(ext, ".html")) return "text/html"; if(iequals(ext, ".php")) return "text/html"; if(iequals(ext, ".css")) return "text/css"; if(iequals(ext, ".txt")) return "text/plain"; if(iequals(ext, ".js")) return "application/javascript"; if(iequals(ext, ".json")) return "application/json"; if(iequals(ext, ".xml")) return "application/xml"; if(iequals(ext, ".swf")) return "application/x-shockwave-flash"; if(iequals(ext, ".flv")) return "video/x-flv"; if(iequals(ext, ".png")) return "image/png"; if(iequals(ext, ".jpe")) return "image/jpeg"; if(iequals(ext, ".jpeg")) return "image/jpeg"; if(iequals(ext, ".jpg")) return "image/jpeg"; if(iequals(ext, ".gif")) return "image/gif"; if(iequals(ext, ".bmp")) return "image/bmp"; if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon"; if(iequals(ext, ".tiff")) return "image/tiff"; if(iequals(ext, ".tif")) return "image/tiff"; if(iequals(ext, ".svg")) return "image/svg+xml"; if(iequals(ext, ".svgz")) return "image/svg+xml"; return "application/text"; } } <commit_msg>consertando codigo de responsta de acesso negado<commit_after>#include "response.h" #include "request.h" #include <boost/filesystem.hpp> #include <iomanip> #include "compress.h" namespace httpserver { using field = boost::beast::http::field; httpserver::response getCompressResponse(const string& str) { using namespace httpserver; const auto& req = httpserver::request(); httpserver::response resp; boost::string_view encoding = req[field::accept_encoding]; if(encoding.find("gzip") != boost::string_view::npos && str.size()>1450){ resp.body() = compress_gzip(str); resp.set(field::content_encoding, "gzip"); }else if(encoding.find("deflate") != boost::string_view::npos && str.size()>1450){ resp.body() = compress_deflate(str); resp.set(field::content_encoding, "deflate"); }else resp.body() = str; return resp; } void compress_and_send(const string &str) { httpserver::response resp = getCompressResponse(str); send(resp); } void ok(const std::string& content) { compress_and_send(content); } void ok(const string &content, const string &type, bool compress) { response res = getCompressResponse(content); res.set(boost::beast::http::field::content_type, type); send(res); } type_function_resp_default created = [](const std::string& local) { response resp; resp.result(status::created); resp.set("Local", local ); send(resp); }; type_function_resp_default accepted = [](const std::string& content) { response resp; resp.result(status::accepted); resp.body() = content; send(resp); }; type_function_resp_default forbidden = [](const std::string& why) { response res; res.result(boost::beast::http::status::forbidden); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = why; res.keep_alive(false); res.prepare_payload(); send(res); }; type_function_resp_default bad_request = [](const std::string& why) { response res; res.result(boost::beast::http::status::bad_request); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = why; res.keep_alive(false); res.prepare_payload(); send(res); }; type_function_resp_default not_found = [](const std::string& target) { response res; res.result(boost::beast::http::status::not_found); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = "The resource '" + target + "' was not found."; res.keep_alive(false); res.prepare_payload(); send(res); }; type_function_resp_default server_error = [](const std::string& what) { response res; res.result(boost::beast::http::status::internal_server_error); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "text/html"); res.body() = "An error occurred: '" + what + "'"; res.prepare_payload(); res.keep_alive(false); send(res); }; type_function_resp_default redirect_to = [](const std::string& url) { response res; res.result(boost::beast::http::status::temporary_redirect); res.set(field::location, url); send(res); }; std::function<void(const std::vector<std::string>&)> invalid_parameters = [](const std::vector<std::string>& parameters) { std::string erro = "Processing parameters: "; erro += parameters[0]; for(int i=1; i<parameters.size(); i++) erro += ", "+parameters[i]; server_error(erro); }; response &operator <<(response& resp, const std::string &str) { resp.body() += str; return resp; } response &operator <<(response&& resp, const std::string &str) { resp.body() += str; return resp; } response &operator <<(response&& resp, const char* str) { resp.body() += str; return resp; } template<class R> void setHeader(R& res, const std::string &filename, const size_t size, std::time_t lastWrite) { std::stringstream ss; ss << std::put_time(std::gmtime(&lastWrite), "%a, %d %b %Y %T GMT"); res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, mime_type(filename)); res.set(boost::beast::http::field::last_modified, ss.str()); // res.set(boost::beast::http::field::cache_control, "public"); res.content_length(size); // res.keep_alive(req.keep_alive()); } void send_file(const std::string &filename) { http_session_i* hs = get_http_session(); const auto& req = hs->request(); // Attempt to open the file boost::beast::error_code ec; boost::beast::http::file_body::value_type body; body.open(filename.c_str(), boost::beast::file_mode::scan, ec); // Handle the case where the file doesn't exist if(ec == boost::system::errc::no_such_file_or_directory) return not_found(to_string(req.method()).to_string()+':'+req.target().to_string()); // Handle an unknown error if(ec) return server_error(ec.message()); // Cache the size since we need it after the move auto const size = body.size(); std::time_t lastWrite = boost::filesystem::last_write_time(filename); // Respond to HEAD request if(req.method() == verb::head) { boost::beast::http::response<boost::beast::http::empty_body> res{boost::beast::http::status::ok, req.version()}; setHeader(res, filename, size, lastWrite); return send(std::move(res)); } // Respond to GET request boost::beast::http::response<boost::beast::http::file_body> res{ std::piecewise_construct, std::make_tuple(std::move(body)), std::make_tuple(boost::beast::http::status::ok, req.version())}; setHeader(res, filename, size, lastWrite); return send(std::move(res)); } boost::beast::string_view mime_type(boost::beast::string_view path) { using boost::beast::iequals; auto const ext = [&path] { auto const pos = path.rfind("."); if(pos == boost::beast::string_view::npos) return boost::beast::string_view{}; return path.substr(pos); }(); if(iequals(ext, ".htm")) return "text/html"; if(iequals(ext, ".html")) return "text/html"; if(iequals(ext, ".php")) return "text/html"; if(iequals(ext, ".css")) return "text/css"; if(iequals(ext, ".txt")) return "text/plain"; if(iequals(ext, ".js")) return "application/javascript"; if(iequals(ext, ".json")) return "application/json"; if(iequals(ext, ".xml")) return "application/xml"; if(iequals(ext, ".swf")) return "application/x-shockwave-flash"; if(iequals(ext, ".flv")) return "video/x-flv"; if(iequals(ext, ".png")) return "image/png"; if(iequals(ext, ".jpe")) return "image/jpeg"; if(iequals(ext, ".jpeg")) return "image/jpeg"; if(iequals(ext, ".jpg")) return "image/jpeg"; if(iequals(ext, ".gif")) return "image/gif"; if(iequals(ext, ".bmp")) return "image/bmp"; if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon"; if(iequals(ext, ".tiff")) return "image/tiff"; if(iequals(ext, ".tif")) return "image/tiff"; if(iequals(ext, ".svg")) return "image/svg+xml"; if(iequals(ext, ".svgz")) return "image/svg+xml"; return "application/text"; } } <|endoftext|>
<commit_before>#include <iostream> #include <sys/time.h> #include <unistd.h> using namespace std; void g(int times) { cout << times << ": I'm fucking g.." << endl; } static const int TIMES = 5; static int times = TIMES; static int64_t start = 0; bool visit_card = true; static int64_t last_visit = 0; void f() { struct timeval tv; if (times == TIMES) { gettimeofday(&tv, NULL); start = tv.tv_sec; //cout << last_visit << " " << start << endl; if (start - last_visit < 1) { return; } else { visit_card = true; } } if (visit_card) { g(times--); } if (times == 0) { times = TIMES; gettimeofday(&tv, NULL); int64_t end = tv.tv_sec; //cout << end << " " << start << endl; if (end - start <= 1) { cout << ">>> you visit g() too much!!! visit after 1 second " << endl; visit_card = false; last_visit = end; } } } int main() { for (int i = 0; i < 10; i++) { f(); } sleep(1); for (int i = 0; i < 10; i++) { f(); } return 0; } <commit_msg>add description in visit_control.cc<commit_after>// A small wrapper to control the visit of g(), limit to 5 times in // one second #include <iostream> #include <sys/time.h> #include <unistd.h> using namespace std; void g(int times) { cout << times << ": I'm fucking g.." << endl; } static const int TIMES = 5; static int times = TIMES; static int64_t start = 0; bool visit_card = true; static int64_t last_visit = 0; void f() { struct timeval tv; if (times == TIMES) { gettimeofday(&tv, NULL); start = tv.tv_sec; //cout << last_visit << " " << start << endl; if (start - last_visit < 1) { return; } else { visit_card = true; } } if (visit_card) { g(times--); } if (times == 0) { times = TIMES; gettimeofday(&tv, NULL); int64_t end = tv.tv_sec; //cout << end << " " << start << endl; if (end - start <= 1) { cout << ">>> you visit g() too much!!! visit after 1 second " << endl; visit_card = false; last_visit = end; } } } int main() { for (int i = 0; i < 10; i++) { f(); } sleep(1); for (int i = 0; i < 10; i++) { f(); } return 0; } <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "se_parser_redmine.h" #include "miscutil.h" #include "urlmatch.h" #include <strings.h> #include <iostream> using sp::miscutil; using sp::urlmatch; namespace seeks_plugins { se_parser_redmine::se_parser_redmine(const std::string &url) :se_parser(url),_results_flag(false),_date_flag(false),_title_flag(false),_summary_flag(false) { urlmatch::parse_url_host_and_path(url,_host,_path); } se_parser_redmine::~se_parser_redmine() { } void se_parser_redmine::start_element(parser_context *pc, const xmlChar *name, const xmlChar **attributes) { const char *tag = (const char*)name; if (strcasecmp(tag,"dl")==0) { const char *a_id = se_parser::get_attribute((const char**)attributes,"id"); if (a_id && strcasecmp(a_id,"search-results")==0) _results_flag = true; } else if (_results_flag && strcasecmp(tag,"dt") == 0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); // create new snippet. search_snippet *sp = new search_snippet(_count + 1); _count++; sp->_engine = feeds("redmine",_url); if (a_class) { if (strcasecmp(a_class,"changeset")==0) sp->_doc_type = REVISION; else if (strcasecmp(a_class,"issue")==0) sp->_doc_type = ISSUE; } pc->_current_snippet = sp; pc->_snippets->push_back(pc->_current_snippet); } else if (_results_flag && strcasecmp(tag,"a")==0) { const char *a_href = se_parser::get_attribute((const char**)attributes,"href"); if (a_href) { pc->_current_snippet->set_url(_host + std::string(a_href)); _title_flag = true; } } else if (_results_flag && strcasecmp(tag,"span")==0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); if (a_class) { if (strcasecmp(a_class,"description")==0) _summary_flag = true; else if (strcasecmp(a_class,"author")==0) _date_flag = true; } } } void se_parser_redmine::characters(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_redmine::cdata(parser_context *pc, const xmlChar *chars, int length) { //handle_characters(pc, chars, length); } void se_parser_redmine::handle_characters(parser_context *pc, const xmlChar *chars, int length) { if (_title_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); miscutil::replace_in_string(a_chars,"-"," "); //miscutil::replace_in_string(a_chars,"<span class=\"highlight token-0\">",""); //miscutil::replace_in_string(a_chars,"</span>",""); _title += a_chars; } else if (!_date_flag && _summary_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); miscutil::replace_in_string(a_chars,"-"," "); //miscutil::replace_in_string(a_chars,"<span class=\"highlight token-0\">",""); //miscutil::replace_in_string(a_chars,"</span>",""); _summary += a_chars; } else if (_date_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); miscutil::replace_in_string(a_chars,"-"," "); _date += a_chars; } } void se_parser_redmine::end_element(parser_context *pc, const xmlChar *name) { const char *tag = (const char*) name; if (_results_flag && strcasecmp(tag,"dl")==0) _results_flag = false; else if (_title_flag && strcasecmp(tag,"a")==0) { _title_flag = false; pc->_current_snippet->set_title(_title); _title = ""; } else if (_summary_flag && strcasecmp(tag,"dd")==0) { _summary_flag = false; _date_flag = false; pc->_current_snippet->set_summary(miscutil::chomp_cpp(_summary)); pc->_current_snippet->set_date(miscutil::chomp_cpp(_date)); _summary = ""; _date = ""; } } } /* end of namespace. */ <commit_msg>fix to redmine parser. refs #555<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "se_parser_redmine.h" #include "miscutil.h" #include "urlmatch.h" #include <strings.h> #include <iostream> using sp::miscutil; using sp::urlmatch; namespace seeks_plugins { se_parser_redmine::se_parser_redmine(const std::string &url) :se_parser(url),_results_flag(false),_date_flag(false),_title_flag(false),_summary_flag(false) { urlmatch::parse_url_host_and_path(url,_host,_path); } se_parser_redmine::~se_parser_redmine() { } void se_parser_redmine::start_element(parser_context *pc, const xmlChar *name, const xmlChar **attributes) { const char *tag = (const char*)name; if (strcasecmp(tag,"dl")==0) { const char *a_id = se_parser::get_attribute((const char**)attributes,"id"); if (a_id && strcasecmp(a_id,"search-results")==0) _results_flag = true; } else if (_results_flag && strcasecmp(tag,"dt") == 0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); // create new snippet. search_snippet *sp = new search_snippet(_count + 1); _count++; sp->_engine = feeds("redmine",_url); if (a_class) { if (strcasecmp(a_class,"changeset")==0) sp->_doc_type = REVISION; else if (strncasecmp(a_class,"issue",5)==0) sp->_doc_type = ISSUE; } pc->_current_snippet = sp; pc->_snippets->push_back(pc->_current_snippet); } else if (_results_flag && strcasecmp(tag,"a")==0) { const char *a_href = se_parser::get_attribute((const char**)attributes,"href"); if (a_href) { pc->_current_snippet->set_url(_host + std::string(a_href)); _title_flag = true; } } else if (_results_flag && strcasecmp(tag,"span")==0) { const char *a_class = se_parser::get_attribute((const char**)attributes,"class"); if (a_class) { if (strcasecmp(a_class,"description")==0) _summary_flag = true; else if (strcasecmp(a_class,"author")==0) _date_flag = true; } } } void se_parser_redmine::characters(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_redmine::cdata(parser_context *pc, const xmlChar *chars, int length) { //handle_characters(pc, chars, length); } void se_parser_redmine::handle_characters(parser_context *pc, const xmlChar *chars, int length) { if (_title_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); miscutil::replace_in_string(a_chars,"-"," "); //miscutil::replace_in_string(a_chars,"<span class=\"highlight token-0\">",""); //miscutil::replace_in_string(a_chars,"</span>",""); _title += a_chars; } else if (!_date_flag && _summary_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); miscutil::replace_in_string(a_chars,"-"," "); //miscutil::replace_in_string(a_chars,"<span class=\"highlight token-0\">",""); //miscutil::replace_in_string(a_chars,"</span>",""); _summary += a_chars; } else if (_date_flag) { std::string a_chars = std::string((char*)chars); miscutil::replace_in_string(a_chars,"\n"," "); miscutil::replace_in_string(a_chars,"\r"," "); miscutil::replace_in_string(a_chars,"-"," "); _date += a_chars; } } void se_parser_redmine::end_element(parser_context *pc, const xmlChar *name) { const char *tag = (const char*) name; if (_results_flag && strcasecmp(tag,"dl")==0) _results_flag = false; else if (_title_flag && strcasecmp(tag,"a")==0) { _title_flag = false; pc->_current_snippet->set_title(_title); _title = ""; } else if (_summary_flag && strcasecmp(tag,"dd")==0) { _summary_flag = false; _date_flag = false; pc->_current_snippet->set_summary(miscutil::chomp_cpp(_summary)); pc->_current_snippet->set_date(miscutil::chomp_cpp(_date)); _summary = ""; _date = ""; } } } /* end of namespace. */ <|endoftext|>