Helper function for computing measures derived from timing information.

        These are only computed if the response is textgrid with timing information.

        All times are in seconds.
171390
def compute_duration_measures(self):
        

        prefix = "TIMING_" + self.current_similarity_measure + "_" + self.current_collection_type + "_"

        if self.response_format == 'TextGrid':

            self.compute_response_vowel_duration("TIMING_")  #prefixes don't need collection or measure type
            self.compute_response_continuant_duration("TIMING_")
            self.compute_between_collection_interval_duration(prefix)
            self.compute_within_collection_interval_duration(prefix)

            #these give different values depending on whether singleton clusters are counted or not
            self.compute_within_collection_vowel_duration(prefix, no_singletons = True)
            self.compute_within_collection_continuant_duration(prefix, no_singletons = True)
            self.compute_within_collection_vowel_duration(prefix, no_singletons = False)
            self.compute_within_collection_continuant_duration(prefix, no_singletons = False)
237590
def analyze(self, time: int=None) -> typing.Tuple[float, float, int, int]:
        
        if not time:
            time = int(len(self.times) / 2)
        if self.domains[time] == 0:
            yhat, residuals, mean_residual, error = self._get_fit(time)
            yhat_p = self.ddiff(yhat)
            yhat_pp = self.ddiff(yhat_p)
            noise = self._get_noise(residuals)
            curvature = (1 / self.ratio) * (1 / len(yhat_pp)) * np.sqrt(si.simps(yhat_pp ** 2))
            rng = (self.ratio * (np.max(self.averagedata[:, time]) -
                                 np.min(self.averagedata[:, time])))
            dmn = self.ratio * len(self.averagedata[:, time])

            self.noises[time] = np.log10(noise)
            self.curves[time] = np.log10(curvature)
            self.ranges[time] = np.log10(rng)
            self.domains[time] = np.log10(dmn)
        return self.noises[time], self.curves[time], self.ranges[time], self.domains[time]
1107413
def evaluation(clock)
      clock.repeat == 0 and
        raise BullshitException, "no measurements were gauged"
      result = ''
      result << statistics_table(clock)
      result << "\n"
    end
320734
function getRes(unit) {
      var measured,
          begin,
          count = 30,
          divisor = 1e3,
          ns = timer.ns,
          sample = [];

      // get average smallest measurable time
      while (count--) {
        if (unit == 'us') {
          divisor = 1e6;
          if (ns.stop) {
            ns.start();
            while (!(measured = ns.microseconds())) { }
          } else if (perfName) {
            divisor = 1e3;
            measured = Function('n', 'var r,s=n.' + perfName + '();while(!(r=n.' + perfName + '()-s)){};return r')(ns);
          } else {
            begin = ns();
            while (!(measured = ns() - begin)) { }
          }
        }
        else if (unit == 'ns') {
          divisor = 1e9;
          begin = ns.nanoTime();
          while (!(measured = ns.nanoTime() - begin)) { }
        }
        else {
          begin = new ns;
          while (!(measured = new ns - begin)) { }
        }
        // check for broken timers (nanoTime may have issues)
        // http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/
        if (measured > 0) {
          sample.push(measured);
        } else {
          sample.push(Infinity);
          break;
        }
      }
      // convert to seconds
      return getMean(sample) / divisor;
    }
112775
function () {
    if (beatmap.Tags) {
      beatmap.tagsArray = beatmap.Tags.split(' ');
    }

    eventsLines.forEach(parseEvent);
    beatmap.breakTimes.sort(function (a, b) { return (a.startTime > b.startTime ? 1 : -1); });

    timingLines.forEach(parseTimingPoint);
    beatmap.timingPoints.sort(function (a, b) { return (a.offset > b.offset ? 1 : -1); });

    var timingPoints = beatmap.timingPoints;

    for (var i = 1, l = timingPoints.length; i < l; i++) {
      if (!timingPoints[i].hasOwnProperty('bpm')) {
        timingPoints[i].beatLength = timingPoints[i - 1].beatLength;
        timingPoints[i].bpm        = timingPoints[i - 1].bpm;
      }
    }

    objectLines.forEach(parseHitObject);
    beatmap.hitObjects.sort(function (a, b) { return (a.startTime > b.startTime ? 1 : -1); });

    computeMaxCombo();
    computeDuration();

    return beatmap;
  }
664509
function() {
      var timings = {};
      var requests = win.performance.getEntriesByType("resource");
      for (var i = 0; i < requests.length; i++)
        timings[requests[i].name] = requests[i].responseEnd;
      for (var j = 0; j < rects.length; j++) {
        if (!('tm' in rects[j]))
          rects[j].tm = timings[rects[j].url] !== undefined ? timings[rects[j].url] : 0;
      }
    }
170148
function getHrTimeDurationInMs (startTime, endTime) {
    if (startTime === null || endTime === null) {
        return null;
    }

    var secondDiff = endTime[0] - startTime[0];
    var nanoSecondDiff = endTime[1] - startTime[1];
    var diffInNanoSecond = secondDiff * NS_PER_SEC + nanoSecondDiff;

    return Math.round(diffInNanoSecond / MS_PER_NS);
}
1028372
function(mod) {
			var seconds = this.getTimeSeconds();
			
			if(mod) {
				if(seconds == 60) {
					seconds = 0;
				}
				else {
					seconds = seconds % 60;
				}
			}
			
			return Math.ceil(seconds);
		}
554030
function getMilliseconds( time ) {
  if ( typeof time == 'number' ) {
    return time;
  }
  var matches = time.match( /(^\d*\.?\d*)(\w*)/ );
  var num = matches && matches[1];
  var unit = matches && matches[2];
  if ( !num.length ) {
    return 0;
  }
  num = parseFloat( num );
  var mult = msUnits[ unit ] || 1;
  return num * mult;
}
939708
def _calculate_duration(start_time, finish_time):
    """"""
    if not (start_time and finish_time):
        return 0
    start = datetime.datetime.fromtimestamp(start_time)
    finish = datetime.datetime.fromtimestamp(finish_time)
    duration = finish - start

    decimals = float(("0." + str(duration.microseconds)))
    return duration.seconds + decimals
1316487
def duration(seconds):
    """"""
    if seconds < 1:
        return 'less than 1 sec'
    seconds = int(round(seconds))
    components = []
    for magnitude, label in ((3600, 'hr'), (60, 'min'), (1, 'sec')):
        if seconds >= magnitude:
            components.append('{} {}'.format(seconds // magnitude, label))
            seconds %= magnitude
    return ' '.join(components)
1244035
private static Number[] toHMS(Measure[] measures) {
        Number[] result = new Number[3];
        int lastIdx = -1;
        for (Measure m : measures) {
            if (m.getNumber().doubleValue() < 0.0) {
                return null;
            }
            Integer idxObj = hmsTo012.get(m.getUnit());
            if (idxObj == null) {
                return null;
            }
            int idx = idxObj.intValue();
            if (idx <= lastIdx) {
                // hour before minute before second
                return null;
            }
            lastIdx = idx;
            result[idx] = m.getNumber();
        }
        return result;
    }
1315362
def get_time_eta(total_done, total, start_time):
    
    time_done = int(time()) - start_time
    speed = total_done / time_done

    if time_done > 0 and speed > 0:
        total_to_go = total - total_done
        time_to_go = total_to_go / speed
        minutes, seconds = divmod(time_to_go, 60)
        hours, minutes = divmod(minutes, 60)
        percentage = total_done * 100.0 / total
    else:
        percentage = 0
        hours = 0
        minutes = 0
        seconds = 0

    return {
        "done": int(total_done),
        "tot": int(total),
        "%": float("{0:.2f}".format(percentage)),
        "h": int(hours),
        "m": int(minutes),
        "s": int(seconds)
    }
963188
private Map<MetricName, MetricValue> get_metrics_(DateTime now, Context ctx) {
        final Consumer<Alert> alert_manager = ctx.getAlertManager();
        final long failed_collections = registry_.getFailedCollections();
        final boolean has_config = registry_.hasConfig();
        final Optional<Duration> scrape_duration = registry_.getScrapeDuration();
        final Optional<Duration> rule_eval_duration = registry_.getRuleEvalDuration();
        final Optional<Duration> processor_duration = registry_.getProcessorDuration();
        first_scrape_ts_.compareAndSet(null, now);  // First time, register the timestamp.
        final Duration uptime = new Duration(first_scrape_ts_.get(), now);

        final Optional<DateTime> last_scrape = last_scrape_;
        last_scrape_ = Optional.of(now);

        final long metric_count = ctx.getTSData().getCurrentCollection().getTSValues().stream()
                .map(TimeSeriesValue::getMetrics)
                .collect(Collectors.summingLong(Map::size));

        alert_manager.accept(new Alert(now, MONITOR_FAIL_ALERT, () -> "builtin rule", Optional.of(failed_collections != 0), MON_ALERT_DURATION, "builtin rule: some collectors failed", EMPTY_MAP));
        alert_manager.accept(new Alert(now, HAS_CONFIG_ALERT, () -> "builtin rule", Optional.of(!has_config), Duration.ZERO, "builtin rule: monitor has no configuration file", EMPTY_MAP));

        Map<MetricName, MetricValue> result = new HashMap<>();
        result.put(FAILED_COLLECTIONS_METRIC, MetricValue.fromIntValue(failed_collections));
        result.put(GROUP_COUNT_METRIC, MetricValue.fromIntValue(ctx.getTSData().getCurrentCollection().getGroups(x -> true).size()));
        result.put(METRIC_COUNT_METRIC, MetricValue.fromIntValue(metric_count));
        result.put(CONFIG_PRESENT_METRIC, MetricValue.fromBoolean(has_config));
        result.put(SCRAPE_DURATION, opt_duration_to_metricvalue_(scrape_duration));
        result.put(RULE_EVAL_DURATION, opt_duration_to_metricvalue_(rule_eval_duration));
        result.put(PROCESSOR_DURATION, opt_duration_to_metricvalue_(processor_duration));
        result.put(UPTIME_DURATION, duration_to_metricvalue_(uptime));
        result.put(SCRAPE_COUNT, MetricValue.fromIntValue(++scrape_count_));
        result.put(SCRAPE_INTERVAL, opt_duration_to_metricvalue_(last_scrape.map(prev -> new Duration(prev, now))));
        result.put(SCRAPE_TS, MetricValue.fromIntValue(now.getMillis()));
        return result;
    }
1066820
function timeParamToSeconds(param) {
	var componentValue = function (si) {
		var regex = new RegExp('(\\d+)' + si);
		return param.match(regex) ? parseInt(RegExp.$1, 10) : 0;
	};

	return componentValue('h') * 3600
		+ componentValue('m') * 60
		+ componentValue('s');
}
627540
def _calculate_eta(self, progress, data, value, elapsed):
        ''''''
        if elapsed:
            # The max() prevents zero division errors
            per_item = elapsed.total_seconds() / max(value, 1e-6)
            remaining = progress.max_value - data['value']
            eta_seconds = remaining * per_item
        else:
            eta_seconds = 0

        return eta_seconds
463263
function flushMetrics() {
  var time_stamp = Math.round(new Date().getTime() / 1000);
  if (old_timestamp > 0) {
    gauges[timestamp_lag_namespace] = (time_stamp - old_timestamp - (Number(conf.flushInterval)/1000));
  }
  old_timestamp = time_stamp;

  var metrics_hash = {
    counters: counters,
    gauges: gauges,
    timers: timers,
    timer_counters: timer_counters,
    sets: sets,
    counter_rates: counter_rates,
    timer_data: timer_data,
    pctThreshold: pctThreshold,
    histogram: conf.histogram
  };

  // After all listeners, reset the stats
  backendEvents.once('flush', function clear_metrics(ts, metrics) {
    // TODO: a lot of this should be moved up into an init/constructor so we don't have to do it every
    // single flushInterval....
    // allows us to flag all of these on with a single config but still override them individually
    conf.deleteIdleStats = conf.deleteIdleStats !== undefined ? conf.deleteIdleStats : false;
    if (conf.deleteIdleStats) {
      conf.deleteCounters = conf.deleteCounters !== undefined ? conf.deleteCounters : true;
      conf.deleteTimers = conf.deleteTimers !== undefined ? conf.deleteTimers : true;
      conf.deleteSets = conf.deleteSets !== undefined ? conf.deleteSets : true;
      conf.deleteGauges = conf.deleteGauges !== undefined ? conf.deleteGauges : true;
    }

    // Clear the counters
    conf.deleteCounters = conf.deleteCounters || false;
    for (var counter_key in metrics.counters) {
      if (conf.deleteCounters) {
        if ((counter_key.indexOf("packets_received") != -1) ||
            (counter_key.indexOf("metrics_received") != -1) ||
            (counter_key.indexOf("bad_lines_seen") != -1)) {
          metrics.counters[counter_key] = 0;
        } else {
         delete(metrics.counters[counter_key]);
        }
      } else {
        metrics.counters[counter_key] = 0;
      }
    }

    // Clear the timers
    conf.deleteTimers = conf.deleteTimers || false;
    for (var timer_key in metrics.timers) {
      if (conf.deleteTimers) {
        delete(metrics.timers[timer_key]);
        delete(metrics.timer_counters[timer_key]);
      } else {
        metrics.timers[timer_key] = [];
        metrics.timer_counters[timer_key] = 0;
     }
    }

    // Clear the sets
    conf.deleteSets = conf.deleteSets || false;
    for (var set_key in metrics.sets) {
      if (conf.deleteSets) {
        delete(metrics.sets[set_key]);
      } else {
        metrics.sets[set_key] = new set.Set();
      }
    }

    // Normally gauges are not reset.  so if we don't delete them, continue to persist previous value
    conf.deleteGauges = conf.deleteGauges || false;
    if (conf.deleteGauges) {
      for (var gauge_key in metrics.gauges) {
        delete(metrics.gauges[gauge_key]);
      }
    }
  });

  pm.process_metrics(metrics_hash, flushInterval, time_stamp, function emitFlush(metrics) {
    backendEvents.emit('flush', time_stamp, metrics);
  });

  // Performing this setTimeout at the end of this method rather than the beginning
  // helps ensure we adapt to negative clock skew by letting the method's latency
  // introduce a short delay that should more than compensate.
  setTimeout(flushMetrics, getFlushTimeout(flushInterval));
}