Helper routine to report issues with the schedule
778511
def validate_schedule():
    """"""
    all_items = prefetch_schedule_items()
    errors = []
    for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS:
        if validator(all_items):
            errors.append(msg)

    all_slots = prefetch_slots()
    for validator, _type, msg in SLOT_VALIDATORS:
        if validator(all_slots):
            errors.append(msg)
    return errors
271057
def AddStopTime(self, stop, problems=None, schedule=None, **kwargs):
    
    if problems is None:
      # TODO: delete this branch when StopTime.__init__ doesn't need a
      # ProblemReporter
      problems = problems_module.default_problem_reporter
    stoptime = self.GetGtfsFactory().StopTime(
        problems=problems, stop=stop, **kwargs)
    self.AddStopTimeObject(stoptime, schedule)
430044
def _do_submit_problems(self):
        
        try:
            while True:
                # Pull as many problems as we can, block on the first one,
                # but once we have one problem, switch to non-blocking then
                # submit without blocking again.

                # `None` task is used to signal thread termination
                item = self._submission_queue.get()
                if item is None:
                    break

                ready_problems = [item]
                while len(ready_problems) < self._SUBMIT_BATCH_SIZE:
                    try:
                        ready_problems.append(self._submission_queue.get_nowait())
                    except queue.Empty:
                        break

                # Submit the problems
                _LOGGER.debug("Submitting %d problems", len(ready_problems))
                body = '[' + ','.join(mess.body for mess in ready_problems) + ']'
                try:
                    try:
                        response = self.session.post(posixpath.join(self.endpoint, 'problems/'), body)
                        localtime_of_response = epochnow()
                    except requests.exceptions.Timeout:
                        raise RequestTimeout

                    if response.status_code == 401:
                        raise SolverAuthenticationError()
                    response.raise_for_status()

                    message = response.json()
                    _LOGGER.debug("Finished submitting %d problems", len(ready_problems))
                except BaseException as exception:
                    _LOGGER.debug("Submit failed for %d problems", len(ready_problems))
                    if not isinstance(exception, SolverAuthenticationError):
                        exception = IOError(exception)

                    for mess in ready_problems:
                        mess.future._set_error(exception, sys.exc_info())
                        self._submission_queue.task_done()
                    continue

                # Pass on the information
                for submission, res in zip(ready_problems, message):
                    submission.future._set_clock_diff(response, localtime_of_response)
                    self._handle_problem_status(res, submission.future)
                    self._submission_queue.task_done()

                # this is equivalent to a yield to scheduler in other threading libraries
                time.sleep(0)

        except BaseException as err:
            _LOGGER.exception(err)
1095630
def main():
    """"""

    if "--help" in sys.argv or "-h" in sys.argv or len(sys.argv) > 3:
        raise SystemExit(__doc__)

    try:
        discordian_calendar(*sys.argv[1:])
    except ValueError as error:
        raise SystemExit("Error: {}".format("\n".join(error.args)))
684083
def errors(self):
        
        try:
            self.now = datetime.datetime.now()
            if len(self.alarm_day) < 2 or len(self.alarm_day) > 2:
                print("error: day: usage 'DD' such us '0%s' not '%s'" % (
                    self.alarm_day, self.alarm_day))
                self.RUN_ALARM = False
            if int(self.alarm_day) > calendar.monthrange(
                    self.now.year, self.now.month)[1] or int(
                        self.alarm_day) < 1:
                print("error: day: out of range")
                self.RUN_ALARM = False
            # compare alarm time with alarm pattern
            if (len(self.alarm_time) != len(self.alarm_pattern) or
                    len(self.alarm_time[0]) < 2 or
                    len(self.alarm_time[0]) > 2 or
                    len(self.alarm_time[1]) < 2 or len(self.alarm_time[1]) > 2):
                print("error: time: usage '%s'" % ":".join(self.alarm_pattern))
                self.RUN_ALARM = False
            # compare if alarm hour or alarm minutes
            # is within the range
            if int(self.alarm_hour) not in range(0, 24):
                print("error: hour: out of range")
                self.RUN_ALARM = False
            if int(self.alarm_minutes) not in range(0, 60):
                print("error: minutes: out of range")
                self.RUN_ALARM = False
        except ValueError:
            print("Usage '%s'" % ":".join(self.alarm_pattern))
            self.RUN_ALARM = False
        if not os.path.isfile(self.song):
            print("error: song: file does not exist")
            self.RUN_ALARM = False
90092
def _schedule(self):
        ''''''
        if self._running:
            _logger.debug('')
            self._call_later_handle = self._event_loop.call_later(
                self._timeout, self._check)
734838
def report_problems(filename, problems):
    
    problem_file = filename.replace(".po", ".prob")
    id_filler = textwrap.TextWrapper(width=79, initial_indent="  msgid: ", subsequent_indent=" " * 9)
    tx_filler = textwrap.TextWrapper(width=79, initial_indent="  -----> ", subsequent_indent=" " * 9)
    with codecs.open(problem_file, "w", encoding="utf8") as prob_file:
        for problem in problems:
            desc, msgid = problem[:2]
            prob_file.write(u"{}\n{}\n".format(desc, id_filler.fill(msgid)))
            info = u"{}\n{}\n".format(desc, id_filler.fill(msgid))
            for translation in problem[2:]:
                prob_file.write(u"{}\n".format(tx_filler.fill(translation)))
                info += u"{}\n".format(tx_filler.fill(translation))
            log.info(info)
            prob_file.write(u"\n")

    log.error(" %s problems in %s, details in .prob file", len(problems), filename)
497721
def show_abierrors(self, nids=None, stream=sys.stdout):
        
        lines = []
        app = lines.append

        for task in self.iflat_tasks(status=self.S_ABICRITICAL, nids=nids):
            header = "=== " + task.qout_file.path + "==="
            app(header)
            report = task.get_event_report()

            if report is not None:
                app("num_errors: %s, num_warnings: %s, num_comments: %s" % (
                    report.num_errors, report.num_warnings, report.num_comments))
                app("*** ERRORS ***")
                app("\n".join(str(e) for e in report.errors))
                app("*** BUGS ***")
                app("\n".join(str(b) for b in report.bugs))

            else:
                app("get_envent_report returned None!")

            app("=" * len(header) + 2*"\n")

        return stream.writelines(lines)
738138
def get_monitoring_problems(self):
        
        res = self.get_id()
        res['problems'] = {}

        # Report our schedulers information, but only if a dispatcher exists
        if getattr(self, 'dispatcher', None) is None:
            return res

        for satellite in self.dispatcher.all_daemons_links:
            if satellite.type not in ['scheduler']:
                continue
            if not satellite.active:
                continue

            if satellite.statistics and 'problems' in satellite.statistics:
                res['problems'][satellite.name] = {
                    '_freshness': satellite.statistics['_freshness'],
                    'problems': satellite.statistics['problems']
                }

        return res
1226254
def cli(env, volume_id, schedule_type, retention_count,
        minute, hour, day_of_week):
    """"""
    file_manager = SoftLayer.FileStorageManager(env.client)

    valid_schedule_types = {'INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY'}
    valid_days = {'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
                  'FRIDAY', 'SATURDAY'}

    if schedule_type not in valid_schedule_types:
        raise exceptions.CLIAbort(
            '--schedule-type must be INTERVAL, HOURLY, ' +
            'DAILY, or WEEKLY, not ' + schedule_type)

    if schedule_type == 'INTERVAL' and (minute < 30 or minute > 59):
        raise exceptions.CLIAbort(
            '--minute value must be between 30 and 59')
    if minute < 0 or minute > 59:
        raise exceptions.CLIAbort(
            '--minute value must be between 0 and 59')
    if hour < 0 or hour > 23:
        raise exceptions.CLIAbort(
            '--hour value must be between 0 and 23')
    if day_of_week not in valid_days:
        raise exceptions.CLIAbort(
            '--day_of_week value must be a valid day (ex: SUNDAY)')

    enabled = file_manager.enable_snapshots(volume_id, schedule_type,
                                            retention_count, minute,
                                            hour, day_of_week)

    if enabled:
        click.echo('%s snapshots have been enabled for volume %s'
                   % (schedule_type, volume_id))
353605
function scheduleToSentence(schedule) {
    var outputText = locale.Every + ' ';

    if (schedule['h'] && schedule['m'] && schedule['h'].length <= 2 && schedule['m'].length <= 2) {
      // If there are only one or two specified values for
      // hour or minute, print them in HH:MM format

      var hm = [];
      for (var i = 0; i < schedule['h'].length; i++) {
        for (var j = 0; j < schedule['m'].length; j++) {
          hm.push(zeroPad(schedule['h'][i]) + ':' + zeroPad(schedule['m'][j]));
        }
      }
      if (hm.length < 2) {
        outputText = hm[0];
      } else {
        var lastVal = hm.pop();
        outputText = hm.join(', ') + ` ${locale.and} ` + lastVal;
      }
      if (!schedule['d'] && !schedule['D']) {
        outputText += ` ${locale['every day']}`;
      }
    } else {
      // Otherwise, list out every specified hour/minute value.

      if (schedule['h']) { // runs only at specific hours
        if (schedule['m']) { // and only at specific minutes
          outputText += numberList(schedule['m']) + ` ${locale['minute past the']} ` + numberList(schedule['h']) + ` ${locale['hour']}`;
        } else { // specific hours, but every minute
          outputText += `${locale['minute of']} ` + numberList(schedule['h']) + ` ${locale['hour']}`;
        }
      } else if (schedule['m']) { // every hour, but specific minutes
        outputText += numberList(schedule['m']) + ` ${locale['minute every hour']}`;
      } else { // cronspec has "*" for both hour and minute
        outputText += locale['minute'];
      }
    }

    if (schedule['D']) { // runs only on specific day(s) of month
      outputText += (locale['on the'] ? ` ${locale['on the']} ` : ' ') + numberList(schedule['D']);
      if (!schedule['M']) {
        outputText += ` ${locale['of every month']}`;
      }
    }

    if (schedule['d']) { // runs only on specific day(s) of week
      if (schedule['D']) {
        // if both day fields are specified, cron uses both; superuser.com/a/348372
        outputText += ` ${locale['and every']} `;
      } else {
        outputText += ` ${locale['on']} `;
      }
      outputText += dateList(schedule['d'], 'dow');
    }

    if (schedule['M']) {
      // runs only in specific months; put this output last
      outputText += ` ${locale['in']} ` + dateList(schedule['M'], 'mon');
    }

    return outputText;
  }
1195639
def schedule(identifier, **kwargs):
    ''''''
    source = actions.schedule(identifier, **kwargs)
    msg = 'Scheduled {source.name} with the following crontab: {cron}'
    log.info(msg.format(source=source, cron=source.periodic_task.crontab))
1371728
def parse_schedules(username, password, importer, progress, utc_start=None, 
                    utc_stop=None):
    """"""

    file_obj = get_file_object(username, password, utc_start, utc_stop)
    process_file_object(file_obj, importer, progress)
987826
def _do_cancel_problems(self):
        
        try:
            while True:
                # Pull as many problems as we can, block when none are available.

                # `None` task is used to signal thread termination
                item = self._cancel_queue.get()
                if item is None:
                    break

                item_list = [item]
                while True:
                    try:
                        item_list.append(self._cancel_queue.get_nowait())
                    except queue.Empty:
                        break

                # Submit the problems, attach the ids as a json list in the
                # body of the delete query.
                try:
                    body = [item[0] for item in item_list]

                    try:
                        self.session.delete(posixpath.join(self.endpoint, 'problems/'), json=body)
                    except requests.exceptions.Timeout:
                        raise RequestTimeout

                except Exception as err:
                    for _, future in item_list:
                        if future is not None:
                            future._set_error(err, sys.exc_info())

                # Mark all the ids as processed regardless of success or failure.
                [self._cancel_queue.task_done() for _ in item_list]

                # this is equivalent to a yield to scheduler in other threading libraries
                time.sleep(0)

        except Exception as err:
            _LOGGER.exception(err)
930857
def time_conflict(self, schedule):
        
        if is_nil(schedule):
            return True
        for timerange in self._excluded_times:
            if timerange.conflicts_with(schedule):
                return False
        return True
798268
private void addCalendarExceptions(Table table, ProjectCalendar calendar, Integer exceptionID)
   {
      Integer currentExceptionID = exceptionID;
      while (true)
      {
         MapRow row = table.find(currentExceptionID);
         if (row == null)
         {
            break;
         }

         Date date = row.getDate("DATE");
         ProjectCalendarException exception = calendar.addCalendarException(date, date);
         if (row.getBoolean("WORKING"))
         {
            exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);
            exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);
         }

         currentExceptionID = row.getInteger("NEXT_CALENDAR_EXCEPTION_ID");
      }
   }
617572
private void processExceptionDays(ProjectCalendar mpxjCalendar, net.sf.mpxj.planner.schema.Calendar plannerCalendar) throws MPXJException
   {
      Days days = plannerCalendar.getDays();
      if (days != null)
      {
         List<net.sf.mpxj.planner.schema.Day> dayList = days.getDay();
         for (net.sf.mpxj.planner.schema.Day day : dayList)
         {
            if (day.getType().equals("day-type"))
            {
               Date exceptionDate = getDate(day.getDate());
               ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate);
               if (getInt(day.getId()) == 0)
               {
                  for (int hoursIndex = 0; hoursIndex < m_defaultWorkingHours.size(); hoursIndex++)
                  {
                     DateRange range = m_defaultWorkingHours.get(hoursIndex);
                     exception.addRange(range);
                  }
               }
            }
         }
      }
   }