/*
Given a cronspec, return the next date for when it will next run.
(This is just a wrapper for later.js)
485544
function(cronspec, sixth) {
    later.date.localTime();
    var schedule = later.parse.cron(cronspec, sixth);
    return later.schedule(schedule).next();
  }
300362
def nextSolarReturn(date, lon):
    
    jd = eph.nextSolarReturn(date.jd, lon)
    return Datetime.fromJD(jd, date.utcoffset)
1010015
function(d) {
    return d.s || (d.s = later.date.getSec.call(d));
  }
683119
function icalrecur_iterator_next() {
      var before = (this.last ? this.last.clone() : null);

      if ((this.rule.count && this.occurrence_number >= this.rule.count) ||
          (this.rule.until && this.last.compare(this.rule.until) > 0)) {

        //XXX: right now this is just a flag and has no impact
        //     we can simplify the above case to check for completed later.
        this.completed = true;

        return null;
      }

      if (this.occurrence_number == 0 && this.last.compare(this.dtstart) >= 0) {
        // First of all, give the instance that was initialized
        this.occurrence_number++;
        return this.last;
      }


      var valid;
      do {
        valid = 1;

        switch (this.rule.freq) {
        case "SECONDLY":
          this.next_second();
          break;
        case "MINUTELY":
          this.next_minute();
          break;
        case "HOURLY":
          this.next_hour();
          break;
        case "DAILY":
          this.next_day();
          break;
        case "WEEKLY":
          this.next_week();
          break;
        case "MONTHLY":
          valid = this.next_month();
          break;
        case "YEARLY":
          this.next_year();
          break;

        default:
          return null;
        }
      } while (!this.check_contracting_rules() ||
               this.last.compare(this.dtstart) < 0 ||
               !valid);

      // TODO is this valid?
      if (this.last.compare(before) == 0) {
        throw new Error("Same occurrence found twice, protecting " +
                        "you from death by recursion");
      }

      if (this.rule.until && this.last.compare(this.rule.until) > 0) {
        this.completed = true;
        return null;
      } else {
        this.occurrence_number++;
        return this.last;
      }
    }
8282
def get_last_next(self, date):
        
        past, future = (None, None), (None, None)

        for mjd, value in reversed(self.data):
            if mjd <= date:
                past = (mjd, value)
                break
            future = (mjd, value)

        return past, future
1129801
def next_on(context, rrevent=None):
    
    request = context['request']
    if rrevent is None:
        rrevent = context.get('page')
    eventNextOn = getattr(rrevent, '_nextOn', lambda _:None)
    return eventNextOn(request)
823995
public function nextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
    {
        return Date::instance(CronExpression::factory(
            $this->getExpression()
        )->getNextRunDate($currentTime, $nth, $allowCurrentDate, $this->timezone));
    }
1335195
def _schedule_next_run(self):
        
        if self.unit not in ('seconds', 'minutes', 'hours', 'days', 'weeks'):
            raise ScheduleValueError('Invalid unit')

        if self.latest is not None:
            if not (self.latest >= self.interval):
                raise ScheduleError('`latest` is greater than `interval`')
            interval = random.randint(self.interval, self.latest)
        else:
            interval = self.interval

        self.period = datetime.timedelta(**{self.unit: interval})
        self.next_run = datetime.datetime.now() + self.period
        if self.start_day is not None:
            if self.unit != 'weeks':
                raise ScheduleValueError('`unit` should be \'weeks\'')
            weekdays = (
                'monday',
                'tuesday',
                'wednesday',
                'thursday',
                'friday',
                'saturday',
                'sunday'
            )
            if self.start_day not in weekdays:
                raise ScheduleValueError('Invalid start day')
            weekday = weekdays.index(self.start_day)
            days_ahead = weekday - self.next_run.weekday()
            if days_ahead <= 0:  # Target day already happened this week
                days_ahead += 7
            self.next_run += datetime.timedelta(days_ahead) - self.period
        if self.at_time is not None:
            if (self.unit not in ('days', 'hours', 'minutes')
                    and self.start_day is None):
                raise ScheduleValueError(('Invalid unit without'
                                          ' specifying start day'))
            kwargs = {
                'second': self.at_time.second,
                'microsecond': 0
            }
            if self.unit == 'days' or self.start_day is not None:
                kwargs['hour'] = self.at_time.hour
            if self.unit in ['days', 'hours'] or self.start_day is not None:
                kwargs['minute'] = self.at_time.minute
            self.next_run = self.next_run.replace(**kwargs)
            # If we are running for the first time, make sure we run
            # at the specified time *today* (or *this hour*) as well
            if not self.last_run:
                now = datetime.datetime.now()
                if (self.unit == 'days' and self.at_time > now.time() and
                        self.interval == 1):
                    self.next_run = self.next_run - datetime.timedelta(days=1)
                elif self.unit == 'hours' \
                        and self.at_time.minute > now.minute \
                        or (self.at_time.minute == now.minute
                            and self.at_time.second > now.second):
                    self.next_run = self.next_run - datetime.timedelta(hours=1)
                elif self.unit == 'minutes' \
                        and self.at_time.second > now.second:
                    self.next_run = self.next_run - \
                                    datetime.timedelta(minutes=1)
        if self.start_day is not None and self.at_time is not None:
            # Let's see if we will still make that time we specified today
            if (self.next_run - datetime.datetime.now()).days >= 7:
                self.next_run -= self.period
42920
function parseRetryAfter(retryAfter) {
    // Only parse once
    if (typeof retryAfter === 'number') {
        return retryAfter;
    } else if (isNaN(retryAfter)) {
      return Math.ceil((new Date(retryAfter).getTime() / 1000) - Date.now() / 1000);
    } else {
      return parseInt(retryAfter, 10); 
    }
}
798192
function nextTick (next, err) {
  return process.nextTick(function () {
    try {
      next(err)
    } catch (e) {
      // istanbul ignore next
      next(e)
    }
  })
}
288967
function nextTick(fn) {
  const promise = new Promise((resolve) => {
    proc.nextTick(() => {
      resolve(fn());
    });
  });

  return promise;
}
190445
def get_next(self):
        """"""
        return self.loop_time + (self.croniter.get_next(float) - self.time)
331281
function getFutureMs(ms) {
    var now = new Date();
    now.setMilliseconds(now.getMilliseconds() + ms);
    return now;
}
191883
public DateValue next() {
        if (null == this.pendingUtc_) {
            this.fetchNext();
        }
        DateValue next = this.pendingUtc_;
        this.pendingUtc_ = null;
        return next;
    }
908140
@Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        if (triggerContext.lastScheduledExecutionTime() == null) {
            return new Date(System.currentTimeMillis() + this.initialDelay);
        } else if (this.fixedRate) {
            return new Date(triggerContext.lastScheduledExecutionTime().getTime() + this.period);
        }
        return new Date(triggerContext.lastCompletionTime().getTime() + this.period);
    }
192881
function(cronspec, sixth) {
    var schedule = later.parse.cron(cronspec, sixth);
    return scheduleToSentence(schedule['schedules'][0], sixth);
  }
404648
def _find_next(server):
    
    from datetime import datetime
    #Re-load the database in case we have multiple instances of the script
    #running in memory.
    _load_db()
    result = None
    visited = []
    
    if "status" in db:
        for reponame, status in db["status"].items():
            vms("Checking cron status for {}: {}".format(reponame, status))
            start = None if "started" not in status else status["started"]
            end = None if "end" not in status else status["end"]
            running = start is not None and end is not None and start > end
            add = False
            
            if not running and end is not None:
                #Check the last time it was run and see if enough time has
                #elapsed.
                elapsed = (datetime.now() - end).seconds/60
                add = elapsed > server.cron.settings[reponame].frequency
                if not add:
                    vms("'{}' skipped because the interval hasn't ".format(reponame) +
                        "elapsed ({} vs. {})".format(elapsed, server.cron.settings[reponame].frequency))
            elif end is None:
                add = True

            if add:
                result = reponame
                break
            visited.append(reponame)
    else:
        db["status"] = {}        


    if result is None:
        #We still need to check the newly installed repos.            
        for reponame, repo in server.repositories.items():
            if reponame not in visited:
                #These are newly installed repos that have never run before.
                vms("Added '{}' as new repo for cron execution.".format(reponame))
                result = reponame
                break

    return result