void clock_device::update_timer() { if (!m_signal_handler.isnull() && m_clock > 0) { if (m_timer == nullptr) { m_timer = timer_alloc(0); m_timer->adjust(period()); } else { attotime next = period() - m_timer->elapsed(); if (next < attotime::zero) { next = attotime::zero; } m_timer->adjust(next); } } else if (m_timer != nullptr) { m_timer->adjust(attotime::never); } }
int main() { int i,c=0,cPrev=-1; for(i=3;i<=1000;i++) { c=period(i); if(c>cPrev) { cPrev=c; //printf("ok 1"); printf("%d = %d\n",i,period(i));//printf("Period : %d = %d \n",i,period(i)); } } }
// Note: not guaranteed to print entire state void PulseWave::printState(void) { const char *enabledStr = enabled ? "enabled" : "disabled"; float frequency = 1.0 / period(); printf("Pulse wave channel %d: %s, duty %f, divider %d (%f Hz)\n", // dummy channel number below -1, enabledStr, duty, divider, frequency); }
void GroupNodeImpl::update_groups() { #ifndef _WIN32 sigset_t signal_set; sigaddset(&signal_set, SIGINT); sigaddset(&signal_set, SIGTERM); sigaddset(&signal_set, SIGHUP); sigaddset(&signal_set, SIGPIPE); pthread_sigmask(SIG_BLOCK, &signal_set, NULL); #endif // called by a thread in an infinite loop at a fixed rate (i.e. 1s) while (ok()) { auto start = std::chrono::high_resolution_clock::now(); zlist_t* all_groups = zyre_peer_groups(node_); void* item = zlist_first(all_groups); while (item != NULL) { char* grp = static_cast<char*>(item); // zyre only joins the group if we are not ALREADY in the group // so it does a hash lookup - we would be duplicating work zyre_join(node_, grp); item = zlist_next(all_groups); } std::chrono::duration<double,std::milli> period(1000); std::this_thread::sleep_until(start + period); } }
OsStatus MpodBufferRecorder::enableDevice(unsigned samplesPerFrame, unsigned samplesPerSec, MpFrameTime currentFrameTime, OsCallback &frameTicker) { assert(!isEnabled()); assert(mpBuffer == NULL); mSamplesPerFrame = samplesPerFrame; mSamplesPerSec = samplesPerSec; mBufferLength = mBufferLengthMS * mSamplesPerSec / 1000; mpBuffer = new MpAudioSample[mBufferLength]; mBufferEnd = 0; mIsEnabled = TRUE; if (mpTickerTimer != NULL) { mpTickerTimer->stop(TRUE); delete mpTickerTimer; mpTickerTimer = NULL; } mpTickerNotification = &frameTicker; // Start firing events mpTickerTimer = new OsTimer((OsNotification&)*mpTickerNotification); OsTime period(samplesPerFrame*1000/samplesPerSec); mpTickerTimer->periodicEvery(period, period); return OS_SUCCESS; }
void z80ctc_device::ctc_channel::trigger(uint8_t data) { // normalize data data = data ? 1 : 0; // see if the trigger value has changed if (data != m_extclk) { m_extclk = data; // see if this is the active edge of the trigger if (((m_mode & EDGE) == EDGE_RISING && data) || ((m_mode & EDGE) == EDGE_FALLING && !data)) { // if we're waiting for a trigger, start the timer if ((m_mode & WAITING_FOR_TRIG) && (m_mode & MODE) == MODE_TIMER) { attotime curperiod = period(); VPRINTF_CHANNEL(("CTC period %s\n", curperiod.as_string())); m_timer->adjust(curperiod, m_index, curperiod); } // we're no longer waiting m_mode &= ~WAITING_FOR_TRIG; // if we're clocking externally, decrement the count if ((m_mode & MODE) == MODE_COUNTER) { // if we hit zero, do the same thing as for a timer interrupt if (--m_down == 0) timer_callback(nullptr,0); } } } }
bool spin() { ros::Duration period(4,0) ; // Repeat Every 4 seconds ros::Time next_time = ros::Time::now() ; while ( ok() ) { usleep(100) ; if (ros::Time::now() >= next_time) { next_time.from_double(next_time.to_double() + period.to_double()) ; BuildCloud::request req ; BuildCloud::response resp ; req.begin.from_double(next_time.to_double() - period.to_double() ) ; req.end = next_time ; req.target_frame_id = "base" ; printf("Making Service Call...\n") ; ros::service::call("build_cloud", req, resp) ; printf("Done with service call\n") ; publish("full_cloud", resp.cloud) ; printf("Published Cloud size=%u\n", resp.cloud.get_pts_size()) ; } } return true ; }
void hp98035_io_card::device_reset() { hp9845_io_card_device::device_reset(); install_readwrite_handler(read16_delegate(FUNC(hp98035_io_card::reg_r) , this) , write16_delegate(FUNC(hp98035_io_card::reg_w) , this)); m_idr_full = false; m_idr = 0; m_odr = 0; m_ibuffer_ptr = 0; m_obuffer_len = 0; m_obuffer_ptr = 0; sts_w(true); set_flg(true); // Set real time from the real world system_time systime; machine().base_datetime(systime); m_msec = 0; m_sec = systime.local_time.second; m_min = systime.local_time.minute; m_hrs = systime.local_time.hour; m_dom = systime.local_time.mday; m_mon = systime.local_time.month + 1; attotime period(attotime::from_msec(1)); m_msec_timer->adjust(period , 0 , period); half_init(); }
FastPWM::FastPWM(PinName pin) : PWMObject(pin){ //Set clock source LPC_SC->PCLKSEL0|=1<<12; _duty=0; _period=0.02; if (pin==p26||pin==LED1) { PWMUnit=1; MR=&LPC_PWM1->MR1; } else if (pin==p25||pin==LED2){ PWMUnit=2; MR=&LPC_PWM1->MR2; } else if (pin==p24||pin==LED3){ PWMUnit=3; MR=&LPC_PWM1->MR3; } else if (pin==p23||pin==LED4){ PWMUnit=4; MR=&LPC_PWM1->MR4; } else if (pin==p22){ PWMUnit=5; MR=&LPC_PWM1->MR5; } else if (pin==p21){ PWMUnit=6; MR=&LPC_PWM1->MR6; } else error("No hardware PWM pin\n\r"); period(_period); }
void clock_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { m_signal = !m_signal; m_signal_handler(m_signal); m_timer->adjust(period()); }
TEST_F(PeriodicActionPoolTest, cancellation) { PeriodicActionPool::Ptr pool(PeriodicActionPool::create("TestPool", nthreads_)); boost::promise<bool> promise; boost::unique_future<bool> future(promise.get_future()); bool running = false; auto fun([&]() -> PeriodicActionContinue { if (not running) { promise.set_value(true); running = true; } return PeriodicActionContinue::T; }); std::atomic<uint64_t> period(3600); std::unique_ptr<PeriodicActionPool::Task> t(pool->create_task("LongPeriod", std::move(fun), period, true)); EXPECT_TRUE(future.get()); }
TEST_F(PeriodicActionPoolTest, basics) { PeriodicActionPool::Ptr pool(PeriodicActionPool::create("TestPool", nthreads_)); const size_t iterations = 10; size_t count = 0; boost::promise<bool> promise; boost::unique_future<bool> future(promise.get_future()); auto fun([&]() -> PeriodicActionContinue { if (++count == iterations) { promise.set_value(true); } return PeriodicActionContinue::T; }); std::atomic<uint64_t> period(10); std::unique_ptr<PeriodicActionPool::Task> t(pool->create_task("counter", std::move(fun), period, false)); EXPECT_TRUE(future.get()); }
nsresult nsDASHWebMODParser::SetPeriods(MPD* aMpd) { NS_ENSURE_TRUE(mRoot, NS_ERROR_NOT_INITIALIZED); nsCOMPtr<nsIDOMElement> child, nextChild; nsresult rv = mRoot->GetFirstElementChild(getter_AddRefs(child)); NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE); #ifdef PR_LOGGING int i = 0; #endif while (child) { nsAutoString tagName; rv = child->GetTagName(tagName); NS_ENSURE_SUCCESS(rv, rv); if (tagName.EqualsLiteral("Period")) { nsAutoPtr<Period> period(new Period()); // Get start time and duration nsAutoString value; rv = GetAttribute(child, NS_LITERAL_STRING("start"), value); NS_ENSURE_SUCCESS(rv, rv); if (!value.IsEmpty()) { double startTime = -1; rv = GetTime(value, startTime); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(0 <= startTime, NS_ERROR_ILLEGAL_VALUE); period->SetStart(startTime); } rv = GetAttribute(child, NS_LITERAL_STRING("duration"), value); NS_ENSURE_SUCCESS(rv, rv); if (!value.IsEmpty()) { double duration = -1; rv = GetTime(value, duration); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(0 <= duration, NS_ERROR_ILLEGAL_VALUE); period->SetDuration(duration); } bool bIgnoreThisPeriod; rv = SetAdaptationSets(child, period, bIgnoreThisPeriod); NS_ENSURE_SUCCESS(rv, rv); // |Period| should be ignored if its child elems are invalid if (bIgnoreThisPeriod) { LOG("Ignoring period"); } else { aMpd->AddPeriod(period.forget()); LOG("Period #%d: added to MPD", i++); } } rv = child->GetNextElementSibling(getter_AddRefs(nextChild)); NS_ENSURE_SUCCESS(rv, rv); child = nextChild; } return NS_OK; }
void EasingGraph::setPeriod(qreal newPeriod) { if ((period() != newPeriod) && (easingShape()==QLatin1String("Elastic"))) { m_curveFunction.setPeriod(newPeriod); emit periodChanged(); update(); } }
void idle_callback(std::size_t /*num_thread*/) { #if defined(HPX_HAVE_THREAD_MANAGER_IDLE_BACKOFF) // Put this thread to sleep for some time, additionally it gets // woken up on new work. #if BOOST_VERSION < 105000 boost::posix_time::millisec period(++wait_count_); boost::unique_lock<boost::mutex> l(mtx_); cond_.timed_wait(l, period); #else boost::chrono::milliseconds period(++wait_count_); boost::unique_lock<boost::mutex> l(mtx_); cond_.wait_for(l, period); #endif #endif }
static inline void bind(const std::shared_ptr<threading::Reaction>& reaction) { // If this is the first time we have used this watchdog service it if (!operation::CacheGet<message::ServiceWatchdog<WatchdogGroup>>::template get<DSL>(*reaction)) { reaction->reactor.emit(std::make_unique<message::ServiceWatchdog<WatchdogGroup>>()); } reaction->unbinders.push_back([](const threading::Reaction& r) { r.reactor.emit<emit::Direct>(std::make_unique<operation::Unbind<operation::ChronoTask>>(r.id)); }); // Send our configuration out reaction->reactor.emit<emit::Direct>(std::make_unique<operation::ChronoTask>( [reaction](NUClear::clock::time_point& time) { // Get the latest time the watchdog was serviced auto service_time = operation::CacheGet<message::ServiceWatchdog<WatchdogGroup>>::template get<DSL>(*reaction) ->time; // Check if our watchdog has timed out if (NUClear::clock::now() > (service_time + period(ticks))) { try { // Submit the reaction to the thread pool auto task = reaction->get_task(); if (task) { reaction->reactor.powerplant.submit(std::move(task)); } } catch (...) { } // Now automatically service the watchdog time = NUClear::clock::now() + period(ticks); } // Change our wait time to our new watchdog time else { time = service_time + period(ticks); } // We renew! return true; }, NUClear::clock::now() + period(ticks), reaction->id)); }
int main( int argc, char** argv ) { // initialize ROS ros::init(argc, argv, "iiwa_hw", ros::init_options::NoSigintHandler); // ros spinner ros::AsyncSpinner spinner(1); spinner.start(); // custom signal handlers signal(SIGTERM, quitRequested); signal(SIGINT, quitRequested); signal(SIGHUP, quitRequested); // construct the lbr iiwa ros::NodeHandle iiwa_nh; IIWA_HW iiwa_robot(iiwa_nh); // configuration routines iiwa_robot.start(); ros::Time last(ros::Time::now()); ros::Time now; ros::Duration period(1.0); //the controller manager controller_manager::ControllerManager manager(&iiwa_robot, iiwa_nh); // run as fast as possible while( !g_quit ) { // get the time / period now = ros::Time::now(); period = now - last; last = now; // read current robot position iiwa_robot.read(period); // update the controllers manager.update(now, period); // send command position to the robot iiwa_robot.write(period); // wait for some milliseconds defined in controlFrequency iiwa_robot.getRate()->sleep(); } std::cerr << "Stopping spinner..." << std::endl; spinner.stop(); std::cerr << "Bye!" << std::endl; return 0; }
void idle_callback(std::size_t /*num_thread*/) { #if defined(HPX_THREAD_BACKOFF_ON_IDLE) // Put this thread to sleep for some time, additionally it gets // woken up on new work. #if BOOST_VERSION < 105000 boost::posix_time::millisec period(++wait_count_); boost::mutex::scoped_lock l(mtx_); policies::detail::reset_on_exit w(waiting_); cond_.timed_wait(l, period); #else boost::chrono::milliseconds period(++wait_count_); boost::mutex::scoped_lock l(mtx_); policies::detail::reset_on_exit w(waiting_); cond_.wait_for(l, period); #endif #endif }
/* find a generator for the multiplicative group mod p, where p is prime */ static int find_generator(int p) { int g; for (g = 1; g < p; ++g) if (period(g, p) == p - 1) break; if (g == p) fftw_die("couldn't find generator for Rader\n"); return g; }
bool SubjectBotCommand::invoke(BotCommandInfo *info) const { BotCommandArgs args = info->parseArgs(2); if(args.size() < 1 || !this->checkPassword(args[0])) { info->setResponse("Wrong password"); return false; } boost::gregorian::date now(boost::gregorian::day_clock::local_day()); std::string formatstr = this->getOption("subject", "format"); if("" == formatstr) formatstr = this->_defaultFormat; StringFormat format(formatstr); std::string datestr = this->getOption("subject", "eventdate"); if(datestr.length() > 0) { std::vector<std::string> dates; boost::algorithm::split(dates,datestr,boost::algorithm::is_any_of(",")); for(unsigned int i = 0; i < dates.size(); i++) { boost::algorithm::trim(dates[i]); if(dates[i].length() < 1) continue; boost::gregorian::date_period period(now, boost::gregorian::from_string(dates[i])); format.assign(boost::lexical_cast<std::string>(i+1),period.length()); } } if(args.size()<2 && this->_defaultFormat==formatstr) { info->setResponse("Expecting custom subject"); return false; } if(args.size()>=2) format.assign("_", args[1]); else // don't display anything if there is nothing to display format.assign("_",""); std::string result = format.produce(); this->_room->setSubject(result); info->setResponse("Subject set to \"" + result + "\"."); return true; }
/** This function is called whenever the physical boundaries, cutoffs, etc. are changed. */ void CellList::rebuild() { _is_good = true; std::vector<double> period(3, 0.0); for (int i=0; i<3; i++) { period[i] = _box_max[i] - _box_min[i]; } double irx = period[0] / _interaction_range; double iry = period[1] / _interaction_range; double irz = period[2] / _interaction_range; if (!(irx >= 3.0 || !_periodic[0]) || !(iry >= 3.0 || !_periodic[1]) || !(irz >= 3.0 || !_periodic[2]) ) { _is_good = false; } if (_min_cell_size > 0.0) { _ncellx = (int)(period[0]/_min_cell_size); _ncelly = (int)(period[1]/_min_cell_size); _ncellz = (int)(period[2]/_min_cell_size); } else { _ncellx = (int)(period[0]/_interaction_range); _ncelly = (int)(period[1]/_interaction_range); _ncellz = (int)(period[2]/_interaction_range); } _ncellyz = _ncelly*_ncellz; _cell_size[0] = period[0]/_ncellx; _cell_size[1] = period[1]/_ncelly; _cell_size[2] = period[2]/_ncellz; _inv_cell_size[0] = 1.0/_cell_size[0]; _inv_cell_size[1] = 1.0/_cell_size[1]; _inv_cell_size[2] = 1.0/_cell_size[2]; if (_ncellx*_ncelly*_ncellz != (int)_cell.size()) { _force_rebuild = true; } if (_force_rebuild) { clear(); _cell.resize(_ncellx*_ncelly*_ncellz); divideBoxIntoCells(); _force_rebuild = false; } }
// // /// \brief parse a character into a string frequency /// @param freq a character in 'A' (annual), 'S' (semiannual), 'Q' (quarterly), /// 'B' (bimonthly) 'M' (monthly) /// @return a integer indicationg the number of months /// \ingroup tools inline period charFrequencyToPeriod(const char& freq) { char uf = std::toupper(freq); if(uf == 'A') return period(12); else if(uf == 'S') return period(6); else if(uf == 'Q') return period(3); else if(uf == 'B') return period(2); else if(uf == 'M') return period(1); else if(uf == 'W') return period(0,7); else if(uf == 'D') return period(0,1); else QM_FAIL("unrecognized frequency character. It must be in ('A','S','Q','M','W','D')"); }
int sessioninfo(Fmt *f) { int got, i; Sessinfo *si; si = nil; if((got = RAPsessionenum(Sess, &Ipc, &si)) == -1){ fmtprint(f, "RAPsessionenum: %r\n"); return 0; } for(i = 0; i < got; i++){ fmtprint(f, "%-24q %-24q ", si[i].user, si[i].wrkstn); fmtprint(f, "%12s ", period(si[i].sesstime)); fmtprint(f, "%12s\n", period(si[i].idletime)); free(si[i].wrkstn); free(si[i].user); } free(si); return 0; }
int energy_diff(std::vector< std::vector<char> >& cluster, int i, int j, int ferro) { int energy = 0, energy1 = 0, energy2 = 0; energy1 += ferro*cluster[i][j]*cluster[period(i+1)][j]; energy1 += ferro*cluster[i][j]*cluster[period(i-1)][j]; energy1 += ferro*cluster[i][j]*cluster[i][period(j-1)]; energy1 += ferro*cluster[i][j]*cluster[i][period(j+1)]; energy2 -= ferro*cluster[i][j]*cluster[period(i+1)][j]; energy2 -= ferro*cluster[i][j]*cluster[period(i-1)][j]; energy2 -= ferro*cluster[i][j]*cluster[i][period(j-1)]; energy2 -= ferro*cluster[i][j]*cluster[i][period(j+1)]; energy = energy1-energy2; return energy; }
RcppExport SEXP cfdates(SEXP params){ SEXP rl = R_NilValue; char* exceptionMesg = NULL; try { RcppParams rparam(params); double basis = rparam.getDoubleValue("dayCounter"); DayCounter dayCounter = getDayCounter(basis); double p = rparam.getDoubleValue("period"); Frequency freq = getFrequency(p); Period period(freq); double emr = rparam.getDoubleValue("emr"); bool endOfMonth = false; if (emr == 1) endOfMonth = true; QuantLib::Date d1(dateFromR(rparam.getDateValue("settle"))); QuantLib::Date d2(dateFromR(rparam.getDateValue("maturity"))); Calendar calendar=UnitedStates(UnitedStates::GovernmentBond); Schedule sch(d1, d2, period, calendar, Unadjusted, Unadjusted, DateGeneration::Backward, endOfMonth); //cfdates int numCol = 1; std::vector<std::string> colNames(numCol); colNames[0] = "Date"; RcppFrame frame(colNames); std::vector<QuantLib::Date> dates = sch.dates(); for (unsigned int i = 0; i< dates.size(); i++){ std::vector<ColDatum> row(numCol); Date d = dates[i]; row[0].setDateValue(RcppDate(d.month(), d.dayOfMonth(), d.year())); frame.addRow(row); } RcppResultSet rs; rs.add("", frame); rl = rs.getReturnList(); } catch(std::exception& ex) { exceptionMesg = copyMessageToR(ex.what()); } catch(...) { exceptionMesg = copyMessageToR("unknown reason"); } if(exceptionMesg != NULL) Rf_error(exceptionMesg); return rl; }
bool RecurrenceWidget::modified() const { if (DEBUG) qDebug() << "recurring:" << isRecurring() << _prevRecurring << "\n" << "period:" << period() << _prevPeriod << "\n" << "frequency:" << frequency() << _prevFrequency << "\n" << "startDateTime:" << startDateTime()<< _prevStartDateTime << "\n" << "endDateTime:" << endDateTime() << _prevEndDateTime << "\n" << "max:" << max() << _prevMax << "\n" << "_parentId:" << _parentId << _prevParentId << "\n" << "_parentType:" << _parentType << _prevParentType ; bool returnVal = (isRecurring() != _prevRecurring || period() != _prevPeriod || frequency() != _prevFrequency || startDateTime() != _prevStartDateTime|| endDateTime() != _prevEndDateTime || max() != _prevMax || _parentId != _prevParentId || _parentType != _prevParentType); return returnVal; }
void GroupNodeImpl::wait_join(const std::string& group) { // how do we wait for joins? we should receive at least one join message // but we MAY have received it in the PAST! std::chrono::duration<int,std::milli> period(500); basic_lock lk(join_mutex_); if (joins_[group] > 0) return; else { while (joins_[group] == 0 && ok()) { // check periodically to make sure we're still running join_cond_.wait_for(lk, period); } } }
void PWMController::PWMCycle() { ros::Rate period((1)/period_s); while(ros::ok() && (!stop)) { ros::spinOnce(); pwm->SetOutput(HIGH); ros::Duration(period_s * duty_cycle).sleep(); pwm->SetOutput(LOW); ros::Duration(period_s * (1 - duty_cycle)).sleep(); period.sleep(); } }
void on_open(connection_ptr connection) { if (!m_timer) { m_timer.reset(new boost::asio::deadline_timer(connection->get_io_service(),boost::posix_time::seconds(0))); m_timer->expires_from_now(boost::posix_time::milliseconds(250)); m_timer->async_wait(boost::bind(&type::on_timer,this,connection,boost::asio::placeholders::error)); } m_connections_cur++; if (m_connections_cur == m_connections_max) { boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_period period(m_start_time,now); int ms = period.length().total_milliseconds(); std::cout << "started " << m_connections_cur << " in " << ms << "ms" << " (" << m_connections_cur/(ms/1000.0) << "/s)" << std::endl; } }
void ofxUIMultiImageToggle::init(float w, float h, bool *_value, string _pathURL, string _name, int _size) { name = string(_name); kind = OFX_UI_WIDGET_MULTIIMAGETOGGLE; paddedRect = new ofxUIRectangle(-padding, -padding, w+padding*2.0, h+padding*2.0); paddedRect->setParent(rect); label = new ofxUILabel(w+padding*2.0,0, (name+" LABEL"), name, _size); label->setParent(label); label->setRectParent(rect); label->setEmbedded(true); if(useReference) { value = _value; } else { value = new bool(); *value = *_value; } setValue(*_value); drawLabel = false; label->setVisible(drawLabel); string coreURL = _pathURL; string extension = ""; string period ("."); size_t found; found=_pathURL.find(period); if (found!=string::npos) { coreURL = _pathURL.substr(0,found); extension = _pathURL.substr(found); } back = new ofImage(); back->loadImage(_pathURL); down = new ofImage(); down->loadImage(coreURL+"down"+extension); over = new ofImage(); over->loadImage(coreURL+"over"+extension); on = new ofImage(); on->loadImage(coreURL+"on"+extension); }