For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
    returned value is a tuple of length patterns. Tokens should be a list.
421313
def _percent_match(date_classes, tokens):
    
    match_count = [0] * len(date_classes)

    for i, date_class in enumerate(date_classes):
        for token in tokens:
            if date_class.is_match(token):
                match_count[i] += 1

    percentages = tuple([float(m) / len(tokens) for m in match_count])
    return percentages
455554
def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]:
        """"""
        if not date_str:
            return None

        found_time = False
        found_day = False
        found_month = False
        found_year = False

        hour = minute = second = 0
        day = 0
        month = 0
        year = 0

        for token_match in cls.DATE_TOKENS_RE.finditer(date_str):

            token = token_match.group("token")

            if not found_time:
                time_match = cls.DATE_HMS_TIME_RE.match(token)
                if time_match:
                    found_time = True
                    hour, minute, second = [
                        int(s) for s in time_match.groups()]
                    continue

            if not found_day:
                day_match = cls.DATE_DAY_OF_MONTH_RE.match(token)
                if day_match:
                    found_day = True
                    day = int(day_match.group())
                    continue

            if not found_month:
                month_match = cls.DATE_MONTH_RE.match(token)
                if month_match:
                    found_month = True
                    month = month_match.lastindex
                    continue

            if not found_year:
                year_match = cls.DATE_YEAR_RE.match(token)
                if year_match:
                    found_year = True
                    year = int(year_match.group())

        if 70 <= year <= 99:
            year += 1900
        elif 0 <= year <= 69:
            year += 2000

        if False in (found_day, found_month, found_year, found_time):
            return None

        if not 1 <= day <= 31:
            return None

        if year < 1601 or hour > 23 or minute > 59 or second > 59:
            return None

        return datetime.datetime(year, month, day,
                                 hour, minute, second,
                                 tzinfo=datetime.timezone.utc)
135244
function formatPercent(value, locale, digitsInfo) {
    var format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent);
    var pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign));
    var res = formatNumberToLocaleString(value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true);
    return res.replace(new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign));
}
558591
def compute_percentile(self, percentage):
        
        all_patches = self.get_all_patches()
        return all_patches[
            int(len(all_patches) * percentage / 100)
        ].start_position
1334876
def to_percentage(number, rounding=2):
    
    number = float(number) * 100
    number_as_int = int(number)
    rounded = round(number, rounding)

    return '{}%'.format(number_as_int if number_as_int == rounded else rounded)
633831
def datetime2utsec(t: Union[str, datetime.date, datetime.datetime, np.datetime64]) -> float:
    
    if isinstance(t, (tuple, list, np.ndarray)):
        return np.asarray([datetime2utsec(T) for T in t])
    elif isinstance(t, datetime.date) and not isinstance(t, datetime.datetime):
        return 0.
    elif isinstance(t, np.datetime64):
        t = t.astype(datetime.datetime)
    elif isinstance(t, str):
        t = parse(t)

    return datetime.timedelta.total_seconds(t - datetime.datetime.combine(t.date(),
                                                                          datetime.datetime.min.time()))
308802
def pformat_tokens(self, tokens):
        
        result = []
        for token_value in self.iter_token_values(tokens):
            char = self.token2ascii(token_value)
            if token_value > 0xff:
                result.append("\t$%04x -> %s" % (token_value, repr(char)))
            else:
                result.append("\t  $%02x -> %s" % (token_value, repr(char)))

        return result
478019
def _tokenize(self, text, token_class=None):
        
        token_class = token_class or Token
        tokens = {}

        for i, match in enumerate(self.regex.finditer(text)):
            value = match.group(0)

            try:
                token = tokens[value]
            except KeyError:
                type = match.lastgroup
                token = token_class(value, type=type)
                tokens[value] = token

            yield token
324171
function(value, token) {
			var score, pos;

			if (!value) return 0;
			value = String(value || '');
			pos = value.search(token.regex);
			if (pos === -1) return 0;
			score = token.string.length / value.length;
			if (pos === 0) score += 0.5;
			return score;
		}
856046
private int percent(final long val, final long total) {
        if (total == 0) {
            return 100;
        }

        if (val == 0) {
            return 0;
        }

        double dVal = (double) val;
        double dTotal = (double) total;

        return (int) (dVal / dTotal * 100);
    }
882714
def parse(s, return_type=int):
    '''
    
    '''
    RE_DAY = r'([0-9]+)d(ay)?'
    RE_HOUR = r'([0-9]+)h(our)?'
    RE_MINUTE = r'([0-9]+)m(in(ute)?)?'
    RE_SECOND = r'([0-9]+)(s(ec(ond)?)?)?'

    def _parse_time_with_unit(s):
        retval = 0
        md = re.match(RE_DAY, s)
        mh = re.match(RE_HOUR, s)
        mm = re.match(RE_MINUTE, s)
        ms = re.match(RE_SECOND, s)
        if md:
            retval = 86400 * int(md.group(1))
        elif mh:
            retval = 3600 * int(mh.group(1))
        elif mm:
            retval = 60 * int(mm.group(1))
        elif ms:
            retval = int(ms.group(1))
        return retval

    if isinstance(s, (type(None), int, float)):
        return s

    if s[-1] in '0123456789':
        s += 's'

    m = re.match(r'^(%s)?(%s)?(%s)?(%s)?$' % (RE_DAY, RE_HOUR,
                                              RE_MINUTE, RE_SECOND),
                 s)
    if not m:
        raise ParseError('invalid string: "%s"' % s)

    times = [x for x in m.groups() if isinstance(x, str) and
             re.match(r'[0-9]+[a-z]+', x)]
    seconds = sum(_parse_time_with_unit(z) for z in times)

    if return_type is int:
        return seconds
    elif return_type is timedelta:
        return timedelta(seconds=seconds)
    else:
        raise TypeError('return_type "{}" is not supported.'.format(
            return_type.__name__))
608148
function(tokens) {
            	if(typeof tokens === "string") {
            		tokens = [tokens];
            	}
                    var results = [];
            	var rule_count = rules$3.length;
            	var num_tokens = tokens.length;
                    var i, token, r, rule;
                
                    for (i = 0; i < num_tokens; i++) {
                        token = tokens[i];
                        // Check the conversion table
                        if (conversionTable[token.toLowerCase()]) {
                            results = results.concat(conversionTable[token.toLowerCase()].split(/\W+/));
                        }
                        
                        // Apply the rules
                        else {
                            var matched = false;
                            for ( r = 0; r < rule_count; r++) {
                                rule = rules$3[r];
                                if (token.match(rule.regex)) {
                                    results = results.concat(token.replace(rule.regex, rule.output).split(/\W+/));
                                    matched = true;
                                    break;
                                }
                            }
                            if (!matched) {
                                results.push(token);
                            }
                        }
                    }

            	return results;
            }
298052
def percent_rank(expr, sort=None, ascending=True):
    
    return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending)
315348
def global_unlock_percent(self):
        
        percent = CRef.cfloat()
        result = self._iface.get_ach_progress(self.name, percent)

        if not result:
            return 0.0

        return float(percent)
895655
def plotSegmentationResults(flags_ind, flags_ind_gt, class_names, mt_step, ONLY_EVALUATE=False):
    '''
    
    '''    
    flags = [class_names[int(f)] for f in flags_ind]
    (segs, classes) = flags2segs(flags, mt_step)    
    min_len = min(flags_ind.shape[0], flags_ind_gt.shape[0])    
    if min_len > 0:
        accuracy = numpy.sum(flags_ind[0:min_len] == 
                             flags_ind_gt[0:min_len]) / float(min_len)
    else:
        accuracy = -1

    if not ONLY_EVALUATE:
        duration = segs[-1, 1]
        s_percentages = numpy.zeros((len(class_names), 1))
        percentages = numpy.zeros((len(class_names), 1))
        av_durations = numpy.zeros((len(class_names), 1))

        for iSeg in range(segs.shape[0]):
            s_percentages[class_names.index(classes[iSeg])] += \
                (segs[iSeg, 1]-segs[iSeg, 0])

        for i in range(s_percentages.shape[0]):
            percentages[i] = 100.0 * s_percentages[i] / duration
            S = sum(1 for c in classes if c == class_names[i])
            if S > 0:
                av_durations[i] = s_percentages[i] / S
            else:
                av_durations[i] = 0.0

        for i in range(percentages.shape[0]):
            print(class_names[i], percentages[i], av_durations[i])

        font = {'size': 10}
        plt.rc('font', **font)

        fig = plt.figure()
        ax1 = fig.add_subplot(211)
        ax1.set_yticks(numpy.array(range(len(class_names))))
        ax1.axis((0, duration, -1, len(class_names)))
        ax1.set_yticklabels(class_names)
        ax1.plot(numpy.array(range(len(flags_ind))) * mt_step +
                 mt_step / 2.0, flags_ind)
        if flags_ind_gt.shape[0] > 0:
            ax1.plot(numpy.array(range(len(flags_ind_gt))) * mt_step +
                     mt_step / 2.0, flags_ind_gt + 0.05, '--r')
        plt.xlabel("time (seconds)")
        if accuracy >= 0:
            plt.title('Accuracy = {0:.1f}%'.format(100.0 * accuracy))

        ax2 = fig.add_subplot(223)
        plt.title("Classes percentage durations")
        ax2.axis((0, len(class_names) + 1, 0, 100))
        ax2.set_xticks(numpy.array(range(len(class_names) + 1)))
        ax2.set_xticklabels([" "] + class_names)
        ax2.bar(numpy.array(range(len(class_names))) + 0.5, percentages)

        ax3 = fig.add_subplot(224)
        plt.title("Segment average duration per class")
        ax3.axis((0, len(class_names)+1, 0, av_durations.max()))
        ax3.set_xticks(numpy.array(range(len(class_names) + 1)))
        ax3.set_xticklabels([" "] + class_names)
        ax3.bar(numpy.array(range(len(class_names))) + 0.5, av_durations)
        fig.tight_layout()
        plt.show()
    return accuracy
109653
def as_percent(self, percent):
        
        if not self:
            return self.wrap_str()

        length = len(self)
        # Using mod 100, to provide some kind of "auto reset". 0 is 0 though.
        percentmod = (int(percent) % 100) or min(percent, 100)
        index = int((length / 100) * percentmod)
        try:
            barstr = str(self[index])
        except IndexError:
            barstr = self[-1]

        return self.wrap_str(barstr)
1007630
def get_trend(timeseries):
    

    last = timeseries['value'][len(timeseries['value']) - 1]
    prev = timeseries['value'][len(timeseries['value']) - 2]
    trend = last - prev
    trend_percentage = None

    if last == 0:
        if prev > 0:
            trend_percentage = -100
        else:
            trend_percentage = 0
    else:
        trend_percentage = int((trend / last) * 100)
    return (last, trend_percentage)