find xxx in a string of the form xxx[yyy=zzz] or xxxx
14498
static private Class findClassFor(String s) throws ClassNotFoundException
	{ 
		int endClassIndex = s.indexOf('[');
		if (endClassIndex>=0) s = s.substring(0,endClassIndex);
		try {
			return Class.forName(s);
		} catch (ClassNotFoundException e) {
			return Class.forName("com.wcohen.ss."+s);
		}
	}
631070
def parse_diff(base_str):
        
        temp_dict = {'years': 0,
                     'months': 0,
                     'weeks': 0,
                     'days': 0,
                     'hours': 0,
                     'minutes': 0,
                     'seconds': 0}

        _pure_str = re.findall("[a-zA-Z]+", base_str)
        pure_num = [int(_) for _ in re.findall(r'\d+', base_str)]
        pure_str = [filter_unit(_) for _ in _pure_str]
        result_dict = dict(chain(temp_dict.items(), dict(zip(pure_str, pure_num)).items()))
        if result_dict['months'] >= 12:
            advance = result_dict['months'] // 12
            remain = result_dict['months'] % 12
            result_dict['years'] += advance
            result_dict['months'] = remain
        if result_dict['weeks']:
            result_dict['days'] += result_dict['weeks'] * 7
        return result_dict
373769
function parse(string) {
            var match = isoDateExpression.exec(string);
            if (match) {
                // parse months, days, hours, minutes, seconds, and milliseconds
                // provide default values if necessary
                // parse the UTC offset component
                var year = $Number(match[1]),
                    month = $Number(match[2] || 1) - 1,
                    day = $Number(match[3] || 1) - 1,
                    hour = $Number(match[4] || 0),
                    minute = $Number(match[5] || 0),
                    second = $Number(match[6] || 0),
                    millisecond = Math.floor($Number(match[7] || 0) * 1000),
                    // When time zone is missed, local offset should be used
                    // (ES 5.1 bug)
                    // see https://bugs.ecmascript.org/show_bug.cgi?id=112
                    isLocalTime = Boolean(match[4] && !match[8]),
                    signOffset = match[9] === '-' ? 1 : -1,
                    hourOffset = $Number(match[10] || 0),
                    minuteOffset = $Number(match[11] || 0),
                    result;
                var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
                if (
                    hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
                    minute < 60 && second < 60 && millisecond < 1000 &&
                    month > -1 && month < 12 && hourOffset < 24 &&
                    minuteOffset < 60 && // detect invalid offsets
                    day > -1 &&
                    day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
                ) {
                    result = (
                        (dayFromMonth(year, month) + day) * 24 +
                        hour +
                        hourOffset * signOffset
                    ) * 60;
                    result = (
                        (result + minute + minuteOffset * signOffset) * 60 +
                        second
                    ) * 1000 + millisecond;
                    if (isLocalTime) {
                        result = toUTC(result);
                    }
                    if (-8.64e15 <= result && result <= 8.64e15) {
                        return result;
                    }
                }
                return NaN;
            }
            return NativeDate.parse.apply(this, arguments);
        }
1254772
def match_string(self, tokens, item):
        """"""
        prefix, name = tokens
        return self.match_mstring((prefix, name, None), item, use_bytes=prefix.startswith("b"))
1044827
def parse_date(datestring):
    
    datestring = str(datestring).strip()

    if not datestring[0].isdigit():
        raise ParseError()

    if 'W' in datestring.upper():
        try:
            datestring = datestring[:-1] + str(int(datestring[-1:]) -1)
        except:
            pass

    for regex, pattern in DATE_FORMATS:
        if regex.match(datestring):
            found = regex.search(datestring).groupdict()
            dt = datetime.utcnow().strptime(found['matched'], pattern)

            if 'fraction' in found and found['fraction'] is not None:
                dt = dt.replace(microsecond=int(found['fraction'][1:]))

            if 'timezone' in found and found['timezone'] is not None:
                dt = dt.replace(tzinfo=Timezone(found.get('timezone', '')))

            return dt

    return parse_time(datestring)
792907
def stringToDateTime(s, tzinfo=None):
    
    try:
        year = int(s[0:4])
        month = int(s[4:6])
        day = int(s[6:8])
        hour = int(s[9:11])
        minute = int(s[11:13])
        second = int(s[13:15])
        if len(s) > 15:
            if s[15] == 'Z':
                tzinfo = getTzid('UTC')
    except:
        raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
    year = year and year or 2000
    if tzinfo is not None and hasattr(tzinfo,'localize'):  # PyTZ case
        return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
    return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
939372
def strptime(string, timezone=0):
    """"""
    year = int(string[0:4])
    month = int(string[5:7])
    day = int(string[8:10])
    hour = int(string[-5:-3])
    minute = int(string[-2:])
    ts = datetime.datetime(year, month, day) + \
        datetime.timedelta(hours=hour, minutes=minute) - \
        datetime.timedelta(hours=timezone)
    return ts
930820
def parse_datetime(value):
    """"""

    if isinstance(value, (string_types, text_type, binary_type)):
        value = dateutil.parser.parse(value)
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    elif isinstance(value, datetime.datetime):
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    elif isinstance(value, datetime.date):
        value = datetime.datetime(value.year, value.month, value.day)
        value.replace(tzinfo=dateutil.tz.tzutc())
        return value
    else:
        raise ValueError('Value must be parsable to datetime object. Got `{}`'.format(type(value)))
30746
def GetString(self, text, idx):
        '''
        '''
        next = string.find(text, '\x00', idx)
        chunk = text[idx:next]
        return chunk
1252966
def _parse_date(string: str) -> datetime.date:
    
    return datetime.datetime.strptime(string, '%Y-%m-%d').date()
931547
def _date_by_len(self, string):
        

        strlen = len(string)

        year_num = int(string[0:2])
        if year_num < 50:
            prefix = '20'
        else:
            prefix = '19'

        if strlen == 10:
            return datetime.strptime(prefix + string, '%Y%m%d%H%M')

        if strlen == 12:
            return datetime.strptime(prefix + string, '%Y%m%d%H%M%S')

        return string
806723
def string2dt(self, s, lower_bound=None):
        """"""
        original_s = s

        result = {}
        dt = None

        # if s is completely empty, return start or end,
        # depending on what parameter is evaluated
        if s == '':
            return self.end if lower_bound else self.start

        # first try to match the defined regexes
        for idx in self.dtRegexes:
            regex = self.dtRegexes[idx]
            mo = regex.search(s)
            # if match was found, cut it out of original string and
            # store in result
            if mo:
                result[idx] = mo
                s = s[:mo.start(0)] + s[mo.end(0):]

        # handle constants
        if 'constant' in result:
            constant = result['constant'].group(0).strip()
            if constant == 'end':
                dt = self.end
            elif constant == 'start':
                dt = self.start
            elif constant == 'today':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0)
            elif constant == 'yesterday':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0) - timedelta(days=1)
            elif constant == 'now':
                dt = datetime.now()

        elif 'weekday' in result:
                weekday = result['weekday'].group(0).strip()
                # assume most-recently occured weekday in logfile
                most_recent_date = self.end.replace(hour=0, minute=0, second=0,
                                                    microsecond=0)
                offset = (most_recent_date.weekday() -
                          self.weekdays.index(weekday)) % 7
                dt = most_recent_date - timedelta(days=offset)

        # if anything remains unmatched, try parsing it with dateutil's parser
        if s.strip() != '':
            try:
                if dt:
                    dt = default_tzinfo(parser.parse(s, default=dt), tzutc)
                else:
                    # check if it's only time, then use the start dt as
                    # default, else just use the current year
                    if re.match('(?P<hour>\d{1,2}):(?P<minute>\d{2,2})'
                                '(?::(?P<second>\d{2,2})'
                                '(?:.(?P<microsecond>\d{3,3}))?)?'
                                '(?P<timezone>[0-9Z:\+\-]+)?$', s):
                        default = self.end if lower_bound else self.start
                    else:
                        default = datetime(self.end.year, 1, 1, 0, 0, 0)
                    default = default.replace(second=0, microsecond=0)

                    dt = parser.parse(s, default=default)

            except ValueError:
                raise ValueError("Error in DateTimeBoundaries: "
                                 "can't parse datetime from %s" % s)

        if not dt:
            dt = lower_bound or self.end

        # if no timezone specified, use the one from the logfile
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=self.start.tzinfo)

        # time is applied separately (not through the parser) so that string
        # containing only time don't use today as default date
        # (parser behavior)
        # if 'time' in result:
        #     dct = dict((k, int(v))
        #                for k,v in six.iteritems(result['time'].groupdict(0)))
        #     dct['microsecond'] *= 1000
        #     dt = dt.replace(**dct)

        # apply offset
        if 'offset' in result:

            # separate in operator, value, unit
            dct = result['offset'].groupdict()

            mult = 1
            if dct['unit'] in ['s', 'sec', 'secs']:
                dct['unit'] = 'seconds'
            elif dct['unit'] in ['m', 'min', 'mins']:
                dct['unit'] = 'minutes'
            elif dct['unit'] in ['h', 'hour', 'hours']:
                dct['unit'] = 'hours'
            elif dct['unit'] in ['d', 'day', 'days']:
                dct['unit'] = 'days'
            elif dct['unit'] in ['w', 'week', 'weeks']:
                dct['unit'] = 'days'
                mult = 7
            elif dct['unit'] in ['mo', 'month', 'months']:
                dct['unit'] = 'days'
                mult = 30.43
            elif dct['unit'] in ['y', 'year', 'years']:
                dct['unit'] = 'days'
                mult = 365.24

            if dct['operator'] == '-':
                mult *= -1

            dt = dt + eval('timedelta(%s=%i)' % (dct['unit'],
                                                 mult * int(dct['value'])))

        # if parsed datetime is out of bounds and no year specified,
        # try to adjust year
        year_present = re.search('\d{4,4}', original_s)

        if not year_present and 'constant' not in result:
            if (dt < self.start and
                    dt.replace(year=dt.year + 1) >= self.start and
                    dt.replace(year=dt.year + 1) <= self.end):
                dt = dt.replace(year=dt.year + 1)
            elif (dt > self.end and
                    dt.replace(year=dt.year - 1) >= self.start and
                    dt.replace(year=dt.year - 1) <= self.end):
                dt = dt.replace(year=dt.year - 1)

        return dt
1059768
function parseInput(str, idx) {
  var raw = String(str || '');
  var sliced = raw.slice(0, idx);
  var sections = sliced.split('|');
  var prefix = sections.slice(0, sections.length - 1) || [];
  prefix.push('');
  prefix = prefix.join('|');
  var suffix = getSuffix(raw.slice(idx));
  var context = sections[sections.length - 1];
  return {
    raw: raw,
    prefix: prefix,
    suffix: suffix,
    context: context
  };
}
1144629
def _decode_var(cls, string):
        

        str_match = cls.quoted_string_regex.match(string)
        if str_match:
            return string.strip("'" if str_match.groups()[0] else '"')
        # NOTE: "¹".isdigit() results in True because they are idiots
        elif string.isdigit() and cls.is_digit_regex.match(string) is not None:
            return int(string)
        elif string.lower() in ("true", "false"):
            return string.lower() == "true"
        elif string.lstrip("-").isdigit():
            try:
                return int(string)
            except ValueError:
                # case where we mistake something like "--0" as a int
                return string
        elif "." in string.lstrip("-"):
            try:
                return float(string)
            except ValueError:
                # one off case where we mistake a single "." as a float
                return string
        else:
            return string
322666
def parse(cls, s):
        
        try:
            numbers = map(int, s.split("-"))
        except (ValueError, AttributeError):
            raise ValueError("Date string must be in format YYYY-MM-DD")
        else:
            numbers = list(numbers)
            if len(numbers) == 3:
                return cls(*numbers)
            raise ValueError("Date string must be in format YYYY-MM-DD")
329930
def common_time_extrator(self, string):
        

        try:
            if not self.year_check:
                str_year = int(re.search('(\d{4})年', string).group(1))
                check_year = datetime.datetime.now().year
                if str_year in range(1970, check_year + 1):
                    self.year = str_year
                    self.year_check = True
        except:
            pass
        try:
            if not self.month_check:
                str_month = int(re.search('(\d{1,2})月', string).group(1))
                if str_month in range(1, 13):
                    self.month = str_month
                    self.month_check = True
        except:
            pass
        try:
            if not self.day_check:
                str_day = int(re.search('(\d{1,2})[日号]', string).group(1))
                if str_day in range(1, 32):
                    self.day = str_day
                    self.day_check = True
        except:
            pass
1134115
static boolean mayBeDate(String s) {
        if (s == null || s.length() != "yyyy-MM-dd_HH-mm-ss".length()) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case '-':
                    switch (i) {
                        case 4:
                        case 7:
                        case 13:
                        case 16:
                            break;
                        default:
                            return false;
                    }
                    break;
                case '_':
                    if (i != 10) {
                        return false;
                    }
                    break;
                case '0':
                case '1':
                    switch (i) {
                        case 4: // -
                        case 7: // -
                        case 10: // _
                        case 13: // -
                        case 16: // -
                            return false;
                        default:
                            break;
                    }
                    break;
                case '2':
                    switch (i) {
                        case 4: // -
                        case 5: // months 0-1
                        case 7: // -
                        case 10: // _
                        case 13: // -
                        case 16: // -
                            return false;
                        default:
                            break;
                    }
                    break;
                case '3':
                    switch (i) {
                        case 0: // year will safely begin with digit 2 for next 800-odd years
                        case 4: // -
                        case 5: // months 0-1
                        case 7: // -
                        case 10: // _
                        case 11: // hours 0-2
                        case 13: // -
                        case 16: // -
                            return false;
                        default:
                            break;
                    }
                    break;
                case '4':
                case '5':
                    switch (i) {
                        case 0: // year will safely begin with digit 2 for next 800-odd years
                        case 4: // -
                        case 5: // months 0-1
                        case 7: // -
                        case 8: // days 0-3
                        case 10: // _
                        case 11: // hours 0-2
                        case 13: // -
                        case 16: // -
                            return false;
                        default:
                            break;
                    }
                    break;
                case '6':
                case '7':
                case '8':
                case '9':
                    switch (i) {
                        case 0: // year will safely begin with digit 2 for next 800-odd years
                        case 4: // -
                        case 5: // months 0-1
                        case 7: // -
                        case 8: // days 0-3
                        case 10: // _
                        case 11: // hours 0-2
                        case 13: // -
                        case 14: // minutes 0-5
                        case 16: // -
                        case 17: // seconds 0-5
                            return false;
                        default:
                            break;
                    }
                    break;
                default:
                    return false;
            }
        }
        return true;
    }