text:
/*
 * This is a TypeScript port of the original Java version, which was written by
 * Gil Tene as described in
 * https://github.com/HdrHistogram/HdrHistogram
 * and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */
import RecordedValuesIterator from "./RecordedValuesIterator";
import PercentileIterator from "./PercentileIterator";
import HistogramIterationValue from "./HistogramIterationValue";
import { integerFormatter, floatFormatter } from "./formatters";
import ulp from "./ulp";
import Histogram, { NO_TAG, toSummary, HistogramSummary } from "./Histogram";

const { pow, floor, ceil, log2, max, min } = Math;

export abstract class JsHistogram implements Histogram {
  static identityBuilder: number;

  identity: number;
  autoResize: boolean = false;

  highestTrackableValue: number;
  lowestDiscernibleValue: number;
  numberOfSignificantValueDigits: number;

  bucketCount: number;
  /**
   * Power-of-two length of linearly scaled array slots in the counts array. Long enough to hold the first sequence of
   * entries that must be distinguished by a single unit (determined by configured precision).
   */
  subBucketCount: number;
  countsArrayLength: number;
  wordSizeInBytes: number;

  startTimeStampMsec: number = Number.MAX_SAFE_INTEGER;
  endTimeStampMsec: number = 0;
  tag: string = NO_TAG;

  percentileIterator: PercentileIterator;
  recordedValuesIterator: RecordedValuesIterator;

  // "Hot" accessed fields (used in the the value recording code path) are bunched here, such
  // that they will have a good chance of ending up in the same cache line as the totalCounts and
  // counts array reference fields that subclass implementations will typically add.

  /**
   * Number of leading zeros in the largest value that can fit in bucket 0.
   */
  leadingZeroCountBase: number;
  subBucketHalfCountMagnitude: number;
  /**
   * Largest k such that 2^k <= lowestDiscernibleValue
   */
  unitMagnitude: number;
  subBucketHalfCount: number;

  lowestDiscernibleValueRounded: number;

  /**
   * Biggest value that can fit in bucket 0
   */
  subBucketMask: number;
  /**
   * Lowest unitMagnitude bits are set
   */
  unitMagnitudeMask: number;

  maxValue: number = 0;
  minNonZeroValue: number = Number.MAX_SAFE_INTEGER;

  _totalCount: number;

  incrementTotalCount() {
    this._totalCount++;
  }

  addToTotalCount(value: number) {
    this._totalCount += value;
  }

  setTotalCount(value: number) {
    this._totalCount = value;
  }

  /**
   * Get the total count of all recorded values in the histogram
   * @return the total count of all recorded values in the histogram
   */
  get totalCount() {
    return this._totalCount;
  }

  //
  //
  //
  // Abstract, counts-type dependent methods to be provided by subclass implementations:
  //
  //
  //

  abstract getCountAtIndex(index: number): number;

  abstract incrementCountAtIndex(index: number): void;

  abstract addToCountAtIndex(index: number, value: number): void;

  abstract setCountAtIndex(index: number, value: number): void;

  abstract clearCounts(): void;

  protected abstract _getEstimatedFootprintInBytes(): number;

  abstract resize(newHighestTrackableValue: number): void;

  private updatedMaxValue(value: number): void {
    const internalValue: number = value + this.unitMagnitudeMask;
    this.maxValue = internalValue;
  }

  private updateMinNonZeroValue(value: number): void {
    if (value <= this.unitMagnitudeMask) {
      return;
    }
    const internalValue =
      floor(value / this.lowestDiscernibleValueRounded) *
      this.lowestDiscernibleValueRounded;
    this.minNonZeroValue = internalValue;
  }

  constructor(
    lowestDiscernibleValue: number,
    highestTrackableValue: number,
    numberOfSignificantValueDigits: number
  ) {
    this.identity = 0;
    this.highestTrackableValue = 0;
    this.lowestDiscernibleValue = 0;
    this.numberOfSignificantValueDigits = 0;
    this.bucketCount = 0;
    this.subBucketCount = 0;
    this.countsArrayLength = 0;
    this.wordSizeInBytes = 0;
    // Verify argument validity
    if (lowestDiscernibleValue < 1) {
      throw new Error("lowestDiscernibleValue must be >= 1");
    }
    if (highestTrackableValue < 2 * lowestDiscernibleValue) {
      throw new Error(
        `highestTrackableValue must be >= 2 * lowestDiscernibleValue ( 2 * ${lowestDiscernibleValue} )`
      );
    }
    if (
      numberOfSignificantValueDigits < 0 ||
      numberOfSignificantValueDigits > 5
    ) {
      throw new Error("numberOfSignificantValueDigits must be between 0 and 5");
    }
    this.identity = JsHistogram.identityBuilder++;

    this.init(
      lowestDiscernibleValue,
      highestTrackableValue,
      numberOfSignificantValueDigits
    );
  }

  init(
    lowestDiscernibleValue: number,
    highestTrackableValue: number,
    numberOfSignificantValueDigits: number
  ) {
    this.lowestDiscernibleValue = lowestDiscernibleValue;
    this.highestTrackableValue = highestTrackableValue;
    this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;

    /*
     * Given a 3 decimal point accuracy, the expectation is obviously for "+/- 1 unit at 1000". It also means that
     * it's "ok to be +/- 2 units at 2000". The "tricky" thing is that it is NOT ok to be +/- 2 units at 1999. Only
     * starting at 2000. So internally, we need to maintain single unit resolution to 2x 10^decimalPoints.
     */
    const largestValueWithSingleUnitResolution =
      2 * floor(pow(10, numberOfSignificantValueDigits));

    this.unitMagnitude = floor(log2(lowestDiscernibleValue));

    this.lowestDiscernibleValueRounded = pow(2, this.unitMagnitude);
    this.unitMagnitudeMask = this.lowestDiscernibleValueRounded - 1;

    // We need to maintain power-of-two subBucketCount (for clean direct indexing) that is large enough to
    // provide unit resolution to at least largestValueWithSingleUnitResolution. So figure out
    // largestValueWithSingleUnitResolution's nearest power-of-two (rounded up), and use that:
    const subBucketCountMagnitude = ceil(
      log2(largestValueWithSingleUnitResolution)
    );
    this.subBucketHalfCountMagnitude =
      (subBucketCountMagnitude > 1 ? subBucketCountMagnitude : 1) - 1;
    this.subBucketCount = pow(2, this.subBucketHalfCountMagnitude + 1);
    this.subBucketHalfCount = this.subBucketCount / 2;
    this.subBucketMask =
      (floor(this.subBucketCount) - 1) * pow(2, this.unitMagnitude);

    this.establishSize(highestTrackableValue);

    this.leadingZeroCountBase =
      53 - this.unitMagnitude - this.subBucketHalfCountMagnitude - 1;
    this.percentileIterator = new PercentileIterator(this, 1);
    this.recordedValuesIterator = new RecordedValuesIterator(this);
  }

  /**
   * The buckets (each of which has subBucketCount sub-buckets, here assumed to be 2048 as an example) overlap:
   *
   *

   * The 0'th bucket covers from 0...2047 in multiples of 1, using all 2048 sub-buckets
   * The 1'th bucket covers from 2048..4097 in multiples of 2, using only the top 1024 sub-buckets
   * The 2'th bucket covers from 4096..8191 in multiple of 4, using only the top 1024 sub-buckets
   * ...
   *

   *
   * Bucket 0 is "special" here. It is the only one that has 2048 entries. All the rest have 1024 entries (because
   * their bottom half overlaps with and is already covered by the all of the previous buckets put together). In other
   * words, the k'th bucket could represent 0 * 2^k to 2048 * 2^k in 2048 buckets with 2^k precision, but the midpoint
   * of 1024 * 2^k = 2048 * 2^(k-1) = the k-1'th bucket's end, so we would use the previous bucket for those lower
   * values as it has better precision.
   */
  establishSize(newHighestTrackableValue: number): void {
    // establish counts array length:
    this.countsArrayLength = this.determineArrayLengthNeeded(
      newHighestTrackableValue
    );
    // establish exponent range needed to support the trackable value with no overflow:
    this.bucketCount = this.getBucketsNeededToCoverValue(
      newHighestTrackableValue
    );
    // establish the new highest trackable value:
    this.highestTrackableValue = newHighestTrackableValue;
  }

  determineArrayLengthNeeded(highestTrackableValue: number): number {
    if (highestTrackableValue < 2 * this.lowestDiscernibleValue) {
      throw new Error(
        "highestTrackableValue (" +
          highestTrackableValue +
          ") cannot be < (2 * lowestDiscernibleValue)"
      );
    }
    //determine counts array length needed:
    const countsArrayLength = this.getLengthForNumberOfBuckets(
      this.getBucketsNeededToCoverValue(highestTrackableValue)
    );
    return countsArrayLength;
  }

  /**
   * If we have N such that subBucketCount * 2^N > max value, we need storage for N+1 buckets, each with enough
   * slots to hold the top half of the subBucketCount (the lower half is covered by previous buckets), and the +1
   * being used for the lower half of the 0'th bucket. Or, equivalently, we need 1 more bucket to capture the max
   * value if we consider the sub-bucket length to be halved.
   */
  getLengthForNumberOfBuckets(numberOfBuckets: number): number {
    const lengthNeeded: number =
      (numberOfBuckets + 1) * (this.subBucketCount / 2);
    return lengthNeeded;
  }

  getBucketsNeededToCoverValue(value: number): number {
    // the k'th bucket can express from 0 * 2^k to subBucketCount * 2^k in units of 2^k
    let smallestUntrackableValue =
      this.subBucketCount * pow(2, this.unitMagnitude);
    // always have at least 1 bucket
    let bucketsNeeded = 1;
    while (smallestUntrackableValue <= value) {
      if (smallestUntrackableValue > Number.MAX_SAFE_INTEGER / 2) {
        // TODO check array max size in JavaScript
        // next shift will overflow, meaning that bucket could represent values up to ones greater than
        // Number.MAX_SAFE_INTEGER, so it's the last bucket
        return bucketsNeeded + 1;
      }
      smallestUntrackableValue = smallestUntrackableValue * 2;
      bucketsNeeded++;
    }
    return bucketsNeeded;
  }

  /**
   * Record a value in the histogram
   *
   * @param value The value to be recorded
   * @throws may throw Error if value is exceeds highestTrackableValue
   */
  recordValue(value: number) {
    this.recordSingleValue(value);
  }

  recordSingleValue(value: number) {
    const countsIndex = this.countsArrayIndex(value);
    if (countsIndex >= this.countsArrayLength) {
      this.handleRecordException(1, value);
    } else {
      this.incrementCountAtIndex(countsIndex);
    }
    this.updateMinAndMax(value);
    this.incrementTotalCount();
  }

  handleRecordException(count: number, value: number) {
    if (!this.autoResize) {
      throw new Error(
        "Value " + value + " is outside of histogram covered range"
      );
    }
    this.resize(value);
    var countsIndex: number = this.countsArrayIndex(value);
    this.addToCountAtIndex(countsIndex, count);
    this.highestTrackableValue = this.highestEquivalentValue(
      this.valueFromIndex(this.countsArrayLength - 1)
    );
  }

  countsArrayIndex(value: number): number {
    if (value < 0) {
      throw new Error("Histogram recorded value cannot be negative.");
    }
    const bucketIndex = this.getBucketIndex(value);
    const subBucketIndex = this.getSubBucketIndex(value, bucketIndex);
    return this.computeCountsArrayIndex(bucketIndex, subBucketIndex);
  }

  private computeCountsArrayIndex(bucketIndex: number, subBucketIndex: number) {
    // TODO
    //assert(subBucketIndex < subBucketCount);
    //assert(bucketIndex == 0 || (subBucketIndex >= subBucketHalfCount));

    // Calculate the index for the first entry that will be used in the bucket (halfway through subBucketCount).
    // For bucketIndex 0, all subBucketCount entries may be used, but bucketBaseIndex is still set in the middle.
    const bucketBaseIndex =
      (bucketIndex + 1) * pow(2, this.subBucketHalfCountMagnitude);
    // Calculate the offset in the bucket. This subtraction will result in a positive value in all buckets except
    // the 0th bucket (since a value in that bucket may be less than half the bucket's 0 to subBucketCount range).
    // However, this works out since we give bucket 0 twice as much space.
    const offsetInBucket = subBucketIndex - this.subBucketHalfCount;
    // The following is the equivalent of ((subBucketIndex  - subBucketHalfCount) + bucketBaseIndex;
    return bucketBaseIndex + offsetInBucket;
  }

  /**
   * @return the lowest (and therefore highest precision) bucket index that can represent the value
   */
  getBucketIndex(value: number) {
    // Calculates the number of powers of two by which the value is greater than the biggest value that fits in
    // bucket 0. This is the bucket index since each successive bucket can hold a value 2x greater.
    // The mask maps small values to bucket 0.

    // return this.leadingZeroCountBase - Long.numberOfLeadingZeros(value | subBucketMask);
    return max(
      floor(log2(value)) -
        this.subBucketHalfCountMagnitude -
        this.unitMagnitude,
      0
    );
  }

  getSubBucketIndex(value: number, bucketIndex: number) {
    // For bucketIndex 0, this is just value, so it may be anywhere in 0 to subBucketCount.
    // For other bucketIndex, this will always end up in the top half of subBucketCount: assume that for some bucket
    // k > 0, this calculation will yield a value in the bottom half of 0 to subBucketCount. Then, because of how
    // buckets overlap, it would have also been in the top half of bucket k-1, and therefore would have
    // returned k-1 in getBucketIndex(). Since we would then shift it one fewer bits here, it would be twice as big,
    // and therefore in the top half of subBucketCount.
    return floor(value / pow(2, bucketIndex + this.unitMagnitude));
  }

  updateMinAndMax(value: number) {
    if (value > this.maxValue) {
      this.updatedMaxValue(value);
    }
    if (value < this.minNonZeroValue && value !== 0) {
      this.updateMinNonZeroValue(value);
    }
  }

  /**
   * Get the value at a given percentile.
   * When the given percentile is > 0.0, the value returned is the value that the given
   * percentage of the overall recorded value entries in the histogram are either smaller than
   * or equivalent to. When the given percentile is 0.0, the value returned is the value that all value
   * entries in the histogram are either larger than or equivalent to.
   *

   * Note that two values are "equivalent" in this statement if
   * {@link org.HdrHistogram.JsHistogram#valuesAreEquivalent} would return true.
   *
   * @param percentile  The percentile for which to return the associated value
   * @return The value that the given percentage of the overall recorded value entries in the
   * histogram are either smaller than or equivalent to. When the percentile is 0.0, returns the
   * value that all value entries in the histogram are either larger than or equivalent to.
   */
  getValueAtPercentile(percentile: number) {
    const requestedPercentile = min(percentile, 100); // Truncate down to 100%

    // round count up to nearest integer, to ensure that the largest value that the requested percentile
    // of overall recorded values is actually included. However, this must be done with care:
    //
    // First, Compute fp value for count at the requested percentile. Note that fp result end up
    // being 1 ulp larger than the correct integer count for this percentile:
    const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount;
    // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from
    // making us skip a count:
    const countAtPercentile = max(
      ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up
      1 // Make sure we at least reach the first recorded entry
    );

    let totalToCurrentIndex = 0;
    for (let i = 0; i < this.countsArrayLength; i++) {
      totalToCurrentIndex += this.getCountAtIndex(i);
      if (totalToCurrentIndex >= countAtPercentile) {
        var valueAtIndex: number = this.valueFromIndex(i);
        return percentile === 0.0
          ? this.lowestEquivalentValue(valueAtIndex)
          : this.highestEquivalentValue(valueAtIndex);
      }
    }
    return 0;
  }

  valueFromIndexes(bucketIndex: number, subBucketIndex: number) {
    return subBucketIndex * pow(2, bucketIndex + this.unitMagnitude);
  }

  valueFromIndex(index: number) {
    let bucketIndex = floor(index / this.subBucketHalfCount) - 1;
    let subBucketIndex =
      (index % this.subBucketHalfCount) + this.subBucketHalfCount;
    if (bucketIndex < 0) {
      subBucketIndex -= this.subBucketHalfCount;
      bucketIndex = 0;
    }
    return this.valueFromIndexes(bucketIndex, subBucketIndex);
  }

  /**
   * Get the lowest value that is equivalent to the given value within the histogram's resolution.
   * Where "equivalent" means that value samples recorded for any two
   * equivalent values are counted in a common total count.
   *
   * @param value The given value
   * @return The lowest value that is equivalent to the given value within the histogram's resolution.
   */
  lowestEquivalentValue(value: number) {
    const bucketIndex = this.getBucketIndex(value);
    const subBucketIndex = this.getSubBucketIndex(value, bucketIndex);
    const thisValueBaseLevel = this.valueFromIndexes(
      bucketIndex,
      subBucketIndex
    );
    return thisValueBaseLevel;
  }

  /**
   * Get the highest value that is equivalent to the given value within the histogram's resolution.
   * Where "equivalent" means that value samples recorded for any two
   * equivalent values are counted in a common total count.
   *
   * @param value The given value
   * @return The highest value that is equivalent to the given value within the histogram's resolution.
   */
  highestEquivalentValue(value: number) {
    return this.nextNonEquivalentValue(value) - 1;
  }

  /**
   * Get the next value that is not equivalent to the given value within the histogram's resolution.
   * Where "equivalent" means that value samples recorded for any two
   * equivalent values are counted in a common total count.
   *
   * @param value The given value
   * @return The next value that is not equivalent to the given value within the histogram's resolution.
   */
  nextNonEquivalentValue(value: number) {
    return (
      this.lowestEquivalentValue(value) + this.sizeOfEquivalentValueRange(value)
    );
  }

  /**
   * Get the size (in value units) of the range of values that are equivalent to the given value within the
   * histogram's resolution. Where "equivalent" means that value samples recorded for any two
   * equivalent values are counted in a common total count.
   *
   * @param value The given value
   * @return The size of the range of values equivalent to the given value.
   */
  sizeOfEquivalentValueRange(value: number) {
    const bucketIndex = this.getBucketIndex(value);
    const subBucketIndex = this.getSubBucketIndex(value, bucketIndex);
    const distanceToNextValue = pow(
      2,
      this.unitMagnitude +
        (subBucketIndex >= this.subBucketCount ? bucketIndex + 1 : bucketIndex)
    );
    return distanceToNextValue;
  }

  /**
   * Get a value that lies in the middle (rounded up) of the range of values equivalent the given value.
   * Where "equivalent" means that value samples recorded for any two
   * equivalent values are counted in a common total count.
   *
   * @param value The given value
   * @return The value lies in the middle (rounded up) of the range of values equivalent the given value.
   */
  medianEquivalentValue(value: number) {
    return (
      this.lowestEquivalentValue(value) +
      floor(this.sizeOfEquivalentValueRange(value) / 2)
    );
  }

  /**
   * Get the computed mean value of all recorded values in the histogram
   *
   * @return the mean value (in value units) of the histogram data
   */
  get mean() {
    if (this.totalCount === 0) {
      return 0;
    }
    this.recordedValuesIterator.reset();
    let totalValue = 0;
    while (this.recordedValuesIterator.hasNext()) {
      const iterationValue = this.recordedValuesIterator.next();
      totalValue +=
        this.medianEquivalentValue(iterationValue.valueIteratedTo) *
        iterationValue.countAtValueIteratedTo;
    }
    return totalValue / this.totalCount;
  }

  private getStdDeviation(mean: number = this.mean) {
    if (this.totalCount === 0) {
      return 0;
    }
    let geometric_deviation_total = 0.0;
    this.recordedValuesIterator.reset();
    while (this.recordedValuesIterator.hasNext()) {
      const iterationValue = this.recordedValuesIterator.next();
      const deviation =
        this.medianEquivalentValue(iterationValue.valueIteratedTo) - mean;
      geometric_deviation_total +=
        deviation * deviation * iterationValue.countAddedInThisIterationStep;
    }
    const std_deviation = Math.sqrt(
      geometric_deviation_total / this.totalCount
    );
    return std_deviation;
  }

  /**
   * Get the computed standard deviation of all recorded values in the histogram
   *
   * @return the standard deviation (in value units) of the histogram data
   */
  get stdDeviation() {
    if (this.totalCount === 0) {
      return 0;
    }
    const mean = this.mean;
    let geometric_deviation_total = 0.0;
    this.recordedValuesIterator.reset();
    while (this.recordedValuesIterator.hasNext()) {
      const iterationValue = this.recordedValuesIterator.next();
      const deviation =
        this.medianEquivalentValue(iterationValue.valueIteratedTo) - mean;
      geometric_deviation_total +=
        deviation * deviation * iterationValue.countAddedInThisIterationStep;
    }
    const std_deviation = Math.sqrt(
      geometric_deviation_total / this.totalCount
    );
    return std_deviation;
  }

  /**
   * Produce textual representation of the value distribution of histogram data by percentile. The distribution is
   * output with exponentially increasing resolution, with each exponentially decreasing half-distance containing
   * dumpTicksPerHalf percentile reporting tick points.
   *
   * @param printStream    Stream into which the distribution will be output
   *

   * @param percentileTicksPerHalfDistance  The number of reporting points per exponentially decreasing half-distance
   *

   * @param outputValueUnitScalingRatio    The scaling factor by which to divide histogram recorded values units in
   *                                     output
   * @param useCsvFormat  Output in CSV format if true. Otherwise use plain text form.
   */
  outputPercentileDistribution(
    percentileTicksPerHalfDistance = 5,
    outputValueUnitScalingRatio = 1,
    useCsvFormat = false
  ): string {
    let result = "";
    if (useCsvFormat) {
      result += '"Value","Percentile","TotalCount","1/(1-Percentile)"\n';
    } else {
      result += "       Value     Percentile TotalCount 1/(1-Percentile)\n\n";
    }

    const iterator = this.percentileIterator;
    iterator.reset(percentileTicksPerHalfDistance);

    let lineFormatter: (iterationValue: HistogramIterationValue) => string;
    let lastLineFormatter: (iterationValue: HistogramIterationValue) => string;

    if (useCsvFormat) {
      const valueFormatter = floatFormatter(
        0,
        this.numberOfSignificantValueDigits
      );
      const percentileFormatter = floatFormatter(0, 12);
      const lastFormatter = floatFormatter(0, 2);

      lineFormatter = (iterationValue: HistogramIterationValue) =>
        valueFormatter(
          iterationValue.valueIteratedTo / outputValueUnitScalingRatio
        ) +
        "," +
        percentileFormatter(iterationValue.percentileLevelIteratedTo / 100) +
        "," +
        iterationValue.totalCountToThisValue +
        "," +
        lastFormatter(
          1 / (1 - iterationValue.percentileLevelIteratedTo / 100)
        ) +
        "\n";
      lastLineFormatter = (iterationValue: HistogramIterationValue) =>
        valueFormatter(
          iterationValue.valueIteratedTo / outputValueUnitScalingRatio
        ) +
        "," +
        percentileFormatter(iterationValue.percentileLevelIteratedTo / 100) +
        "," +
        iterationValue.totalCountToThisValue +
        ",Infinity\n";
    } else {
      const valueFormatter = floatFormatter(
        12,
        this.numberOfSignificantValueDigits
      );
      const percentileFormatter = floatFormatter(2, 12);
      const totalCountFormatter = integerFormatter(10);
      const lastFormatter = floatFormatter(14, 2);

      lineFormatter = (iterationValue: HistogramIterationValue) =>
        valueFormatter(
          iterationValue.valueIteratedTo / outputValueUnitScalingRatio
        ) +
        " " +
        percentileFormatter(iterationValue.percentileLevelIteratedTo / 100) +
        " " +
        totalCountFormatter(iterationValue.totalCountToThisValue) +
        " " +
        lastFormatter(
          1 / (1 - iterationValue.percentileLevelIteratedTo / 100)
        ) +
        "\n";

      lastLineFormatter = (iterationValue: HistogramIterationValue) =>
        valueFormatter(
          iterationValue.valueIteratedTo / outputValueUnitScalingRatio
        ) +
        " " +
        percentileFormatter(iterationValue.percentileLevelIteratedTo / 100) +
        " " +
        totalCountFormatter(iterationValue.totalCountToThisValue) +
        "\n";
    }

    while (iterator.hasNext()) {
      const iterationValue = iterator.next();
      if (iterationValue.percentileLevelIteratedTo < 100) {
        result += lineFormatter(iterationValue);
      } else {
        result += lastLineFormatter(iterationValue);
      }
    }

    if (!useCsvFormat) {
      // Calculate and output mean and std. deviation.
      // Note: mean/std. deviation numbers are very often completely irrelevant when
      // data is extremely non-normal in distribution (e.g. in cases of strong multi-modal
      // response time distribution associated with GC pauses). However, reporting these numbers
      // can be very useful for contrasting with the detailed percentile distribution
      // reported by outputPercentileDistribution(). It is not at all surprising to find
      // percentile distributions where results fall many tens or even hundreds of standard
      // deviations away from the mean - such results simply indicate that the data sampled
      // exhibits a very non-normal distribution, highlighting situations for which the std.
      // deviation metric is a useless indicator.
      //
      const formatter = floatFormatter(12, this.numberOfSignificantValueDigits);
      const _mean = this.mean;
      const mean = formatter(_mean / outputValueUnitScalingRatio);
      const std_deviation = formatter(
        this.getStdDeviation(_mean) / outputValueUnitScalingRatio
      );
      const max = formatter(this.maxValue / outputValueUnitScalingRatio);
      const intFormatter = integerFormatter(12);
      const totalCount = intFormatter(this.totalCount);
      const bucketCount = intFormatter(this.bucketCount);
      const subBucketCount = intFormatter(this.subBucketCount);

      result += `#[Mean    = ${mean}, StdDeviation   = ${std_deviation}]
#[Max     = ${max}, Total count    = ${totalCount}]
#[Buckets = ${bucketCount}, SubBuckets     = ${subBucketCount}]
`;
    }

    return result;
  }

  get summary(): HistogramSummary {
    return toSummary(this);
  }

  toJSON(): HistogramSummary {
    return this.summary;
  }

  inspect() {
    return this.toString();
  }

  [Symbol.for("nodejs.util.inspect.custom")]() {
    return this.toString();
  }

  /**
   * Provide a (conservatively high) estimate of the Histogram's total footprint in bytes
   *
   * @return a (conservatively high) estimate of the Histogram's total footprint in bytes
   */
  get estimatedFootprintInBytes() {
    return this._getEstimatedFootprintInBytes();
  }

  recordSingleValueWithExpectedInterval(
    value: number,
    expectedIntervalBetweenValueSamples: number
  ) {
    this.recordSingleValue(value);
    if (expectedIntervalBetweenValueSamples <= 0) {
      return;
    }
    for (
      let missingValue = value - expectedIntervalBetweenValueSamples;
      missingValue >= expectedIntervalBetweenValueSamples;
      missingValue -= expectedIntervalBetweenValueSamples
    ) {
      this.recordSingleValue(missingValue);
    }
  }

  private recordCountAtValue(count: number, value: number) {
    const countsIndex = this.countsArrayIndex(value);
    if (countsIndex >= this.countsArrayLength) {
      this.handleRecordException(count, value);
    } else {
      this.addToCountAtIndex(countsIndex, count);
    }
    this.updateMinAndMax(value);
    this.addToTotalCount(count);
  }

  /**
   * Record a value in the histogram (adding to the value's current count)
   *
   * @param value The value to be recorded
   * @param count The number of occurrences of this value to record
   * @throws ArrayIndexOutOfBoundsException (may throw) if value is exceeds highestTrackableValue
   */
  recordValueWithCount(value: number, count: number) {
    this.recordCountAtValue(count, value);
  }

  /**
   * Record a value in the histogram.
   *

   * To compensate for the loss of sampled values when a recorded value is larger than the expected
   * interval between value samples, Histogram will auto-generate an additional series of decreasingly-smaller
   * (down to the expectedIntervalBetweenValueSamples) value records.
   *

   * Note: This is a at-recording correction method, as opposed to the post-recording correction method provided
   * by {@link #copyCorrectedForCoordinatedOmission(long)}.
   * The two methods are mutually exclusive, and only one of the two should be be used on a given data set to correct
   * for the same coordinated omission issue.
   *

   * See notes in the description of the Histogram calls for an illustration of why this corrective behavior is
   * important.
   *
   * @param value The value to record
   * @param expectedIntervalBetweenValueSamples If expectedIntervalBetweenValueSamples is larger than 0, add
   *                                           auto-generated value records as appropriate if value is larger
   *                                           than expectedIntervalBetweenValueSamples
   * @throws ArrayIndexOutOfBoundsException (may throw) if value is exceeds highestTrackableValue
   */
  recordValueWithExpectedInterval(
    value: number,
    expectedIntervalBetweenValueSamples: number
  ) {
    this.recordSingleValueWithExpectedInterval(
      value,
      expectedIntervalBetweenValueSamples
    );
  }

  private recordValueWithCountAndExpectedInterval(
    value: number,
    count: number,
    expectedIntervalBetweenValueSamples: number
  ) {
    this.recordCountAtValue(count, value);
    if (expectedIntervalBetweenValueSamples <= 0) {
      return;
    }
    for (
      let missingValue = value - expectedIntervalBetweenValueSamples;
      missingValue >= expectedIntervalBetweenValueSamples;
      missingValue -= expectedIntervalBetweenValueSamples
    ) {
      this.recordCountAtValue(count, missingValue);
    }
  }

  /**
   * Add the contents of another histogram to this one, while correcting the incoming data for coordinated omission.
   *

   * To compensate for the loss of sampled values when a recorded value is larger than the expected
   * interval between value samples, the values added will include an auto-generated additional series of
   * decreasingly-smaller (down to the expectedIntervalBetweenValueSamples) value records for each count found
   * in the current histogram that is larger than the expectedIntervalBetweenValueSamples.
   *
   * Note: This is a post-recording correction method, as opposed to the at-recording correction method provided
   * by {@link #recordValueWithExpectedInterval(long, long) recordValueWithExpectedInterval}. The two
   * methods are mutually exclusive, and only one of the two should be be used on a given data set to correct
   * for the same coordinated omission issue.
   * by
   *

   * See notes in the description of the Histogram calls for an illustration of why this corrective behavior is
   * important.
   *
   * @param otherHistogram The other histogram. highestTrackableValue and largestValueWithSingleUnitResolution must match.
   * @param expectedIntervalBetweenValueSamples If expectedIntervalBetweenValueSamples is larger than 0, add
   *                                           auto-generated value records as appropriate if value is larger
   *                                           than expectedIntervalBetweenValueSamples
   * @throws ArrayIndexOutOfBoundsException (may throw) if values exceed highestTrackableValue
   */
  addWhileCorrectingForCoordinatedOmission(
    otherHistogram: JsHistogram,
    expectedIntervalBetweenValueSamples: number
  ) {
    const toHistogram = this;

    const otherValues = new RecordedValuesIterator(otherHistogram);

    while (otherValues.hasNext()) {
      const v = otherValues.next();
      toHistogram.recordValueWithCountAndExpectedInterval(
        v.valueIteratedTo,
        v.countAtValueIteratedTo,
        expectedIntervalBetweenValueSamples
      );
    }
  }

  /**
   * Get a copy of this histogram, corrected for coordinated omission.
   *

   * To compensate for the loss of sampled values when a recorded value is larger than the expected
   * interval between value samples, the new histogram will include an auto-generated additional series of
   * decreasingly-smaller (down to the expectedIntervalBetweenValueSamples) value records for each count found
   * in the current histogram that is larger than the expectedIntervalBetweenValueSamples.
   *
   * Note: This is a post-correction method, as opposed to the at-recording correction method provided
   * by {@link #recordValueWithExpectedInterval(long, long) recordValueWithExpectedInterval}. The two
   * methods are mutually exclusive, and only one of the two should be be used on a given data set to correct
   * for the same coordinated omission issue.
   * by
   *

   * See notes in the description of the Histogram calls for an illustration of why this corrective behavior is
   * important.
   *
   * @param expectedIntervalBetweenValueSamples If expectedIntervalBetweenValueSamples is larger than 0, add
   *                                           auto-generated value records as appropriate if value is larger
   *                                           than expectedIntervalBetweenValueSamples
   * @return a copy of this histogram, corrected for coordinated omission.
   */
  abstract copyCorrectedForCoordinatedOmission(
    expectedIntervalBetweenValueSamples: number
  ): JsHistogram;

  /**
   * Add the contents of another histogram to this one.
   *

   * As part of adding the contents, the start/end timestamp range of this histogram will be
   * extended to include the start/end timestamp range of the other histogram.
   *
   * @param otherHistogram The other histogram.
   * @throws (may throw) if values in fromHistogram's are
   * higher than highestTrackableValue.
   */
  add(otherHistogram: JsHistogram) {
    if (!(otherHistogram instanceof JsHistogram)) {
      // should be impossible to be in this situation but actually
      // TypeScript has some flaws...
      throw new Error("Cannot add a WASM histogram to a regular JS histogram");
    }
    const highestRecordableValue = this.highestEquivalentValue(
      this.valueFromIndex(this.countsArrayLength - 1)
    );

    if (highestRecordableValue < otherHistogram.maxValue) {
      if (!this.autoResize) {
        throw new Error(
          "The other histogram includes values that do not fit in this histogram's range."
        );
      }
      this.resize(otherHistogram.maxValue);
    }

    if (
      this.bucketCount === otherHistogram.bucketCount &&
      this.subBucketCount === otherHistogram.subBucketCount &&
      this.unitMagnitude === otherHistogram.unitMagnitude
    ) {
      // Counts arrays are of the same length and meaning, so we can just iterate and add directly:
      let observedOtherTotalCount = 0;
      for (let i = 0; i < otherHistogram.countsArrayLength; i++) {
        const otherCount = otherHistogram.getCountAtIndex(i);
        if (otherCount > 0) {
          this.addToCountAtIndex(i, otherCount);
          observedOtherTotalCount += otherCount;
        }
      }
      this.setTotalCount(this.totalCount + observedOtherTotalCount);
      this.updatedMaxValue(max(this.maxValue, otherHistogram.maxValue));
      this.updateMinNonZeroValue(
        min(this.minNonZeroValue, otherHistogram.minNonZeroValue)
      );
    } else {
      // Arrays are not a direct match (or the other could change on the fly in some valid way),
      // so we can't just stream through and add them. Instead, go through the array and add each
      // non-zero value found at it's proper value:

      // Do max value first, to avoid max value updates on each iteration:
      const otherMaxIndex = otherHistogram.countsArrayIndex(
        otherHistogram.maxValue
      );
      let otherCount = otherHistogram.getCountAtIndex(otherMaxIndex);
      this.recordCountAtValue(
        otherCount,
        otherHistogram.valueFromIndex(otherMaxIndex)
      );

      // Record the remaining values, up to but not including the max value:
      for (let i = 0; i < otherMaxIndex; i++) {
        otherCount = otherHistogram.getCountAtIndex(i);
        if (otherCount > 0) {
          this.recordCountAtValue(otherCount, otherHistogram.valueFromIndex(i));
        }
      }
    }
    this.startTimeStampMsec = min(
      this.startTimeStampMsec,
      otherHistogram.startTimeStampMsec
    );
    this.endTimeStampMsec = max(
      this.endTimeStampMsec,
      otherHistogram.endTimeStampMsec
    );
  }

  /**
   * Get the count of recorded values at a specific value (to within the histogram resolution at the value level).
   *
   * @param value The value for which to provide the recorded count
   * @return The total count of values recorded in the histogram within the value range that is
   * {@literal >=} lowestEquivalentValue(value) and {@literal <=} highestEquivalentValue(value)
   */
  private getCountAtValue(value: number) {
    const index = min(
      max(0, this.countsArrayIndex(value)),
      this.countsArrayLength - 1
    );
    return this.getCountAtIndex(index);
  }

  /**
   * Subtract the contents of another histogram from this one.
   *

   * The start/end timestamps of this histogram will remain unchanged.
   *
   * @param otherHistogram The other histogram.
   * @throws ArrayIndexOutOfBoundsException (may throw) if values in otherHistogram's are higher than highestTrackableValue.
   *
   */
  subtract(otherHistogram: JsHistogram) {
    const highestRecordableValue = this.valueFromIndex(
      this.countsArrayLength - 1
    );
    if (!(otherHistogram instanceof JsHistogram)) {
      // should be impossible to be in this situation but actually
      // TypeScript has some flaws...
      throw new Error(
        "Cannot subtract a WASM histogram to a regular JS histogram"
      );
    }
    if (highestRecordableValue < otherHistogram.maxValue) {
      if (!this.autoResize) {
        throw new Error(
          "The other histogram includes values that do not fit in this histogram's range."
        );
      }
      this.resize(otherHistogram.maxValue);
    }

    if (
      this.bucketCount === otherHistogram.bucketCount &&
      this.subBucketCount === otherHistogram.subBucketCount &&
      this.unitMagnitude === otherHistogram.unitMagnitude
    ) {
      // optim
      // Counts arrays are of the same length and meaning, so we can just iterate and add directly:
      let observedOtherTotalCount = 0;
      for (let i = 0; i < otherHistogram.countsArrayLength; i++) {
        const otherCount = otherHistogram.getCountAtIndex(i);
        if (otherCount > 0) {
          this.addToCountAtIndex(i, -otherCount);
          observedOtherTotalCount += otherCount;
        }
      }
      this.setTotalCount(this.totalCount - observedOtherTotalCount);
    } else {
      for (let i = 0; i < otherHistogram.countsArrayLength; i++) {
        const otherCount = otherHistogram.getCountAtIndex(i);
        if (otherCount > 0) {
          const otherValue = otherHistogram.valueFromIndex(i);
          if (this.getCountAtValue(otherValue) < otherCount) {
            throw new Error(
              "otherHistogram count (" +
                otherCount +
                ") at value " +
                otherValue +
                " is larger than this one's (" +
                this.getCountAtValue(otherValue) +
                ")"
            );
          }
          this.recordCountAtValue(-otherCount, otherValue);
        }
      }
    }
    // With subtraction, the max and minNonZero values could have changed:
    if (
      this.getCountAtValue(this.maxValue) <= 0 ||
      this.getCountAtValue(this.minNonZeroValue) <= 0
    ) {
      this.establishInternalTackingValues();
    }
  }

  establishInternalTackingValues(lengthToCover = this.countsArrayLength) {
    this.maxValue = 0;
    this.minNonZeroValue = Number.MAX_VALUE;
    let maxIndex = -1;
    let minNonZeroIndex = -1;
    let observedTotalCount = 0;
    for (let index = 0; index < lengthToCover; index++) {
      const countAtIndex = this.getCountAtIndex(index);
      if (countAtIndex > 0) {
        observedTotalCount += countAtIndex;
        maxIndex = index;
        if (minNonZeroIndex == -1 && index != 0) {
          minNonZeroIndex = index;
        }
      }
    }
    if (maxIndex >= 0) {
      this.updatedMaxValue(
        this.highestEquivalentValue(this.valueFromIndex(maxIndex))
      );
    }
    if (minNonZeroIndex >= 0) {
      this.updateMinNonZeroValue(this.valueFromIndex(minNonZeroIndex));
    }
    this.setTotalCount(observedTotalCount);
  }

  reset() {
    this.clearCounts();
    this.setTotalCount(0);
    this.startTimeStampMsec = 0;
    this.endTimeStampMsec = 0;
    this.tag = NO_TAG;
    this.maxValue = 0;
    this.minNonZeroValue = Number.MAX_SAFE_INTEGER;
  }

  destroy() {
    // no op - not needed here
  }
}

export { JsHistogram as default };


text:
/*
 * Created by IntelliJ IDEA.
 * User: mike
 * Date: Oct 31, 2002
 * Time: 6:33:01 PM
 * To change template for new class use
 * Code Style | Class Templates options (Tools | IDE Options).
 */
package com.intellij.openapi.updateSettings.impl;

import com.intellij.ide.IdeBundle;
import com.intellij.ide.reporter.ConnectionException;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.BuildNumber;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.io.UrlConnectionUtil;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.text.DateFormatUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * XML sample:
 * <idea>
 * <build>456</build>
 * <version>4.5.2</version>
 * <title>New Intellij IDEA Version</title>
 * <message>
 * New version of IntelliJ IDEA is available.
 * Please visit http://www.intellij.com/ for more info.
 * </message>
 * </idea>
 */
public final class UpdateChecker {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker");

  public static String ADDITIONAL_REQUEST_OPTIONS = "";

  public static enum DownloadPatchResult {
    SUCCESS, FAILED, CANCELED
  }

  private static long checkInterval = 0;
  private static boolean myVeryFirstOpening = true;

  @NonNls
  private static final String DISABLED_UPDATE = "disabled_update.txt";
  private static TreeSet<String> ourDisabledToUpdatePlugins;

  private static class StringHolder {
    private static final String UPDATE_URL = ApplicationInfoEx.getInstanceEx().getUpdateUrls().getCheckingUrl();
    private static final String PATCHES_URL = ApplicationInfoEx.getInstanceEx().getUpdateUrls().getPatchesUrl();
  }

  private static String getUpdateUrl() {
    return StringHolder.UPDATE_URL;
  }

  private static String getPatchesUrl() {
    return StringHolder.PATCHES_URL;
  }

  public static boolean isMyVeryFirstOpening() {
    return myVeryFirstOpening;
  }

  public static void setMyVeryFirstOpening(final boolean myVeryFirstProjectOpening) {
    myVeryFirstOpening = myVeryFirstProjectOpening;
  }

  public static boolean checkNeeded() {

    final UpdateSettings settings = UpdateSettings.getInstance();
    if (settings == null || getUpdateUrl() == null) return false;

    final String checkPeriod = settings.CHECK_PERIOD;
    if (checkPeriod.equals(UpdateSettingsConfigurable.ON_START_UP)) {
      checkInterval = 0;
    }
    if (checkPeriod.equals(UpdateSettingsConfigurable.DAILY)) {
      checkInterval = DateFormatUtil.DAY;
    }
    if (settings.CHECK_PERIOD.equals(UpdateSettingsConfigurable.WEEKLY)) {
      checkInterval = DateFormatUtil.WEEK;
    }
    if (settings.CHECK_PERIOD.equals(UpdateSettingsConfigurable.MONTHLY)) {
      checkInterval = DateFormatUtil.MONTH;
    }

    final long timeDelta = System.currentTimeMillis() - settings.LAST_TIME_CHECKED;
    if (Math.abs(timeDelta) < checkInterval) return false;

    return settings.CHECK_NEEDED;
  }

  public static List<PluginDownloader> updatePlugins(final boolean showErrorDialog) {
    final List<PluginDownloader> downloaded = new ArrayList<PluginDownloader>();
    final Set<String> failed = new HashSet<String>();
    for (String host : UpdateSettingsConfigurable.getInstance().getPluginHosts()) {
      try {
        checkPluginsHost(host, downloaded);
      }
      catch (Exception e) {
        LOG.info(e);
        failed.add(host);
      }
    }
    if (!failed.isEmpty()) {
      final String failedMessage = IdeBundle.message("connection.failed.message", StringUtil.join(failed, ","));
      if (showErrorDialog) {
        Messages.showErrorDialog(failedMessage, IdeBundle.message("title.connection.error"));
      }
      else {
        LOG.info(failedMessage);
      }
    }
    return downloaded.isEmpty() ? null : downloaded;
  }

  public static boolean checkPluginsHost(final String host, final List<PluginDownloader> downloaded) throws Exception {
    final Document document = loadVersionInfo(host);
    if (document == null) return false;
    boolean success = true;
    for (Object plugin : document.getRootElement().getChildren("plugin")) {
      Element pluginElement = (Element)plugin;
      final String pluginId = pluginElement.getAttributeValue("id");
      final String pluginUrl = pluginElement.getAttributeValue("url");
      final String pluginVersion = pluginElement.getAttributeValue("version");
      if (pluginId == null) {
        LOG.info("plugin id should not be null");
        success = false;
        continue;
      }

      if (pluginUrl == null) {
        LOG.info("plugin url should not be null");
        success = false;
        continue;
      }

      ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
        public void run() {
          try {
            final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
            if (progressIndicator != null) {
              progressIndicator.setText(pluginUrl);
            }
            final PluginDownloader uploader = new PluginDownloader(pluginId, pluginUrl, pluginVersion);
            if (uploader.prepareToInstall()) {
              downloaded.add(uploader);
            }
          }
          catch (IOException e) {
            LOG.info(e);
          }
        }
      }, IdeBundle.message("update.uploading.plugin.progress.title"), true, null);
    }
    return success;
  }

  @Nullable
  private static Product findProduct(Element products, String code) {
    for (Object productNode : products.getChildren("product")) {
      Product product = new Product((Element)productNode);
      if (product.hasCode(code)) {
        return product;
      }
    }
    return null;
  }

  @Nullable
  public static UpdateChannel checkForUpdates() throws ConnectionException {
    try {
      BuildNumber ourBuild = ApplicationInfo.getInstance().getBuild();
      if (LOG.isDebugEnabled()) {
        LOG.debug("enter: checkForUpdates()");
      }

      final Document document;
      try {
        document = loadVersionInfo(getUpdateUrl());
        if (document == null) return null;
      }
      catch (Throwable t) {
        LOG.debug(t);
        throw new ConnectionException(t);
      }

      Element root = document.getRootElement();
      UpdateChannel channel = findUpdateChannel(root, ourBuild.getProductCode());
      if (channel == null) return null;

      BuildInfo latestBuild = channel.getLatestBuild();
      if (latestBuild == null) return null;

      if (ourBuild.compareTo(latestBuild.getNumber()) < 0) {
        return channel;
      }

      return null;
    }
    catch (Throwable t) {
      LOG.debug(t);
      return null;
    }
    finally {
      UpdateSettings.getInstance().LAST_TIME_CHECKED = System.currentTimeMillis();
    }
  }

  @Nullable
  private static UpdateChannel findUpdateChannel(Element root, String productCode) {
    if (root == null) {
      LOG.info("cannot read " + getUpdateUrl());
      return null;
    }

    Product product = findProduct(root, productCode);
    if (product == null) return null;

    UpdateChannel channel = product.findUpdateChannelById(UpdateSettings.getInstance().CURRENT_UPDATE_CHANNEL);
    if (channel != null) return channel;

    for (UpdateChannel c : product.getChannels()) {
      BuildInfo cBuild = c.getLatestBuild();
      if (cBuild == null) continue;

      if (channel == null) {
        channel = c;
      }
      else {
        BuildInfo build = channel.getLatestBuild();
        assert build != null;

        if (build.compareTo(cBuild) < 0) {
          channel = c;
        }
      }
    }

    return channel;
  }

  private static Document loadVersionInfo(final String url) throws Exception {
    if (LOG.isDebugEnabled()) {
      LOG.debug("enter: loadVersionInfo(UPDATE_URL='" + url + "' )");
    }
    final Document[] document = new Document[]{null};
    final Exception[] exception = new Exception[]{null};
    Future<?> downloadThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
      public void run() {
        try {
          HttpConfigurable.getInstance().prepareURL(url);
          final URL requestUrl = new URL(url + "?build=" + ApplicationInfo.getInstance().getBuild().asString() + ADDITIONAL_REQUEST_OPTIONS);
          final InputStream inputStream = requestUrl.openStream();
          try {
            document[0] = JDOMUtil.loadDocument(inputStream);
          }
          finally {
            inputStream.close();
          }
        }
        catch (IOException e) {
          exception[0] = e;
        }
        catch (JDOMException e) {
          LOG.info(e); // Broken xml downloaded. Don't bother telling user.
        }
      }
    });

    try {
      downloadThreadFuture.get(5, TimeUnit.SECONDS);
    }
    catch (TimeoutException e) {
      // ignore
    }

    if (!downloadThreadFuture.isDone()) {
      downloadThreadFuture.cancel(true);
      throw new ConnectionException(IdeBundle.message("updates.timeout.error"));
    }

    if (exception[0] != null) throw exception[0];
    return document[0];
  }

  public static void showNoUpdatesDialog(boolean enableLink, final List<PluginDownloader> updatePlugins) {
    NoUpdatesDialog dialog = new NoUpdatesDialog(true, updatePlugins, enableLink);
    dialog.show();
  }

  public static void showUpdateInfoDialog(boolean enableLink, final UpdateChannel channel, final List<PluginDownloader> updatePlugins) {
    new UpdateInfoDialog(true, channel, updatePlugins, enableLink).show();
  }

  public static boolean install(List<PluginDownloader> downloaders) {
    boolean installed = false;
    for (PluginDownloader downloader : downloaders) {
      if (getDisabledToUpdatePlugins().contains(downloader.getPluginId())) continue;
      try {
        downloader.install();
        installed = true;
      }
      catch (IOException e) {
        LOG.info(e);
      }
    }
    return installed;
  }

  public static DownloadPatchResult downloadAndInstallPatch(final BuildInfo newVersion) {
    final DownloadPatchResult[] result = new DownloadPatchResult[]{DownloadPatchResult.CANCELED};

    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
      public void run() {
        try {
          doDownloadAndInstallPatch(newVersion, ProgressManager.getInstance().getProgressIndicator());
          result[0] = DownloadPatchResult.SUCCESS;
        }
        catch (final IOException e) {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              Messages.showErrorDialog(e.getMessage(), "Failed to download patch file");
            }
          });
          LOG.info(e);
          result[0] = DownloadPatchResult.FAILED;
        }
      }
    }, IdeBundle.message("update.downloading.patch.progress.title"), true, null)) {
      return DownloadPatchResult.CANCELED;
    }

    return result[0];
  }

  private static void doDownloadAndInstallPatch(BuildInfo newVersion, ProgressIndicator i) throws IOException {
    PatchInfo patch = newVersion.findPatchForCurrentBuild();
    if (patch == null) throw new IOException("No patch is available for current version");

    String platform = System.getProperty("idea.platform.prefix", "idea");

    String osSuffix = "";
    if (SystemInfo.isWindows) {
      osSuffix = "-win";
    }
    else if (SystemInfo.isMac) {
      osSuffix = "-mac";
    }
    else if (SystemInfo.isUnix) osSuffix = "-unix";

    String fileName = platform + "-" + patch.getFromBuild().asString() + "-" + newVersion.getNumber().asString() + "-patch" + osSuffix + ".jar";
    URLConnection connection = null;
    InputStream in = null;
    OutputStream out = null;

    String patchFileName = "jetbrains.patch.jar." + platform;
    File patchFile = new File(FileUtil.getTempDirectory(), patchFileName);

    try {
      connection = new URL(new URL(getPatchesUrl()), fileName).openConnection();
      in = UrlConnectionUtil.getConnectionInputStreamWithException(connection, i);
      out = new BufferedOutputStream(new FileOutputStream(patchFile));

      i.setIndeterminate(false);

      byte[] buffer = new byte[10 * 1024];
      int total = connection.getContentLength();
      int count;
      int read = 0;

      while ((count = in.read(buffer)) > 0) {
        i.checkCanceled();
        out.write(buffer, 0, count);
        read += count;
        i.setFraction(((double)read) / total);
        i.setText2((read / 1024) + "/" + (total / 1024) + " KB");
      }
    }
    catch (IOException e) {
      patchFile.delete();
      throw e;
    }
    catch (ProcessCanceledException e) {
      patchFile.delete();
      throw e;
    }
    catch (Throwable e) {
      patchFile.delete();
      throw new RuntimeException(e);
    }
    finally {
      if (out != null) out.close();
      if (in != null) in.close();
      if (connection instanceof HttpURLConnection) ((HttpURLConnection)connection).disconnect();
    }
  }

  public static Set<String> getDisabledToUpdatePlugins() {
    if (ourDisabledToUpdatePlugins == null) {
      ourDisabledToUpdatePlugins = new TreeSet<String>();
      if (!ApplicationManager.getApplication().isUnitTestMode()) {
        try {
          final File file = new File(PathManager.getConfigPath(), DISABLED_UPDATE);
          if (file.isFile()) {
            final String[] ids = new String(FileUtil.loadFileText(file)).split("[\\s]");
            for (String id : ids) {
              if (id != null && id.trim().length() > 0) {
                ourDisabledToUpdatePlugins.add(id.trim());
              }
            }
          }
        }
        catch (IOException e) {
          LOG.error(e);
        }
      }
    }
    return ourDisabledToUpdatePlugins;
  }

  public static void saveDisabledToUpdatePlugins() {
    try {
      File plugins = new File(PathManager.getConfigPath(), DISABLED_UPDATE);
      FileUtil.ensureCanCreateFile(plugins);

      PrintWriter printWriter = null;
      try {
        printWriter = new PrintWriter(new BufferedWriter(new FileWriter(plugins)));
        for (String id : getDisabledToUpdatePlugins()) {
          printWriter.println(id);
        }
        printWriter.flush();
      }
      finally {
        if (printWriter != null) {
          printWriter.close();
        }
      }
    }
    catch (IOException e) {
      LOG.error(e);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
WinRM-config CHANGELOG
======================
This file is used to list changes made in each version of the winrm-config cookbook.

0.2.9 (2020-02-03)
------------------
- Backport a fix for windows_http_acl idempotency for older versions for Chef

0.2.8 (2019-09-09)
------------------
- Allow to disable automatic restart of winrm service on configuration change.

0.2.7 (2019-09-08)
------------------
- Fix winrm_config_listner resources names

0.2.6 (2019-08-27)
------------------
- Fix compatibility with various Chef version (12+)
- Migrate LWRP to custom resources

0.2.5 (2018-10-24)
------------------
- Make default recipe compatible with Chef 13+ (Thanks Jugatsu)

0.2.4 (2016-11-22)
------------------
- Unlock constraint on windows cookbook

0.2.3 (2015-11-20)
------------------
- Leverage windows LWRPs for sslcert and urlacl

0.2.2 (2014-04-01)
------------------
- Handle properly winrm http urlacl and sslcert via winrm_config_listener

0.2.1 (2014-03-20)
------------------
- Allow everyone to access certmapping password hash

0.2.0 (2014-03-16)
------------------
- Fix winrm-config::service convergence issue
- Fix winrm_config_listener converge issue
- Fix type in winrm_config_listener
- Properly implement winrm_config_service_certmapping
- Support why_run in both service_certmapping and listener LWRP
- Improve tests for winrm_config_listener & winrm_config_service_certmapping LWRPs

0.1.0 (2014-03-10)
------------------
- Initial release of winrm-config
- Provide LWRP to configure
 - winrm listeners
 - winrm service certmapping
- Provide recipe to enable winrm windows service
- Provide recipes to configure
 - winrm service
 - winrm client
 - winrm protocol
 - winrm listeners
 - winrs
- Provide Chefspec tests and proper documentation


text:
package gonum

import "gonum.org/v1/gonum/blas"

// Dgelq2 computes the LQ factorization of the m×n matrix A.
//
// In an LQ factorization, L is a lower triangular m×n matrix, and Q is an n×n
// orthonormal matrix.
//
// a is modified to contain the information to construct L and Q.
// The lower triangle of a contains the matrix L. The upper triangular elements
// (not including the diagonal) contain the elementary reflectors. tau is modified
// to contain the reflector scales. tau must have length of at least k = min(m,n)
// and this function will panic otherwise.
//
// See Dgeqr2 for a description of the elementary reflectors and orthonormal
// matrix Q. Q is constructed as a product of these elementary reflectors,
// Q = H_{k-1} * ... * H_1 * H_0.
//
// work is temporary storage of length at least m and this function will panic otherwise.
//
// Dgelq2 is an internal routine. It is exported for testing purposes.
func (impl Implementation) Dgelq2(m, n int, a []float64, lda int, tau, work []float64) {
	switch {
	case m < 0:
		panic(mLT0)
	case n < 0:
		panic(nLT0)
	case lda < max(1, n):
		panic(badLdA)
	}

	// Quick return if possible.
	k := min(m, n)
	if k == 0 {
		return
	}

	switch {
	case len(a) < (m-1)*lda+n:
		panic(shortA)
	case len(tau) < k:
		panic(shortTau)
	case len(work) < m:
		panic(shortWork)
	}

	for i := 0; i < k; i++ {
		a[i*lda+i], tau[i] = impl.Dlarfg(n-i, a[i*lda+i], a[i*lda+min(i+1, n-1):], 1)
		if i < m-1 {
			aii := a[i*lda+i]
			a[i*lda+i] = 1
			impl.Dlarf(blas.Right, m-i-1, n-i,
				a[i*lda+i:], 1,
				tau[i],
				a[(i+1)*lda+i:], lda,
				work)
			a[i*lda+i] = aii
		}
	}
}


text:
/**
 * @generated SignedSource<<269b7fa6108622215ad2f89bfe9fa389>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { Fragment, ReaderFragment } from 'relay-runtime';
export type CommerceOrderStateEnum = "ABANDONED" | "APPROVED" | "CANCELED" | "FULFILLED" | "PENDING" | "PROCESSING_APPROVAL" | "REFUNDED" | "SUBMITTED" | "%future added value";
export type CommercePaymentMethodEnum = "CREDIT_CARD" | "SEPA_DEBIT" | "US_BANK_ACCOUNT" | "WIRE_TRANSFER" | "%future added value";
import { FragmentRefs } from "relay-runtime";
export type ShippingSummaryItem_order$data = {
  readonly lineItems: {
    readonly edges: ReadonlyArray<{
      readonly node: {
        readonly artwork: {
          readonly shippingOrigin: string | null;
        } | null;
      } | null;
    } | null> | null;
  } | null;
  readonly paymentMethod: CommercePaymentMethodEnum | null;
  readonly requestedFulfillment: {
    readonly __typename: string;
    readonly " $fragmentSpreads": FragmentRefs<"ShippingAddress_ship">;
  } | null;
  readonly state: CommerceOrderStateEnum;
  readonly " $fragmentType": "ShippingSummaryItem_order";
};
export type ShippingSummaryItem_order$key = {
  readonly " $data"?: ShippingSummaryItem_order$data;
  readonly " $fragmentSpreads": FragmentRefs<"ShippingSummaryItem_order">;
};

const node: ReaderFragment = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "ShippingSummaryItem_order",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "state",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "paymentMethod",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": null,
      "kind": "LinkedField",
      "name": "requestedFulfillment",
      "plural": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "__typename",
          "storageKey": null
        },
        {
          "args": null,
          "kind": "FragmentSpread",
          "name": "ShippingAddress_ship"
        }
      ],
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": "CommerceLineItemConnection",
      "kind": "LinkedField",
      "name": "lineItems",
      "plural": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "concreteType": "CommerceLineItemEdge",
          "kind": "LinkedField",
          "name": "edges",
          "plural": true,
          "selections": [
            {
              "alias": null,
              "args": null,
              "concreteType": "CommerceLineItem",
              "kind": "LinkedField",
              "name": "node",
              "plural": false,
              "selections": [
                {
                  "alias": null,
                  "args": null,
                  "concreteType": "Artwork",
                  "kind": "LinkedField",
                  "name": "artwork",
                  "plural": false,
                  "selections": [
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "shippingOrigin",
                      "storageKey": null
                    }
                  ],
                  "storageKey": null
                }
              ],
              "storageKey": null
            }
          ],
          "storageKey": null
        }
      ],
      "storageKey": null
    }
  ],
  "type": "CommerceOrder",
  "abstractKey": "__isCommerceOrder"
};

(node as any).hash = "6b6c70e787b01d75b4bf97f952905b88";

export default node;


text:
layout: post
title: Startup Weekend Brussels Was Awesome
date: 2011-04-15 13:14:00.000000000 +02:00
type: post
published: true
status: publish
categories: []
tags:
- presentation
- startupweekendbrussels
- swbru
meta:
  _original_post_id: ''
  _original_import_author: 'Ramon Suarez: Internet Entrepreneurship and Marketing'
author:
  login: ramonsuarez
  email: ramon@betacowork.com
  display_name: ramonsuarez
  first_name: Ramon
  last_name: Suarez
excerpt: N ? 2 is brewing. Targeting fall 2011 for the next Startup Weekend Brussels
  :)
---

startup weekend brussels nr 1 - it was awesome.pdf

Nº 2 is brewing. Targeting fall 2011 for the next Startup Weekend Brussels :)


text:
Given(/^There is no db\/migrate folder before a migration is generated in a single database app$/) do
  expect('../../single-db-dummy/db/migrate').not_to be_an_existing_directory
end

Then(/^I should see the db\/migrate folder in a single database app$/) do
  expect('../../single-db-dummy/db/migrate').to be_an_existing_directory
end

Then(/^I should see a migration file in the db\/migrate folder in a single database app$/) do
  expect('../../single-db-dummy/db/migrate').not_to be_empty
  expect(Dir.entries("single-db-dummy/db/migrate").last).to include "_create_fools_table.rb"
end

Given(/^There are no migration folders before a migration is generated in a multi database app$/) do
  expect('../../multi-db-dummy/db/migrate').not_to be_an_existing_directory
  expect('../../multi-db-dummy/db/users_migrate').not_to be_an_existing_directory
  expect('../../multi-db-dummy/db/widgets_migrate').not_to be_an_existing_directory
end

Then(/^I should see the db\/migrate folder for the default database$/) do
  expect('../../multi-db-dummy/db/migrate').to be_an_existing_directory
end

Then(/^I should see a migration file in the db\/migrate folder in a multi database app$/) do
  expect('../../multi-db-dummy/db/migrate').not_to be_empty
  expect(Dir.entries("multi-db-dummy/db/migrate").last).to include "_create_fools_table.rb"
end

Then(/^I should see the db\/users_migrate folder for the default database$/) do
   expect('../../multi-db-dummy/db/users_migrate').to be_an_existing_directory
end

Then(/^I should see a migration file in the db\/users_migrate folder in a multi database app$/) do
  expect('../../multi-db-dummy/db/users_migrate').not_to be_empty
  expect(Dir.entries("multi-db-dummy/db/users_migrate").last).to include "_create_fools_table.rb"
end

Then(/^I should see the db\/widgets_migrate folder for the default database$/) do
  expect('../../multi-db-dummy/db/widgets_migrate').to be_an_existing_directory
end

Then(/^I should see a migration file in the db\/widgets_migrate folder in a multi database app$/) do
  expect('../../multi-db-dummy/db/widgets_migrate').not_to be_empty
  expect(Dir.entries("multi-db-dummy/db/widgets_migrate").last).to include "_create_fools_table.rb"
end


text:
using MbDotNet.Models.Predicates;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MbDotNet.Tests.Models.Predicates
{
	[TestClass, TestCategory("Unit")]
	public class NotPredicateTests : PredicateTestBase
	{
		[TestMethod]
		public void NotPredicate_Constructor_SetsChildPredicate()
		{
			var expectedChildPredicate = new EqualsPredicate<TestPredicateFields>(new TestPredicateFields());

			var predicate = new NotPredicate(expectedChildPredicate);

			Assert.AreEqual(expectedChildPredicate, predicate.ChildPredicate);
		}
	}
}


text:
require 'resque'
require 'resque/scheduler'
module ResqueSlidingWindow
  module SchedulerPatches
    def self.extended(base)
      class << base
        alias_method :delayed_timestamp_peek_without_rescue, :delayed_timestamp_peek
        alias_method :delayed_timestamp_peek, :delayed_timestamp_peek_with_rescue
      end
    end

    def next_item_for_timestamp(timestamp)
      key = "delayed:#{timestamp.to_i}"

      item = patched_decode redis.lpop(key)

      # If the list is empty, remove it.
      clean_up_timestamp(key, timestamp)
      item
    end

    def delayed_timestamp_peek_with_rescue(timestamp, start, count)
      delayed_timestamp_peek_without_rescue timestamp, start, count
    rescue Resque::Helpers::DecodeException => e
      []
    end

    def patched_decode(payload)
      decode payload
    rescue Exception => e
    end
  end
end
Resque.extend ResqueSlidingWindow::SchedulerPatches


text:
Related posts

  {% for page in site.related_posts limit: 3 %}

{{ page.title }}

        {% include post-meta.html %}
        {{ page.excerpt | markdownify | truncatewords: 20 }}

  {% endfor %}


text:
/*
 */
#include <avr/io.h>
#include <avr/interrupt.h>
#include "LCD4.h"
#include "keypad.h"

#define ALERT_ON    1
#define ALERT_OFF   0

#define ARM_DISARM  0
#define ARM_AWAY    1
#define ARM_STAY    2
#define ARM_INSTANT 3

#define SENSOR_ARMED        1
#define SENSOR_DISARMED     0
#define SENSOR_ACTIVATED    1
#define SENSOR_DISACTIVATED 0

#define SENSOR_COUNT 3

//TODO calcualte threasholds for voltages
#define SENSOR_LOW  300
#define SENSOR_HIGH 700

struct SystemState
{
    char alert;
    char arm;
};

struct Sensor{
    char pin;
    char active;
    char armed;
};

struct SystemState state;
struct Sensor sensors[SENSOR_COUNT];

void init();
void init_timer();
void configure_state();
void poll_sensors();

void init_sensors();
unsigned int sensor_read(struct Sensor sensor);

int main(void)
{
    init();

    while(1)
    {
        configure_state();
        poll_sensors();
    }

    return 0;
}

void init()
{
    init4LCD();
    init_timer();
    init_sensors();
}

void init_timer()
{
    //TODO
}

void init_sensors()
{
    //TODO
}

void configure_state()
{
    if(state.alert == ALERT_ON)
    {
        //TODO activate siren
    }
    else
    {
        //TODO disactivate siren
    }

    switch(state.arm)
    {
    case ARM_AWAY:
        //TODO
        break;

    case ARM_STAY:
        //TODO
        break;

    case ARM_INSTANT:
        //TODO
        break;

    case ARM_DISARM:
        //TODO
        break;

    }

}

void poll_sensors()
{
    short i;
    unsigned int sensor_level;

    for(i=0;i<SENSOR_COUNT;i++){
        //TODO
        sensor_level = sensor_read(sensors[i]);
        if(sensor_level <= SENSOR_LOW || sensor_level >= SENSOR_HIGH )
            sensors[i].active = SENSOR_ACTIVATED;
        else
            sensors[i].active = SENSOR_DISACTIVATED;
    }
}

unsigned int sensor_read(struct Sensor sensor){
    unsigned int level;
    //TODO ADC from sensor pin to level;
    level = 0;

    return level;
}

//Interupts
ISR(TIMER0_OVF_vect){
    //TODO
    //Timer/Counter0 Overflow
}
ISR(TIMER0_COMP_vect){
    //TODO
    //Timer/Counter0 Compare Match
}
ISR(INT1_vect){
    //TODO recode to make it useful for the alarm program

    //static keyword: keep scoped to the function, but not re-allocated every call
    static unsigned char counter = 0;
    static unsigned char keymap[] = {'A','3','2','1','B','6','5','4','C','9','8','7','D','#','0','*'};

    unsigned char keypad;

    if(counter == 16)
    {
        goto4LCD(1,0);
    }
    else if(counter == 32)
    {
        clearLCD();
        counter = 0;
    }

    keypad = PINB & KEYPAD_DATA; //lower nibble
    send4Char(keymap[keypad]);
    counter++;
}


text:
<!DOCTYPE html>

<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/shift.css" rel="stylesheet">

<link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css">
    <link rel="stylesheet" href="login.css">

Register

Log In

Home

Catalogue

<form method = "post" action = "./login.cgi">

Please login

	Username
	<input type="username" name="inputUserName" class="form-control" placeholder="Username" required autofocus>

	Password
        <input type="password" name="inputPassword" class="form-control" placeholder="Password" required autofocus>

<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
      </form>


text:
title: Data Access in the Commons Library
slug: data-access-in-the-commons-library
aliases:
- /blog/data-access-in-the-commons-library
date: 2013-08-25
draft: false
tags:
- csharp
- dotnet
- architecture
---
The data access block in the [Commons Library]({{< ref "the-commons-library" >}}) is based on the *Unit of Work* and *Repository* patterns - or at least my take on them.

#### Unit of Work

You start with a unit-of-work factory (which is an implementation if `IUnitOfWorkFactory`) and call `Create` on it to get an instance of `IUnitOfWork` which is also `IDisposable`. So, you get a unit-of-work and do your business inside a `using` block, and call `Commit` before you leave the block. Methods in `IUnitOfWork` are all based on working with a specific entity type (which is just a POCO with an identifier field) and uses LINQ and `IQueryable` - makes it easy to use as a consumer, but also makes it easy to implement providers as most providers worth their salt already have a LINQ interface. As of the time of this writing, I've written two providers - one based on Fluent NHibernate and one based on MongoDB.

The unit-of-work factory is where the DB configuration and initialization takes place. All settings are retrieved from the commons library configuration block. You can use multiple providers and give them different names. You can then access each factory using a MEF imported instance of `IAppDataAccess` which lets you access it like a dictionary with the key being the name you used during configuration.

So, given an instance of `IAppDataAccess` called, say, `appDataAccess` and assuming you have a provider configured with the name "MyDB", a typical unit-of-work operation looks as follows:

	using (var unit = appDataAccess["MyDB"].Create())
	{
		// ... Do your thing on "unit".

		unit.Commit();
	}

#### Repositories

As far as repositories are concerned, they're light-weight wrappers around a unit-of-work tailored for a specific entity. Given an entity `Foo` with an integer identifier, you would have an `IFooRepository` that is essentially just `IRepository<Foo, int>` implemented by a `FooRepository` that is `RepositoryBase<Foo, int>`. You can, of course, extend it with other methods to implement different queries and such - but I rarely find the need, and I prefer such logic live in the services. Thus, repositories become more of a convenience than anything else - in my applications, I auto-generate all repositories using my [Modeling Kit](http://aashishkoirala.github.io/modeling/).

Technical details can be found in the Data Access section [here](http://aashishkoirala.github.io/commons/). As usual, feedback and suggestions for improvement are most welcome.


text:
.. default-domain:: py
.. currentmodule:: input_reader

The :class:`SUPPRESS` class
==============================

.. autoclass:: SUPPRESS


text:
namespace ash {

using AshColorProviderTest = AshTestBase;

// Tests the color mode in non-active user sessions.
TEST_F(AshColorProviderTest, ColorModeInNonActiveUserSessions) {
  auto* client = GetSessionControllerClient();
  auto* color_provider = AshColorProvider::Get();

  // When dark/light mode is enabled. Color mode in non-active user sessions
  // (e.g, login page) should be DARK, but LIGHT while in OOBE.
  base::test::ScopedFeatureList enable_dark_light;
  enable_dark_light.InitAndEnableFeature(chromeos::features::kDarkLightMode);
  client->SetSessionState(session_manager::SessionState::UNKNOWN);
  EXPECT_TRUE(color_provider->IsDarkModeEnabled());
  client->SetSessionState(session_manager::SessionState::OOBE);
  EXPECT_FALSE(color_provider->IsDarkModeEnabled());

  // When dark/light mode is disabled. Color mode in non-active user sessions
  // (e.g, login page) should still be DARK.
  base::test::ScopedFeatureList disable_dark_light;
  disable_dark_light.InitAndDisableFeature(chromeos::features::kDarkLightMode);
  client->SetSessionState(session_manager::SessionState::UNKNOWN);
  EXPECT_TRUE(color_provider->IsDarkModeEnabled());
  client->SetSessionState(session_manager::SessionState::OOBE);
  EXPECT_TRUE(color_provider->IsDarkModeEnabled());
}

}  // namespace ash


text:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>BMSCE LAB MANAGEMENT SYSTEM</title>
 <link rel="stylesheet" href="/bootstrap.min.css">

{{Firstname}} {{Lastname}}

DETAILS

FIRST NAME:{{Firstname}}

LAST NAME:{{Lastname}}

SEM:{{Semester}}

EMAIL:{{Email}}

PASSWORD:{{Password}}


text:
import time
from nose.tools import assert_equal, assert_not_equal
from ..connection.info import custom_setup, custom_teardown
from imcsdk.apis.server.adaptor import adaptor_properties_set, \
    adaptor_properties_get, adaptor_reset, vnic_create, vnic_delete, vnic_get, \
    vhba_create, vhba_delete, vhba_get

handle = None
ADAPTOR_ID = "1"
ADAPTOR_ID = "MLOM"
# ADAPTOR_ID = "SIOC1"

def setup_module():
    global handle
    handle = custom_setup()

def teardown_module():
    custom_teardown(handle)

def test_non_vntag_mode():
    adaptor_properties_set(handle, adaptor_slot=ADAPTOR_ID, fip_mode=True,
                                 vntag_mode=False)
    mo = adaptor_properties_get(handle, adaptor_slot=ADAPTOR_ID)
    assert_equal(mo.vntag_mode.lower(), "disabled")

def test_non_vntag_create_vnic():
    vnic_mo = vnic_create(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic-nv",
                          class_of_service=5, mac="00:11:22:33:44:56",
                          mtu=1500, pxe_boot=True, uplink_port=0)
    rcvd_mo = vnic_get(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic-nv")
    assert_not_equal(rcvd_mo, None)
    assert_equal(vnic_mo.name, rcvd_mo.name)
    assert_equal(vnic_mo.class_of_service, rcvd_mo.class_of_service)

def test_non_vntag_delete_vnic():
    vnic_delete(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic-nv")
    assert_equal(vnic_get(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic-nv"), None)

def test_vntag_mode():
    adaptor_properties_set(handle, adaptor_slot=ADAPTOR_ID, fip_mode=True,
                                 vntag_mode=True, num_vmfex_ifs=5, lldp=True)
    adaptor_reset(handle, adaptor_slot=ADAPTOR_ID)
    time.sleep(5)
    mo = adaptor_properties_get(handle, adaptor_slot=ADAPTOR_ID)
    assert_equal(mo.vntag_mode.lower(), "enabled")
    assert_equal(mo.fip_mode.lower(), "enabled")
    assert_equal(mo.lldp.lower(), "enabled")

def test_vntag_create_vnic():
    vnic_mo = vnic_create(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic",
                          channel_number=100, mac="00:11:22:33:44:55",
                          mtu=1500, pxe_boot=True, uplink_port=0)
    rcvd_mo = vnic_get(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic")
    assert_not_equal(rcvd_mo, None)
    assert_equal(vnic_mo.name, rcvd_mo.name)
    assert_equal(vnic_mo.channel_number, rcvd_mo.channel_number)

def test_vntag_delete_vnic():
    vnic_delete(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic")
    assert_equal(vnic_get(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vnic"), None)

def test_vntag_create_vhba():
    vhba_mo = vhba_create(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vhba",
                          channel_number=101, wwnn="10:00:11:3A:7D:D0:9A:43",
                          wwpn="20:00:11:3A:7D:D0:9A:43",
                          san_boot=True, uplink_port=0)
    rcvd_mo = vhba_get(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vhba")
    assert_not_equal(rcvd_mo, None)
    assert_equal(vhba_mo.name, rcvd_mo.name)
    assert_equal(vhba_mo.channel_number, rcvd_mo.channel_number)

def test_vntag_delete_vhba():
    vhba_delete(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vhba")
    assert_equal(vhba_get(handle, adaptor_slot=ADAPTOR_ID, name="sdk-test-vhba"), None)

def test_disable_vntag_mode():
    adaptor_properties_set(handle, adaptor_slot=ADAPTOR_ID, fip_mode=False,
                                 vntag_mode=False, num_vmfex_ifs=5, lldp=False)
    adaptor_reset(handle, adaptor_slot=ADAPTOR_ID)
    time.sleep(5)
    mo = adaptor_properties_get(handle, adaptor_slot=ADAPTOR_ID)
    assert_equal(mo.vntag_mode.lower(), "disabled")
    assert_equal(mo.fip_mode.lower(), "disabled")
    assert_equal(mo.lldp.lower(), "disabled")


text:
This is a [p5.js][p5js-home] sketch that allows you to type letters and numbers and see the corresponding [International Maritime Signal Flag][wikipedia-int-maritime].

## Controls

* Keyboard:
    - `SHIFT` + `P` Will save the canvas as a PNG to your computer.
    - `A` - `Z` By themselves will show the flag for that [letter][wiki-int-letters].
    - `0` - `9` By themselves will show the flag for that [number][wiki-int-numbers].
    - `SHIFT` + `0-9` Will show the NATO variant of the [number][wiki-int-numbers].
    - `CTRL` + `1-4` Will show the [Substitute flags][wiki-int-substitute], 1 -4, when you don't have enough flags of one letter.
    - `.` Will show the CODE flag, also known as the 'Answering Pennant', used to start a response to request or as a decimal point.
    - `CTRL` + Two-Char code for special flags.
        - `FL` For Flotilla.
        - `SQ` For Squadron.
        - `DI` For Division.
        - `SU` For Subdivision.
        - `PR` For Preparative.
        - `IN` For Interrogative.
        - `NE` For Negative.
        - `SC` For Screen.
        - `FO` For Formation.
        - `CO` For Corpen (Course Pennant)
        - `TU` For Turn.
        - `SB` For Starboard.
        - `PO` For Port.
        - `SP` For Speed.
        - `ST` For Station.
        - `EM` For Emergency.
        - `DE` For Designation.

# References

Multiple sources were used in determining proportions of the flags.

* Flag Shapes and Meanings:
    - Wikipedia: [International maritime signal flags][wikipedia-int-maritime]
    * [mainharbors.com][mainharbors.com] (circular dots on Pennants 1 and 2)
    * [US Navy Signal Flags][us-navy-mil] (elliptical dots on Pennants 1 and 2)

* Other:
    - Wikipedia: [Int'l Code of Signals][wikipedia-ics-multi] - Shows how combinations of flags can have specific meanings.
    - Wikipedia: [Racing Rules][wikipedia-racing] - How these flags may be used in the context of Sailing races.
    - [Semaphore Flag Signaling][au-semaphore-flags] - How other signal flags are used with a signaler holding two of the same flags in their two arms in different patterns to convey the alphabet and other signals.
    - [Special NATO flags][marinewaypoints.com] - Includes details of secondary flags used by NATO in regards to maneuvering.
    - [International Flags][reddit-int-flags] - Another visual reference.

# Links:

* [Live View][live-view]
* [Source on Github][source-code]

# Screenshots:

![screenshot][screenshot-01]

## Screen captures

Cycling through A -> Z, CODE flag, 0-9 pennants, 0-9 NATO numerical, and finally substitute flags.

![screencap][screencap-01]

[p5js-home]: http://p5js.org/
[processing-home]: http://processing/
[source-code]: https://github.com/brianhonohan/sketchbook/tree/master/p5js/nautical-flags/
[live-view]: https://brianhonohan.com/sketchbook/p5js/nautical-flags/
[screenshot-01]: ./screenshot-01.png
[screencap-01]: ./screencap-01.gif

[mainharbors.com]: http://www.maineharbors.com/flag.htm
[us-navy-mil]: https://www.navy.mil/navydata/communications/flags/flags.html
[wikipedia-int-maritime]: https://en.wikipedia.org/wiki/International_maritime_signal_flags
[wiki-int-letters]: https://en.wikipedia.org/wiki/International_maritime_signal_flags#Letter_flags_(with_ICS_meaning)
[wiki-int-numbers]: https://en.wikipedia.org/wiki/International_maritime_signal_flags#Number_flags
[wiki-int-substitute]: https://en.wikipedia.org/wiki/International_maritime_signal_flags#Substitute

[wikipedia-ics-multi]: https://en.wikipedia.org/wiki/International_Code_of_Signals#Examples_of_multiple-flag_signals
[wikipedia-racing]: https://en.wikipedia.org/wiki/Racing_Rules_of_Sailing
[au-semaphore-flags]: http://www.anbg.gov.au/flags/semaphore.html
[marinewaypoints.com]: http://www.marinewaypoints.com/learn/flags/flags.shtml
[reddit-int-flags]: https://www.reddit.com/r/vexillology/comments/4a9kpq/international_naval_flags_and_pennants/


text:
var mapPanel, printMapPanel, legendPanel;

Ext.onReady(function() {

    var bounds = new OpenLayers.Bounds(
        143.835, -43.648,
        148.479, -39.574
    );
    mapPanel = new GeoExt.MapPanel({
        region: "center",
        map: {
            maxExtent: bounds,
            maxResolution: 0.018140625,
            projection: "EPSG:4326",
            units: 'degrees'
        },
        layers: [
            new OpenLayers.Layer.WMS("Tasmania State Boundaries",
                "http://demo.opengeo.org/geoserver/wms",
                {layers: "topp:tasmania_state_boundaries"},
                {singleTile: true, numZoomLevels: 8}),
            new OpenLayers.Layer.WMS("Tasmania Water Bodies",
                "http://demo.opengeo.org/geoserver/wms",
                {layers: "topp:tasmania_water_bodies", transparent: true},
                {buffer: 0})],
        extent: bounds,
        bbar: [{
            text: "Print...",
            handler: showPrintWindow
        }]
    });

    legendPanel = new GeoExt.LegendPanel({
        width: 200,
        region: "west",
        defaults: {
            style: "padding:5px",
            baseParams: {FORMAT: "image/png"}
        }
    });
    new Ext.Panel({
        layout: "border",
        renderTo: "content",
        width: 800,
        height: 350,
        items: [mapPanel, legendPanel]
    });
});

function showPrintWindow() {
    var printWindow = new Ext.Window({
        title: "Print",
        modal: true,
        border: false,
        resizable: false,
        width: 360,
        autoHeight: true,
        items: new GeoExt.ux.PrintPreview({
            autoHeight: true,
            printMapPanel: {
                // limit scales to those that can be previewed
                limitScales: true,
                // no zooming on the map
                map: {controls: [
                    new OpenLayers.Control.Navigation({
                        zoomBoxEnabled: false,
                        zoomWheelEnabled: false
                    }),
                    new OpenLayers.Control.PanPanel()
                ]}
            },
            printProvider: {
                // using get for remote service access without same origin
                // restriction. For async requests, we would set method to "POST".
                method: "GET",
                //method: "POST",

                // capabilities from script tag in Printing.html.
                capabilities: printCapabilities,
                listeners: {
                    "print": function() {printWindow.close();}
                }
            },
            includeLegend: true,
            mapTitle: "PrintMapPanel Demo",
            sourceMap: mapPanel,
            legend: legendPanel
        })
    }).show().center();
}


text:
namespace cc {

// The SchedulerStateMachine decides how to coordinate main thread activites
// like painting/running javascript with rendering and input activities on the
// impl thread.
//
// The state machine tracks internal state but is also influenced by external state.
// Internal state includes things like whether a frame has been requested, while
// external state includes things like the current time being near to the vblank time.
//
// The scheduler seperates "what to do next" from the updating of its internal state to
// make testing cleaner.
class CC_EXPORT SchedulerStateMachine {
public:
    SchedulerStateMachine();

    enum CommitState {
        COMMIT_STATE_IDLE,
        COMMIT_STATE_FRAME_IN_PROGRESS,
        COMMIT_STATE_READY_TO_COMMIT,
        COMMIT_STATE_WAITING_FOR_FIRST_DRAW,
    };

    enum TextureState {
        LAYER_TEXTURE_STATE_UNLOCKED,
        LAYER_TEXTURE_STATE_ACQUIRED_BY_MAIN_THREAD,
        LAYER_TEXTURE_STATE_ACQUIRED_BY_IMPL_THREAD,
    };

    enum ContextState {
        CONTEXT_ACTIVE,
        CONTEXT_LOST,
        CONTEXT_RECREATING,
    };

    bool commitPending() const
    {
        return m_commitState != COMMIT_STATE_IDLE;
    }

    bool redrawPending() const { return m_needsRedraw; }

    enum Action {
        ACTION_NONE,
        ACTION_BEGIN_FRAME,
        ACTION_COMMIT,
        ACTION_DRAW_IF_POSSIBLE,
        ACTION_DRAW_FORCED,
        ACTION_BEGIN_CONTEXT_RECREATION,
        ACTION_ACQUIRE_LAYER_TEXTURES_FOR_MAIN_THREAD,
    };
    Action nextAction() const;
    void updateState(Action);

    // Indicates whether the scheduler needs a vsync callback in order to make
    // progress.
    bool vsyncCallbackNeeded() const;

    // Indicates that the system has entered and left a vsync callback.
    // The scheduler will not draw more than once in a given vsync callback.
    void didEnterVSync();
    void didLeaveVSync();

    // Indicates whether the LayerTreeHostImpl is visible.
    void setVisible(bool);

    // Indicates that a redraw is required, either due to the impl tree changing
    // or the screen being damaged and simply needing redisplay.
    void setNeedsRedraw();

    // As setNeedsRedraw(), but ensures the draw will definitely happen even if
    // we are not visible.
    void setNeedsForcedRedraw();

    // Indicates whether ACTION_DRAW_IF_POSSIBLE drew to the screen or not.
    void didDrawIfPossibleCompleted(bool success);

    // Indicates that a new commit flow needs to be performed, either to pull
    // updates from the main thread to the impl, or to push deltas from the impl
    // thread to main.
    void setNeedsCommit();

    // As setNeedsCommit(), but ensures the beginFrame will definitely happen even if
    // we are not visible.
    // After this call we expect to go through the forced commit flow and then return
    // to waiting for a non-forced beginFrame to finish.
    void setNeedsForcedCommit();

    // Call this only in response to receiving an ACTION_BEGIN_FRAME
    // from nextState. Indicates that all painting is complete.
    void beginFrameComplete();

    // Call this only in response to receiving an ACTION_BEGIN_FRAME
    // from nextState if the client rejects the beginFrame message.
    void beginFrameAborted();

    // Request exclusive access to the textures that back single buffered
    // layers on behalf of the main thread. Upon acqusition,
    // ACTION_DRAW_IF_POSSIBLE will not draw until the main thread releases the
    // textures to the impl thread by committing the layers.
    void setMainThreadNeedsLayerTextures();

    // Indicates whether we can successfully begin a frame at this time.
    void setCanBeginFrame(bool can) { m_canBeginFrame = can; }

    // Indicates whether drawing would, at this time, make sense.
    // canDraw can be used to supress flashes or checkerboarding
    // when such behavior would be undesirable.
    void setCanDraw(bool can) { m_canDraw = can; }

    void didLoseContext();
    void didRecreateContext();

    // Exposed for testing purposes.
    void setMaximumNumberOfFailedDrawsBeforeDrawIsForced(int);

    std::string toString();

protected:
    bool shouldDrawForced() const;
    bool drawSuspendedUntilCommit() const;
    bool scheduledToDraw() const;
    bool shouldDraw() const;
    bool shouldAcquireLayerTexturesForMainThread() const;
    bool hasDrawnThisFrame() const;

    CommitState m_commitState;

    int m_currentFrameNumber;
    int m_lastFrameNumberWhereDrawWasCalled;
    int m_consecutiveFailedDraws;
    int m_maximumNumberOfFailedDrawsBeforeDrawIsForced;
    bool m_needsRedraw;
    bool m_needsForcedRedraw;
    bool m_needsForcedRedrawAfterNextCommit;
    bool m_needsCommit;
    bool m_needsForcedCommit;
    bool m_expectImmediateBeginFrame;
    bool m_mainThreadNeedsLayerTextures;
    bool m_insideVSync;
    bool m_visible;
    bool m_canBeginFrame;
    bool m_canDraw;
    bool m_drawIfPossibleFailed;
    TextureState m_textureState;
    ContextState m_contextState;

    DISALLOW_COPY_AND_ASSIGN(SchedulerStateMachine);
};

}

#endif  // CC_SCHEDULER_STATE_MACHINE_H_


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "s_variants".
 *
 * @property string $id
 * @property integer $product_id
 * @property string $sku
 * @property string $name
 * @property double $price
 * @property double $compare_price
 * @property integer $stock
 * @property integer $position
 * @property string $attachment
 * @property string $external_id
 */
class Variants extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 's_variants';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'sku', 'name', 'price', 'position', 'attachment', 'external_id'], 'required'],
            [['product_id', 'stock', 'position'], 'integer'],
            [['price', 'compare_price'], 'number'],
            [['sku', 'name', 'attachment'], 'string', 'max' => 255],
            [['external_id'], 'string', 'max' => 36],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'product_id' => 'Product ID',
            'sku' => 'Sku',
            'name' => 'Name',
            'price' => 'Price',
            'compare_price' => 'Compare Price',
            'stock' => 'Stock',
            'position' => 'Position',
            'attachment' => 'Attachment',
            'external_id' => 'External ID',
        ];
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="me.kevingleason.pubrtc.IncomingCallActivity"
    android:orientation="vertical"
    android:background="@color/Blue">

    <TextView
        android:text="@string/incoming_call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="26sp"
        android:textColor="@color/White"
        android:layout_margin="25dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/ic_pubrtc" />

    <TextView
        android:id="@+id/caller_id"
        android:text="@string/incoming_call_from"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="26sp"
        android:textColor="@color/White"
        android:layout_margin="25dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="60dp">

        <ImageButton
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/Green"
            android:onClick="acceptCall"
            android:src="@drawable/ic_action_call" />

        <ImageButton
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:background="@color/Red2"
            android:layout_weight="1"
            android:onClick="rejectCall"
            android:src="@drawable/ic_action_end_call" />

    </LinearLayout>

</LinearLayout>


text:
"""Test the Resource manager.

"""
import pytest
from pyvisa.rname import ResourceName
from pyvisa.testsuite.keysight_assisted_tests import (
    RESOURCE_ADDRESSES,
    copy_func,
    require_virtual_instr,
)
from pyvisa.testsuite.keysight_assisted_tests.test_resource_manager import (
    TestResourceManager as BaseTestResourceManager,
    TestResourceParsing as BaseTestResourceParsing,
)

@require_virtual_instr
class TestPyResourceManager(BaseTestResourceManager):
    """ """

    def test_list_resource(self):
        """Test listing the available resources.
        The bot supports only TCPIP and of those resources we expect to be able
        to list only INSTR resources not SOCKET.
        """
        # Default settings
        resources = self.rm.list_resources()
        for v in (v for v in RESOURCE_ADDRESSES.values() if v.endswith("INSTR")):
            assert str(ResourceName.from_string(v)) in resources

    test_last_status = pytest.mark.xfail(
        copy_func(BaseTestResourceManager.test_last_status)
    )

    test_opening_resource_with_lock = pytest.mark.xfail(
        copy_func(BaseTestResourceManager.test_opening_resource_with_lock)
    )

@require_virtual_instr
class TestPyResourceParsing(BaseTestResourceParsing):
    """ """

    pass


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [DOMDebugger](./puppeteer.protocol.domdebugger.md) > [EventListener](./puppeteer.protocol.domdebugger.eventlistener.md) > [originalHandler](./puppeteer.protocol.domdebugger.eventlistener.originalhandler.md)

## Protocol.DOMDebugger.EventListener.originalHandler property

Event original handler function value.

<b>Signature:</b>

```typescript
originalHandler?: Runtime.RemoteObject;
```