Create a iCal file from the schedule
519794
def get(self, request):
        """"""
        # Heavily inspired by https://djangosnippets.org/snippets/2223/ and
        # the icalendar documentation
        calendar = Calendar()
        site = get_current_site(request)
        calendar.add('prodid', '-//%s Schedule//%s//' % (site.name, site.domain))
        calendar.add('version', '2.0')

        # Since we don't need to format anything here, we can just use a list
        # of schedule items
        for item in ScheduleItem.objects.all():
            sched_event = Event()
            sched_event.add('dtstamp', item.last_updated)
            sched_event.add('summary', item.get_title())
            sched_event.add('location', item.venue.name)
            sched_event.add('dtstart', item.get_start_datetime())
            sched_event.add('duration', datetime.timedelta(minutes=item.get_duration_minutes()))
            sched_event.add('class', 'PUBLIC')
            sched_event.add('uid', '%s@%s' % (item.pk, site.domain))
            calendar.add_component(sched_event)
        response = HttpResponse(calendar.to_ical(), content_type="text/calendar")
        response['Content-Disposition'] = 'attachment; filename=schedule.ics'
        return response
175739
private void addCalendars(MpxjTreeNode parentNode, ProjectFile file)
   {
      for (ProjectCalendar calendar : file.getCalendars())
      {
         addCalendar(parentNode, calendar);
      }
   }
1142334
def schedule(ident, cron=None, minute='*', hour='*',
             day_of_week='*', day_of_month='*', month_of_year='*'):
    ''''''
    source = get_source(ident)

    if cron:
        minute, hour, day_of_month, month_of_year, day_of_week = cron.split()

    crontab = PeriodicTask.Crontab(
        minute=str(minute),
        hour=str(hour),
        day_of_week=str(day_of_week),
        day_of_month=str(day_of_month),
        month_of_year=str(month_of_year)
    )

    if source.periodic_task:
        source.periodic_task.modify(crontab=crontab)
    else:
        source.modify(periodic_task=PeriodicTask.objects.create(
            task='harvest',
            name='Harvest {0}'.format(source.name),
            description='Periodic Harvesting',
            enabled=True,
            args=[str(source.id)],
            crontab=crontab,
        ))
    signals.harvest_source_scheduled.send(source)
    return source
701283
function(aSrc, aDeep) {
    if (!aSrc || typeof aSrc != "object") {
      return aSrc;
    } else if (aSrc instanceof Date) {
      return new Date(aSrc.getTime());
    } else if ("clone" in aSrc) {
      return aSrc.clone();
    } else if (Array.isArray(aSrc)) {
      var arr = [];
      for (var i = 0; i < aSrc.length; i++) {
        arr.push(aDeep ? ICAL.helpers.clone(aSrc[i], true) : aSrc[i]);
      }
      return arr;
    } else {
      var obj = {};
      for (var name in aSrc) {
        // uses prototype method to allow use of Object.create(null);
        /* istanbul ignore else */
        if (Object.prototype.hasOwnProperty.call(aSrc, name)) {
          if (aDeep) {
            obj[name] = ICAL.helpers.clone(aSrc[name], true);
          } else {
            obj[name] = aSrc[name];
          }
        }
      }
      return obj;
    }
  }
885211
def _create_scheduler(self, save_sensors):
        """"""
        @asyncio.coroutine
        def schedule_save():
            """Save sensors and schedule a new save."""
            yield from self.loop.run_in_executor(None, save_sensors)
            callback = partial(self.loop.create_task, schedule_save())
            task = self.loop.call_later(10.0, callback)
            self._cancel_save = task.cancel
        return schedule_save
1144485
private static Calendar toCalendar(Date self) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(self);
        return cal;
    }
1010199
def schedule_blast_from_template(template, list, schedule_time, options={})
      post = options ? options : {}
      post[:copy_template] = template
      post[:list] = list
      post[:schedule_time] = schedule_time
      api_post(:blast, post)
    end
1172619
function() {
      var string = this.toString();

      if (string.length > 10) {
        return ICAL.design.icalendar.value['date-time'].toICAL(string);
      } else {
        return ICAL.design.icalendar.value.date.toICAL(string);
      }
    }
934076
public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {
		return new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),
				getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());
	}
175799
def append_vobject(self, ical, filename=None):
        """"""
        if not filename:
            filename = self._filename
        elif filename not in self._reminders:
            return

        with self._lock:
            outdat = self.to_reminders(ical)
            open(filename, 'a').write(outdat)

        return Remind._get_uid(outdat)
189232
def create(sub_array_id):
    """"""
    config = request.data
    config['sub_array_id'] = 'subarray-{:02d}'.format(sub_array_id)
    return add_scheduling_block(config)
534642
def parse_ics(icsfile):
    """"""
    events = []

    cal = Calendar.from_ical(open(icsfile, 'rb').read())
    for component in cal.walk('vevent'):
        dtstart = component['dtstart'].dt
        rrule = component['rrule']

        freq, args = convert_rrule(rrule)
        args['dtstart'] = dtstart

        rrule = dateutil.rrule.rrule(freq, **args)

        summary = vText.from_ical(component.get('summary', u''))
        description = vText.from_ical(component.get('description', u''))
        organizer = vText.from_ical(component.get('organizer', u''))

        # TODO: Find an event id.  If it's not there, then compose one
        # with dtstart, summary, and organizer.
        event_id = "::".join((str(dtstart), summary, organizer))

        events.append(Event(event_id, rrule, summary, description))
    return events
116741
def save_ical(self, ical_location):  # type: (str) -> None
        
        data = self.cal.to_ical()
        with open(ical_location, 'w') as ical_file:
            ical_file.write(data.decode('utf-8'))
465332
private void processCalendarData() throws MPXJException, IOException
   {
      DirectoryEntry calDir = (DirectoryEntry) m_projectDir.getEntry("TBkndCal");
      FixFix calendarFixedData = new FixFix(36, new DocumentInputStream(((DocumentEntry) calDir.getEntry("FixFix   0"))));
      FixDeferFix calendarVarData = new FixDeferFix(new DocumentInputStream(((DocumentEntry) calDir.getEntry("FixDeferFix   0"))));

      ProjectCalendar cal;
      ProjectCalendarHours hours;
      ProjectCalendarException exception;
      String name;
      byte[] baseData;
      byte[] extData;

      int periodCount;
      int index;
      int offset;
      int defaultFlag;
      Date start;
      long duration;
      int exceptionCount;

      //
      // Configure default time ranges
      //
      SimpleDateFormat df = new SimpleDateFormat("HH:mm");
      Date defaultStart1;
      Date defaultEnd1;
      Date defaultStart2;
      Date defaultEnd2;

      try
      {
         defaultStart1 = df.parse("08:00");
         defaultEnd1 = df.parse("12:00");
         defaultStart2 = df.parse("13:00");
         defaultEnd2 = df.parse("17:00");
      }

      catch (ParseException ex)
      {
         throw new MPXJException(MPXJException.INVALID_FORMAT, ex);
      }

      int calendars = calendarFixedData.getItemCount();
      int calendarID;
      int baseCalendarID;
      int periodIndex;
      Day day;
      List<Pair<ProjectCalendar, Integer>> baseCalendars = new LinkedList<Pair<ProjectCalendar, Integer>>();

      for (int loop = 0; loop < calendars; loop++)
      {
         baseData = calendarFixedData.getByteArrayValue(loop);
         calendarID = MPPUtility.getInt(baseData, 0);
         baseCalendarID = MPPUtility.getInt(baseData, 4);
         name = calendarVarData.getUnicodeString(getOffset(baseData, 20));

         //
         // Uncommenting the call to this method is useful when trying
         // to determine the function of unknown task data.
         //
         //dumpUnknownData (name + " " + MPPUtility.getInt(baseData), UNKNOWN_CALENDAR_DATA, baseData);

         //
         // Skip calendars with negative ID values
         //
         if (calendarID < 0)
         {
            continue;
         }

         //
         // Populate the basic calendar
         //
         ExtendedData ed = new ExtendedData(calendarVarData, getOffset(baseData, 32));
         offset = -1 - ed.getInt(Integer.valueOf(8));

         if (offset == -1)
         {
            if (baseCalendarID > 0)
            {
               cal = m_file.addDefaultDerivedCalendar();
               baseCalendars.add(new Pair<ProjectCalendar, Integer>(cal, Integer.valueOf(baseCalendarID)));
            }
            else
            {
               cal = m_file.addDefaultBaseCalendar();
               cal.setName(name);
            }

            cal.setUniqueID(Integer.valueOf(calendarID));
         }
         else
         {
            if (baseCalendarID > 0)
            {
               cal = m_file.addCalendar();
               baseCalendars.add(new Pair<ProjectCalendar, Integer>(cal, Integer.valueOf(baseCalendarID)));
            }
            else
            {
               cal = m_file.addCalendar();
               cal.setName(name);
            }

            cal.setUniqueID(Integer.valueOf(calendarID));

            extData = calendarVarData.getByteArray(offset);

            for (index = 0; index < 7; index++)
            {
               offset = 4 + (40 * index);

               defaultFlag = MPPUtility.getShort(extData, offset);
               day = Day.getInstance(index + 1);

               if (defaultFlag == 1)
               {
                  cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]);
                  if (cal.isWorkingDay(day) == true)
                  {
                     hours = cal.addCalendarHours(net.sf.mpxj.Day.getInstance(index + 1));
                     hours.addRange(new DateRange(defaultStart1, defaultEnd1));
                     hours.addRange(new DateRange(defaultStart2, defaultEnd2));
                  }
               }
               else
               {
                  periodCount = MPPUtility.getShort(extData, offset + 2);
                  if (periodCount == 0)
                  {
                     cal.setWorkingDay(day, false);
                  }
                  else
                  {
                     cal.setWorkingDay(day, true);
                     hours = cal.addCalendarHours(Day.getInstance(index + 1));

                     for (periodIndex = 0; periodIndex < periodCount; periodIndex++)
                     {
                        start = MPPUtility.getTime(extData, offset + 8 + (periodIndex * 2));
                        duration = MPPUtility.getDuration(extData, offset + 16 + (periodIndex * 4));
                        hours.addRange(new DateRange(start, new Date(start.getTime() + duration)));
                     }
                  }
               }
            }

            //
            // Handle any exceptions
            //
            exceptionCount = MPPUtility.getShort(extData, 0);
            if (exceptionCount != 0)
            {
               for (index = 0; index < exceptionCount; index++)
               {
                  offset = 4 + (40 * 7) + (index * 44);

                  Date fromDate = MPPUtility.getDate(extData, offset);
                  Date toDate = MPPUtility.getDate(extData, offset + 2);
                  exception = cal.addCalendarException(fromDate, toDate);

                  periodCount = MPPUtility.getShort(extData, offset + 6);
                  if (periodCount != 0)
                  {
                     for (int exceptionPeriodIndex = 0; exceptionPeriodIndex < periodCount; exceptionPeriodIndex++)
                     {
                        start = MPPUtility.getTime(extData, offset + 12 + (exceptionPeriodIndex * 2));
                        duration = MPPUtility.getDuration(extData, offset + 20 + (exceptionPeriodIndex * 4));
                        exception.addRange(new DateRange(start, new Date(start.getTime() + duration)));
                     }
                  }
               }
            }
         }

         m_calendarMap.put(Integer.valueOf(calendarID), cal);
         m_eventManager.fireCalendarReadEvent(cal);
      }

      updateBaseCalendarNames(baseCalendars);
   }
252302
public function initFile($file)
    {
        if (empty($this->cal)) {
            $lines = $this->fileOrUrl($file);

            $this->initLines($lines);
        } else {
            trigger_error('ICal::initFile: Calendar already initialised in constructor', E_USER_NOTICE);
        }

        return $this;
    }
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))
803018
function cronToText(cronspec, sixth, locale = LOCALE) {
  var schedule = parseCron(cronspec, sixth);

  function absFloor(number) {
    if (number < 0) {
      return Math.ceil(number);
    } else {
      return Math.floor(number);
    }
  }

  function toInt(argumentForCoercion) {
    var coercedNumber = +argumentForCoercion,
      value = 0;

    if (coercedNumber !== 0 && isFinite(coercedNumber)) {
      value = absFloor(coercedNumber);
    }

    return value;
  }

  function ordinal(number) {
    var b = number % 10,
      output = (toInt(number % 100 / 10) === 1) ? locale.ORDINALS.th :
        (b === 1) ? locale.ORDINALS.st :
          (b === 2) ? locale.ORDINALS.nd :
            (b === 3) ? locale.ORDINALS.rd : locale.ORDINALS.th;
    return number + output;
  }

  /**
   * For an array of numbers, e.g. a list of hours in a schedule,
   * return a string listing out all of the values (complete with
   * "and" plus ordinal text on the last item).
   * @param {Number[]} numbers
   * @returns {string}
   */
  function numberList(numbers) {
    if (numbers.length < 2) {
      return ordinal(numbers);
    }

    var lastVal = numbers.pop();
    return numbers.join(', ') + ` ${locale['and']} ` + ordinal(lastVal);
  }

  /**
   * Parse a number into day of week, or a month name;
   * used in dateList below.
   * @param {Number|String} value
   * @param {String} type
   * @returns {String}
   */
  function numberToDateName(value, type) {
    if (type == 'dow') {
      return locale.DOW[value - 1];
    } else if (type == 'mon') {
      return locale.MONTH[value - 1];
    }
  }

  /**
   * From an array of numbers corresponding to dates (given in type: either
   * days of the week, or months), return a string listing all the values.
   * @param {Number[]} numbers
   * @param {String} type
   * @returns {String}
   */
  function dateList(numbers, type) {
    if (numbers.length < 2) {
      return numberToDateName('' + numbers[0], type);
    }

    var lastVal = '' + numbers.pop();
    var outputText = '';

    for (var i = 0, value; value = numbers[i]; i++) {
      if (outputText.length > 0) {
        outputText += ', ';
      }
      outputText += numberToDateName(value, type);
    }
    return outputText + ` ${locale['and']} ` + numberToDateName(lastVal, type);
  }

  /**
   * Pad to equivalent of sprintf('%02d').
   * @param {Number} x
   * @returns {string}
   */
  function zeroPad(x) {
    return (x < 10) ? '0' + x : x;
  }

  //----------------

  /**
   * Given a schedule, generate a friendly sentence description.
   * @param {Object} schedule
   * @returns {string}
   */
  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;
  }

  return scheduleToSentence(schedule.schedules[0]);
}