Wrapper around Google Calendar API's quickAdd
429162
def QuickAddEvent(self, event_text, reminders=None):
        """"""
        if not event_text:
            raise GcalcliError('event_text is required for a quickAdd')

        if len(self.cals) != 1:
            # TODO: get a better name for this exception class
            # and use it elsewhere
            raise GcalcliError('You must only specify a single calendar\n')

        new_event = self._retry_with_backoff(
            self.get_cal_service()
                .events()
                .quickAdd(
                    calendarId=self.cals[0]['id'],
                    text=event_text
                )
        )

        if reminders or not self.options['default_reminders']:
            rem = {}
            rem['reminders'] = {'useDefault': False,
                                'overrides': []}
            for r in reminders:
                n, m = utils.parse_reminder(r)
                rem['reminders']['overrides'].append({'minutes': n,
                                                      'method': m})

            new_event = self._retry_with_backoff(
                            self.get_cal_service()
                                .events()
                                .patch(
                                    calendarId=self.cals[0]['id'],
                                    eventId=new_event['id'],
                                    body=rem
                                )
                        )

        if self.details.get('url'):
            hlink = new_event['htmlLink']
            self.printer.msg('New event added: %s\n' % hlink, 'green')

        return new_event
943455
def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter):
    

    log('iCal importer running')

    objectmodels = ctx.obj['db'].objectmodels

    if objectmodels['user'].count({'name': owner}) > 0:
        owner_object = objectmodels['user'].find_one({'name': owner})
    elif objectmodels['user'].count({'uuid': owner}) > 0:
        owner_object = objectmodels['user'].find_one({'uuid': owner})
    else:
        log('User unknown. Specify either uuid or name.', lvl=warn)
        return

    log('Found user')

    if objectmodels['calendar'].count({'name': calendar}) > 0:
        calendar = objectmodels['calendar'].find_one({'name': calendar})
    elif objectmodels['calendar'].count({'uuid': owner}) > 0:
        calendar = objectmodels['calendar'].find_one({'uuid': calendar})
    elif create_calendar:
        calendar = objectmodels['calendar']({
            'uuid': std_uuid(),
            'name': calendar
        })
    else:
        log('Calendar unknown and no --create-calendar specified. Specify either uuid or name of an existing calendar.',
            lvl=warn)
        return

    log('Found calendar')

    if clear_calendar is True:
        log('Clearing calendar events')
        for item in objectmodels['event'].find({'calendar': calendar.uuid}):
            item.delete()

    with open(filename, 'rb') as file_object:
        caldata = Calendar.from_ical(file_object.read())

    keys = {
        'class': 'str',
        'created': 'dt',
        'description': 'str',
        'dtstart': 'dt',
        'dtend': 'dt',
        'timestamp': 'dt',
        'modified': 'dt',
        'location': 'str',
        'status': 'str',
        'summary': 'str',
        'uid': 'str'
    }
    mapping = {
        'description': 'summary',
        'summary': 'name'
    }

    imports = []

    def ical_import_filter(original, logfacilty):
        log('Passthrough filter')
        return original

    if execfilter is not None:
        import os

        textFilePath = os.path.abspath(os.path.join(os.path.curdir, execfilter))
        textFileFolder = os.path.dirname(textFilePath)

        from importlib.machinery import SourceFileLoader

        filter_module = SourceFileLoader("importfilter", textFilePath).load_module()
        ical_import_filter = filter_module.ical_import_filter

    for event in caldata.walk():
        if event.name == 'VEVENT':
            log(event, lvl=verbose, pretty=True)
            initializer = {
                'uuid': std_uuid(),
                'calendar': calendar.uuid,
            }

            for item in keys:
                thing = event.get(item, None)
                if thing is None:
                    thing = 'NO-' + item
                else:
                    if keys[item] == 'str':
                        thing = str(thing)
                    else:
                        thing = parser.parse(str(thing.dt))
                        thing = thing.isoformat()

                if item in mapping:
                    item_assignment = mapping[item]
                else:
                    item_assignment = item

                initializer[item_assignment] = thing
            new_event = objectmodels['event'](initializer)

            new_event = ical_import_filter(new_event, log)

            imports.append(new_event)

            log(new_event, lvl=debug)

    for ev in imports:
        log(ev.summary)

    if not dry:
        log('Bulk creating events')
        objectmodels['event'].bulk_create(imports)

        calendar.save()
    else:
        log('Dry run - nothing stored.', lvl=warn)
816332
function wrappedOrigCall(orgFunc, newFunc) {
    return function() {
        var args = [].slice.call(arguments);
        try { orgFunc.apply(WinConsole, args); } catch (e) {}
        try { newFunc.apply(console,    args); } catch (e) {}
    };
}
1155243
def put_calendar(self, calendar_id, body=None, params=None):
        
        if calendar_id in SKIP_IN_PATH:
            raise ValueError(
                "Empty value passed for a required argument 'calendar_id'."
            )
        return self.transport.perform_request(
            "PUT", _make_path("_ml", "calendars", calendar_id), params=params, body=body
        )
268816
def tag_event(self, calendar_id, event_id, extendedProperties):
        '''
        '''
        event_body = self.service.events().get(calendarId = self.configured_calendar_ids[calendar_id], eventId=event_id).execute()
        event_body['extendedProperties'] = event_body.get('extendedProperties', {})
        event_body['extendedProperties']['shared'] = event_body['extendedProperties'].get('shared', {})
        event_body['extendedProperties']['private'] = event_body['extendedProperties'].get('private', {})
        assert(sorted(set(extendedProperties.keys()).union(set(['shared', 'private']))) == ['private', 'shared'])
        for k, v in extendedProperties['shared'].iteritems():
            event_body['extendedProperties']['shared'][k] = v
        for k, v in extendedProperties['private'].iteritems():
            event_body['extendedProperties']['private'][k] = v
        raise Exception('not tested yet')
        updated_event = self.service.events().update(calendarId = self.configured_calendar_ids[calendar_id], eventId = event_id, body = event_body).execute()
1206355
def attach(item, action, greedy=False, ignore_no_tokens=None, ignore_one_token=None):
    """"""
    if use_computation_graph:
        # use the action's annotations to generate the defaults
        if ignore_no_tokens is None:
            ignore_no_tokens = getattr(action, "ignore_no_tokens", False)
        if ignore_one_token is None:
            ignore_one_token = getattr(action, "ignore_one_token", False)
        # only include True keyword arguments in the partial, since False is the default
        kwargs = {}
        if greedy:
            kwargs["greedy"] = greedy
        if ignore_no_tokens:
            kwargs["ignore_no_tokens"] = ignore_no_tokens
        if ignore_one_token:
            kwargs["ignore_one_token"] = ignore_one_token
        action = partial(ComputationNode, action, **kwargs)
    return add_action(item, action)
619082
function getDayPeriods(localeData, dayPeriodsList) {
  const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
  const result = {};
  // cleaning up unused keys
  Object.keys(dayPeriods).forEach(key1 => {          // format / stand-alone
    result[key1] = {};
    Object.keys(dayPeriods[key1]).forEach(key2 => {  // narrow / abbreviated / wide
      result[key1][key2] = {};
      Object.keys(dayPeriods[key1][key2]).forEach(key3 => {
        if (dayPeriodsList.indexOf(key3) !== -1) {
          result[key1][key2][key3] = dayPeriods[key1][key2][key3];
        }
      });
    });
  });

  return result;
}
313678
def build_calendar_etc(pfeed):
    
    windows = pfeed.service_windows.copy()

    # Create a service ID for each distinct days_active field and map the
    # service windows to those service IDs
    def get_sid(bitlist):
        return 'srv' + ''.join([str(b) for b in bitlist])

    weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
      'saturday', 'sunday']
    bitlists = set()

    # Create a dictionary <service window ID> -> <service ID>
    d = dict()
    for index, window in windows.iterrows():
        bitlist = window[weekdays].tolist()
        d[window['service_window_id']] = get_sid(bitlist)
        bitlists.add(tuple(bitlist))
    service_by_window = d

    # Create calendar
    start_date = pfeed.meta['start_date'].iat[0]
    end_date = pfeed.meta['end_date'].iat[0]
    F = []
    for bitlist in bitlists:
        F.append([get_sid(bitlist)] + list(bitlist) +
          [start_date, end_date])
    calendar = pd.DataFrame(F, columns=(
      ['service_id'] + weekdays + ['start_date', 'end_date']))

    return calendar, service_by_window
834797
def upsert_event(self, calendar_id, event):
        
        event['start'] = format_event_time(event['start'])
        event['end'] = format_event_time(event['end'])
        self.request_handler.post(
            endpoint='calendars/%s/events' % calendar_id, data=event)
1046269
private StringBuffer format(Calendar cal, DisplayContext capitalizationContext,
            StringBuffer toAppendTo, FieldPosition pos, List<FieldPosition> attributes) {
        // Initialize
        pos.setBeginIndex(0);
        pos.setEndIndex(0);

        // Careful: For best performance, minimize the number of calls
        // to StringBuffer.append() by consolidating appends when
        // possible.

        Object[] items = getPatternItems();
        for (int i = 0; i < items.length; i++) {
            if (items[i] instanceof String) {
                toAppendTo.append((String)items[i]);
            } else {
                PatternItem item = (PatternItem)items[i];
                int start = 0;
                if (attributes != null) {
                    // Save the current length
                    start = toAppendTo.length();
                }
                if (useFastFormat) {
                    subFormat(toAppendTo, item.type, item.length, toAppendTo.length(),
                              i, capitalizationContext, pos, cal);
                } else {
                    toAppendTo.append(subFormat(item.type, item.length, toAppendTo.length(),
                                                i, capitalizationContext, pos, cal));
                }
                if (attributes != null) {
                    // Check the sub format length
                    int end = toAppendTo.length();
                    if (end - start > 0) {
                        // Append the attribute to the list
                        DateFormat.Field attr = patternCharToDateFormatField(item.type);
                        FieldPosition fp = new FieldPosition(attr);
                        fp.setBeginIndex(start);
                        fp.setEndIndex(end);
                        attributes.add(fp);
                    }
                }
            }
        }
        return toAppendTo;

    }
195327
function createLogDumpAsync(userComments, callback) {
    g_browser.updateAllInfo(
        onUpdateAllCompleted.bind(null, userComments, callback));
  }
351150
function plugin(params) {
	logger = params.logger;
	params.dirname = params.dirname ? _.template(params.dirname)(params) : params.event.dir.resourcesPlatform;
	logger.trace("fixing underscore in directory: " + params.dirname);

	replace_content(path.join(params.dirname, "alloy.js"))
	replace_content(path.join(params.dirname, "alloy", "sync", "properties.js"))
	replace_content(path.join(params.dirname, "alloy", "sync", "sql.js"))
}
1342545
function pegParser(options, extension, cb) {
  if (typeof cb === 'undefined') {
    cb = extension;
    extension = null;
  }

  var grammarFiles = [];
  if (typeof options === 'string') {
    options = {grammar: options};
  }
  var grammar = options.grammar;
  if (typeof grammar === 'object') {
    if (grammar[extension]) {
      grammar = grammar[extension];
    }
  }
  if (typeof grammar !== 'string') {
    if (extension === 'js') {
      grammar = 'javascript';
    } else if (extension === 'md') {
      grammar = 'markdown';
    }
  }
  if (grammar) {
    grammarFiles.push(grammar);
    grammarFiles.push(path.join(__dirname, '../grammar', grammar + '.pegjs'));
  } else {
    grammarFiles.push(path.join(__dirname, '../grammar/javascript.pegjs'));
  }

  function findGrammarFile(wrapper, cb) {
    var grammarFile = wrapper.file;
    var cachedParser = quickpeg.parserFromMemory(grammarFile);
    if (cachedParser) {
      wrapper.parser = cachedParser;
      return cb(true);
    }

    var fsExists = fs.exists || path.exists;
    fsExists(grammarFile, function (exists) {
      if (!exists) {
        return cb(false);
      }

      quickpeg(grammarFile, function (err, cachedParser) {
        if (err) {
          wrapper.err = err;
          return;
        }
        wrapper.parser = cachedParser;
        return cb(true);
      });
    });
  }
  var grammarFileWrappers = grammarFiles.map(function (file) {
    return {
      parser: null,
      file: file,
      err: null
    };
  });
  async.detectSeries(grammarFileWrappers, findGrammarFile, function (wrapper) {
    if (wrapper.err || wrapper.parser) {
      return cb(wrapper.err, wrapper.parser, wrapper.file);
    }
    cb(new Error('grammar file not found'));
  });
}
266424
function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
    if (resultSelector) {
        if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__["isScheduler"])(resultSelector)) {
            scheduler = resultSelector;
        }
        else {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_4__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
            };
        }
    }
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var params = {
            subject: undefined,
            args: args,
            callbackFunc: callbackFunc,
            scheduler: scheduler,
            context: this,
        };
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) {
            var context = params.context;
            var subject = params.subject;
            if (!scheduler) {
                if (!subject) {
                    subject = params.subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
                    var handler = function () {
                        var innerArgs = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            innerArgs[_i] = arguments[_i];
                        }
                        var err = innerArgs.shift();
                        if (err) {
                            subject.error(err);
                            return;
                        }
                        subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
                        subject.complete();
                    };
                    try {
                        callbackFunc.apply(context, args.concat([handler]));
                    }
                    catch (err) {
                        subject.error(err);
                    }
                }
                return subject.subscribe(subscriber);
            }
            else {
                return scheduler.schedule(dispatch, 0, { params: params, subscriber: subscriber, context: context });
            }
        });
    };
}
1164026
function checkAdd(list, key, func) {
    list.push({key: key, func: func});
  }
200551
function bindCallback(callbackFunc, resultSelector, scheduler) {
    if (resultSelector) {
        if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_4__["isScheduler"])(resultSelector)) {
            scheduler = resultSelector;
        }
        else {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(_operators_map__WEBPACK_IMPORTED_MODULE_2__["map"])(function (args) { return Object(_util_isArray__WEBPACK_IMPORTED_MODULE_3__["isArray"])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
            };
        }
    }
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var context = this;
        var subject;
        var params = {
            context: context,
            subject: subject,
            callbackFunc: callbackFunc,
            scheduler: scheduler,
        };
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (subscriber) {
            if (!scheduler) {
                if (!subject) {
                    subject = new _AsyncSubject__WEBPACK_IMPORTED_MODULE_1__["AsyncSubject"]();
                    var handler = function () {
                        var innerArgs = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            innerArgs[_i] = arguments[_i];
                        }
                        subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
                        subject.complete();
                    };
                    try {
                        callbackFunc.apply(context, args.concat([handler]));
                    }
                    catch (err) {
                        subject.error(err);
                    }
                }
                return subject.subscribe(subscriber);
            }
            else {
                var state = {
                    args: args, subscriber: subscriber, params: params,
                };
                return scheduler.schedule(dispatch, 0, state);
            }
        });
    };
}
1103393
def _calendar_json_for_occurrence(self, occurrence):
        
        # Slugify the plugin's verbose name for use as a class name.
        if occurrence.is_all_day:
            start = occurrence.start
            # `end` is exclusive according to the doc in
            # http://fullcalendar.io/docs/event_data/Event_Object/, so
            # we need to add 1 day to ``end`` to have the end date
            # included in the calendar.
            end = occurrence.start + timedelta(days=1)
        else:
            start = djtz.localize(occurrence.start)
            end = djtz.localize(occurrence.end)
        if occurrence.is_cancelled and occurrence.cancel_reason:
            title = u"{0} [{1}]".format(
                occurrence.event.title, occurrence.cancel_reason)
        else:
            title = occurrence.event.title

        if occurrence.event.primary_type:
            color = occurrence.event.primary_type.color
        else:
            color = "#cccccc"
        return {
            'title': title,
            'allDay': occurrence.is_all_day or occurrence.event.contained_events.exists(),
            'start': start,
            'end': end,
            'url': reverse('admin:icekit_events_eventbase_change',
                           args=[occurrence.event.pk]),
            'className': self._calendar_classes_for_occurrence(occurrence),
            'backgroundColor': color,
        }