<commit_before>/* ------------- Imports -------------- */
import React, { Component } from 'react';

/* ------------- Form  Library Imports -------------- */
import {
  Form,
  Text
} from '../src/index';

/* ---------------- Other Imports ------------------ */

import Data from './Data';
import Code from './Code';

/* ------------------ Form Stuff --------------------*/

const FormWithArraysCode = () => {

  const code = `
  import { Form, Text } from 'react-form';

  class FormWithArrays extends Component {

    constructor( props ) {
      super( props );
      this.state = {};
    }

    render() {
      return (

          <Form
            onSubmit={submittedValues => this.setState( { submittedValues } )}>
            { formApi => (
              <form onSubmit={formApi.submitForm} id="form3">
                First name
                <Text field="firstName" id="firstName2" />
                Friend1
                <Text field={['friends', 0]} id="friend1" />
                Friend2
                <Text field={['friends', 1]} id="friend2" />
                Friend3
                <Text field={['friends', 2]} id="friend3" />
                <button type="submit" className="mb-4 btn btn-primary">Submit</button>
              </form>
            )}
          </Form>

      );
    }
  }
`;

  return (

Source Code:

        {code}

  );
};

class FormWithArrays extends Component {

  constructor( props ) {
    super( props );
    this.state = {};
  }

  render() {

    return (

Form With Array

          Fields can also be assotiated with an array. Here is an example
          where you can input three friends.

        <Form
          defaultValues={{ numberField: 0 }}
          onSubmit={submittedValues => this.setState( { submittedValues } )}>
          { formApi => (

              <form onSubmit={formApi.submitForm} id="form3">
                First name
                <Text field="firstName" id="firstName2" />
                Friend1
                <Text field={['friends', 0]} id="friend1" />
                Friend2
                <Text field={['friends', 1]} id="friend2" />
                Friend3
                <Text field={['friends', 2]} id="friend3" />
                Number field
                <Text field="numberField" id="numberField" type="number" />
                <button type="submit" className="mb-4 btn btn-primary">Submit</button>
              </form>

              <Data title="Values" reference="formApi.values" data={formApi.values} />
              <Data title="Touched" reference="formApi.touched" data={formApi.touched} />
              <Data title="Submission attempts" reference="formApi.submits" data={formApi.submits} />
              <Data title="Submitted" reference="formApi.submitted" data={formApi.submitted} />
              <Data title="Submitted values" reference="onSubmit={submittedValues => this.setState( { submittedValues } )}" data={this.state.submittedValues} />

          )}
        </Form>

        <FormWithArraysCode />

    );
  }
}

export default FormWithArrays;
<commit_msg>Remove example code<commit_after>/* ------------- Imports -------------- */
import React, { Component } from 'react';

/* ------------- Form  Library Imports -------------- */
import {
  Form,
  Text
} from '../src/index';

/* ---------------- Other Imports ------------------ */

import Data from './Data';
import Code from './Code';

/* ------------------ Form Stuff --------------------*/

const FormWithArraysCode = () => {

  const code = `
  import { Form, Text } from 'react-form';

  class FormWithArrays extends Component {

    constructor( props ) {
      super( props );
      this.state = {};
    }

    render() {
      return (

          <Form
            onSubmit={submittedValues => this.setState( { submittedValues } )}>
            { formApi => (
              <form onSubmit={formApi.submitForm} id="form3">
                First name
                <Text field="firstName" id="firstName2" />
                Friend1
                <Text field={['friends', 0]} id="friend1" />
                Friend2
                <Text field={['friends', 1]} id="friend2" />
                Friend3
                <Text field={['friends', 2]} id="friend3" />
                <button type="submit" className="mb-4 btn btn-primary">Submit</button>
              </form>
            )}
          </Form>

      );
    }
  }
`;

  return (

Source Code:

        {code}

  );
};

class FormWithArrays extends Component {

  constructor( props ) {
    super( props );
    this.state = {};
  }

  render() {

    return (

Form With Array

          Fields can also be assotiated with an array. Here is an example
          where you can input three friends.

        <Form
          onSubmit={submittedValues => this.setState( { submittedValues } )}>
          { formApi => (

              <form onSubmit={formApi.submitForm} id="form3">
                First name
                <Text field="firstName" id="firstName2" />
                Friend1
                <Text field={['friends', 0]} id="friend1" />
                Friend2
                <Text field={['friends', 1]} id="friend2" />
                Friend3
                <Text field={['friends', 2]} id="friend3" />
                <button type="submit" className="mb-4 btn btn-primary">Submit</button>
              </form>

              <Data title="Values" reference="formApi.values" data={formApi.values} />
              <Data title="Touched" reference="formApi.touched" data={formApi.touched} />
              <Data title="Submission attempts" reference="formApi.submits" data={formApi.submits} />
              <Data title="Submitted" reference="formApi.submitted" data={formApi.submitted} />
              <Data title="Submitted values" reference="onSubmit={submittedValues => this.setState( { submittedValues } )}" data={this.state.submittedValues} />

          )}
        </Form>

        <FormWithArraysCode />

    );
  }
}

export default FormWithArrays;
<|endoftext|>


<commit_before>'use strict';

const SG = require('ml-savitzky-golay-generalized');

const defaultOptions = {
  sgOptions: {
    windowSize: 9,
    polynomial: 3
  },
  minMaxRatio: 0.00025,
  broadRatio: 0.00,
  maxCriteria: true,
  smoothY: true,
  realTopDetection: false,
  heightFactor: 0,
  boundaries: false,
  derivativeThreshold: -1
};

/**
 * Global spectra deconvolution
 * @param {Array<number>} x - Independent variable
 * @param {Array<number>} yIn - Dependent variable
 * @param {object} [options] - Options object
 * @param {object} [options.sgOptions] - Options object for Savitzky-Golay filter. See https://github.com/mljs/savitzky-golay-generalized#options
 * @param {number} [options.sgOptions.windowSize = 9] - points to use in the approximations
 * @param {number} [options.sgOptions.polynomial = 3] - degree of the polynomial to use in the approximations
 * @param {number} [options.minMaxRatio = 0.00025] - Threshold to determine if a given peak should be considered as a noise
 * @param {number} [options.broadRatio = 0.00] - If `broadRatio` is higher than 0, then all the peaks which second derivative
 * smaller than `broadRatio * maxAbsSecondDerivative` will be marked with the soft mask equal to true.
 * @param {number} [options.noiseLevel = 0] - Noise threshold in spectrum units
 * @param {boolean} [options.maxCriteria = true] - Peaks are local maximum(true) or minimum(false)
 * @param {boolean} [options.smoothY = true] - Select the peak intensities from a smoothed version of the independent variables
 * @param {boolean} [options.realTopDetection = false] - Use a quadratic optimizations with the peak and its 3 closest neighbors
 * to determine the true x,y values of the peak?
 * @param {number} [options.heightFactor = 0] - Factor to multiply the calculated height (usually 2)
 * @param {boolean} [options.boundaries = false] - Return also the inflection points of the peaks
 * @param {number} [options.derivativeThreshold = -1] - Filters based on the amplitude of the first derivative
 * @return {Array<object>}
 */
function gsd(x, yIn, options) {
  options = Object.assign({}, defaultOptions, options);
  let sgOptions = options.sgOptions;
  const y = [].concat(yIn);

  if (!('noiseLevel' in options)) {
    // We have to know if x is equally spaced
    var maxDx = 0;

    var minDx = Number.MAX_VALUE;

    var tmp;
    for (let i = 0; i < x.length - 1; ++i) {
      tmp = Math.abs(x[i + 1] - x[i]);
      if (tmp < minDx) {
        minDx = tmp;
      }
      if (tmp > maxDx) {
        maxDx = tmp;
      }
    }

    if ((maxDx - minDx) / maxDx < 0.05) {
      options.noiseLevel = getNoiseLevel(y);
    } else {
      options.noiseLevel = 0;
    }
  }
  const yCorrection = { m: 1, b: options.noiseLevel };
  if (!options.maxCriteria) {
    yCorrection.m = -1;
    yCorrection.b *= -1;
  }

  for (let i = 0; i < y.length; i++) {
    y[i] = yCorrection.m * y[i] - yCorrection.b;
  }

  for (let i = 0; i < y.length; i++) {
    if (y[i] < 0) {
      y[i] = 0;
    }
  }
  // If the max difference between delta x is less than 5%, then, we can assume it to be equally spaced variable
  let Y = y;
  let dY, ddY;
  if ((maxDx - minDx) / maxDx < 0.05) {
    if (options.smoothY) {
      Y = SG(y, x[1] - x[0], { windowSize: sgOptions.windowSize, polynomial: sgOptions.polynomial, derivative: 0 });
    }
    dY = SG(y, x[1] - x[0], { windowSize: sgOptions.windowSize, polynomial: sgOptions.polynomial, derivative: 1 });
    ddY = SG(y, x[1] - x[0], { windowSize: sgOptions.windowSize, polynomial: sgOptions.polynomial, derivative: 2 });
  } else {
    if (options.smoothY) {
      Y = SG(y, x, { windowSize: sgOptions.windowSize, polynomial: sgOptions.polynomial, derivative: 0 });
    }
    dY = SG(y, x, { windowSize: sgOptions.windowSize, polynomial: sgOptions.polynomial, derivative: 1 });
    ddY = SG(y, x, { windowSize: sgOptions.windowSize, polynomial: sgOptions.polynomial, derivative: 2 });
  }

  const X = x;
  const dx = x[1] - x[0];
  var maxDdy = 0;
  var maxY = 0;
  for (let i = 0; i < Y.length; i++) {
    if (Math.abs(ddY[i]) > maxDdy) {
      maxDdy = Math.abs(ddY[i]);
    }
    if (Math.abs(Y[i]) > maxY) {
      maxY = Math.abs(Y[i]);
    }
  }

  var lastMax = null;
  var lastMin = null;
  var minddY = new Array(Y.length - 2);
  var intervalL = new Array(Y.length);
  var intervalR = new Array(Y.length);
  var broadMask = new Array(Y.length - 2);
  var minddYLen = 0;
  var intervalLLen = 0;
  var intervalRLen = 0;
  var broadMaskLen = 0;
  // By the intermediate value theorem We cannot find 2 consecutive maximum or minimum
  for (let i = 1; i < Y.length - 1; ++i) {
    // filter based on derivativeThreshold
    if (Math.abs(dY[i]) > options.derivativeThreshold) {
      // Minimum in first derivative
      if ((dY[i] < dY[i - 1]) && (dY[i] <= dY[i + 1]) ||
                (dY[i] <= dY[i - 1]) && (dY[i] < dY[i + 1])) {
        lastMin = {
          x: X[i],
          index: i
        };
        if (dx > 0 && lastMax !== null) {
          intervalL[intervalLLen++] = lastMax;
          intervalR[intervalRLen++] = lastMin;
        }
      }

      // Maximum in first derivative
      if ((dY[i] >= dY[i - 1]) && (dY[i] > dY[i + 1]) ||
                (dY[i] > dY[i - 1]) && (dY[i] >= dY[i + 1])) {
        lastMax = {
          x: X[i],
          index: i
        };
        if (dx < 0 && lastMin !== null) {
          intervalL[intervalLLen++] = lastMax;
          intervalR[intervalRLen++] = lastMin;
        }
      }
    }

    // Minimum in second derivative
    if ((ddY[i] < ddY[i - 1]) && (ddY[i] < ddY[i + 1])) {
      // TODO should we change this to have 3 arrays ? Huge overhead creating arrays
      minddY[minddYLen++] = i; // ( [X[i], Y[i], i] );
      broadMask[broadMaskLen++] = Math.abs(ddY[i]) <= options.broadRatio * maxDdy;
    }
  }
  minddY.length = minddYLen;
  intervalL.length = intervalLLen;
  intervalR.length = intervalRLen;
  broadMask.length = broadMaskLen;

  let signals = new Array(minddY.length);
  let signalsLen = 0;
  let lastK = -1;
  let possible, frequency, distanceJ, minDistance, gettingCloser;
  for (let j = 0; j < minddY.length; ++j) {
    frequency = X[minddY[j]];
    possible = -1;
    let k = lastK + 1;
    minDistance = Number.MAX_VALUE;
    distanceJ = 0;
    gettingCloser = true;
    while (possible === -1 && (k < intervalL.length) && gettingCloser) {
      distanceJ = Math.abs(frequency - (intervalL[k].x + intervalR[k].x) / 2);

      // Still getting closer?
      if (distanceJ < minDistance) {
        minDistance = distanceJ;
      } else {
        gettingCloser = false;
      }
      if (distanceJ < Math.abs(intervalL[k].x - intervalR[k].x) / 2) {
        possible = k;
        lastK = k;
      }
      ++k;
    }

    if (possible !== -1) {
      if (Math.abs(Y[minddY[j]]) > options.minMaxRatio * maxY) {
        signals[signalsLen++] = {
          index: minddY[j],
          x: frequency,
          y: (Y[minddY[j]] + yCorrection.b) / yCorrection.m,
          width: Math.abs(intervalR[possible].x - intervalL[possible].x), // widthCorrection
          soft: broadMask[j]
        };
        if (options.boundaries) {
          signals[signalsLen - 1].left = intervalL[possible];
          signals[signalsLen - 1].right = intervalR[possible];
        }
        if (options.heightFactor) {
          let yLeft = Y[intervalL[possible].index];
          let yRight = Y[intervalR[possible].index];
          signals[signalsLen - 1].height = options.heightFactor * (signals[signalsLen - 1].y - ((yLeft + yRight) / 2));
        }
      }
    }
  }
  signals.length = signalsLen;

  if (options.realTopDetection) {
    realTopDetection(signals, X, Y);
  }

  // Correct the values to fit the original spectra data
  for (let j = 0; j < signals.length; j++) {
    signals[j].base = options.noiseLevel;
  }

  signals.sort(function (a, b) {
    return a.x - b.x;
  });

  return signals;
}

function getNoiseLevel(y) {
  var mean = 0;

  var stddev = 0;
  var length = y.length;
  for (let i = 0; i < length; ++i) {
    mean += y[i];
  }
  mean /= length;
  var averageDeviations = new Array(length);
  for (let i = 0; i < length; ++i) {
    averageDeviations[i] = Math.abs(y[i] - mean);
  }
  averageDeviations.sort();
  if (length % 2 === 1) {
    stddev = averageDeviations[(length - 1) / 2] / 0.6745;
  } else {
    stddev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;
  }

  return stddev;
}

function realTopDetection(peakList, x, y) {
  var alpha, beta, gamma, p, currentPoint;
  for (var j = 0; j < peakList.length; j++) {
    currentPoint = peakList[j].i;// peakList[j][2];
    // The detected peak could be moved 1 or 2 unit to left or right.
    if (y[currentPoint - 1] >= y[currentPoint - 2]
            && y[currentPoint - 1] >= y[currentPoint]) {
      currentPoint--;
    } else {
      if (y[currentPoint + 1] >= y[currentPoint]
                && y[currentPoint + 1] >= y[currentPoint + 2]) {
        currentPoint++;
      } else {
        if (y[currentPoint - 2] >= y[currentPoint - 3]
                    && y[currentPoint - 2] >= y[currentPoint - 1]) {
          currentPoint -= 2;
        } else {
          if (y[currentPoint + 2] >= y[currentPoint + 1]
                        && y[currentPoint + 2] >= y[currentPoint + 3]) {
            currentPoint += 2;
          }
        }
      }
    }
    // interpolation to a sin() function
    if (y[currentPoint - 1] > 0 && y[currentPoint + 1] > 0
            && y[currentPoint] >= y[currentPoint - 1]
            && y[currentPoint] >= y[currentPoint + 1]) {
      alpha = 20 * Math.log10(y[currentPoint - 1]);
      beta = 20 * Math.log10(y[currentPoint]);
      gamma = 20 * Math.log10(y[currentPoint + 1]);
      p = 0.5 * (alpha - gamma) / (alpha - 2 * beta + gamma);
      // console.log("p: "+p);
      // console.log(x[currentPoint]+" "+tmp+" "+currentPoint);
      peakList[j].x = x[currentPoint] + (x[currentPoint] - x[currentPoint - 1]) * p;
      peakList[j].y = y[currentPoint] - 0.25 * (y[currentPoint - 1] - y[currentPoint + 1]) * p;
    }
  }
}

module.exports = gsd;
<commit_msg>fix realtop detection<commit_after>'use strict';

const SG = require('ml-savitzky-golay-generalized');

const defaultOptions = {
  sgOptions: {
    windowSize: 9,
    polynomial: 3
  },
  minMaxRatio: 0.00025,
  broadRatio: 0.0,
  maxCriteria: true,
  smoothY: true,
  realTopDetection: false,
  heightFactor: 0,
  boundaries: false,
  derivativeThreshold: -1
};

/**
 * Global spectra deconvolution
 * @param {Array<number>} x - Independent variable
 * @param {Array<number>} yIn - Dependent variable
 * @param {object} [options] - Options object
 * @param {object} [options.sgOptions] - Options object for Savitzky-Golay filter. See https://github.com/mljs/savitzky-golay-generalized#options
 * @param {number} [options.sgOptions.windowSize = 9] - points to use in the approximations
 * @param {number} [options.sgOptions.polynomial = 3] - degree of the polynomial to use in the approximations
 * @param {number} [options.minMaxRatio = 0.00025] - Threshold to determine if a given peak should be considered as a noise
 * @param {number} [options.broadRatio = 0.00] - If `broadRatio` is higher than 0, then all the peaks which second derivative
 * smaller than `broadRatio * maxAbsSecondDerivative` will be marked with the soft mask equal to true.
 * @param {number} [options.noiseLevel = 0] - Noise threshold in spectrum units
 * @param {boolean} [options.maxCriteria = true] - Peaks are local maximum(true) or minimum(false)
 * @param {boolean} [options.smoothY = true] - Select the peak intensities from a smoothed version of the independent variables
 * @param {boolean} [options.realTopDetection = false] - Use a quadratic optimizations with the peak and its 3 closest neighbors
 * to determine the true x,y values of the peak?
 * @param {number} [options.heightFactor = 0] - Factor to multiply the calculated height (usually 2)
 * @param {boolean} [options.boundaries = false] - Return also the inflection points of the peaks
 * @param {number} [options.derivativeThreshold = -1] - Filters based on the amplitude of the first derivative
 * @return {Array<object>}
 */
function gsd(x, yIn, options) {
  options = Object.assign({}, defaultOptions, options);
  let sgOptions = options.sgOptions;
  const y = [].concat(yIn);

  if (!('noiseLevel' in options)) {
    // We have to know if x is equally spaced
    var maxDx = 0;

    var minDx = Number.MAX_VALUE;

    var tmp;
    for (let i = 0; i < x.length - 1; ++i) {
      tmp = Math.abs(x[i + 1] - x[i]);
      if (tmp < minDx) {
        minDx = tmp;
      }
      if (tmp > maxDx) {
        maxDx = tmp;
      }
    }

    if ((maxDx - minDx) / maxDx < 0.05) {
      options.noiseLevel = getNoiseLevel(y);
    } else {
      options.noiseLevel = 0;
    }
  }
  const yCorrection = { m: 1, b: options.noiseLevel };
  if (!options.maxCriteria) {
    yCorrection.m = -1;
    yCorrection.b *= -1;
  }

  for (let i = 0; i < y.length; i++) {
    y[i] = yCorrection.m * y[i] - yCorrection.b;
  }

  for (let i = 0; i < y.length; i++) {
    if (y[i] < 0) {
      y[i] = 0;
    }
  }
  // If the max difference between delta x is less than 5%, then, we can assume it to be equally spaced variable
  let Y = y;
  let dY, ddY;
  if ((maxDx - minDx) / maxDx < 0.05) {
    if (options.smoothY) {
      Y = SG(y, x[1] - x[0], {
        windowSize: sgOptions.windowSize,
        polynomial: sgOptions.polynomial,
        derivative: 0
      });
    }
    dY = SG(y, x[1] - x[0], {
      windowSize: sgOptions.windowSize,
      polynomial: sgOptions.polynomial,
      derivative: 1
    });
    ddY = SG(y, x[1] - x[0], {
      windowSize: sgOptions.windowSize,
      polynomial: sgOptions.polynomial,
      derivative: 2
    });
  } else {
    if (options.smoothY) {
      Y = SG(y, x, {
        windowSize: sgOptions.windowSize,
        polynomial: sgOptions.polynomial,
        derivative: 0
      });
    }
    dY = SG(y, x, {
      windowSize: sgOptions.windowSize,
      polynomial: sgOptions.polynomial,
      derivative: 1
    });
    ddY = SG(y, x, {
      windowSize: sgOptions.windowSize,
      polynomial: sgOptions.polynomial,
      derivative: 2
    });
  }

  const X = x;
  const dx = x[1] - x[0];
  var maxDdy = 0;
  var maxY = 0;
  for (let i = 0; i < Y.length; i++) {
    if (Math.abs(ddY[i]) > maxDdy) {
      maxDdy = Math.abs(ddY[i]);
    }
    if (Math.abs(Y[i]) > maxY) {
      maxY = Math.abs(Y[i]);
    }
  }

  var lastMax = null;
  var lastMin = null;
  var minddY = new Array(Y.length - 2);
  var intervalL = new Array(Y.length);
  var intervalR = new Array(Y.length);
  var broadMask = new Array(Y.length - 2);
  var minddYLen = 0;
  var intervalLLen = 0;
  var intervalRLen = 0;
  var broadMaskLen = 0;
  // By the intermediate value theorem We cannot find 2 consecutive maximum or minimum
  for (let i = 1; i < Y.length - 1; ++i) {
    // filter based on derivativeThreshold
    if (Math.abs(dY[i]) > options.derivativeThreshold) {
      // Minimum in first derivative
      if (
        (dY[i] < dY[i - 1] && dY[i] <= dY[i + 1]) ||
        (dY[i] <= dY[i - 1] && dY[i] < dY[i + 1])
      ) {
        lastMin = {
          x: X[i],
          index: i
        };
        if (dx > 0 && lastMax !== null) {
          intervalL[intervalLLen++] = lastMax;
          intervalR[intervalRLen++] = lastMin;
        }
      }

      // Maximum in first derivative
      if (
        (dY[i] >= dY[i - 1] && dY[i] > dY[i + 1]) ||
        (dY[i] > dY[i - 1] && dY[i] >= dY[i + 1])
      ) {
        lastMax = {
          x: X[i],
          index: i
        };
        if (dx < 0 && lastMin !== null) {
          intervalL[intervalLLen++] = lastMax;
          intervalR[intervalRLen++] = lastMin;
        }
      }
    }

    // Minimum in second derivative
    if (ddY[i] < ddY[i - 1] && ddY[i] < ddY[i + 1]) {
      // TODO should we change this to have 3 arrays ? Huge overhead creating arrays
      minddY[minddYLen++] = i; // ( [X[i], Y[i], i] );
      broadMask[broadMaskLen++] =
        Math.abs(ddY[i]) <= options.broadRatio * maxDdy;
    }
  }
  minddY.length = minddYLen;
  intervalL.length = intervalLLen;
  intervalR.length = intervalRLen;
  broadMask.length = broadMaskLen;

  let signals = new Array(minddY.length);
  let signalsLen = 0;
  let lastK = -1;
  let possible, frequency, distanceJ, minDistance, gettingCloser;
  for (let j = 0; j < minddY.length; ++j) {
    frequency = X[minddY[j]];
    possible = -1;
    let k = lastK + 1;
    minDistance = Number.MAX_VALUE;
    distanceJ = 0;
    gettingCloser = true;
    while (possible === -1 && k < intervalL.length && gettingCloser) {
      distanceJ = Math.abs(frequency - (intervalL[k].x + intervalR[k].x) / 2);

      // Still getting closer?
      if (distanceJ < minDistance) {
        minDistance = distanceJ;
      } else {
        gettingCloser = false;
      }
      if (distanceJ < Math.abs(intervalL[k].x - intervalR[k].x) / 2) {
        possible = k;
        lastK = k;
      }
      ++k;
    }

    if (possible !== -1) {
      if (Math.abs(Y[minddY[j]]) > options.minMaxRatio * maxY) {
        signals[signalsLen++] = {
          index: minddY[j],
          x: frequency,
          y: (Y[minddY[j]] + yCorrection.b) / yCorrection.m,
          width: Math.abs(intervalR[possible].x - intervalL[possible].x), // widthCorrection
          soft: broadMask[j]
        };
        if (options.boundaries) {
          signals[signalsLen - 1].left = intervalL[possible];
          signals[signalsLen - 1].right = intervalR[possible];
        }
        if (options.heightFactor) {
          let yLeft = Y[intervalL[possible].index];
          let yRight = Y[intervalR[possible].index];
          signals[signalsLen - 1].height =
            options.heightFactor *
            (signals[signalsLen - 1].y - (yLeft + yRight) / 2);
        }
      }
    }
  }
  signals.length = signalsLen;

  if (options.realTopDetection) {
    realTopDetection(signals, X, Y);
  }

  // Correct the values to fit the original spectra data
  for (let j = 0; j < signals.length; j++) {
    signals[j].base = options.noiseLevel;
  }

  signals.sort(function (a, b) {
    return a.x - b.x;
  });

  return signals;
}

function getNoiseLevel(y) {
  var mean = 0;

  var stddev = 0;
  var length = y.length;
  for (let i = 0; i < length; ++i) {
    mean += y[i];
  }
  mean /= length;
  var averageDeviations = new Array(length);
  for (let i = 0; i < length; ++i) {
    averageDeviations[i] = Math.abs(y[i] - mean);
  }
  averageDeviations.sort();
  if (length % 2 === 1) {
    stddev = averageDeviations[(length - 1) / 2] / 0.6745;
  } else {
    stddev =
      (0.5 *
        (averageDeviations[length / 2] + averageDeviations[length / 2 - 1])) /
      0.6745;
  }

  return stddev;
}

function realTopDetection(peakList, x, y) {
  var alpha, beta, gamma, p, currentPoint;
  for (var j = 0; j < peakList.length; j++) {
    currentPoint = peakList[j].index; // peakList[j][2];
    // The detected peak could be moved 1 or 2 unit to left or right.
    if (
      y[currentPoint - 1] >= y[currentPoint - 2] &&
      y[currentPoint - 1] >= y[currentPoint]
    ) {
      currentPoint--;
    } else {
      if (
        y[currentPoint + 1] >= y[currentPoint] &&
        y[currentPoint + 1] >= y[currentPoint + 2]
      ) {
        currentPoint++;
      } else {
        if (
          y[currentPoint - 2] >= y[currentPoint - 3] &&
          y[currentPoint - 2] >= y[currentPoint - 1]
        ) {
          currentPoint -= 2;
        } else {
          if (
            y[currentPoint + 2] >= y[currentPoint + 1] &&
            y[currentPoint + 2] >= y[currentPoint + 3]
          ) {
            currentPoint += 2;
          }
        }
      }
    }
    // interpolation to a sin() function
    if (
      y[currentPoint - 1] > 0 &&
      y[currentPoint + 1] > 0 &&
      y[currentPoint] >= y[currentPoint - 1] &&
      y[currentPoint] >= y[currentPoint + 1]
    ) {
      alpha = 20 * Math.log10(y[currentPoint - 1]);
      beta = 20 * Math.log10(y[currentPoint]);
      gamma = 20 * Math.log10(y[currentPoint + 1]);
      p = (0.5 * (alpha - gamma)) / (alpha - 2 * beta + gamma);
      // console.log(alpha, beta, gamma, `p: ${p}`);
      // console.log(x[currentPoint]+" "+tmp+" "+currentPoint);
      peakList[j].x =
        x[currentPoint] + (x[currentPoint] - x[currentPoint - 1]) * p;
      peakList[j].y =
        y[currentPoint] -
        0.25 * (y[currentPoint - 1] - y[currentPoint + 1]) * p;
    }
  }
}

module.exports = gsd;
<|endoftext|>


<commit_before>const EventEmitter = require('events'),
  blessed = require('blessed'),
  timestamp = require('./util/timestamp');

class GUI extends EventEmitter {
  constructor(screen) {
    super();
    this.screen = screen;
    this.chatbox = blessed.box({
      label: 'Retrocord Light',
      width: '100%',
      height: '100%-1',
      border: { type: 'line' },
    });

    this.consolebox = blessed.log({
      parent: this.chatbox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true,
    });

    this.inputbox = blessed.textbox({
      bottom: 0,
      width: '100%',
      height: 1,
      inputOnFocus: true,
    });

    this.awaitingResponse = false;
  }

  init() {
    this.inputbox.key('enter', () => {
      if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue());
      else this.emit('input', this.inputbox.getValue());
      this.inputbox.clearValue();
      this.inputbox.focus();
      this.screen.render();
    });

    this.screen.append(this.chatbox);
    this.screen.append(this.inputbox);
    this.screen.render();

    this.inputbox.focus();
  }
  put(text) {
    this.consolebox.log(text);
  }
  putMessages(messages) {
    const me = this;
    messages.forEach(m => {
      const ts = timestamp(m.createdAt),
        arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}↩{/bold}{/green-fg}` : `{green-fg}{bold}↪{/bold}{/green-fg}`,
        txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} : ${m.content}`;
      me.put(txt);
    });
  }
  putMessage(message, opt) {
    return this.putMessages([message], opt);
  }
  putTypingStart(channel, user) {
    this.put(`{yellow-fg}{bold}↪{/bold}{/yellow-fg} {white-fg}{bold}${user.username}{/bold} has {green-fg}started{/green-fg} typing.`);
  }
  putTypingStop(channel, user) {
    this.put(`{yellow-fg}{bold}↪{/bold}{/yellow-fg} {white-fg}{bold}${user.username}{/bold} has {red-fg}stopped{/red-fg} typing.`);
  }
  awaitResponse(text) {
    this.awaitingResponse = true;
    return new Promise((resolve) => {
      this.put(text);
      this.once('internalInput', (input) => {
        this.awaitingResponse = false;
        resolve(input);
      });
    });
  }
}

const screen = blessed.screen({
  smartCSR: true,
  title: 'retrocord',
  fullUnicode: true,
});

const gui = new GUI(screen);

module.exports = gui;
<commit_msg>Make typing messages pretty<commit_after>const EventEmitter = require('events'),
  blessed = require('blessed'),
  timestamp = require('./util/timestamp');

class GUI extends EventEmitter {
  constructor(screen) {
    super();
    this.screen = screen;
    this.chatbox = blessed.box({
      label: 'Retrocord Light',
      width: '100%',
      height: '100%-1',
      border: { type: 'line' },
    });

    this.consolebox = blessed.log({
      parent: this.chatbox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true,
    });

    this.inputbox = blessed.textbox({
      bottom: 0,
      width: '100%',
      height: 1,
      inputOnFocus: true,
    });

    this.awaitingResponse = false;
  }

  init() {
    this.inputbox.key('enter', () => {
      if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue());
      else this.emit('input', this.inputbox.getValue());
      this.inputbox.clearValue();
      this.inputbox.focus();
      this.screen.render();
    });

    this.screen.append(this.chatbox);
    this.screen.append(this.inputbox);
    this.screen.render();

    this.inputbox.focus();
  }
  put(text) {
    this.consolebox.log(text);
  }
  putMessages(messages) {
    const me = this;
    messages.forEach(m => {
      const ts = timestamp(m.createdAt),
        arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}↩{/bold}{/green-fg}` : `{green-fg}{bold}↪{/bold}{/green-fg}`,
        txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} : ${m.content}`;
      me.put(txt);
    });
  }
  putMessage(message, opt) {
    return this.putMessages([message], opt);
  }
  putTypingStart(channel, user) {
    this.put(`{blue-fg}{bold}↷{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {green-fg}started{/green-fg} typing.`);
  }
  putTypingStop(channel, user) {
    this.put(`{blue-fg}{bold}↶{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {red-fg}stopped{/red-fg} typing.`);
  }
  awaitResponse(text) {
    this.awaitingResponse = true;
    return new Promise((resolve) => {
      this.put(text);
      this.once('internalInput', (input) => {
        this.awaitingResponse = false;
        resolve(input);
      });
    });
  }
}

const screen = blessed.screen({
  smartCSR: true,
  title: 'retrocord',
  fullUnicode: true,
});

const gui = new GUI(screen);

module.exports = gui;
<|endoftext|>


<commit_before>const EventEmitter = require('events'),
  blessed = require('blessed'),
  timestamp = require('./util/timestamp'),
  Discord = require('discord.js');

class GUI extends EventEmitter {
  constructor(screen) {
    super();
    this.history = []; // For storing past messages
    this.historyAt = 1; // For indexing history
    this.screen = screen;
    this.chatbox = blessed.box({
      label: 'Retrocord Light',
      left: '0.5%',
      width: '86%',
      height: '96%-1',
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'white'
        }
      }
    });
    this.infobox = blessed.textbox({
      label: 'Info',
      left: '86%',
      width: '14%',
      height: '96%-1',
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "white"
        }
      }
    });
    this.consolebox = blessed.log({
      parent: this.chatbox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.inputbox = blessed.textbox({
      bottom: 0,
      width: '100%',
      height: 3,
      inputOnFocus: true,
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'grey'
        }
      }
    });
    this.infolog = blessed.log({
      parent: this.infobox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.awaitingResponse = false;
  }
  renderInfo() {
    if (global.ctx && ctx.discord && ctx.discord.user) {
      const uname = ctx.discord.user.tag,
        friendCount = ctx.discord.user.friends.array().length,
        friends = ctx.discord.user.friends,
        isInDm = ctx.current.channel ? (ctx.current.channel instanceof Discord.DMChannel) : false,
        listSize = friendCount > 24 ? 25 : friendCount;
      let txt = `
      {yellow-fg}{bold}${uname}{/bold}{/yellow-fg}
      `;
      if (isInDm) {
        txt += `\n{center}DM:\n{white-fg}{bold}${ctx.current.channel.recipient.username}{/white-fg}{/bold}{/center}`;
        if (ctx.dmIsTyping) {
          txt += `\n{center}{underline}{white-fg}is typing...{/white-fg}{/underline}{/center}`;
        }
        txt += `\n{center}{underline}Status: {bold}${ctx.current.channel.recipient.presence.status}{/underline}{/center}\n`;
      }
      if (!ctx.hideFriends) {
        txt += "\nFriends:";
        var fs = friends.array();
        var chns = ctx.discord.channels.filterArray(c => c.type === 'dm');
        // /*
        chns.sort((a, b) => {
          if (!a.recipient.lastMessage || !b.recipient.lastMessage) return -1;
          return (b.recipient.lastMessage.createdTimestamp + a.recipient.lastMessage.createdTimestamp);
        });
        // */
        for (var i = 0; i < listSize; ++i) {
          txt += `\n{white-fg}{bold}-{/bold}{/white-fg} {yellow-fg}${chns[i].recipient.tag}{/yellow-fg}`
        }
      }
      this.infolog.setContent(txt);
    } else {
      this.infolog.setContent('Not logged in :(.');
    }
  }
  init() {
    const me = this;
    this.inputbox.key('enter', () => {
      if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue());
      else this.emit('input', this.inputbox.getValue());
        this.history.push(this.inputbox.getValue());
      this.inputbox.clearValue();
      this.inputbox.focus();
      this.screen.render();
        this.historyAt = 1; // Reset history index after message sent
    });
    this.inputbox.key('up', () => {
        const back = me.history[me.history.length - me.historyAt];
        me.historyAt++;
        if (back) {
            // me.inputbox.setValue(back);
        }
    });
    this.inputbox.key('down', () => {
        if (me.historyAt < 1) {
            return; // History index too small
        }
        const forward = me.history[me.history.length - me.historyAt];
        if (forward) {
            // me.inputbox.setValue(forward);
        }
    });
    this.screen.append(this.chatbox);
    this.screen.append(this.inputbox);
    this.screen.append(this.infobox);
    this.screen.render();
    this.inputbox.focus();
    me.renderInfo.call(me);
    setInterval(() => {
      me.renderInfo.call(me);
    }, 750);
  }
  put(text) {
    this.consolebox.log(text);
  }
  puti(txt) {
    this.infolog.log(txt);
  }
  putMessages(messages) {
    const me = this;
    messages.forEach(m => {
      const ts = timestamp(m.createdAt),
        arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}<{/bold}{/green-fg}` : `{red-fg}{bold}>{/bold}{/red-fg}`,
        txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} ${m.content}`;
      me.put(txt);
    });
  }
  putMessage(message, opt) {
    return this.putMessages([message], opt);
  }
  putTypingStart(channel, user) {
    // athis.put(`{blue-fg}{bold}↷{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {green-fg}started{/green-fg} typing.`);
  }
  putTypingStop(channel, user) {
    // this.put(`{blue-fg}{bold}↶{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {red-fg}stopped{/red-fg} typing.`);
  }
  awaitResponse(text) {
    this.awaitingResponse = true;
    return new Promise((resolve) => {
      this.put(text);
      this.once('internalInput', (input) => {
        this.awaitingResponse = false;
        resolve(input);
      });
    });
  }
}

const screen = blessed.screen({
  smartCSR: true,
  title: 'retrocord',
  fullUnicode: true,
});

const gui = new GUI(screen);

module.exports = gui;
<commit_msg>Speed up info box rendering<commit_after>const EventEmitter = require('events'),
  blessed = require('blessed'),
  timestamp = require('./util/timestamp'),
  Discord = require('discord.js');

class GUI extends EventEmitter {
  constructor(screen) {
    super();
    this.history = []; // For storing past messages
    this.historyAt = 1; // For indexing history
    this.screen = screen;
    this.chatbox = blessed.box({
      label: 'Retrocord Light',
      left: '0.5%',
      width: '86%',
      height: '96%-1',
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'white'
        }
      }
    });
    this.infobox = blessed.textbox({
      label: 'Info',
      left: '86%',
      width: '14%',
      height: '96%-1',
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "white"
        }
      }
    });
    this.consolebox = blessed.log({
      parent: this.chatbox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.inputbox = blessed.textbox({
      bottom: 0,
      width: '100%',
      height: 3,
      inputOnFocus: true,
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'grey'
        }
      }
    });
    this.infolog = blessed.log({
      parent: this.infobox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.awaitingResponse = false;
  }
  renderInfo() {
    if (global.ctx && ctx.discord && ctx.discord.user) {
      const uname = ctx.discord.user.tag,
        friendCount = ctx.discord.user.friends.array().length,
        friends = ctx.discord.user.friends,
        isInDm = ctx.current.channel ? (ctx.current.channel instanceof Discord.DMChannel) : false,
        listSize = friendCount > 24 ? 25 : friendCount;
      let txt = `
      {yellow-fg}{bold}${uname}{/bold}{/yellow-fg}
      `;
      if (isInDm) {
        txt += `\n{center}DM:\n{white-fg}{bold}${ctx.current.channel.recipient.username}{/white-fg}{/bold}{/center}`;
        if (ctx.dmIsTyping) {
          txt += `\n{center}{underline}{white-fg}is typing...{/white-fg}{/underline}{/center}`;
        }
        txt += `\n{center}{underline}Status: {bold}${ctx.current.channel.recipient.presence.status}{/underline}{/center}\n`;
      }
      if (!ctx.hideFriends) {
        txt += "\nFriends:";
        var fs = friends.array();
        var chns = ctx.discord.channels.filterArray(c => c.type === 'dm');
        // /*
        chns.sort((a, b) => {
          if (!a.recipient.lastMessage || !b.recipient.lastMessage) return -1;
          return (b.recipient.lastMessage.createdTimestamp + a.recipient.lastMessage.createdTimestamp);
        });
        // */
        for (var i = 0; i < listSize; ++i) {
          txt += `\n{white-fg}{bold}-{/bold}{/white-fg} {yellow-fg}${chns[i].recipient.tag}{/yellow-fg}`
        }
      }
      this.infolog.setContent(txt);
    } else {
      this.infolog.setContent('Not logged in :(.');
    }
  }
  init() {
    const me = this;
    this.inputbox.key('enter', () => {
      if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue());
      else this.emit('input', this.inputbox.getValue());
        this.history.push(this.inputbox.getValue());
      this.inputbox.clearValue();
      this.inputbox.focus();
      this.screen.render();
        this.historyAt = 1; // Reset history index after message sent
    });
    this.inputbox.key('up', () => {
        const back = me.history[me.history.length - me.historyAt];
        me.historyAt++;
        if (back) {
            // me.inputbox.setValue(back);
        }
    });
    this.inputbox.key('down', () => {
        if (me.historyAt < 1) {
            return; // History index too small
        }
        const forward = me.history[me.history.length - me.historyAt];
        if (forward) {
            // me.inputbox.setValue(forward);
        }
    });
    this.screen.append(this.chatbox);
    this.screen.append(this.inputbox);
    this.screen.append(this.infobox);
    this.screen.render();
    this.inputbox.focus();
    me.renderInfo.call(me);
    setInterval(() => {
      me.renderInfo.call(me);
    }, 500);
  }
  put(text) {
    this.consolebox.log(text);
  }
  puti(txt) {
    this.infolog.log(txt);
  }
  putMessages(messages) {
    const me = this;
    messages.forEach(m => {
      const ts = timestamp(m.createdAt),
        arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}<{/bold}{/green-fg}` : `{red-fg}{bold}>{/bold}{/red-fg}`,
        txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} ${m.content}`;
      me.put(txt);
    });
  }
  putMessage(message, opt) {
    return this.putMessages([message], opt);
  }
  putTypingStart(channel, user) {
    // athis.put(`{blue-fg}{bold}↷{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {green-fg}started{/green-fg} typing.`);
  }
  putTypingStop(channel, user) {
    // this.put(`{blue-fg}{bold}↶{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {red-fg}stopped{/red-fg} typing.`);
  }
  awaitResponse(text) {
    this.awaitingResponse = true;
    return new Promise((resolve) => {
      this.put(text);
      this.once('internalInput', (input) => {
        this.awaitingResponse = false;
        resolve(input);
      });
    });
  }
}

const screen = blessed.screen({
  smartCSR: true,
  title: 'retrocord',
  fullUnicode: true,
});

const gui = new GUI(screen);

module.exports = gui;
<|endoftext|>


<commit_before>var xmlhttp = false;
var total_unread = 0;
var first_run = true;
var display_tags = false;
var global_unread = -1;
var active_title_text = "";
var current_subtitle = "";
var daemon_enabled = false;
var daemon_refresh_only = false;
var _qfd_deleted_feed = 0;
var firsttime_update = true;
var last_refetch = 0;
var cookie_lifetime = 0;
var active_feed_id = 0;
var active_feed_is_cat = false;
var number_of_feeds = 0;

var xmlhttp = Ajax.getTransport();
var xmlhttp_ctr = Ajax.getTransport();

var init_params = new Object();

function toggleTags() {
	display_tags = !display_tags;

	var p = document.getElementById("dispSwitchPrompt");

	if (display_tags) {
		p.innerHTML = "display feeds";
	} else {
		p.innerHTML = "display tags";
	}

	updateFeedList();
}

function dlg_frefresh_callback() {
	if (xmlhttp.readyState == 4) {
//		notify(xmlhttp.responseText);

		if (getActiveFeedId() == _qfd_deleted_feed) {
			var h = document.getElementById("headlines-frame");
			if (h) {
				h.innerHTML = "
No feed selected.
";
			}
		}

		setTimeout('updateFeedList(false, false)', 50);
		closeInfoBox();
	}
}

function refetch_callback() {
	if (xmlhttp_ctr.readyState == 4) {
		try {

			var date = new Date();

			last_refetch = date.getTime() / 1000;

			if (!xmlhttp_ctr.responseXML) {
				notify("refetch_callback: backend did not return valid XML", true, true);
				return;
			}

			var reply = xmlhttp_ctr.responseXML.firstChild;

			if (!reply) {
				notify("refetch_callback: backend did not return expected XML object", true, true);
				updateTitle("");
				return;
			}

			var error_code = reply.getAttribute("error-code");

			if (error_code && error_code != 0) {
				return fatalError(error_code, reply.getAttribute("error-msg"));
			}

			var counters = reply.firstChild;

			parse_counters(counters, true);

			var runtime_info = counters.nextSibling;

			parse_runtime_info(runtime_info);

			debug("refetch_callback: done");

			if (!daemon_enabled && !daemon_refresh_only) {
				notify("All feeds updated.");
				updateTitle("");
			} else {
				notify("");
			}
		} catch (e) {
			exception_error("refetch_callback", e);
			updateTitle("");
		}
	}
}

function backend_sanity_check_callback() {

	if (xmlhttp.readyState == 4) {

		try {

			if (!xmlhttp.responseXML) {
				fatalError(3, "[D001, Received reply is not XML]: " + xmlhttp.responseText);
				return;
			}

			var reply = xmlhttp.responseXML.firstChild.firstChild;

			if (!reply) {
				fatalError(3, "[D002, Invalid RPC reply]: " + xmlhttp.responseText);
				return;
			}

			var error_code = reply.getAttribute("error-code");

			if (error_code && error_code != 0) {
				return fatalError(error_code, reply.getAttribute("error-msg"));
			}

			debug("sanity check ok");

			var params = reply.nextSibling;

			if (params) {
				debug('reading init-params...');
				var param = params.firstChild;

				while (param) {
					var k = param.getAttribute("key");
					var v = param.getAttribute("value");
					debug(k + " => " + v);
					init_params[k] = v;
					param = param.nextSibling;
				}
			}

			init_second_stage();

		} catch (e) {
			exception_error("backend_sanity_check_callback", e);
		}
	}
}

function scheduleFeedUpdate(force) {

	if (!daemon_enabled && !daemon_refresh_only) {
		notify("Updating feeds, please wait.", true);
		updateTitle("Updating");
	}

	var query_str = "backend.php?op=rpc&subop=";

	if (force) {
		query_str = query_str + "forceUpdateAllFeeds";
	} else {
		query_str = query_str + "updateAllFeeds";
	}

	var omode;

	if (firsttime_update && !navigator.userAgent.match("Opera")) {
		firsttime_update = false;
		omode = "T";
	} else {
		if (display_tags) {
			omode = "t";
		} else {
			omode = "flc";
		}
	}

	query_str = query_str + "&omode=" + omode;
	query_str = query_str + "&uctr=" + global_unread;

	debug("in scheduleFeedUpdate");

	var date = new Date();

	if (!xmlhttp_ready(xmlhttp_ctr) && last_refetch < date.getTime() / 1000 - 60) {
		debug("xmlhttp seems to be stuck, aborting");
		xmlhttp_ctr.abort();
	}

	debug("REFETCH query: " + query_str);

	if (xmlhttp_ready(xmlhttp_ctr)) {
		xmlhttp_ctr.open("GET", query_str, true);
		xmlhttp_ctr.onreadystatechange=refetch_callback;
		xmlhttp_ctr.send(null);
	} else {
		debug("xmlhttp_ctr busy");
		//printLockingError();
	}
}

function updateFeedList(silent, fetch) {

//	if (silent != true) {
//		notify("Loading feed list...");
//	}

	var query_str = "backend.php?op=feeds";

	if (display_tags) {
		query_str = query_str + "&tags=1";
	}

	if (getActiveFeedId() && !activeFeedIsCat()) {
		query_str = query_str + "&actid=" + getActiveFeedId();
	}

	if (navigator.userAgent.match("Opera")) {
		var date = new Date();
		var timestamp = Math.round(date.getTime() / 1000);
		query_str = query_str + "&ts=" + timestamp
	}

	if (fetch) query_str = query_str + "&fetch=yes";

//	var feeds_frame = document.getElementById("feeds-frame");
//	feeds_frame.src = query_str;

	debug("updateFeedList Q=" + query_str);

	if (xmlhttp_ready(xmlhttp)) {
		xmlhttp.open("GET", query_str, true);
		xmlhttp.onreadystatechange=feedlist_callback;
		xmlhttp.send(null);
	} else {
		debug("xmlhttp busy");
		//printLockingError();
	}

}

function catchupAllFeeds() {

	var query_str = "backend.php?op=feeds&subop=catchupAll";

	notify("Marking all feeds as read...");

	var feeds_frame = document.getElementById("feeds-frame");

	feeds_frame.src = query_str;

	global_unread = 0;
	updateTitle("");

}

function viewCurrentFeed(subop) {

//	if (getActiveFeedId()) {
	if (getActiveFeedId() != undefined) {
		viewfeed(getActiveFeedId(), subop);
	} else {
		disableContainerChildren("headlinesToolbar", false, document);
//		viewfeed(-1, subop); // FIXME
	}
	return false; // block unneeded form submits
}

function viewfeed(feed, subop) {
	var f = window.frames["feeds-frame"];
	f.viewfeed(feed, subop);
}

function timeout() {
	scheduleFeedUpdate(false);

	var refresh_time = getInitParam("feeds_frame_refresh");

	if (!refresh_time) refresh_time = 600;

	setTimeout("timeout()", refresh_time*1000);
}

function resetSearch() {
	var searchbox = document.getElementById("searchbox")

	if (searchbox.value != "" && getActiveFeedId()) {
		searchbox.value = "";
		viewfeed(getActiveFeedId(), "");
	}
}

function searchCancel() {
	closeInfoBox(true);
}

function search() {
	closeInfoBox();
	viewCurrentFeed(0, "");
}

function localPiggieFunction(enable) {
	if (enable) {
		var query_str = "backend.php?op=feeds&subop=piggie";

		if (xmlhttp_ready(xmlhttp)) {

			xmlhttp.open("GET", query_str, true);
			xmlhttp.onreadystatechange=feedlist_callback;
			xmlhttp.send(null);
		}
	}
}

// if argument is undefined, current subtitle is not updated
// use blank string to clear subtitle
function updateTitle(s) {
	var tmp = "Tiny Tiny RSS";

	if (s != undefined) {
		current_subtitle = s;
	}

	if (global_unread > 0) {
		tmp = tmp + " (" + global_unread + ")";
	}

	if (current_subtitle) {
		tmp = tmp + " - " + current_subtitle;
	}

	if (active_title_text.length > 0) {
		tmp = tmp + " > " + active_title_text;
	}

	document.title = tmp;
}

function genericSanityCheck() {

	if (!xmlhttp) fatalError(1);

	setCookie("ttrss_vf_test", "TEST");

	if (getCookie("ttrss_vf_test") != "TEST") {
		fatalError(2);
	}

	return true;
}

function init() {

	try {

		// this whole shebang is based on http://www.birnamdesigns.com/misc/busted2.html

		if (arguments.callee.done) return;
		arguments.callee.done = true;

		disableContainerChildren("headlinesToolbar", true);

		Form.disable("main_toolbar_form");

		if (!genericSanityCheck())
			return;

		if (getURLParam('debug')) {
			document.getElementById('debug_output').style.display = 'block';
			debug('debug mode activated');
		}

		xmlhttp.open("GET", "backend.php?op=rpc&subop=sanityCheck", true);
		xmlhttp.onreadystatechange=backend_sanity_check_callback;
		xmlhttp.send(null);

	} catch (e) {
		exception_error("init", e);
	}
}

function init_second_stage() {

	try {

		cookie_lifetime = getCookie("ttrss_cltime");

		delCookie("ttrss_vf_test");

		document.onkeydown = hotkey_handler;

		var tb = parent.document.forms["main_toolbar_form"];

//		dropboxSelect(tb.view_mode, getInitParam("toolbar_view_mode"));
//		dropboxSelect(tb.limit, getInitParam("toolbar_limit"));

		daemon_enabled = getInitParam("daemon_enabled") == 1;
		daemon_refresh_only = getInitParam("daemon_refresh_only") == 1;

		setTimeout('updateFeedList(false, false)', 50);

		debug("second stage ok");

	} catch (e) {
		exception_error("init_second_stage", e);
	}
}

function quickMenuChange() {
	var chooser = document.getElementById("quickMenuChooser");
	var opid = chooser[chooser.selectedIndex].value;

	chooser.selectedIndex = 0;
	quickMenuGo(opid);
}

function quickMenuGo(opid) {
	try {

		if (opid == "qmcPrefs") {
			gotoPreferences();
		}

		if (opid == "qmcSearch") {
			displayDlg("search", getActiveFeedId() + ":" + activeFeedIsCat());
			return;
		}

		if (opid == "qmcAddFeed") {
			displayDlg("quickAddFeed");
			return;
		}

		if (opid == "qmcRemoveFeed") {
			var actid = getActiveFeedId();

			if (!actid || activeFeedIsCat()) {
				alert("Please select some feed first.");
				return;
			}

			var fn = getFeedName(actid);

			if (confirm("Unsubscribe from " + fn + "?")) {
				qfdDelete(actid);
			}

			return;
		}

		if (opid == "qmcUpdateFeeds") {
			scheduleFeedUpdate(true);
			return;
		}

		if (opid == "qmcCatchupAll") {
			catchupAllFeeds();
			return;
		}

		if (opid == "qmcShowOnlyUnread") {
			toggleDispRead();
			return;
		}

		if (opid == "qmcAddFilter") {
			displayDlg("quickAddFilter", getActiveFeedId());
		}
	} catch (e) {
		exception_error("quickMenuGo", e);
	}
}

function qfdDelete(feed_id) {

	notify("Removing feed...");

	if (!xmlhttp_ready(xmlhttp)) {
		printLockingError();
		return
	}

	_qfd_deleted_feed = feed_id;

	xmlhttp.open("GET", "backend.php?op=pref-feeds&quiet=1&subop=remove&ids=" + feed_id);
	xmlhttp.onreadystatechange=dlg_frefresh_callback;
	xmlhttp.send(null);

	return false;
}

function updateFeedTitle(t) {
	active_title_text = t;
	updateTitle();
}

function toggleDispRead() {
	try {

		if (!xmlhttp_ready(xmlhttp)) {
			printLockingError();
			return
		}

		var hide_read_feeds = (getInitParam("hide_read_feeds") == "1");

		hide_read_feeds = !hide_read_feeds;

		debug("toggle_disp_read => " + hide_read_feeds);

		hideOrShowFeeds(getFeedsContext().document, hide_read_feeds);

		var query = "backend.php?op=rpc&subop=setpref" +
			"&key=HIDE_READ_FEEDS&value=" + param_escape(hide_read_feeds);

		storeInitParam("hide_read_feeds", hide_read_feeds, true);

		new Ajax.Request(query);

	} catch (e) {
		exception_error("toggleDispRead", e);
	}
}

function parse_runtime_info(elem) {
	var param = elem.firstChild;

	debug("parse_runtime_info: " + param);

	while (param) {
		var k = param.getAttribute("key");
		var v = param.getAttribute("value");

		debug("RI: " + k + " => " + v);

		var w = document.getElementById("noDaemonWarning");

		if (w) {
			if (k == "daemon_is_running" && v != 1) {
				w.style.display = "block";
			} else {
				w.style.display = "none";
			}
		}
		param = param.nextSibling;
	}
}

function catchupCurrentFeed() {

	var fn = getFeedName(getActiveFeedId(), active_feed_is_cat);

	var str = "Mark all articles in " + fn + " as read?";

/*	if (active_feed_is_cat) {
		str = "Mark all articles in this category as read?";
	} */

	if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) {
		return viewCurrentFeed('MarkAllRead')
	}
}

function userSwitch() {
	var chooser = document.getElementById("userSwitch");
	var user = chooser[chooser.selectedIndex].value;
	window.location = "tt-rss.php?swu=" + user;
}

<commit_msg>add loading... prompt to dispSwitch handler<commit_after>var xmlhttp = false;
var total_unread = 0;
var first_run = true;
var display_tags = false;
var global_unread = -1;
var active_title_text = "";
var current_subtitle = "";
var daemon_enabled = false;
var daemon_refresh_only = false;
var _qfd_deleted_feed = 0;
var firsttime_update = true;
var last_refetch = 0;
var cookie_lifetime = 0;
var active_feed_id = 0;
var active_feed_is_cat = false;
var number_of_feeds = 0;

var xmlhttp = Ajax.getTransport();
var xmlhttp_ctr = Ajax.getTransport();

var init_params = new Object();

function toggleTags() {
	display_tags = !display_tags;

	var p = document.getElementById("dispSwitchPrompt");

	if (display_tags) {
		p.innerHTML = "display feeds";
	} else {
		p.innerHTML = "display tags";
	}

	notify("Loading, please wait...");

	updateFeedList();
}

function dlg_frefresh_callback() {
	if (xmlhttp.readyState == 4) {
//		notify(xmlhttp.responseText);

		if (getActiveFeedId() == _qfd_deleted_feed) {
			var h = document.getElementById("headlines-frame");
			if (h) {
				h.innerHTML = "
No feed selected.
";
			}
		}

		setTimeout('updateFeedList(false, false)', 50);
		closeInfoBox();
	}
}

function refetch_callback() {
	if (xmlhttp_ctr.readyState == 4) {
		try {

			var date = new Date();

			last_refetch = date.getTime() / 1000;

			if (!xmlhttp_ctr.responseXML) {
				notify("refetch_callback: backend did not return valid XML", true, true);
				return;
			}

			var reply = xmlhttp_ctr.responseXML.firstChild;

			if (!reply) {
				notify("refetch_callback: backend did not return expected XML object", true, true);
				updateTitle("");
				return;
			}

			var error_code = reply.getAttribute("error-code");

			if (error_code && error_code != 0) {
				return fatalError(error_code, reply.getAttribute("error-msg"));
			}

			var counters = reply.firstChild;

			parse_counters(counters, true);

			var runtime_info = counters.nextSibling;

			parse_runtime_info(runtime_info);

			debug("refetch_callback: done");

			if (!daemon_enabled && !daemon_refresh_only) {
				notify("All feeds updated.");
				updateTitle("");
			} else {
				notify("");
			}
		} catch (e) {
			exception_error("refetch_callback", e);
			updateTitle("");
		}
	}
}

function backend_sanity_check_callback() {

	if (xmlhttp.readyState == 4) {

		try {

			if (!xmlhttp.responseXML) {
				fatalError(3, "[D001, Received reply is not XML]: " + xmlhttp.responseText);
				return;
			}

			var reply = xmlhttp.responseXML.firstChild.firstChild;

			if (!reply) {
				fatalError(3, "[D002, Invalid RPC reply]: " + xmlhttp.responseText);
				return;
			}

			var error_code = reply.getAttribute("error-code");

			if (error_code && error_code != 0) {
				return fatalError(error_code, reply.getAttribute("error-msg"));
			}

			debug("sanity check ok");

			var params = reply.nextSibling;

			if (params) {
				debug('reading init-params...');
				var param = params.firstChild;

				while (param) {
					var k = param.getAttribute("key");
					var v = param.getAttribute("value");
					debug(k + " => " + v);
					init_params[k] = v;
					param = param.nextSibling;
				}
			}

			init_second_stage();

		} catch (e) {
			exception_error("backend_sanity_check_callback", e);
		}
	}
}

function scheduleFeedUpdate(force) {

	if (!daemon_enabled && !daemon_refresh_only) {
		notify("Updating feeds, please wait.", true);
		updateTitle("Updating");
	}

	var query_str = "backend.php?op=rpc&subop=";

	if (force) {
		query_str = query_str + "forceUpdateAllFeeds";
	} else {
		query_str = query_str + "updateAllFeeds";
	}

	var omode;

	if (firsttime_update && !navigator.userAgent.match("Opera")) {
		firsttime_update = false;
		omode = "T";
	} else {
		if (display_tags) {
			omode = "t";
		} else {
			omode = "flc";
		}
	}

	query_str = query_str + "&omode=" + omode;
	query_str = query_str + "&uctr=" + global_unread;

	debug("in scheduleFeedUpdate");

	var date = new Date();

	if (!xmlhttp_ready(xmlhttp_ctr) && last_refetch < date.getTime() / 1000 - 60) {
		debug("xmlhttp seems to be stuck, aborting");
		xmlhttp_ctr.abort();
	}

	debug("REFETCH query: " + query_str);

	if (xmlhttp_ready(xmlhttp_ctr)) {
		xmlhttp_ctr.open("GET", query_str, true);
		xmlhttp_ctr.onreadystatechange=refetch_callback;
		xmlhttp_ctr.send(null);
	} else {
		debug("xmlhttp_ctr busy");
		//printLockingError();
	}
}

function updateFeedList(silent, fetch) {

//	if (silent != true) {
//		notify("Loading feed list...");
//	}

	var query_str = "backend.php?op=feeds";

	if (display_tags) {
		query_str = query_str + "&tags=1";
	}

	if (getActiveFeedId() && !activeFeedIsCat()) {
		query_str = query_str + "&actid=" + getActiveFeedId();
	}

	if (navigator.userAgent.match("Opera")) {
		var date = new Date();
		var timestamp = Math.round(date.getTime() / 1000);
		query_str = query_str + "&ts=" + timestamp
	}

	if (fetch) query_str = query_str + "&fetch=yes";

//	var feeds_frame = document.getElementById("feeds-frame");
//	feeds_frame.src = query_str;

	debug("updateFeedList Q=" + query_str);

	if (xmlhttp_ready(xmlhttp)) {
		xmlhttp.open("GET", query_str, true);
		xmlhttp.onreadystatechange=feedlist_callback;
		xmlhttp.send(null);
	} else {
		debug("xmlhttp busy");
		//printLockingError();
	}

}

function catchupAllFeeds() {

	var query_str = "backend.php?op=feeds&subop=catchupAll";

	notify("Marking all feeds as read...");

	var feeds_frame = document.getElementById("feeds-frame");

	feeds_frame.src = query_str;

	global_unread = 0;
	updateTitle("");

}

function viewCurrentFeed(subop) {

//	if (getActiveFeedId()) {
	if (getActiveFeedId() != undefined) {
		viewfeed(getActiveFeedId(), subop);
	} else {
		disableContainerChildren("headlinesToolbar", false, document);
//		viewfeed(-1, subop); // FIXME
	}
	return false; // block unneeded form submits
}

function viewfeed(feed, subop) {
	var f = window.frames["feeds-frame"];
	f.viewfeed(feed, subop);
}

function timeout() {
	scheduleFeedUpdate(false);

	var refresh_time = getInitParam("feeds_frame_refresh");

	if (!refresh_time) refresh_time = 600;

	setTimeout("timeout()", refresh_time*1000);
}

function resetSearch() {
	var searchbox = document.getElementById("searchbox")

	if (searchbox.value != "" && getActiveFeedId()) {
		searchbox.value = "";
		viewfeed(getActiveFeedId(), "");
	}
}

function searchCancel() {
	closeInfoBox(true);
}

function search() {
	closeInfoBox();
	viewCurrentFeed(0, "");
}

function localPiggieFunction(enable) {
	if (enable) {
		var query_str = "backend.php?op=feeds&subop=piggie";

		if (xmlhttp_ready(xmlhttp)) {

			xmlhttp.open("GET", query_str, true);
			xmlhttp.onreadystatechange=feedlist_callback;
			xmlhttp.send(null);
		}
	}
}

// if argument is undefined, current subtitle is not updated
// use blank string to clear subtitle
function updateTitle(s) {
	var tmp = "Tiny Tiny RSS";

	if (s != undefined) {
		current_subtitle = s;
	}

	if (global_unread > 0) {
		tmp = tmp + " (" + global_unread + ")";
	}

	if (current_subtitle) {
		tmp = tmp + " - " + current_subtitle;
	}

	if (active_title_text.length > 0) {
		tmp = tmp + " > " + active_title_text;
	}

	document.title = tmp;
}

function genericSanityCheck() {

	if (!xmlhttp) fatalError(1);

	setCookie("ttrss_vf_test", "TEST");

	if (getCookie("ttrss_vf_test") != "TEST") {
		fatalError(2);
	}

	return true;
}

function init() {

	try {

		// this whole shebang is based on http://www.birnamdesigns.com/misc/busted2.html

		if (arguments.callee.done) return;
		arguments.callee.done = true;

		disableContainerChildren("headlinesToolbar", true);

		Form.disable("main_toolbar_form");

		if (!genericSanityCheck())
			return;

		if (getURLParam('debug')) {
			document.getElementById('debug_output').style.display = 'block';
			debug('debug mode activated');
		}

		xmlhttp.open("GET", "backend.php?op=rpc&subop=sanityCheck", true);
		xmlhttp.onreadystatechange=backend_sanity_check_callback;
		xmlhttp.send(null);

	} catch (e) {
		exception_error("init", e);
	}
}

function init_second_stage() {

	try {

		cookie_lifetime = getCookie("ttrss_cltime");

		delCookie("ttrss_vf_test");

		document.onkeydown = hotkey_handler;

		var tb = parent.document.forms["main_toolbar_form"];

//		dropboxSelect(tb.view_mode, getInitParam("toolbar_view_mode"));
//		dropboxSelect(tb.limit, getInitParam("toolbar_limit"));

		daemon_enabled = getInitParam("daemon_enabled") == 1;
		daemon_refresh_only = getInitParam("daemon_refresh_only") == 1;

		setTimeout('updateFeedList(false, false)', 50);

		debug("second stage ok");

	} catch (e) {
		exception_error("init_second_stage", e);
	}
}

function quickMenuChange() {
	var chooser = document.getElementById("quickMenuChooser");
	var opid = chooser[chooser.selectedIndex].value;

	chooser.selectedIndex = 0;
	quickMenuGo(opid);
}

function quickMenuGo(opid) {
	try {

		if (opid == "qmcPrefs") {
			gotoPreferences();
		}

		if (opid == "qmcSearch") {
			displayDlg("search", getActiveFeedId() + ":" + activeFeedIsCat());
			return;
		}

		if (opid == "qmcAddFeed") {
			displayDlg("quickAddFeed");
			return;
		}

		if (opid == "qmcRemoveFeed") {
			var actid = getActiveFeedId();

			if (!actid || activeFeedIsCat()) {
				alert("Please select some feed first.");
				return;
			}

			var fn = getFeedName(actid);

			if (confirm("Unsubscribe from " + fn + "?")) {
				qfdDelete(actid);
			}

			return;
		}

		if (opid == "qmcUpdateFeeds") {
			scheduleFeedUpdate(true);
			return;
		}

		if (opid == "qmcCatchupAll") {
			catchupAllFeeds();
			return;
		}

		if (opid == "qmcShowOnlyUnread") {
			toggleDispRead();
			return;
		}

		if (opid == "qmcAddFilter") {
			displayDlg("quickAddFilter", getActiveFeedId());
		}
	} catch (e) {
		exception_error("quickMenuGo", e);
	}
}

function qfdDelete(feed_id) {

	notify("Removing feed...");

	if (!xmlhttp_ready(xmlhttp)) {
		printLockingError();
		return
	}

	_qfd_deleted_feed = feed_id;

	xmlhttp.open("GET", "backend.php?op=pref-feeds&quiet=1&subop=remove&ids=" + feed_id);
	xmlhttp.onreadystatechange=dlg_frefresh_callback;
	xmlhttp.send(null);

	return false;
}

function updateFeedTitle(t) {
	active_title_text = t;
	updateTitle();
}

function toggleDispRead() {
	try {

		if (!xmlhttp_ready(xmlhttp)) {
			printLockingError();
			return
		}

		var hide_read_feeds = (getInitParam("hide_read_feeds") == "1");

		hide_read_feeds = !hide_read_feeds;

		debug("toggle_disp_read => " + hide_read_feeds);

		hideOrShowFeeds(getFeedsContext().document, hide_read_feeds);

		var query = "backend.php?op=rpc&subop=setpref" +
			"&key=HIDE_READ_FEEDS&value=" + param_escape(hide_read_feeds);

		storeInitParam("hide_read_feeds", hide_read_feeds, true);

		new Ajax.Request(query);

	} catch (e) {
		exception_error("toggleDispRead", e);
	}
}

function parse_runtime_info(elem) {
	var param = elem.firstChild;

	debug("parse_runtime_info: " + param);

	while (param) {
		var k = param.getAttribute("key");
		var v = param.getAttribute("value");

		debug("RI: " + k + " => " + v);

		var w = document.getElementById("noDaemonWarning");

		if (w) {
			if (k == "daemon_is_running" && v != 1) {
				w.style.display = "block";
			} else {
				w.style.display = "none";
			}
		}
		param = param.nextSibling;
	}
}

function catchupCurrentFeed() {

	var fn = getFeedName(getActiveFeedId(), active_feed_is_cat);

	var str = "Mark all articles in " + fn + " as read?";

/*	if (active_feed_is_cat) {
		str = "Mark all articles in this category as read?";
	} */

	if (getInitParam("confirm_feed_catchup") != 1 || confirm(str)) {
		return viewCurrentFeed('MarkAllRead')
	}
}

function userSwitch() {
	var chooser = document.getElementById("userSwitch");
	var user = chooser[chooser.selectedIndex].value;
	window.location = "tt-rss.php?swu=" + user;
}

<|endoftext|>


<commit_before>const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const extractCSS = new ExtractTextPlugin('[name].fonts.css');
const extractSCSS = new ExtractTextPlugin('[name].styles.css');

const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');

console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);

module.exports = {
  entry: {
    index: [SRC_DIR + '/index.js']
	},
  output: {
    path: BUILD_DIR,
    filename: '[name].bundle.js'
  },
  watch: true,
  devServer: {
    contentBase: BUILD_DIR,
    //   port: 9001,
    compress: true,
    hot: true,
    open: true
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            presets: ['react', 'env']
          }
        }
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(scss)$/,
        use: ['css-hot-loader'].concat(extractSCSS.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: { alias: { '../img': '../public/img' } }
            },
            {
              loader: 'sass-loader'
            }
          ]
        }))
      },
      {
        test: /\.css$/,
        use: extractCSS.extract({
          fallback: 'style-loader',
          use: 'css-loader'
        })
      },
      {
        test: /\.(png|jpg|jpeg|gif|ico)$/,
        use: [
          {
            // loader: 'url-loader'
            loader: 'file-loader',
            options: {
              name: './img/[name].[hash].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader',
        options: {
          name: './fonts/[name].[hash].[ext]'
        }
      }]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.NamedModulesPlugin(),
    extractCSS,
    extractSCSS,
    new HtmlWebpackPlugin(
      {
        inject: true,
        template: './public/index.html'
      }
    ),
    new CopyWebpackPlugin([
        {from: './public/img', to: 'img'}
      ],
      {copyUnmodified: false}
    )
  ]
}
;<commit_msg>changing url path for prod<commit_after>const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const extractCSS = new ExtractTextPlugin('[name].fonts.css');
const extractSCSS = new ExtractTextPlugin('[name].styles.css');

const BUILD_DIR = path.resolve(__dirname, 'build');
const SRC_DIR = path.resolve(__dirname, 'src');

console.log('BUILD_DIR', BUILD_DIR);
console.log('SRC_DIR', SRC_DIR);

module.exports = {
  entry: {
    index: [SRC_DIR + '/index.js']
	},
  output: {
    path: BUILD_DIR,
    filename: '[name].bundle.js'
  },
  watch: true,
  devServer: {
    contentBase: './public',
    //   port: 9001,
    compress: true,
    hot: true,
    open: true
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            presets: ['react', 'env']
          }
        }
      },
      {
        test: /\.html$/,
        loader: 'html-loader'
      },
      {
        test: /\.(scss)$/,
        use: ['css-hot-loader'].concat(extractSCSS.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              options: { alias: { '../img': '../public/img' } }
            },
            {
              loader: 'sass-loader'
            }
          ]
        }))
      },
      {
        test: /\.css$/,
        use: extractCSS.extract({
          fallback: 'style-loader',
          use: 'css-loader'
        })
      },
      {
        test: /\.(png|jpg|jpeg|gif|ico)$/,
        use: [
          {
            // loader: 'url-loader'
            loader: 'file-loader',
            options: {
              name: './img/[name].[hash].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader',
        options: {
          name: './fonts/[name].[hash].[ext]'
        }
      }]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.NamedModulesPlugin(),
    extractCSS,
    extractSCSS,
    new HtmlWebpackPlugin(
      {
        inject: true,
        template: './public/index.html'
      }
    ),
    new CopyWebpackPlugin([
        {from: './public/img', to: 'img'}
      ],
      {copyUnmodified: false}
    )
  ]
}
;
<|endoftext|>


<commit_before>exports.BattleMovedex = {
        "vinewhip": {
                num: 22,
                accuracy: 100,
                basePower: 35,
                category: "Physical",
                desc: "Deals damage to one adjacent target. Makes contact.",
                shortDesc: "No additional effect.",
                id: "vinewhip",
                name: "Vine Whip",
                pp: 25,
                priority: 0,
                isContact: true,
                secondary: false,
                target: "normal",
                type: "Grass"
        },
      	"lunardance": {
		num: 461,
		accuracy: true,
		basePower: 0,
		category: "Status",
		desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.",
		shortDesc: "User faints. Replacement is fully healed, with PP.",
		id: "lunardance",
		isViable: true,
		name: "Lunar Dance",
		pp: 20,
		priority: 0,
		isSnatchable: true,
		boosts: {
			spa: 1,
			spe: 1
		},
		target: "self",
		type: "Psychic"
	},
	"moonblast": {
		num: 1000,
		accuracy: 90,
		basePower: 130,
		category: "Special",
		desc: "Surronds the user with moonlight energy and releases all of that energy in one blast using up all the energy making the attacks Special Attack go down.",
		shortDesc: "Deals damage and lowers the attacker's SpA.",
		id: "moonblast",
		isViable: true,
		name: "Moonblast",
		pp: 5,
		priority: 0,
		self: {
			boosts: {
				spa: -2

			}
		},
		secondary: false,
		target: "normal",
		type: "Fairy"
	},
	"fairywind": {
		num: 1001,
	        accuracy: 100,
		basePower: 85,
		category: "Special",
		desc: "Deals damage to one adjacent target by summoning a mystical wind that has a chance to encloak the user with mystical energy that boosts speed.",
		shortDesc: "Deals damage and has 10% chance to raise speed.",
		id: "fairywind",
		isViable: true,
		name: "Fairy Wind",
		pp: 15,
		priority: 0,
		secondary: {
			chance: 10,
			self: {
				boosts: {
					spd: 1
				}
			}
		},
		target: "normal",
		type: "Fairy"
	},
		"mysticcrash": {
		num: 1002,
	        accuracy: 100,
		basePower: 120,
		category: "Physical",
		desc: "Deals damage to one adjacent target by crashing into the target with a cloak of mystical energy.",
		shortDesc: "Deals damage and has recoil Basically Double Edge for faries.",
		id: "mysticcrash",
		isViable: true,
		name: "Mystic Crash",
		pp: 15,
		priority: 0,
		isContact: true,
		recoil: [22,100],
		secondary: false,
		target: "normal",
		type: "Fairy"
	},
        "partingshot": {
                num: 1032,
                accuracy: 100,
                basePower: 75,
                category: "Status",
                desc: "Lowers the opponent's Special Attack and Attack by 1, then switches the user out of battle.",
                shortDesc: "User switches out after lowering the target's SpA and Atk.",
                id: "partingshot",
                name: "Parting Shot",
                pp: 25,
                priority: 0,
                boosts: {
                        atk: -1,
                        spa: -1
                },
                selfSwitch: true,
                secondary: false,
                target: "normal",
                type: "Fighting"
        },
        "paraboliccharge": {
                num: 1033,
                accuracy: 100,
                basePower: 80,
                category: "Special",
                desc: "Deals damage to all targets, including its ally. The user recovers half of the HP lost by the target, rounded up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
                shortDesc: "User recovers 50% of the damage dealt.",
                id: "paraboliccharge",
                name: "Parabolic Charge",
                pp: 16,
                priority: 0,
                drain: [1,2],
                secondary: false,
                target: "normal",
                type: "Electric"
        },
        "boomburst": {
                num: 1034,
                accuracy: 100,
                basePower: 100,
                category: "Special",
                desc: "A sound attack that deals damage to all targets, including its ally.",
                shortDesc: "Deals damage to all targets.",
                id: "boomburst",
                name: "Boomburst",
                pp: 16,
                priority: 0,
                isSoundBased: true,
                secondary: false,
                target: "all",
                type: "Normal"
        },
        "moonblast": {
                num: 1035,
                accuracy: 100,
                basePower: 110,
                category: "Special",
                desc: "Deals damage to one adjacent target with a ???% chance to lower Special Attack",
                shortDesc: "30% chance to lower SpA.",
                id: "moonblast",
                name: "Moonblast",
                pp: 25,
                priority: 0,
                secondary: {
                        chance: 30,
                        boosts: {
                                spa: -1
                        }
                },
                target: "normal",
                type: "Fairy"
        },
        "nobleroar": {
                num: 1036,
                accuracy: 100,
                basePower: 85,
                category: "Status",
                desc: "Lowers the foe's Attack and Special Attack by one stage.",
                shortDesc: "Lowers SpA and Atk by 1.",
                id: "nobleroar",
                name: "Noble Roar",
                pp: 16,
                priority: 0,
                boosts: {
                        atk: -1,
                        spa: -1
                },
                secondary: false,
                target: "normal",
                type: "Fire"
        },
        "fairywind": {
                num: 1037,
                accuracy: 100,
                basePower: 85,
                category: "Special",
                desc: "Deals massive damage to all adjacent foes.",
                shortDesc: "Damages all adjacent foes.",
                id: "fairywind",
                name: "Fairy Wind",
                pp: 25,
                priority: 0,
                secondary: false,
                target: "allAdjacentFoes",
                type: "Fairy"
        },
        "topsyturvy": {
                num: 1038,
                accuracy: 100,
                basePower: 0,
                category: "Status",
                desc: "Reverses all stat modifications that the foe has.",
                shortDesc: "Reverses the foe's stat changes.",
                id: "topsyturvy",
                name: "Topsy-Turvy",
                pp: 16,
                priority: 0,
                onHit: function(target) {
                         for (var i in target.boosts) {
                               var target.boosts * .5;
                        }
                        this.add('-reverseboost', target, '[from] move: Topsy-Turvy');
                },
                secondary: false,
                target: "normal",
                type: "Fairy"
        },
        "drainingkiss": {
                num: 1039,
                accuracy: 100,
                basePower: 80,
                category: "Special",
                desc: "Deals damage to one adjacent target. The user recovers half of the HP lost by the target, rounded up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
                shortDesc: "User recovers 50% of the damage dealt.",
                id: "drainingkiss",
                name: "Draining Kiss",
                pp: 16,
                priority: 0,
                drain: [1,2],
                secondary: false,
                target: "normal",
                type: "Fairy"
        },
        "geomancy": {
                num: 1040,
                accuracy: 100,
                basePower: 130,
                category: "Special",
                desc: "Deal massive damage to one adjacent target.",
                shortDesc: "No additional effect.",
                id: "geomancy",
                name: "Geomancy",
                pp: 16,
                priority: 0,
		self: {
			boosts: {
				spa: -1,
                                spd: -1
			}
		},
                secondary: false,
                target: "all",
                type: "Fairy"
        },
        "oblivionwing": {
                num: 1041,
                accuracy: 100,
                basePower: 130,
                category: "Special",
                desc: "Deal massive damage to one adjacent target.",
                shortDesc: "No additional effect.",
                id: "oblivionwing",
                name: "Oblivion Wing",
                pp: 16,
        	priority: 0,
		self: {
			boosts: {
				spa: -1,
                                spd: -1
			}
		},
                secondary: false,
                target: "all",
                type: "Dark"
	}
};
<commit_msg>Update moves.js<commit_after>exports.BattleMovedex = {
        "vinewhip": {
                num: 22,
                accuracy: 100,
                basePower: 35,
                category: "Physical",
                desc: "Deals damage to one adjacent target. Makes contact.",
                shortDesc: "No additional effect.",
                id: "vinewhip",
                name: "Vine Whip",
                pp: 25,
                priority: 0,
                isContact: true,
                secondary: false,
                target: "normal",
                type: "Grass"
        },
      	"lunardance": {
		num: 461,
		accuracy: true,
		basePower: 0,
		category: "Status",
		desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.",
		shortDesc: "User faints. Replacement is fully healed, with PP.",
		id: "lunardance",
		isViable: true,
		name: "Lunar Dance",
		pp: 20,
		priority: 0,
		isSnatchable: true,
		boosts: {
			spa: 1,
			spe: 1
		},
		target: "self",
		type: "Psychic"
	},
	"moonblast": {
		num: 1000,
		accuracy: 90,
		basePower: 130,
		category: "Special",
		desc: "Surronds the user with moonlight energy and releases all of that energy in one blast using up all the energy making the attacks Special Attack go down.",
		shortDesc: "Deals damage and lowers the attacker's SpA.",
		id: "moonblast",
		isViable: true,
		name: "Moonblast",
		pp: 5,
		priority: 0,
		self: {
			boosts: {
				spa: -2

			}
		},
		secondary: false,
		target: "normal",
		type: "Fairy"
	},
	"fairywind": {
		num: 1001,
	        accuracy: 100,
		basePower: 85,
		category: "Special",
		desc: "Deals damage to one adjacent target by summoning a mystical wind that has a chance to encloak the user with mystical energy that boosts speed.",
		shortDesc: "Deals damage and has 10% chance to raise speed.",
		id: "fairywind",
		isViable: true,
		name: "Fairy Wind",
		pp: 15,
		priority: 0,
		secondary: {
			chance: 10,
			self: {
				boosts: {
					spd: 1
				}
			}
		},
		target: "normal",
		type: "Fairy"
	},
		"mysticcrash": {
		num: 1002,
	        accuracy: 100,
		basePower: 120,
		category: "Physical",
		desc: "Deals damage to one adjacent target by crashing into the target with a cloak of mystical energy.",
		shortDesc: "Deals damage and has recoil Basically Double Edge for faries.",
		id: "mysticcrash",
		isViable: true,
		name: "Mystic Crash",
		pp: 15,
		priority: 0,
		isContact: true,
		recoil: [22,100],
		secondary: false,
		target: "normal",
		type: "Fairy"
	},
        "partingshot": {
                num: 1032,
                accuracy: 100,
                basePower: 75,
                category: "Status",
                desc: "Lowers the opponent's Special Attack and Attack by 1, then switches the user out of battle.",
                shortDesc: "User switches out after lowering the target's SpA and Atk.",
                id: "partingshot",
                name: "Parting Shot",
                pp: 25,
                priority: 0,
                boosts: {
                        atk: -1,
                        spa: -1
                },
                selfSwitch: true,
                secondary: false,
                target: "normal",
                type: "Fighting"
        },
        "paraboliccharge": {
                num: 1033,
                accuracy: 100,
                basePower: 80,
                category: "Special",
                desc: "Deals damage to all targets, including its ally. The user recovers half of the HP lost by the target, rounded up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
                shortDesc: "User recovers 50% of the damage dealt.",
                id: "paraboliccharge",
                name: "Parabolic Charge",
                pp: 16,
                priority: 0,
                drain: [1,2],
                secondary: false,
                target: "normal",
                type: "Electric"
        },
        "boomburst": {
                num: 1034,
                accuracy: 100,
                basePower: 100,
                category: "Special",
                desc: "A sound attack that deals damage to all targets, including its ally.",
                shortDesc: "Deals damage to all targets.",
                id: "boomburst",
                name: "Boomburst",
                pp: 16,
                priority: 0,
                isSoundBased: true,
                secondary: false,
                target: "all",
                type: "Normal"
        },
        "moonblast": {
                num: 1035,
                accuracy: 100,
                basePower: 110,
                category: "Special",
                desc: "Deals damage to one adjacent target with a ???% chance to lower Special Attack",
                shortDesc: "30% chance to lower SpA.",
                id: "moonblast",
                name: "Moonblast",
                pp: 25,
                priority: 0,
                secondary: {
                        chance: 30,
                        boosts: {
                                spa: -1
                        }
                },
                target: "normal",
                type: "Fairy"
        },
        "nobleroar": {
                num: 1036,
                accuracy: 100,
                basePower: 85,
                category: "Status",
                desc: "Lowers the foe's Attack and Special Attack by one stage.",
                shortDesc: "Lowers SpA and Atk by 1.",
                id: "nobleroar",
                name: "Noble Roar",
                pp: 16,
                priority: 0,
                boosts: {
                        atk: -1,
                        spa: -1
                },
                secondary: false,
                target: "normal",
                type: "Fire"
        },
        "fairywind": {
                num: 1037,
                accuracy: 100,
                basePower: 85,
                category: "Special",
                desc: "Deals massive damage to all adjacent foes.",
                shortDesc: "Damages all adjacent foes.",
                id: "fairywind",
                name: "Fairy Wind",
                pp: 25,
                priority: 0,
                secondary: false,
                target: "allAdjacentFoes",
                type: "Fairy"
        },
        "topsyturvy": {
                num: 1038,
                accuracy: 100,
                basePower: 0,
                category: "Status",
                desc: "Reverses all stat modifications that the foe has.",
                shortDesc: "Reverses the foe's stat changes.",
                id: "topsyturvy",
                name: "Topsy-Turvy",
                pp: 16,
                priority: 0,
                onHit: function(target) {
                         for (var i in target.boosts) {
                               var target.boosts * .5
                        }
                        this.add('-reverseboost', target, '[from] move: Topsy-Turvy');
                },
                secondary: false,
                target: "normal",
                type: "Fairy"
        },
        "drainingkiss": {
                num: 1039,
                accuracy: 100,
                basePower: 80,
                category: "Special",
                desc: "Deals damage to one adjacent target. The user recovers half of the HP lost by the target, rounded up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
                shortDesc: "User recovers 50% of the damage dealt.",
                id: "drainingkiss",
                name: "Draining Kiss",
                pp: 16,
                priority: 0,
                drain: [1,2],
                secondary: false,
                target: "normal",
                type: "Fairy"
        },
        "geomancy": {
                num: 1040,
                accuracy: 100,
                basePower: 130,
                category: "Special",
                desc: "Deal massive damage to one adjacent target.",
                shortDesc: "No additional effect.",
                id: "geomancy",
                name: "Geomancy",
                pp: 16,
                priority: 0,
		self: {
			boosts: {
				spa: -1,
                                spd: -1
			}
		},
                secondary: false,
                target: "all",
                type: "Fairy"
        },
        "oblivionwing": {
                num: 1041,
                accuracy: 100,
                basePower: 130,
                category: "Special",
                desc: "Deal massive damage to one adjacent target.",
                shortDesc: "No additional effect.",
                id: "oblivionwing",
                name: "Oblivion Wing",
                pp: 16,
        	priority: 0,
		self: {
			boosts: {
				spa: -1,
                                spd: -1
			}
		},
                secondary: false,
                target: "all",
                type: "Dark"
	}
};
<|endoftext|>