Automatically find an appropriate maximum lag to calculate IAT
19690
def _find_max_lag(x, rho_limit=0.05, maxmaxlag=20000, verbose=0):
    """"""

    # Fetch autocovariance matrix
    acv = autocov(x)
    # Calculate rho
    rho = acv[0, 1] / acv[0, 0]

    lam = -1. / np.log(abs(rho))

    # Initial guess at 1.5 times lambda (i.e. 3 times mean life)
    maxlag = int(np.floor(3. * lam)) + 1

    # Jump forward 1% of lambda to look for rholimit threshold
    jump = int(np.ceil(0.01 * lam)) + 1

    T = len(x)

    while ((abs(rho) > rho_limit) & (maxlag < min(T / 2, maxmaxlag))):

        acv = autocov(x, maxlag)
        rho = acv[0, 1] / acv[0, 0]
        maxlag += jump

    # Add 30% for good measure
    maxlag = int(np.floor(1.3 * maxlag))

    if maxlag >= min(T / 2, maxmaxlag):
        maxlag = min(min(T / 2, maxlag), maxmaxlag)
        "maxlag fixed to %d" % maxlag
        return maxlag

    if maxlag <= 1:
        print_("maxlag = %d, fixing value to 10" % maxlag)
        return 10

    if verbose:
        print_("maxlag = %d" % maxlag)
    return maxlag
1162010
def emulate_abs(self, x_val, y_val, timeval):
        """"""
        x_event = self.create_event_object(
            "Absolute",
            0x00,
            x_val,
            timeval)
        y_event = self.create_event_object(
            "Absolute",
            0x01,
            y_val,
            timeval)
        return x_event, y_event
1150347
def auto_display_limits(self):
        """"""
        display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata
        data = display_data_and_metadata.data if display_data_and_metadata else None
        if data is not None:
            # The old algorithm was a problem during EELS where the signal data
            # is a small percentage of the overall data and was falling outside
            # the included range. This is the new simplified algorithm. Future
            # feature may allow user to select more complex algorithms.
            mn, mx = numpy.nanmin(data), numpy.nanmax(data)
            self.display_limits = mn, mx
833546
private void updateMax(int idx, double v) {
    AtomicLong current = max.getCurrent(idx);
    long m = current.get();
    while (v > Double.longBitsToDouble(m)) {
      if (current.compareAndSet(m, Double.doubleToLongBits(v))) {
        break;
      }
      m = current.get();
    }
  }
301871
private void estimateJitter(RtpPacket newPacket) {
        long arrival = rtpClock.getLocalRtpTime();
        long newPacketTimestamp = newPacket.getTimestamp();
        long transit = arrival - newPacketTimestamp;
        long d = transit - currentTransit;
        if (d < 0) {
            d = -d;
        }
        // logger.info(String.format("recalculating jitter: arrival=%d, newPacketTimestamp=%d, transit=%d, transit delta=%d",
        // arrival, newPacketTimestamp, transit, d ));
        currentTransit = transit;
        currentJitter += d - ((currentJitter + 8) >> 4);
    }
327136
synchronized Weight getMaximumFinish() {
        if (calcMaxFinish == null) {
            // Find the longest distance from time zero to a finish.
            Weight result = WeightFactory.NEG_INFINITY;
            if (shortestDistancesFromTimeZeroSource == null) {
                shortestDistancesFromTimeZeroSource = BellmanFord.calcShortestDistances(timeZero, directedGraph,
                        BellmanFord.Mode.SOURCE);
                if (shortestDistancesFromTimeZeroSource == null) {
                    throw new IllegalStateException("Negative cycle detected!");
                }
            }
            for (int i = 0, n = intervals.size(); i < n; i++) {
                Object finish = intervals.get(i).getFinish();
                result = Weight.max(result,
                        (Weight) shortestDistancesFromTimeZeroSource.get(finish));
            }
            calcMaxFinish = result;
        }

        return calcMaxFinish;
    }
679672
def _every(times, step_size, index):
        
        current = index * step_size
        step = current // times * times
        reached = current >= step
        overshot = current >= step + step_size
        return current and reached and not overshot
1107510
function(pool) {
    let toRemove = Math.max(1, pool.idleConnections() - opts.minimumIdle);
    while (toRemove > 0) {
      const conn = idleConnections.peek();
      --toRemove;
      if (conn && conn.lastUse + opts.idleTimeout * 1000 < Date.now()) {
        idleConnections.shift();
        conn.forceEnd().catch(err => {});
        conn.releaseWithoutError();
        continue;
      }
      break;
    }
    ensurePoolSize(pool);
  }
680198
function aggregateMetrics(currentTime, metricData) {
    var aggregateKey;

    /**
     * Place aggregate data into the specified slot.  If the current zoom
     * level matches the aggregate level, the data is emitted to keep the
     * display in sync.
     *
     * @param {Number} index
     * The desired slot for the aggregate.
     *
     * @param {Object} data
     * The aggregate data.
     *
     * @returns {void}
     */
    var setAggregateData =
      function setAggregateData(index, data) {
        this._aggregation[aggregateKey].data[index] = data;

        // if this view (current or not) is scrolled, adjust it
        if (this._aggregation[aggregateKey].scrollOffset) {
          this._aggregation[aggregateKey].scrollOffset--;
        }

        // emit to keep the display in sync
        if (this.isCurrentZoom(aggregateKey)) {
          if (this.isScrolled()) {
            this.emit("refreshMetrics");
          } else {
            this.emit("metrics", data);
          }
        }
      }.bind(this);

    /**
     * Given the current time time index, add any missing logical
     * time slots to have a complete picture of data.
     *
     * @param {Number} currentTimeIndex
     * The time index currently being processed.
     *
     * @returns {void}
     */
    var addMissingTimeSlots =
      function addMissingTimeSlots(currentTimeIndex) {
        var aggregateIndex = this._aggregation[aggregateKey].data.length;
        while (aggregateIndex < currentTimeIndex) {
          setAggregateData(aggregateIndex++, this.emptyAverage);
        }
      }.bind(this);

    /**
     * After having detected a new sampling, aggregate the relevant data points
     *
     * @param {Object[]} rows
     * The array reference.
     *
     * @param {Number} startIndex
     * The starting index to derive an average.
     *
     * @param {Number} endIndex
     * The ending index to derive an average.
     *
     * @returns {void}
     */
    var getAveragedAggregate =
      function getAveragedAggregate(rows, startIndex, endIndex) {
        var averagedAggregate = getInitializedAverage(metricData);

        // this is the number of elements we will aggregate
        var aggregateCount = endIndex - startIndex + 1;

        // you can compute an average of a set of numbers two ways
        // first, you can add all the numbers together and then divide by the count
        // second, you call divide each number by the count and add the quotients
        // the first method is more accurate, however you can overflow an accumulator
        // and result with NaN
        // the second method is employed here to ensure no overflows

        for (var dataKey in metricData) {
          for (var dataMetricKey in metricData[dataKey]) {
            for (var rowIndex = startIndex; rowIndex <= endIndex; rowIndex++) {
              averagedAggregate[dataKey][dataMetricKey] +=
                rows[rowIndex][dataKey][dataMetricKey] / aggregateCount;
            }

            // after the average is done, truncate the averages to one decimal point
            averagedAggregate[dataKey][dataMetricKey] =
              +averagedAggregate[dataKey][dataMetricKey].toFixed(1);
          }
        }

        return averagedAggregate;
      };

    /**
     * Process one row of metric data into aggregate.
     *
     * @param {Number} rowIndex
     * The index of the row being processed.
     *
     * @param {Object[]} rows
     * The array reference.
     *
     * @returns {void}
     */
    var processRow = function processRow(rowIndex, rows) {
      var averagedAggregate;
      var lastTimeIndex = this._aggregation[aggregateKey].lastTimeIndex;

      // get the time index of the aggregate
      var currentTimeIndex =
        convertElapsedTimeToTimeIndex(currentTime, this._startTime, +aggregateKey);

      // when the time index changes, average the data for the time band
      if (currentTimeIndex !== lastTimeIndex) {
        // except for the first one
        if (lastTimeIndex !== undefined) {
          // add in any missing logical time slots
          addMissingTimeSlots.call(this, lastTimeIndex);

          // get the average across the discovered time band
          averagedAggregate = getAveragedAggregate(
            rows,
            this._aggregation[aggregateKey].lastAggregateIndex,
            rowIndex - 1
          );

          // place the average
          setAggregateData(lastTimeIndex, averagedAggregate);

          // now we know where the next aggregate begins
          this._aggregation[aggregateKey].lastAggregateIndex = rowIndex;
        }

        // level-break
        this._aggregation[aggregateKey].lastTimeIndex = currentTimeIndex;
      }
    }.bind(this);

    // iterate over the configured aggregation time buckets
    for (aggregateKey in this._aggregation) {
      // iterate through metrics, beginning where we left off
      processRow(this._lastAggregationIndex, this._metrics);
    }

    // remember where we will begin again
    this._lastAggregationIndex++;
  }
1317141
def _validate_timeout(seconds: float):
    """"""
    val = int(seconds * 1000)
    assert 60000 <= val <= 4294967294, "Bad value: {}".format(val)
    return val
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);
}
78788
function () {
    if (beatmap.timingPoints.length === 0) { return; }

    var maxCombo         = 0;
    var sliderMultiplier = parseFloat(beatmap.SliderMultiplier);
    var sliderTickRate   = parseInt(beatmap.SliderTickRate, 10);

    var timingPoints  = beatmap.timingPoints;
    var currentTiming = timingPoints[0];
    var nextOffset    = timingPoints[1] ? timingPoints[1].offset : Infinity;
    var i = 1;

    beatmap.hitObjects.forEach(function (hitObject) {
      if (hitObject.startTime >= nextOffset) {
        currentTiming = timingPoints[i++];
        nextOffset = timingPoints[i] ? timingPoints[i].offset : Infinity;
      }

      var osupxPerBeat = sliderMultiplier * 100 * currentTiming.velocity;
      var tickLength   = osupxPerBeat / sliderTickRate;

      switch (hitObject.objectName) {
        case 'spinner':
        case 'circle':
          maxCombo++;
          break;
        case 'slider':
          var tickPerSide = Math.ceil((Math.floor(hitObject.pixelLength / tickLength * 100) / 100) - 1);
          maxCombo += (hitObject.edges.length - 1) * (tickPerSide + 1) + 1;  // 1 combo for each tick and endpoint
      }
    });

    beatmap.maxCombo = maxCombo;
  }
746942
function determineUnitForAutoTicks(minUnit, min, max, capacity) {
	var ilen = UNITS.length;
	var i, interval, factor;

	for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
		interval = INTERVALS[UNITS[i]];
		factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;

		if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
			return UNITS[i];
		}
	}

	return UNITS[ilen - 1];
}
59682
def arrival_delay_greater_than(item_id, delay, namespace="_expected_arrival"):
    """"""
    expected = get_state(item_id, namespace=namespace)
    now = time.time()
    if expected and (now - expected) > delay:
        logger.error("Timeout: waited %s seconds for parent.", delay)
        return True
    elif expected:
        logger.info("Still out of order but no timeout: %s-%s <= %s.",
                    now, expected, delay)
        return False
    elif delay > 0:
        logger.info("Storing expected arrival time (%s) for context '%s'",
                    datetime.fromtimestamp(now).isoformat(), item_id)
        set_state(item_id, now, namespace=namespace)
        return False
    else:
        logger.info("Event is out of order but not waiting for parent.")
        return True
1150091
def aggregate_metrics(latencies_ms, duration_ms, num_bucket):
    """"""
    overall_op_count = 0
    op_counts = {operation : len(latency) for operation,
                 latency in latencies_ms.iteritems()}
    overall_op_count = sum([op_count for op_count in op_counts.itervalues()])

    print('[OVERALL], RunTime(ms), %f' % duration_ms)
    print('[OVERALL], Throughput(ops/sec), %f' % (float(overall_op_count) /
                                                duration_ms * 1000.0))

    for operation in op_counts.keys():
        operation_upper = operation.upper()
        print('[%s], Operations, %d' % (operation_upper, op_counts[operation]))
        print('[%s], AverageLatency(us), %f' % (
            operation_upper, numpy.average(latencies_ms[operation]) * 1000.0))
        print('[%s], LatencyVariance(us), %f' % (
            operation_upper, numpy.var(latencies_ms[operation]) * 1000.0))
        print('[%s], MinLatency(us), %f' % (
            operation_upper, min(latencies_ms[operation]) * 1000.0))
        print('[%s], MaxLatency(us), %f' % (
            operation_upper, max(latencies_ms[operation]) * 1000.0))
        print('[%s], 95thPercentileLatency(us), %f' % (
            operation_upper,
            numpy.percentile(latencies_ms[operation], 95.0) * 1000.0))
        print('[%s], 99thPercentileLatency(us), %f' % (
            operation_upper,
            numpy.percentile(latencies_ms[operation], 99.0) * 1000.0))
        print('[%s], 99.9thPercentileLatency(us), %f' % (
            operation_upper,
            numpy.percentile(latencies_ms[operation], 99.9) * 1000.0))
        print('[%s], Return=OK, %d' % (operation_upper, op_counts[operation]))
        latency_array = numpy.array(latencies_ms[operation])
        for j in range(num_bucket):
            print('[%s], %d, %d' % (
                operation_upper, j,
                ((j <= latency_array) & (latency_array < (j + 1))).sum()))
        print('[%s], >%d, %d' % (operation_upper, num_bucket,
                                 (num_bucket <= latency_array).sum()))
784789
def _makeTimingRelative(absoluteDataList):
    '''
    
    '''

    timingSeq = [row[0] for row in absoluteDataList]
    valueSeq = [list(row[1:]) for row in absoluteDataList]

    relTimingSeq, startTime, endTime = makeSequenceRelative(timingSeq)
    
    relDataList = [tuple([time, ] + row) for time, row
                   in zip(relTimingSeq, valueSeq)]

    return relDataList, startTime, endTime
627123
def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per):
        
        return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i)