TEST(state, capsule_carries_its_own_watchers) { auto sig = std::shared_ptr<detail::state_up_down_signal<int>>{}; auto s = testing::spy(); { auto st = make_state(42); sig = detail::access::signal(st); watch(st, s); sig->push_down(12); sig->send_down(); sig->notify(); EXPECT_EQ(1, s.count()); } sig->push_down(7); sig->send_down(); sig->notify(); EXPECT_EQ(1, s.count()); EXPECT_TRUE(sig->observers().empty()); }
void test(BCollator *collator, const char *name, int8 strength) { collator->SetDefaultStrength(strength); BStopWatch watch(name, true); for (uint32 j = 0; j < kIterations; j++) { for (uint32 i = 0; i < kNumStrings; i++) { BString key; collator->GetSortKey(kStrings[i], &key); } } watch.Suspend(); double secs = watch.ElapsedTime() / 1000000.0; printf("\t%s%9Ld usecs, %6.3g secs,%9lu keys/s\n", name, watch.ElapsedTime(), secs, uint32(kIterations * kNumStrings / secs)); }
ConsumerStateTable::ConsumerStateTable(DBConnector *db, std::string tableName) : RedisTransactioner(db) , TableName_KeySet(tableName) , POP_BATCH_SIZE(128) { for (;;) { RedisReply watch(m_db, "WATCH " + getKeySetName(), REDIS_REPLY_STATUS); watch.checkStatusOK(); multi(); enqueue(std::string("SCARD ") + getKeySetName(), REDIS_REPLY_INTEGER); subscribe(m_db, getChannelName()); bool succ = exec(); if (succ) break; } RedisReply r(dequeueReply()); setQueueLength(r.getReply<long long int>()); }
void CommandLineInterface::mainMenu() { while (true) { std::cout << "\n"; std::cout << "Type a command (type 'help' or 'h' for help)" << std::endl; std::cout << "\n"; std::cout << "> "; std::string input; std::getline(std::cin, input); std::vector<std::string> args = string_utils::split(input); if (args.empty()) { std::cout << "Invalid input." << std::endl; } else { std::string command = args[0]; args.erase(args.begin()); clearScreen(); if (command == "create") { createEntities(args); } else if (command == "remove" || command == "delete") { removeEntities(args); } else if (command == "list" || command == "l") { listEntities(args); } else if (command == "setq") { setQueue(args); } else if (command == "unsetq") { unsetQueue(args); } else if (command == "start") { startQueueHandler(args); } else if (command == "stop") { stopQueueHandler(args); } else if (command == "watch" || command == "w") { watch(); } else if (command == "help" || command == "h") { showHelp(); } else if (command == "quit" || command == "q") { std::cout << "Bye." << std::endl; break; } else { std::cout << "Sorry. Command not recognized." << std::endl; } } } }
main(int argc, char **argv) { int port; char txt[2048], buf[83]; FILE *fl; if (argc != 3) { fputs("Usage: sign (<filename> | - ) <port #>\n", stderr); exit(); } if (!strcmp(argv[1], "-")) { fl = stdin; puts("Input text (terminate with ^D)"); } else if (!(fl = fopen(argv[1], "r"))) { perror(argv[1]); exit(); } for (;;) { fgets(buf, 81, fl); if (feof(fl)) break; strcat(buf, ""); if (strlen(buf) + strlen(txt) > 2048) { fputs("String too long\n", stderr); exit(); } strcat(txt, buf); } if ((port = atoi(argv[2])) <= 1024) { fputs("Illegal port #\n", stderr); exit(); } watch(port, txt); }
status_t ServerIconExportUpdateProcess::_Unpack(BPath& tarGzFilePath) { status_t result; printf("[%s] delete any existing stored data\n", Name()); StorageUtils::RemoveDirectoryContents(fLocalIconStoragePath); BFile *tarGzFile = new BFile(tarGzFilePath.Path(), O_RDONLY); BDataIO* tarIn; BZlibDecompressionParameters* zlibDecompressionParameters = new BZlibDecompressionParameters(); result = BZlibCompressionAlgorithm() .CreateDecompressingInputStream(tarGzFile, zlibDecompressionParameters, tarIn); if (result == B_OK) { BStopWatch watch( "ServerIconExportUpdateProcess::DownloadAndUnpack_Unpack", true); result = TarArchiveService::Unpack(*tarIn, fLocalIconStoragePath, NULL); if (result == B_OK) { double secs = watch.ElapsedTime() / 1000000.0; printf("[%s] did unpack icon tgz in (%6.3g secs)\n", Name(), secs); if (0 != remove(tarGzFilePath.Path())) { printf("unable to delete the temporary tgz path; %s\n", tarGzFilePath.Path()); } } } delete tarGzFile; printf("[%s] did complete unpacking icons\n", Name()); return result; }
void peano::applications::faxen::repositories::FaxenBatchJobRepositoryForSpacetreeGridArrayStackImplementation::iterate() { tarch::utils::Watch watch( "peano::applications::faxen::repositories::FaxenBatchJobRepositoryForSpacetreeGridArrayStackImplementation", "iterate()", false); #ifdef Parallel if (tarch::parallel::Node::getInstance().isMasterProcess()) { tarch::parallel::NodePool::getInstance().broadcastToWorkingNodes( _repositoryState, peano::kernel::parallel::SendReceiveBufferPool::getInstance().getIterationManagementTag() ); } #endif peano::kernel::datatraversal::autotuning::Oracle::getInstance().switchToOracle(_repositoryState.getAction()); switch ( _repositoryState.getAction()) { case FaxenBatchJobRepositoryState::UseAdapterInitialize: watch.startTimer(); _gridWithInitialize.iterate(_solverState); watch.stopTimer(); _countInitializeRuns++; _measureInitializeCPUTime += watch.getCPUTime(); _measureInitializeCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterInitializeAndSetBoundary: watch.startTimer(); _gridWithInitializeAndSetBoundary.iterate(_solverState); watch.stopTimer(); _countInitializeAndSetBoundaryRuns++; _measureInitializeAndSetBoundaryCPUTime += watch.getCPUTime(); _measureInitializeAndSetBoundaryCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterPlotGrid: watch.startTimer(); _gridWithPlotGrid.iterate(_solverState); watch.stopTimer(); _countPlotGridRuns++; _measurePlotGridCPUTime += watch.getCPUTime(); _measurePlotGridCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterControlTimeStep: watch.startTimer(); _gridWithControlTimeStep.iterate(_solverState); watch.stopTimer(); _countControlTimeStepRuns++; _measureControlTimeStepCPUTime += watch.getCPUTime(); _measureControlTimeStepCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterSetVelocitiesBoundary: watch.startTimer(); _gridWithSetVelocitiesBoundary.iterate(_solverState); watch.stopTimer(); _countSetVelocitiesBoundaryRuns++; _measureSetVelocitiesBoundaryCPUTime += watch.getCPUTime(); _measureSetVelocitiesBoundaryCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterSetScenarioBoundary: watch.startTimer(); _gridWithSetScenarioBoundary.iterate(_solverState); watch.stopTimer(); _countSetScenarioBoundaryRuns++; _measureSetScenarioBoundaryCPUTime += watch.getCPUTime(); _measureSetScenarioBoundaryCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterComputeVelocitiesDerivatives: watch.startTimer(); _gridWithComputeVelocitiesDerivatives.iterate(_solverState); watch.stopTimer(); _countComputeVelocitiesDerivativesRuns++; _measureComputeVelocitiesDerivativesCPUTime += watch.getCPUTime(); _measureComputeVelocitiesDerivativesCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterComputeRightHandSide: watch.startTimer(); _gridWithComputeRightHandSide.iterate(_solverState); watch.stopTimer(); _countComputeRightHandSideRuns++; _measureComputeRightHandSideCPUTime += watch.getCPUTime(); _measureComputeRightHandSideCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterSetZeroPressureBoundary: watch.startTimer(); _gridWithSetZeroPressureBoundary.iterate(_solverState); watch.stopTimer(); _countSetZeroPressureBoundaryRuns++; _measureSetZeroPressureBoundaryCPUTime += watch.getCPUTime(); _measureSetZeroPressureBoundaryCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterSetPressureBoundary: watch.startTimer(); _gridWithSetPressureBoundary.iterate(_solverState); watch.stopTimer(); _countSetPressureBoundaryRuns++; _measureSetPressureBoundaryCPUTime += watch.getCPUTime(); _measureSetPressureBoundaryCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterSORStep: watch.startTimer(); _gridWithSORStep.iterate(_solverState); watch.stopTimer(); _countSORStepRuns++; _measureSORStepCPUTime += watch.getCPUTime(); _measureSORStepCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterComputeResidualNorm: watch.startTimer(); _gridWithComputeResidualNorm.iterate(_solverState); watch.stopTimer(); _countComputeResidualNormRuns++; _measureComputeResidualNormCPUTime += watch.getCPUTime(); _measureComputeResidualNormCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterComputeVelocities: watch.startTimer(); _gridWithComputeVelocities.iterate(_solverState); watch.stopTimer(); _countComputeVelocitiesRuns++; _measureComputeVelocitiesCPUTime += watch.getCPUTime(); _measureComputeVelocitiesCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::UseAdapterPlotSolution: watch.startTimer(); _gridWithPlotSolution.iterate(_solverState); watch.stopTimer(); _countPlotSolutionRuns++; _measurePlotSolutionCPUTime += watch.getCPUTime(); _measurePlotSolutionCalendarTime += watch.getCalendarTime(); break; case FaxenBatchJobRepositoryState::Terminate: assertionMsg( false, "this branch/state should never be reached" ); break; case FaxenBatchJobRepositoryState::ReadCheckpoint: assertionMsg( false, "not implemented yet" ); break; case FaxenBatchJobRepositoryState::WriteCheckpoint: assertionMsg( false, "not implemented yet" ); break; } }
string tm_link_rep::read_packet (int channel, int timeout, bool& success) { success= false; string& r= watch (channel); time_t start= texmacs_time (); while (!message_complete (r)) { int n= N(r); if (timeout > 0) listen (timeout); if (N(r) == n && (texmacs_time () - start >= timeout)) return ""; } if (channel == LINK_OUT && N(r) > 0 && r[0] == '!') { secure_server (message_receive (r)); return ""; } else { string back= message_receive (r); if (secret != "") back= secret_decode (back, secret); success= true; return back; } }
int main(void) { int ifd; /* Init */ #ifndef CONFIG_DEBUG openlog("gadged", LOG_CONS | LOG_NDELAY | LOG_PID, LOG_DAEMON); #else openlog("gadged", LOG_PERROR, LOG_DAEMON); #endif if ((ifd = inotify_init()) < 0) die("inotify_init()"); signal(SIGCHLD, SIG_IGN); /* Run */ for (;;) { int wd; FILE *klog; /* Try until we can open $klog. */ while (!(klog = fopen(KLOG, "r"))) { syslog(LOG_WARNING, KLOG": %m"); sleep(10); } if (fseek(klog, 0, SEEK_END) < 0) die("seek("KLOG")"); else if ((wd = inotify_add_watch(ifd, KLOG, IN_MODIFY|IN_MOVE_SELF|IN_DELETE_SELF|IN_ATTRIB)) < 0) die("inotify_add_watch("KLOG")"); watch(ifd, klog); inotify_rm_watch(ifd, wd); fclose(klog); } /* for ever */ return 0; }
bool wxFileSystemWatcherBase::Add(const wxFileName& path, int events) { // args validation & consistency checks if (!path.FileExists() && !path.DirExists()) return false; wxString canonical = GetCanonicalPath(path); if (canonical.IsEmpty()) return false; wxCHECK_MSG(m_watches.find(canonical) == m_watches.end(), false, wxString::Format("Path '%s' is already watched", canonical)); // adding a path in a platform specific way wxFSWatchInfo watch(canonical, events); if ( !m_service->Add(watch) ) return false; // on success, add path to our 'watch-list' wxFSWatchInfoMap::value_type val(canonical, watch); return m_watches.insert(val).second; }
void ThresholdManipulator::start_threads() { BStopWatch watch("thresholding time"); system_info info; get_system_info(&info); number_of_threads = info.cpu_count; thread_id *threads = new thread_id[number_of_threads]; for (int32 i=0;i<number_of_threads;i++) { threads[i] = spawn_thread(thread_entry,"threshold_thread",B_NORMAL_PRIORITY,this); resume_thread(threads[i]); send_data(threads[i],i,NULL,0); } for (int32 i=0;i<number_of_threads;i++) { int32 return_value; wait_for_thread(threads[i],&return_value); } delete[] threads; }
// Set some watchers so we can monitorize dirs, files etc. void On::setWatchers() { // Set JSON watcher Inotify notify; InotifyWatch watch("/var/local/asturix/launcherjsonview.json", IN_CLOSE_WRITE); notify.Add(watch); for (;;) { notify.WaitForEvents(); size_t count = notify.GetEventCount(); while (count > 0) { InotifyEvent event; bool got_event = notify.GetEvent(&event); if (got_event) { QMetaObject::invokeMethod(this,"appsChanged",Qt::QueuedConnection); } count--; } } DConfClient *dConfWallpaper = dconf_client_new(NULL, iconThemeChanged, NULL, NULL); dconf_client_watch(dConfWallpaper, "/org/gnome/desktop/interface/icon-theme", NULL, NULL); }
EventManager::EventCB ClientServer::to_callbacks(Protocol& proto) { return EventManager::EventCB{ { EventType::READ, EventManager::CB([&proto, this] (int fd) mutable { while (true) { auto client = accept(fd, nullptr, nullptr); if (client == -1) { //cout << "[accept] end pid=" + to_string(Utils::getpid()) << endl; return; } proto.on_connect(client); watch(client, EventManager::EventCB{ { EventType::READ, initial_message_wrapper( [&proto] (int client, string message) mutable { proto.on_message(client, message); } ), }, { EventType::CLOSE, EventManager::CB([&proto] (int client) { proto.on_close(client); }) } }); } }) } }; }
void CatalogSpeed::TestIdCreation() { BStopWatch watch("catalogSpeed", true); watch.Suspend(); status_t res; BString s("string"); s << "\x01" << typeid(*this).name() << "\x01"; //size_t hashVal = __stl_hash_string(s.String()); assert(be_locale != NULL); system("mkdir -p ./locale/catalogs/"catSig); // create an empty catalog of default type... BPrivate::EditableCatalog cat1("Default", catSig, "klingon"); assert(cat1.InitCheck() == B_OK); // ...and populate the catalog with some data: for (uint32 i = 0; i < kNumStrings; i++) { trls[i] = BString("id_translation#") << 6000000+i; } watch.Reset(); watch.Resume(); for (uint32 i = 0; i < kNumStrings; i++) { cat1.SetString(i, trls[i].String()); } watch.Suspend(); printf("\tadded %ld strings by id in %9Ld usecs\n", cat1.CountItems(), watch.ElapsedTime()); watch.Reset(); watch.Resume(); res = cat1.WriteToFile("./locale/catalogs/"catSig"/klingon.catalog"); assert( res == B_OK); watch.Suspend(); printf("\t%ld strings written to disk in %9Ld usecs\n", cat1.CountItems(), watch.ElapsedTime()); }
void FileManager::onFileAdded(const Path &path) { bool emitJS = false; { std::lock_guard<std::mutex> lock(mMutex); if (path.isEmpty()) { error("Got empty file added here"); return; } const Filter::Result res = Filter::filter(path); switch (res) { case Filter::Directory: reload(Asynchronous); return; case Filter::Filtered: return; default: break; } std::shared_ptr<Project> project = mProject.lock(); assert(project); FilesMap &map = project->files(); const Path parent = path.parentDir(); if (!parent.isEmpty()) { Set<String> &dir = map[parent]; if (dir.isEmpty()) watch(parent); dir.insert(path.fileName()); emitJS = path.endsWith(".js"); } else { error() << "Got empty parent here" << path; } assert(!map.contains(Path())); } if (emitJS) mJSFilesChanged(); }
void peano::applications::navierstokes::prototype1::repositories::PrototypeRepositoryForRegularGridStandardImplementation::iterate(bool reduceState) { tarch::utils::Watch watch( "peano::applications::navierstokes::prototype1::repositories::PrototypeRepositoryForRegularGridStandardImplementation", "iterate(int, bool)", false); _repositoryState.setReduceState(reduceState); #ifdef Parallel if (tarch::parallel::Node::getInstance().isMasterProcess()) { tarch::parallel::NodePool::getInstance().broadcastToWorkingNodes( _repositoryState, peano::kernel::parallel::SendReceiveBufferPool::getInstance().getIterationManagementTag() ); } #endif peano::kernel::datatraversal::autotuning::Oracle::getInstance().switchToOracle(_repositoryState.getAction()); switch ( _repositoryState.getAction()) { case PrototypeRepositoryState::UseAdapterInitialiseScenario: watch.startTimer(); _gridWithInitialiseScenario.iterate(reduceState); watch.stopTimer(); _countInitialiseScenarioRuns++; _measureInitialiseScenarioCPUTime += watch.getCPUTime(); _measureInitialiseScenarioCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterMergeA: watch.startTimer(); _gridWithMergeA.iterate(reduceState); watch.stopTimer(); _countMergeARuns++; _measureMergeACPUTime += watch.getCPUTime(); _measureMergeACalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterCalculateF: watch.startTimer(); _gridWithCalculateF.iterate(reduceState); watch.stopTimer(); _countCalculateFRuns++; _measureCalculateFCPUTime += watch.getCPUTime(); _measureCalculateFCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterCalculatePPERHS: watch.startTimer(); _gridWithCalculatePPERHS.iterate(reduceState); watch.stopTimer(); _countCalculatePPERHSRuns++; _measureCalculatePPERHSCPUTime += watch.getCPUTime(); _measureCalculatePPERHSCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterGaussSeidelForEnhancedDivFree: watch.startTimer(); _gridWithGaussSeidelForEnhancedDivFree.iterate(reduceState); watch.stopTimer(); _countGaussSeidelForEnhancedDivFreeRuns++; _measureGaussSeidelForEnhancedDivFreeCPUTime += watch.getCPUTime(); _measureGaussSeidelForEnhancedDivFreeCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterUpdateVelocity: watch.startTimer(); _gridWithUpdateVelocity.iterate(reduceState); watch.stopTimer(); _countUpdateVelocityRuns++; _measureUpdateVelocityCPUTime += watch.getCPUTime(); _measureUpdateVelocityCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterPlotSolutionVTK: watch.startTimer(); _gridWithPlotSolutionVTK.iterate(reduceState); watch.stopTimer(); _countPlotSolutionVTKRuns++; _measurePlotSolutionVTKCPUTime += watch.getCPUTime(); _measurePlotSolutionVTKCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterPlotRegularSolutionVTK: watch.startTimer(); _gridWithPlotRegularSolutionVTK.iterate(reduceState); watch.stopTimer(); _countPlotRegularSolutionVTKRuns++; _measurePlotRegularSolutionVTKCPUTime += watch.getCPUTime(); _measurePlotRegularSolutionVTKCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::UseAdapterUpdateScenario: watch.startTimer(); _gridWithUpdateScenario.iterate(reduceState); watch.stopTimer(); _countUpdateScenarioRuns++; _measureUpdateScenarioCPUTime += watch.getCPUTime(); _measureUpdateScenarioCalendarTime += watch.getCalendarTime(); break; case PrototypeRepositoryState::Terminate: assertionMsg( false, "this branch/state should never be reached" ); break; case PrototypeRepositoryState::ReadCheckpoint: assertionMsg( false, "not implemented yet" ); break; case PrototypeRepositoryState::WriteCheckpoint: assertionMsg( false, "not implemented yet" ); break; } }
void CmdPrint::setClientOutput(DebuggerClient &client) { client.setOutputType(DebuggerClient::OTValues); Array values; if (m_isForWatch) { // Manipulating the watch list, output the current list DebuggerClient::WatchPtrVec &watches = client.getWatches(); for (int i = 0; i < (int)watches.size(); i++) { ArrayInit watch(2); watch.set(s_format, watches[i]->first); watch.set(s_php, watches[i]->second); values.append(watch.create()); } } else { // Just print an expression, do similar output as eval values.set(s_body, m_body); if (client.getDebuggerClientApiModeSerialize()) { values.set(s_value_serialize, DebuggerClient::FormatVariable(m_ret, 200)); } else { values.set(s_value, m_ret); } } client.setOTValues(values); }
/** * MAIN */ int main(int argc, char *argv[]) { /* bind the signal handler */ signal(SIGINT, (void*)signal_callback_handler); if (parse_command_line(argc, argv) == 0) { /* File descriptor inotify */ fd = inotify_init(); /* List of all watch directories */ list_wd = list_init(); /* Watch the path */ if (watch(root_path, NULL) == -1) { printf("An error occured while adding \"%s\" as watched resource!\n", root_path); return EXIT_FAILURE; } /* Start monitoring */ return monitor(); } return EXIT_SUCCESS; }
void CatalogSpeed::TestLookup() { BStopWatch watch("catalogSpeed", true); BCatalog *cat = be_catalog = new BCatalog(catSig, "klingon"); assert(cat != NULL); assert(cat->InitCheck() == B_OK); watch.Suspend(); printf("\t%ld strings read from disk in %9Ld usecs\n", cat->CountItems(), watch.ElapsedTime()); watch.Reset(); watch.Resume(); for (uint32 i = 0; i < kNumStrings; i++) { translated = TR(strs[i].String()); } watch.Suspend(); printf("\tlooked up %lu strings in %9Ld usecs\n", kNumStrings, watch.ElapsedTime()); delete cat; }
/** * Tell the observer to watch the given folder. * Then, the observer will process all the rules * * @param string path the path to be watched * @param vector<Rule> the list of rules to be checked */ void Observer::observe(string path, vector<Rule*> rules){ this->_observing[path] = true; try { Inotify notify; InotifyWatch watch(path, IN_CREATE); notify.Add(watch); cout << "Start observing for changes in " << path << endl; while (this->_observing[path]) { notify.WaitForEvents(); size_t count = notify.GetEventCount(); while (count > 0) { InotifyEvent event; bool got_event = notify.GetEvent(&event); if (got_event) { string mask_str; event.DumpTypes(mask_str); string filename = event.GetName(); this->run_rules(rules, path + '/' + filename, mask_str); } count--; } } } catch (InotifyException &e) { cerr << "Inotify exception occured: " << e.GetMessage() << endl; } catch (exception &e) { cerr << "STL exception occured: " << e.what() << endl; } catch (...) { cerr << "unknown exception occured" << endl; } }
backlight_module::backlight_module(const bar_settings& bar, string name_) : inotify_module<backlight_module>(bar, move(name_)) { auto card = m_conf.get(name(), "card"); // Add formats and elements m_formatter->add(DEFAULT_FORMAT, TAG_LABEL, {TAG_LABEL, TAG_BAR, TAG_RAMP}); if (m_formatter->has(TAG_LABEL)) { m_label = load_optional_label(m_conf, name(), TAG_LABEL, "%percentage%%"); } if (m_formatter->has(TAG_BAR)) { m_progressbar = load_progressbar(m_bar, m_conf, name(), TAG_BAR); } if (m_formatter->has(TAG_RAMP)) { m_ramp = load_ramp(m_conf, name(), TAG_RAMP); } // Build path to the file where the current/maximum brightness value is located m_val.filepath(string_util::replace(PATH_BACKLIGHT_VAL, "%card%", card)); m_max.filepath(string_util::replace(PATH_BACKLIGHT_MAX, "%card%", card)); // Add inotify watch watch(string_util::replace(PATH_BACKLIGHT_VAL, "%card%", card)); }
int main(int argc, char** argv) { errno = 0; try { auto do_lint = false; auto split_by_track = false; auto clear_workouts = false; int debug_level = 0; std::string from_image; std::string to_image; std::string device_fn; std::string output_fn; std::string epo_fn; opterr = 0; while (1) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'f'}, {"epo", required_argument, 0, 'e'}, {"clear", no_argument, 0, 'c'}, {"device", required_argument, 0, 'd'}, {"from_image", required_argument, 0, 'i'}, {"to_image", required_argument, 0, 't'}, {"split", no_argument, 0, 's'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'w'}, {"lint", no_argument, 0, 'l'}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long(argc, argv, "h", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': std::cerr << PACKAGE_STRING "\n" "crane_gps_watch_client --help\n" "\n" "crane_gps_watch_client [--clear] [--epo epo-filename] [--output output-filename | --split] [--device auto | --from_image image-file] [--to_image image-file] [--verbose]\n" "\n" "See README.md or https://github.com/mru00/crane_gps_watch for details\n" "Send bugreports to " PACKAGE_BUGREPORT << std::endl; exit (0); case 'w': std::cerr << PACKAGE_STRING << std::endl; exit (0); case 'd': if (!from_image.empty()) { throw std::runtime_error("cannot use --device and --from_image at the same time"); } device_fn = optarg; break; case 'c': clear_workouts = true; break; case 'e': epo_fn = optarg; break; case 's': if (!output_fn.empty()) { throw std::runtime_error("cannot use --output and --split at the same time"); } split_by_track = true; break; case 'f': if (split_by_track) { throw std::runtime_error("cannot use --output and --split at the same time"); } output_fn = optarg; break; case 'i': if (!device_fn.empty()) { throw std::runtime_error("cannot use --device and --from_image at the same time"); } from_image = optarg; break; case 't': to_image = optarg; break; case 'v': debug_level++; break; case 'l': do_lint = true; break; default: std::cerr << "unknown option" << std::endl; exit(1); } } if (device_fn.empty()) { device_fn = "auto"; } if (output_fn.empty()) { output_fn = format_date_filename() + ".tcx"; } std::shared_ptr<DeviceInterface> device; if (from_image.empty()) { if (device_fn == "auto") { device = scan_serial_ports(); if (!device) { throw std::runtime_error("Failed to auto-detect serial port. Please check connection and access rights; consider using the '--device' option to skip autodetect and specify the serial port manually."); } } else { device = std::make_shared<SerialLink>(device_fn); } } else { device = std::make_shared<ImageLink>(from_image); } Watch watch(device); watch.addRecipient(std::make_shared<TcxWriter>(output_fn, split_by_track)); if (!to_image.empty()) { watch.addRecipient(std::make_shared<ImageWriter>(to_image)); } watch.addRecipient(std::make_shared<DebugWriter>(debug_level)); if (do_lint) { watch.addRecipient(std::make_shared<GpsLint>()); } watch.parse(); if (clear_workouts) { std::cerr << "clearing watch data" << std::endl; watch.clearWorkouts(); std::cerr << "clearing watch data: done" << std::endl; } if (! epo_fn.empty() ) { std::cerr << "downloading EPO data" << std::endl; watch.downloadEPO(epo_fn); std::cerr << "downloading EPO data: done" << std::endl; } return 0; } catch(const std::runtime_error& error) { std::cerr << "error: " << error.what() << std::endl << "Terminating" << std::endl; return 1; } catch(const std::ifstream::failure& error) { std::cerr << "error: " << error.what() << std::endl << "Terminating" << std::endl; return 1; } }
void ForEachBaselineAction::ReaderFunction::operator()() { Stopwatch watch(true); bool finished = false; size_t threadCount = _action.mathThreadCount(); size_t minRecommendedBufferSize, maxRecommendedBufferSize; MSImageSet *msImageSet = dynamic_cast<MSImageSet*>(_action._artifacts->ImageSet()); if(msImageSet != 0) { minRecommendedBufferSize = msImageSet->Reader()->GetMinRecommendedBufferSize(threadCount); maxRecommendedBufferSize = msImageSet->Reader()->GetMaxRecommendedBufferSize(threadCount) - _action.GetBaselinesInBufferCount(); } else { minRecommendedBufferSize = 1; maxRecommendedBufferSize = 2; } do { watch.Pause(); _action.WaitForBufferAvailable(minRecommendedBufferSize); size_t wantedCount = maxRecommendedBufferSize - _action.GetBaselinesInBufferCount(); size_t requestedCount = 0; boost::mutex::scoped_lock lock(_action._artifacts->IOMutex()); watch.Start(); for(size_t i=0;i<wantedCount;++i) { ImageSetIndex *index = _action.GetNextIndex(); if(index != 0) { _action._artifacts->ImageSet()->AddReadRequest(*index); ++requestedCount; delete index; } else { finished = true; break; } } if(requestedCount > 0) { _action._artifacts->ImageSet()->PerformReadRequests(); watch.Pause(); for(size_t i=0;i<requestedCount;++i) { BaselineData *baseline = _action._artifacts->ImageSet()->GetNextRequested(); boost::mutex::scoped_lock bufferLock(_action._mutex); _action._baselineBuffer.push(baseline); bufferLock.unlock(); } } lock.unlock(); _action._dataAvailable.notify_all(); watch.Start(); } while(!finished); _action.SetFinishedBaselines(); _action._dataAvailable.notify_all(); watch.Pause(); AOLogger::Debug << "Time spent on reading: " << watch.ToString() << '\n'; }
bool tm_link_rep::complete_packet (int channel) { string s= watch (channel); return message_complete (s); }
int overlay_mdp_setup_sockets() { struct sockaddr_un name; int len; name.sun_family = AF_UNIX; #ifndef HAVE_LINUX_IF_H /* Abstrack name space (i.e., non-file represented) unix domain sockets are a linux-only thing. */ mdp_abstract.poll.fd = -1; #else if (mdp_abstract.poll.fd<=0) { /* Abstract name space unix sockets is a special Linux thing, which is convenient for us because Android is Linux, but does not have a shared writable path that is on a UFS partition, so we cannot use traditional named unix domain sockets. So the abstract name space gives us a solution. */ name.sun_path[0]=0; /* XXX The 100 should be replaced with the actual maximum allowed. Apparently POSIX requires it to be at least 100, but I would still feel more comfortable with using the appropriate constant. */ snprintf(&name.sun_path[1],100, confValueGet("mdp.socket",DEFAULT_MDP_SOCKET_NAME)); len = 1+strlen(&name.sun_path[1]) + sizeof(name.sun_family); mdp_abstract.poll.fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (mdp_abstract.poll.fd>-1) { int reuseP=1; if (setsockopt( mdp_abstract.poll.fd, SOL_SOCKET, SO_REUSEADDR, &reuseP, sizeof(reuseP)) == -1) { WARN_perror("setsockopt(SO_REUSEADDR)"); WARN("Could not set socket reuse addresses"); } if (bind(mdp_abstract.poll.fd, (struct sockaddr *)&name, len) == -1) { WARN_perror("bind"); close(mdp_abstract.poll.fd); mdp_abstract.poll.fd = -1; WARN("bind of abstract name space socket failed (not a problem on non-linux systems)"); } int send_buffer_size=64*1024; if (setsockopt(mdp_abstract.poll.fd, SOL_SOCKET, SO_SNDBUF, &send_buffer_size, sizeof(send_buffer_size)) == -1) WARN_perror("setsockopt(SO_SNDBUF)"); mdp_abstract.poll.events = POLLIN; watch(&mdp_abstract); } } #endif if (mdp_named.poll.fd<=0) { if (!form_serval_instance_path(&name.sun_path[0], 100, "mdp.socket")) return WHY("Cannot construct name of unix domain socket."); unlink(&name.sun_path[0]); len = 0+strlen(&name.sun_path[0]) + sizeof(name.sun_family)+1; mdp_named.poll.fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (mdp_named.poll.fd>-1) { int reuseP=1; if(setsockopt( mdp_named.poll.fd, SOL_SOCKET, SO_REUSEADDR, &reuseP, sizeof(reuseP)) == -1) { WARN_perror("setsockopt(SO_REUSEADDR)"); WARN("Could not set socket reuse addresses"); } if (bind(mdp_named.poll.fd, (struct sockaddr *)&name, len) == -1) { WARN_perror("bind"); close(mdp_named.poll.fd); mdp_named.poll.fd = -1; WARN("Could not bind named unix domain socket"); } int send_buffer_size=64*1024; if (setsockopt(mdp_named.poll.fd, SOL_SOCKET, SO_RCVBUF, &send_buffer_size, sizeof(send_buffer_size)) == -1) WARN_perror("setsockopt(SO_RCVBUF)"); mdp_named.function = overlay_mdp_poll; mdp_named.stats = &mdp_stats; mdp_named.poll.events = POLLIN; watch(&mdp_named); } } return 0; }
bool CNBugTest() { /* We will do our linear algebra using Epetra */ VectorType<double> vecType = new EpetraVectorType(); MeshType meshType = new BasicSimplicialMeshType(); int nx = 1; MeshSource mesher = new PartitionedLineMesher(0.0, 1.0, nx, meshType); Mesh mesh = mesher.getMesh(); /* Create a cell filter that will identify the maximal cells * in the interior of the domain */ CellFilter interior = new MaximalCellFilter(); /* Create unknown function */ BasisFamily L1=new Lagrange(1); Expr u = new UnknownFunction(L1, "u"); Expr w = new TestFunction(L1, "w"); Expr dx = new Derivative(0); Expr x = new CoordExpr(0); /* We need a quadrature rule for doing the integrations */ QuadratureFamily quad = new GaussianQuadrature(4); DiscreteSpace discSpaceL1(mesh, L1, vecType); Expr ud = x; //proj.project(); WatchFlag watch("watch"); watch.setParam("evaluation", 5); watch.setParam("evaluator setup", 5); watch.setParam("discrete function evaluation", 1); watch.setParam("integration setup", 0); watch.setParam("symbolic preprocessing", 3); watch.setParam("integration", 0); Expr eqn1 = Integral(interior, w*(dx*(u+ud)), quad, watch); Expr eqn2 = Integral(interior, w*(dx*u)+w*(dx*ud), quad, watch); Expr bc; Out::root() << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" << " @@@@@@@@@@@@@@@ creating BAD operator @@@@@@@@@@@@@\n" << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" << endl; LinearProblem prob1(mesh, eqn1, bc, w, u, vecType); LinearOperator<double> A1 = prob1.getOperator(); Out::root() << "BAD operator = " << endl << A1 << endl << endl << endl; Out::root() << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" << " @@@@@@@@@@@@@@@ creating GOOD operator @@@@@@@@@@@@\n" << " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n" << endl; LinearProblem prob2(mesh, eqn2, bc, w, u, vecType); LinearOperator<double> A2 = prob2.getOperator(); Out::root() << "GOOD operator = " << endl << A2 << endl; Vector<double> b = A2.domain().createMember(); b.randomize(); Vector<double> r = A2*b - A1*b; Out::root() << "difference in operator application = " << r.norm2() << endl; double tol = 1000.0; return SundanceGlobal::checkTest(r.norm2(), tol); }
TestApplication::TestApplication() : BApplication("application/x-vnd.ARP-layoutest") { TestWindow *aWindow; // Instantiate the test window, and make it visible. aWindow = new TestWindow(this); aWindow->Show(); fflush(stdout); fflush(stderr); { DB(DBALL,cdb << "Testing messages..." << endl); BMessage testMsg; status_t res = testMsg.AddInt32("A param...",65); DB(DBALL,cdb << "Added an int32; result=" << res << endl); res = testMsg.AddFloat("A param...",103.4); DB(DBALL,cdb << "Added a float; result=" << res << endl); DB(DBALL,cdb << "Final message = " << testMsg << endl); DB(DBALL,cdb.flush()); } { BStopWatch watch("FuncCall StopWatch"); watch.Reset(); printf("Testing virtual function calls...\n"); int64 i; watch.Resume(); const int fcount = 10000000; for( i=0; i<fcount; i++ ) { aWindow->TestFunc("a string",23); } watch.Suspend(); bigtime_t el = watch.ElapsedTime(); printf("Operations per second: %f\n", (((float)fcount)*1000000.0)/(float)el); } { BStopWatch watch("BMessage StopWatch"); watch.Reset(); printf("Testing BMessage invocation...\n"); int64 i; watch.Resume(); const int fcount = 10000000; for( i=0; i<fcount; i++ ) { BMessage testMsg; aWindow->TestMsg(testMsg); } watch.Suspend(); bigtime_t el = watch.ElapsedTime(); printf("Operations per second: %f\n", (((float)fcount)*1000000.0)/(float)el); } { BStopWatch watch("BMessage init StopWatch"); watch.Reset(); printf("Testing BMessage initialization...\n"); int64 i; watch.Resume(); const int fcount = 10000; for( i=0; i<fcount; i++ ) { BMessage testMsg; testMsg.AddInt32("A param...",65); aWindow->TestMsg(testMsg); } watch.Suspend(); bigtime_t el = watch.ElapsedTime(); printf("Operations per second: %f\n", (((float)fcount)*1000000.0)/(float)el); } }
void peano::applications::poisson::vhhjacobi::repositories::JacobiBatchJobRepositoryForRegularGridStandardImplementation::iterate() { tarch::utils::Watch watch( "peano::applications::poisson::vhhjacobi::repositories::JacobiBatchJobRepositoryForRegularGridStandardImplementation", "iterate()", false); iterate( true ); }
/*! ******************************************************************************* * \brief menu View ******************************************************************************/ void menu_view(bool clear) { switch (menu_state) { case menu_startup: LCD_AllSegments(LCD_MODE_ON); // all segments on break; case menu_version: clr_show1(LCD_SEG_COL1); LCD_PrintHexW(VERSION_N,LCD_MODE_ON); break; #if (! REMOTE_SETTING_ONLY) case menu_set_year: LCD_AllSegments(LCD_MODE_OFF); // all segments off LCD_PrintDecW(RTC_GetYearYYYY(),LCD_MODE_BLINK_1); break; case menu_set_month: case menu_set_day: clr_show1(LCD_SEG_COL1); // decimal point LCD_PrintDec(RTC_GetMonth(), 0, ((menu_state==menu_set_month)?LCD_MODE_BLINK_1:LCD_MODE_ON)); LCD_PrintDec(RTC_GetDay(), 2, ((menu_state==menu_set_day)?LCD_MODE_BLINK_1:LCD_MODE_ON)); break; case menu_set_hour: case menu_set_minute: case menu_home4: // time #if HAVE_NEWLCD if (clear) clr_show1(LCD_SEG_COL2); #else if (clear) clr_show2(LCD_SEG_COL1,LCD_SEG_COL2); #endif LCD_PrintDec(RTC_GetHour(), 2, ((menu_state == menu_set_hour) ? LCD_MODE_BLINK_1 : LCD_MODE_ON)); LCD_PrintDec(RTC_GetMinute(), 0, ((menu_state == menu_set_minute) ? LCD_MODE_BLINK_1 : LCD_MODE_ON)); break; #else case menu_home4: // time #if HAVE_NEWLCD if (clear) clr_show1(LCD_SEG_COL2); #else if (clear) clr_show2(LCD_SEG_COL1,LCD_SEG_COL2); #endif LCD_PrintDec(RTC_GetHour(), 2, LCD_MODE_ON); LCD_PrintDec(RTC_GetMinute(), 0, LCD_MODE_ON); break; #endif #if MENU_SHOW_BATTERY case menu_home5: // battery LCD_AllSegments(LCD_MODE_OFF); LCD_PrintDec(bat_average/100, 2, LCD_MODE_ON); LCD_PrintDec(bat_average%100, 0, LCD_MODE_ON); break; #endif case menu_home: // wanted temp / error code / adaptation status if (MOTOR_calibration_step>0) { clr_show1(LCD_SEG_BAR24); LCD_PrintChar(LCD_CHAR_A,3,LCD_MODE_ON); if (MOTOR_ManuCalibration==-1) LCD_PrintChar(LCD_CHAR_d,2,LCD_MODE_ON); LCD_PrintChar(LCD_CHAR_0 + (MOTOR_calibration_step%10), 0, LCD_MODE_ON); goto MENU_COMMON_STATUS; // optimization } else { if (clear) clr_show1(LCD_SEG_BAR24); if (CTL_error!=0) { #if HAVE_NEWLCD==0 if (CTL_error & CTL_ERR_BATT_LOW) { LCD_PrintStringID(LCD_STRING_BAtt,LCD_MODE_BLINK_1); } else #endif if (CTL_error & CTL_ERR_MONTAGE) { LCD_PrintStringID(LCD_STRING_E2,LCD_MODE_ON); } else if (CTL_error & CTL_ERR_MOTOR) { LCD_PrintStringID(LCD_STRING_E3,LCD_MODE_ON); } else #if HAVE_NEWLCD==0 if (CTL_error & CTL_ERR_BATT_WARNING) { LCD_PrintStringID(LCD_STRING_BAtt,LCD_MODE_ON); } else #endif if (CTL_error & CTL_ERR_RFM_SYNC) { LCD_PrintStringID(LCD_STRING_E4,LCD_MODE_ON); } goto MENU_COMMON_STATUS; // optimization } else { if (mode_window()) { LCD_PrintStringID(LCD_STRING_OPEn,LCD_MODE_ON); goto MENU_COMMON_STATUS; // optimization } } } // do not use break at this position / optimization case menu_home_no_alter: // wanted temp if (clear) clr_show1(LCD_SEG_BAR24); LCD_PrintTemp(CTL_temp_wanted,LCD_MODE_ON); //! \note hourbar status calculation is complex we don't want calculate it every view, use chache MENU_COMMON_STATUS: LCD_SetSeg(LCD_SEG_AUTO, (CTL_test_auto()?LCD_MODE_ON:LCD_MODE_OFF)); LCD_SetSeg(LCD_SEG_MANU, (CTL_mode_auto?LCD_MODE_OFF:LCD_MODE_ON)); #if HAVE_NEWLCD if (CTL_error & (CTL_ERR_BATT_LOW | CTL_ERR_BATT_WARNING)) LCD_SetSeg(LCD_SEG_BAT, (CTL_error & CTL_ERR_BATT_LOW)?LCD_MODE_BLINK_1:LCD_MODE_ON); #endif LCD_HourBarBitmap(hourbar_buff); break; case menu_home2: // real temperature if (clear) LCD_AllSegments(LCD_MODE_OFF); LCD_PrintTempInt(temp_average,LCD_MODE_ON); break; case menu_home3: // valve pos if (clear) LCD_AllSegments(LCD_MODE_OFF); // LCD_PrintDec3(MOTOR_GetPosPercent(), 1 ,LCD_MODE_ON); // LCD_PrintChar(LCD_CHAR_2lines,0,LCD_MODE_ON); { uint8_t prc = MOTOR_GetPosPercent(); if (prc<=100) { LCD_PrintDec3(MOTOR_GetPosPercent(), 0 ,LCD_MODE_ON); } else { LCD_PrintStringID(LCD_STRING_minusCminus,LCD_MODE_ON); } } break; #if (! REMOTE_SETTING_ONLY) case menu_set_timmer_dow: clr_show1(LCD_SEG_PROG); // all segments off LCD_PrintDayOfWeek(menu_set_dow, LCD_MODE_BLINK_1); break; case menu_set_timmer: //! \todo calculate "hourbar" status, actual position in mode LCD_MODE_BLINK_1 // clr_show3(LCD_SEG_COL1,LCD_SEG_COL2,LCD_SEG_PROG); clr_show2(LCD_SEG_COL1,LCD_SEG_COL2); timmers_patch_offset=timers_get_raw_index(menu_set_dow, menu_set_slot); timmers_patch_data = menu_set_time + ((uint16_t)menu_set_mode<<12); LCD_HourBarBitmap(RTC_DowTimerGetHourBar(menu_set_dow)); timmers_patch_offset=0xff; LCD_SetHourBarSeg(menu_set_time/60, LCD_MODE_BLINK_1); if (menu_set_time < 24*60) { LCD_PrintDec(menu_set_time/60, 2, LCD_MODE_BLINK_1); LCD_PrintDec(menu_set_time%60, 0, LCD_MODE_BLINK_1); } else { LCD_PrintStringID(LCD_STRING_4xminus,LCD_MODE_BLINK_1); } show_selected_temperature_type(menu_set_mode,LCD_MODE_BLINK_1); break; #endif case menu_lock: // "bloc" message LCD_AllSegments(LCD_MODE_OFF); // all segments off LCD_PrintStringID(LCD_STRING_bloc,LCD_MODE_ON); break; case menu_service1: case menu_service2: // service menu; left side index, right value LCD_AllSegments(LCD_MODE_ON); LCD_PrintHex(service_idx, 2, ((menu_state == menu_service1) ? LCD_MODE_BLINK_1 : LCD_MODE_ON)); LCD_PrintHex(config_raw[service_idx], 0, ((menu_state == menu_service2) ? LCD_MODE_BLINK_1 : LCD_MODE_ON)); break; case menu_service_watch: LCD_AllSegments(LCD_MODE_ON); LCD_PrintHexW(watch(service_watch_n),LCD_MODE_ON); LCD_SetHourBarSeg(service_watch_n, LCD_MODE_BLINK_1); break; #if (! REMOTE_SETTING_ONLY) case menu_preset_temp0: case menu_preset_temp1: case menu_preset_temp2: case menu_preset_temp3: LCD_AllSegments(LCD_MODE_OFF); LCD_PrintTemp(menu_set_temp,LCD_MODE_BLINK_1); show_selected_temperature_type(menu_state-menu_preset_temp0,LCD_MODE_ON); #endif default: break; } LCD_Update(); }
void fs::SLOT_WATCH(const QString &path){ emit watch(path); }