Handle repeater-quarter-name/scalar-year
515460
def handle_rqn_sy(tokens, options)
      year = tokens[1].get_tag(ScalarYear).type
      quarter_tag = tokens[0].get_tag(RepeaterQuarterName)
      quarter_tag.start = Chronic.construct(year)
      quarter_tag.this(:none)
    end
996242
function quarterFormat() {

  const format = function(d) {
    return formats.year.data(d) + "q" + formatQuarter(d);
  };

  format.parse = function(dateString) {
    const matchedDate = dateString.match(/^(\d{4})q(\d)$/);
    return matchedDate ? getDateFromQuarter(matchedDate[1], matchedDate[2]) : null;
  };

  const formatQuarter = function(d) {
    if (!(d instanceof Date)) d = new Date(+d);
    return ((d.getUTCMonth() / 3) | 0) + 1;
  };

  const getDateFromQuarter = function(p1, p2) {
    const quarter = parseInt(p2);
    const month = 3 * quarter - 2; // first month in quarter
    const year = p1;
    return formats.month.data.parse([year, (month < 9 ? "0" : "") + month].join("-"));
  };

  return format;
}
1259540
def repeater(self, value):
        
        try:
            value = int(value)
            self.repeater_start = value
            self.repeater_end = value
            return self
        except ValueError:
            pass
        if value == '+':
            self.repeater_start = 1
            self.repeater_end = None
        if value == '*':
            self.repeater_start = 0
            self.repeater_end = None
        elif value == '?':
            self.repeater_start = 0
            self.repeater_end = 1
        else:
            match = re.match(r'\{\s*(\d*)\s*,?\s*(\d*)\s*\}', value)
            if match:
                start = match.group(1)
                end = match.group(2)
                if start or end:
                    self.repeater_start = int(start) if start else 0
                    self.repeater_end = int(end) if end else None
        return self
3475
public static function getQuarter($quarter = 'current')
    {

        $response['startDate']  = null;
        $response['endDate']    = null;

        switch ($quarter)
        {
            case 'current': // current quarter
                $currentMonth   = date('m');
                $currentYear    = date('Y');

                if($currentMonth >= 1 && $currentMonth <= 3)
                {
                    $response['startDate']  = strtotime('1-January-' . $currentYear);  // timestamp or 1-Januray 12:00:00 AM
                    $response['endDate']    = strtotime('1-April-' . $currentYear);  // timestamp or 1-April 12:00:00 AM means end of 31 March
                }
                elseif($currentMonth >= 4 && $currentMonth <= 6)
                {
                    $response['startDate']  = strtotime('1-April-' . $currentYear);  // timestamp or 1-April 12:00:00 AM
                    $response['endDate']    = strtotime('1-July-' . $currentYear);  // timestamp or 1-July 12:00:00 AM means end of 30 June
                }
                elseif($currentMonth >= 7 && $currentMonth <= 9)
                {
                    $response['startDate']  = strtotime('1-July-' . $currentYear);  // timestamp or 1-July 12:00:00 AM
                    $response['endDate']    = strtotime('1-October-' . $currentYear);  // timestamp or 1-October 12:00:00 AM means end of 30 September
                }
                elseif($currentMonth >= 10 && $currentMonth <= 12)
                {
                    $response['startDate']  = strtotime('1-October-' . $currentYear);  // timestamp or 1-October 12:00:00 AM
                    $response['endDate']    = strtotime('1-January-' . ($currentYear + 1));  // timestamp or 1-January Next year 12:00:00 AM means end of 31 December this year
                }
                break;

            case 'last': // daily, get values of last day
                $currentMonth = date('m');
                $currentYear = date('Y');

                if($currentMonth >= 1 && $currentMonth <= 3)
                {
                    $response['startDate']  = strtotime('1-October-' . ($currentYear - 1));  // timestamp or 1-October Last Year 12:00:00 AM
                    $response['endDate']    = strtotime('1-January-' . $currentYear);  // // timestamp or 1-January  12:00:00 AM means end of 31 December Last year
                }
                elseif($currentMonth >= 4 && $currentMonth <= 6)
                {
                    $response['startDate']  = strtotime('1-January-' . $currentYear);  // timestamp or 1-Januray 12:00:00 AM
                    $response['endDate']    = strtotime('1-April-' . $currentYear);  // timestamp or 1-April 12:00:00 AM means end of 31 March
                }
                elseif($currentMonth >= 7 && $currentMonth <= 9)
                {
                    $response['startDate']  = strtotime('1-April-' . $currentYear);  // timestamp or 1-April 12:00:00 AM
                    $response['endDate']    = strtotime('1-July-' . $currentYear);  // timestamp or 1-July 12:00:00 AM means end of 30 June
                }
                elseif($currentMonth >= 10 && $currentMonth <= 12)
                {
                    $response['startDate']  = strtotime('1-July-' . $currentYear);  // timestamp or 1-July 12:00:00 AM
                    $response['endDate']    = strtotime('1-October-' . $currentYear);  // timestamp or 1-October 12:00:00 AM means end of 30 September
                }
                break;
        }

        return $response;
    }
1305934
Object getValue(String str, ValidationContext vc) throws DatatypeException {
    boolean negative = false;
    int year = 2000; // any leap year will do
    int month = 1;
    int day = 1;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    int milliseconds = 0;
    int pos = 0;
    int len = str.length();
    for (int templateIndex = 0, templateLength = template.length();
         templateIndex < templateLength;
         templateIndex++) {
      char templateChar = template.charAt(templateIndex);
      switch (templateChar) {
      case 'Y':
        negative = str.charAt(pos) == '-';
        int yearStartIndex = negative ? pos + 1 : pos;
        pos = skipDigits(str, yearStartIndex);
        try {
          year = Integer.parseInt(str.substring(yearStartIndex, pos));
        }
        catch (NumberFormatException e) {
          throw createLexicallyInvalidException();
        }
        break;
      case 'M':
        month = parse2Digits(str, pos);
        pos += 2;
        break;
      case 'D':
        day = parse2Digits(str, pos);
        pos += 2;
        break;
      case 't':
        hours = parse2Digits(str, pos);
        pos += 3;
        minutes = parse2Digits(str, pos);
        pos += 3;
        seconds = parse2Digits(str, pos);
        pos += 2;
        if (pos < len && str.charAt(pos) == '.') {
          int end = skipDigits(str, ++pos);
          for (int j = 0; j < 3; j++) {
            milliseconds *= 10;
            if (pos < end)
              milliseconds += str.charAt(pos++) - '0';
          }
          pos = end;
        }
        break;
      default:
        pos++;
        break;
      }
    }
    boolean hasTimeZone = pos < len;
    int tzOffset;
    if (hasTimeZone && str.charAt(pos) != 'Z')
      tzOffset = parseTimeZone(str, pos);
    else
      tzOffset = 0;
    int leapMilliseconds;
    if (seconds == 60) {
      leapMilliseconds = milliseconds + 1;
      milliseconds = 999;
      seconds = 59;
    }
    else
      leapMilliseconds = 0;
    try {
      GregorianCalendar cal = CalendarFactory.getCalendar();
      Date date;
      if (cal == CalendarFactory.cal) {
        synchronized (cal) {
          date = createDate(cal, tzOffset, negative, year, month, day, hours, minutes, seconds, milliseconds);
        }
      }
      else
        date = createDate(cal, tzOffset, negative, year, month, day, hours, minutes, seconds, milliseconds);
      return new DateTime(date, leapMilliseconds, hasTimeZone);
    }
    catch (IllegalArgumentException e) {
      throw createLexicallyInvalidException();
    }
  }
1129194
def handle_sm_sy(tokens, options)
      month = tokens[0].get_tag(ScalarMonth).type
      year = tokens[1].get_tag(ScalarYear).type

      if month == 12
        next_month_year = year + 1
        next_month_month = 1
      else
        next_month_year = year
        next_month_month = month + 1
      end

      begin
        end_time = Chronic.time_class.local(next_month_year, next_month_month)
        Span.new(Chronic.time_class.local(year, month), end_time)
      rescue ArgumentError
        nil
      end
    end
729211
@Override
  public Date getFireTimeAfter(Date afterTime) {

    if (complete) {
      return null;
    }

    if ((timesTriggered > repeatCount) && (repeatCount != REPEAT_INDEFINITELY)) {
      return null;
    }

    if (afterTime == null) {
      afterTime = new Date();
    }

    if (repeatCount == 0 && afterTime.compareTo(getStartTime()) >= 0) {
      return null;
    }

    long startMillis = getStartTime().getTime();
    long afterMillis = afterTime.getTime();
    long endMillis = (getEndTime() == null) ? Long.MAX_VALUE : getEndTime().getTime();

    if (endMillis <= afterMillis) {
      return null;
    }

    if (afterMillis < startMillis) {
      return new Date(startMillis);
    }

    long numberOfTimesExecuted = ((afterMillis - startMillis) / repeatInterval) + 1;

    if ((numberOfTimesExecuted > repeatCount) && (repeatCount != REPEAT_INDEFINITELY)) {
      return null;
    }

    Date time = new Date(startMillis + (numberOfTimesExecuted * repeatInterval));

    if (endMillis <= time.getTime()) {
      return null;
    }

    return time;
  }
653341
static Year parseYear(final String string) {
		return string != null ? Year.of(Integer.parseInt(string)) : null;
	}
853168
protected void handleVersion(
      EntityDesc entityDesc, EntityPropertyDesc propertyDesc, ColumnMeta columnMeta) {
    if (isVersionAnnotatable(propertyDesc.getPropertyClassName())) {
      if (versionColumnNamePattern.matcher(columnMeta.getName()).matches()) {
        propertyDesc.setVersion(true);
      }
    }
  }
724332
def formatmonthname(self, theyear, themonth, withyear=True):
        """"""
        monthname = '%s %s' % (MONTHS[themonth].title(), theyear)
        return '<caption>%s</caption>' % monthname
188585
def _serialize_date(value):
    """"""
    if not isinstance(value, date):
        raise ValueError(u'The received object was not a date: '
                         u'{} {}'.format(type(value), value))
    return value.isoformat()
1051754
@Deprecated
    protected int handleGetExtendedYear() {
        int eyear;
        if (newerField(EXTENDED_YEAR, YEAR) == EXTENDED_YEAR) {
            eyear = internalGet(EXTENDED_YEAR, 1); // Default to year 1
        } else {
            // The year defaults to the epoch start, the era to AD
            int era = internalGet(ERA, CE);
            if (era == BCE) {
                eyear = 1 - internalGet(YEAR, 1); // Convert to extended year
            } else {
                eyear = internalGet(YEAR, 1); // Default to year 1
            }
        }
        return eyear;
    }
1200911
function getWhatYear (date, year, month) {
  var number
  date = toStringDate(date)
  if (baseExports.isDate(date)) {
    if (year) {
      number = year && !isNaN(year) ? year : 0
      date.setFullYear(_dateFullYear(date) + number)
    }
    if (month || !isNaN(month)) {
      if (month === STRING_FIRST) {
        return new Date(_dateFullYear(date), 0, 1)
      } else if (month === STRING_LAST) {
        date.setMonth(11)
        return getWhatMonth(date, 0, STRING_LAST)
      } else {
        date.setMonth(month)
      }
    }
  }
  return date
}
490294
def handle_orr(tokens, outer_span, options)
      repeater = tokens[1].get_tag(Repeater)
      repeater.start = outer_span.begin - 1
      ordinal = tokens[0].get_tag(Ordinal).type
      span = nil

      ordinal.times do
        span = repeater.next(:future)

        if span.begin >= outer_span.end
          span = nil
          break
        end
      end

      span
    end
109543
private void handleGetAllMetricName(final int executorId, final HttpServletRequest req,
      final HashMap<String, Object> ret) throws IOException {
    final Map<String, Object> result;
    try {
      result =
          this.execManagerAdapter.callExecutorStats(executorId,
              ConnectorParams.STATS_GET_ALLMETRICSNAME,
              (Pair<String, String>[]) null);

      if (result.containsKey(ConnectorParams.RESPONSE_ERROR)) {
        ret.put("error", result.get(ConnectorParams.RESPONSE_ERROR).toString());
      } else {
        ret.put("metricList", result.get("data"));
      }
    } catch (final ExecutorManagerException e) {
      logger.error(e.getMessage(), e);
      ret.put("error", "Failed to fetch metric names for executor : "
          + executorId);
    }
  }
301063
public void parse(String recur) {
        /*
         * From RFC 2445 section 4.3.10:
         *
         * recur = "FREQ"=freq *(
         *       ; either UNTIL or COUNT may appear in a 'recur',
         *       ; but UNTIL and COUNT MUST NOT occur in the same 'recur'
         *
         *       ( ";" "UNTIL" "=" enddate ) /
         *       ( ";" "COUNT" "=" 1*DIGIT ) /
         *
         *       ; the rest of these keywords are optional,
         *       ; but MUST NOT occur more than once
         *
         *       ( ";" "INTERVAL" "=" 1*DIGIT )          /
         *       ( ";" "BYSECOND" "=" byseclist )        /
         *       ( ";" "BYMINUTE" "=" byminlist )        /
         *       ( ";" "BYHOUR" "=" byhrlist )           /
         *       ( ";" "BYDAY" "=" bywdaylist )          /
         *       ( ";" "BYMONTHDAY" "=" bymodaylist )    /
         *       ( ";" "BYYEARDAY" "=" byyrdaylist )     /
         *       ( ";" "BYWEEKNO" "=" bywknolist )       /
         *       ( ";" "BYMONTH" "=" bymolist )          /
         *       ( ";" "BYSETPOS" "=" bysplist )         /
         *       ( ";" "WKST" "=" weekday )              /
         *       ( ";" x-name "=" text )
         *       )
         *
         *  The rule parts are not ordered in any particular sequence.
         *
         * Examples:
         *   FREQ=MONTHLY;INTERVAL=2;COUNT=10;BYDAY=1SU,-1SU
         *   FREQ=YEARLY;INTERVAL=4;BYMONTH=11;BYDAY=TU;BYMONTHDAY=2,3,4,5,6,7,8
         *
         * Strategy:
         * (1) Split the string at ';' boundaries to get an array of rule "parts".
         * (2) For each part, find substrings for left/right sides of '=' (name/value).
         * (3) Call a <name>-specific parsing function to parse the <value> into an
         *     output field.
         *
         * By keeping track of which names we've seen in a bit vector, we can verify the
         * constraints indicated above (FREQ appears first, none of them appear more than once --
         * though x-[name] would require special treatment), and we have either UNTIL or COUNT
         * but not both.
         *
         * In general, RFC 2445 property names (e.g. "FREQ") and enumerations ("TU") must
         * be handled in a case-insensitive fashion, but case may be significant for other
         * properties.  We don't have any case-sensitive values in RRULE, except possibly
         * for the custom "X-" properties, but we ignore those anyway.  Thus, we can trivially
         * convert the entire string to upper case and then use simple comparisons.
         *
         * Differences from previous version:
         * - allows lower-case property and enumeration values [optional]
         * - enforces that FREQ appears first
         * - enforces that only one of UNTIL and COUNT may be specified
         * - allows (but ignores) X-* parts
         * - improved validation on various values (e.g. UNTIL timestamps)
         * - error messages are more specific
         *
         * TODO: enforce additional constraints listed in RFC 5545, notably the "N/A" entries
         * in section 3.3.10.  For example, if FREQ=WEEKLY, we should reject a rule that
         * includes a BYMONTHDAY part.
         */

        /* TODO: replace with "if (freq != 0) throw" if nothing requires this */
        resetFields();

        int parseFlags = 0;
        String[] parts;
        if (ALLOW_LOWER_CASE) {
            parts = recur.toUpperCase().split(";");
        } else {
            parts = recur.split(";");
        }
        for (String part : parts) {
            // allow empty part (e.g., double semicolon ";;")
            if (TextUtils.isEmpty(part)) {
                continue;
            }
            int equalIndex = part.indexOf('=');
            if (equalIndex <= 0) {
                /* no '=' or no LHS */
                throw new InvalidFormatException("Missing LHS in " + part);
            }

            String lhs = part.substring(0, equalIndex);
            String rhs = part.substring(equalIndex + 1);
            if (rhs.length() == 0) {
                throw new InvalidFormatException("Missing RHS in " + part);
            }

            /*
             * In lieu of a "switch" statement that allows string arguments, we use a
             * map from strings to parsing functions.
             */
            PartParser parser = sParsePartMap.get(lhs);
            if (parser == null) {
                if (lhs.startsWith("X-")) {
                    //Log.d(TAG, "Ignoring custom part " + lhs);
                    continue;
                }
                throw new InvalidFormatException("Couldn't find parser for " + lhs);
            } else {
                int flag = parser.parsePart(rhs, this);
                if ((parseFlags & flag) != 0) {
                    throw new InvalidFormatException("Part " + lhs + " was specified twice");
                }
                parseFlags |= flag;
            }
        }

        // If not specified, week starts on Monday.
        if ((parseFlags & PARSED_WKST) == 0) {
            wkst = MO;
        }

        // FREQ is mandatory.
        if ((parseFlags & PARSED_FREQ) == 0) {
            throw new InvalidFormatException("Must specify a FREQ value");
        }

        // Can't have both UNTIL and COUNT.
        if ((parseFlags & (PARSED_UNTIL | PARSED_COUNT)) == (PARSED_UNTIL | PARSED_COUNT)) {
            if (ONLY_ONE_UNTIL_COUNT) {
                throw new InvalidFormatException("Must not specify both UNTIL and COUNT: " + recur);
            } else {
                Log.w(TAG, "Warning: rrule has both UNTIL and COUNT: " + recur);
            }
        }
    }
71227
def set_year(self, year):
        
        self._set_attr(TDRC(encoding=3, text=str(year)))