<commit_before>(function() {

  "use strict";

  var math = require('mathjs');

  // var R = require('ramda');
  var Rp = require('./plus-fp/plus-fp');

  var rotate = function(point, centre, angle) {

    // assumes zero centre

    var x = point.x - centre.x;
    var y = point.y - centre.y;

    if ((x !== 0) || (y !== 0)) {
      var r = math.sqrt(x * x + y * y);
      var theta = math.atan2(y, x);

      theta += angle;

      x = r * math.cos(theta);
      y = r * math.sin(theta);

      x += centre.x;
      y += centre.y;
    }

    return {
      x: x,
      y: y
    };
  };

  var makeLine = function(x1, y1, x2, y2, centre, angle) {

    let point1 = {
      x: x1,
      y: y1
    };

    let point2 = {
      x: x2,
      y: y2
    };

    point1 = rotate(point1, centre, angle);
    point2 = rotate(point2, centre, angle);

    return {
      p1: point1,
      p2: point2
    };
  };

  var makePolygon = () => {

    let polygon = {};

    var centre = {
      x: 0,
      y: 0
    };

    var points = 3 + Rp.bandomInt(6, 2);
    var radius1 = math.random(0, 1);
    var radius2 = math.random(0, 1);
    var radius = math.max(radius1, radius2);
    var angle = math.random(0, 2 * math.pi);

    var lines = [];

    for (var p = 0; p < points; p++) {
      var x1 = centre.x + radius1 * math.cos(math.pi * 2 / points * p);
      var y1 = centre.y + radius2 * math.sin(math.pi * 2 / points * p);

      var x2 = centre.x + radius1 * math.cos(math.pi * 2 / points * (p + 1));
      var y2 = centre.y + radius2 * math.sin(math.pi * 2 / points * (p + 1));

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    polygon.lines = lines;

    polygon.params = {
      radius: radius,
      angle: angle
    };

    polygon.name = "polygon";

    return polygon;
  };

  var makeCrosshatch = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points1 = 2 + Rp.bandomInt(6, 2);
    let points2 = 2 + Rp.bandomInt(6, 2);
    let angle = math.random(0, 2 * math.pi);
    let isBordered = math.random(0, 1) < 0.5;

    let lines = [];

    for (let p1 = (isBordered ? 0 : 1); p1 < (isBordered ? points1 + 1 : points1); p1++) {
      let x1 = radius * (-1 + 2 / points1 * p1);
      let y1 = -radius;

      let x2 = x1;
      let y2 = radius;

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    for (let p2 = (isBordered ? 0 : 1); p2 < (isBordered ? points2 + 1 : points2); p2++) {
      let x1 = -radius;
      let y1 = radius * (-1 + 2 / points2 * p2);

      let x2 = radius;
      let y2 = y1;

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      points1: points1,
      points2: points2,
      isBordered: isBordered,
      angle: angle
    };

    shape.name = "crosshatch";

    return shape;
  };

  var makeZigzag = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points = 3 + Rp.bandomInt(8, 2);
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p = 0; p < points; p++) {

      let x1 = radius * (p % 2 ? 1 : -1);
      let x2 = -x1;

      let y1 = radius - (2 * radius) / points * p;
      let y2 = radius - (2 * radius) / points * (p + 1);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      points: points,
      angle: angle
    };

    shape.name = "zigzag";

    return shape;
  };

  var makeWavy = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points = 50; // segments
    let angle = math.random(0, 2 * math.pi);

    let freq = math.randomInt(1, 9);
    let ampl = math.random(0, 1);
    let phase = math.random(0, 2 * math.pi);

    // reverse image
    let isHelix = (math.random() < 0.1);

    let lines = [];

    var pif = 2 * math.pi * freq / radius / 2;

    for (let p = 0; p < points; p++) {

      let x1 = -radius + (2 * radius) / points * p;
      let x2 = -radius + (2 * radius) / points * (p + 1);

      let y1 = ampl * math.cos(pif * x1 + phase);
      let y2 = ampl * math.cos(pif * x2 + phase);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));

      if (isHelix) {
        lines.push(makeLine(x1, -y1, x2, -y2, centre, angle));
      }
    }

    shape.lines = lines;

    shape.params = {
      freq: freq,
      ampl: ampl,
      phase: phase,
      radius: radius,
      helix: isHelix,
      angle: angle
    };

    shape.name = "wavy";

    return shape;
  };

  var makeCrescent = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points = 50; // segments
    let angle = math.random(0, 2 * math.pi);

    let freq = 0.5;
    let ampl = [math.random(0, 1), math.random(0, 1)];

    let isBead = (math.random() < 0.1);

    let lines = [];

    var pif = 2 * math.pi * freq / radius / 2;

    for (let arc = 0; arc < 2; arc++) {

      for (let p = 0; p < points; p++) {

        let x1 = -radius + (2 * radius) / points * p;
        let x2 = -radius + (2 * radius) / points * (p + 1);

        let y1 = ampl[arc] * math.cos(pif * x1);
        let y2 = ampl[arc] * math.cos(pif * x2);

        if (arc === 1 && isBead) {
          y1 = -y1;
          y2 = -y2;
        }

        lines.push(makeLine(x1, y1, x2, y2, centre, angle));
      }
    }

    shape.lines = lines;

    shape.params = {
      ampl: ampl,
      radius: radius,
      bead: isBead,
      angle: angle
    };

    shape.name = "crescent";

    return shape;
  };

  var makeEllipse = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius1 = math.random(0, 1);
    let radius2 = math.random(0, 1);
    let points = 50; // segments
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p = 0; p < points; p++) {

      var angle1 = math.pi * 2 / points * p;
      var angle2 = math.pi * 2 / points * (p + 1);

      var x1 = radius1 * math.cos(angle1);
      var y1 = radius2 * math.sin(angle1);
      var x2 = radius1 * math.cos(angle2);
      var y2 = radius2 * math.sin(angle2);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      radius1: radius1,
      radius2: radius2,
      angle: angle
    };

    shape.name = "ellipse";

    return shape;
  };

  var makeStar = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius1 = math.random(0, 1);
    let radius2 = math.random(0, 1);
    let points = 2 * (math.randomInt(3, 26));
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p = 0; p < points; p++) {

      var angle1 = math.pi * 2 / points * p;
      var angle2 = math.pi * 2 / points * (p + 1);

      var eradius1 = (p % 2 ? radius1 : radius2);
      var eradius2 = (p % 2 ? radius2 : radius1);

      var x1 = eradius1 * math.cos(angle1);
      var y1 = eradius1 * math.sin(angle1);
      var x2 = eradius2 * math.cos(angle2);
      var y2 = eradius2 * math.sin(angle2);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      radius1: radius1,
      radius2: radius2,
      angle: angle
    };

    shape.name = "star";

    return shape;
  };

  var makeAsterisk = function() {

    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let linesCount = 2 + Rp.bandomInt(7, 1);
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p1 = 0; p1 < linesCount; p1++) {
      lines.push(makeLine(-radius, 0, radius, 0, centre, math.pi * 2 / linesCount * p1 + angle));
    }

    shape.lines = lines;

    shape.params = {
      angle: angle
    };

    shape.name = "asterisk";

    return shape;
  };

  var makeArrow = function() {

    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    // stem
    lines.push(makeLine(-radius, 0, radius, 0, centre, angle));

    // arrow
    lines.push(makeLine(radius / 2, radius / 2, radius, 0, centre, angle));
    lines.push(makeLine(radius / 2, -radius / 2, radius, 0, centre, angle));

    shape.lines = lines;

    shape.params = {
      angle: angle
    };

    shape.name = "arrow";

    return shape;
  };

  //---

  exports.shapers = [
    {
      fn: function() {

        return {
          name: "polygon",
          make: () => {

            return makePolygon();
          }
        };
      },
      weight: 4,
    },
    {
      fn: function() {

        return {
          name: "crosshatch",
          make: () => {

            return makeCrosshatch();
          }
        };
      },
      weight: 1,
    },
    {
      fn: function() {

        return {
          name: "asterisk",
          make: () => {

            return makeAsterisk();
          }
        };
      },
      weight: 1,
    },
    {
      fn: function() {

        return {
          name: "arrow",
          make: () => {

            return makeArrow();
          }
        };
      },
      weight: 1,
    },
    {
      fn: function() {

        return {
          name: "zigzag",
          make: () => {

            return makeZigzag();
          }
        };
      },
      weight: 1
    },
    {
      fn: function() {

        return {
          name: "wavy",
          make: () => {

            return makeWavy();
          }
        };
      },
      weight: 4
    },
    {
      fn: function() {

        return {
          name: "crescent",
          make: () => {

            return makeCrescent();
          }
        };
      },
      weight: 1
    },
    {
      fn: function() {

        return {
          name: "ellipse",
          make: () => {

            return makeEllipse();
          }
        };
      },
      weight: 1
    },
    {
      fn: function() {

        return {
          name: "star",
          make: () => {

            return makeStar();
          }
        };
      },
      weight: 1
    }
  ];
}());
<commit_msg>log radii<commit_after>(function() {

  "use strict";

  var math = require('mathjs');

  // var R = require('ramda');
  var Rp = require('./plus-fp/plus-fp');

  var rotate = function(point, centre, angle) {

    // assumes zero centre

    var x = point.x - centre.x;
    var y = point.y - centre.y;

    if ((x !== 0) || (y !== 0)) {
      var r = math.sqrt(x * x + y * y);
      var theta = math.atan2(y, x);

      theta += angle;

      x = r * math.cos(theta);
      y = r * math.sin(theta);

      x += centre.x;
      y += centre.y;
    }

    return {
      x: x,
      y: y
    };
  };

  var makeLine = function(x1, y1, x2, y2, centre, angle) {

    let point1 = {
      x: x1,
      y: y1
    };

    let point2 = {
      x: x2,
      y: y2
    };

    point1 = rotate(point1, centre, angle);
    point2 = rotate(point2, centre, angle);

    return {
      p1: point1,
      p2: point2
    };
  };

  var makePolygon = () => {

    let polygon = {};

    var centre = {
      x: 0,
      y: 0
    };

    var points = 3 + Rp.bandomInt(6, 2);
    var radius1 = math.random(0, 1);
    var radius2 = math.random(0, 1);
    var angle = math.random(0, 2 * math.pi);

    var lines = [];

    for (var p = 0; p < points; p++) {
      var x1 = centre.x + radius1 * math.cos(math.pi * 2 / points * p);
      var y1 = centre.y + radius2 * math.sin(math.pi * 2 / points * p);

      var x2 = centre.x + radius1 * math.cos(math.pi * 2 / points * (p + 1));
      var y2 = centre.y + radius2 * math.sin(math.pi * 2 / points * (p + 1));

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    polygon.lines = lines;

    polygon.params = {
      radius1: radius1,
      radius2: radius2,
      angle: angle
    };

    polygon.name = "polygon";

    return polygon;
  };

  var makeCrosshatch = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points1 = 2 + Rp.bandomInt(6, 2);
    let points2 = 2 + Rp.bandomInt(6, 2);
    let angle = math.random(0, 2 * math.pi);
    let isBordered = math.random(0, 1) < 0.5;

    let lines = [];

    for (let p1 = (isBordered ? 0 : 1); p1 < (isBordered ? points1 + 1 : points1); p1++) {
      let x1 = radius * (-1 + 2 / points1 * p1);
      let y1 = -radius;

      let x2 = x1;
      let y2 = radius;

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    for (let p2 = (isBordered ? 0 : 1); p2 < (isBordered ? points2 + 1 : points2); p2++) {
      let x1 = -radius;
      let y1 = radius * (-1 + 2 / points2 * p2);

      let x2 = radius;
      let y2 = y1;

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      points1: points1,
      points2: points2,
      isBordered: isBordered,
      angle: angle
    };

    shape.name = "crosshatch";

    return shape;
  };

  var makeZigzag = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points = 3 + Rp.bandomInt(8, 2);
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p = 0; p < points; p++) {

      let x1 = radius * (p % 2 ? 1 : -1);
      let x2 = -x1;

      let y1 = radius - (2 * radius) / points * p;
      let y2 = radius - (2 * radius) / points * (p + 1);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      points: points,
      angle: angle
    };

    shape.name = "zigzag";

    return shape;
  };

  var makeWavy = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points = 50; // segments
    let angle = math.random(0, 2 * math.pi);

    let freq = math.randomInt(1, 9);
    let ampl = math.random(0, 1);
    let phase = math.random(0, 2 * math.pi);

    // reverse image
    let isHelix = (math.random() < 0.1);

    let lines = [];

    var pif = 2 * math.pi * freq / radius / 2;

    for (let p = 0; p < points; p++) {

      let x1 = -radius + (2 * radius) / points * p;
      let x2 = -radius + (2 * radius) / points * (p + 1);

      let y1 = ampl * math.cos(pif * x1 + phase);
      let y2 = ampl * math.cos(pif * x2 + phase);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));

      if (isHelix) {
        lines.push(makeLine(x1, -y1, x2, -y2, centre, angle));
      }
    }

    shape.lines = lines;

    shape.params = {
      freq: freq,
      ampl: ampl,
      phase: phase,
      radius: radius,
      helix: isHelix,
      angle: angle
    };

    shape.name = "wavy";

    return shape;
  };

  var makeCrescent = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let points = 50; // segments
    let angle = math.random(0, 2 * math.pi);

    let freq = 0.5;
    let ampl = [math.random(0, 1), math.random(0, 1)];

    let isBead = (math.random() < 0.1);

    let lines = [];

    var pif = 2 * math.pi * freq / radius / 2;

    for (let arc = 0; arc < 2; arc++) {

      for (let p = 0; p < points; p++) {

        let x1 = -radius + (2 * radius) / points * p;
        let x2 = -radius + (2 * radius) / points * (p + 1);

        let y1 = ampl[arc] * math.cos(pif * x1);
        let y2 = ampl[arc] * math.cos(pif * x2);

        if (arc === 1 && isBead) {
          y1 = -y1;
          y2 = -y2;
        }

        lines.push(makeLine(x1, y1, x2, y2, centre, angle));
      }
    }

    shape.lines = lines;

    shape.params = {
      ampl: ampl,
      radius: radius,
      bead: isBead,
      angle: angle
    };

    shape.name = "crescent";

    return shape;
  };

  var makeEllipse = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius1 = math.random(0, 1);
    let radius2 = math.random(0, 1);
    let points = 50; // segments
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p = 0; p < points; p++) {

      var angle1 = math.pi * 2 / points * p;
      var angle2 = math.pi * 2 / points * (p + 1);

      var x1 = radius1 * math.cos(angle1);
      var y1 = radius2 * math.sin(angle1);
      var x2 = radius1 * math.cos(angle2);
      var y2 = radius2 * math.sin(angle2);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      radius1: radius1,
      radius2: radius2,
      angle: angle
    };

    shape.name = "ellipse";

    return shape;
  };

  var makeStar = function() {
    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius1 = math.random(0, 1);
    let radius2 = math.random(0, 1);
    let points = 2 * (math.randomInt(3, 26));
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p = 0; p < points; p++) {

      var angle1 = math.pi * 2 / points * p;
      var angle2 = math.pi * 2 / points * (p + 1);

      var eradius1 = (p % 2 ? radius1 : radius2);
      var eradius2 = (p % 2 ? radius2 : radius1);

      var x1 = eradius1 * math.cos(angle1);
      var y1 = eradius1 * math.sin(angle1);
      var x2 = eradius2 * math.cos(angle2);
      var y2 = eradius2 * math.sin(angle2);

      lines.push(makeLine(x1, y1, x2, y2, centre, angle));
    }

    shape.lines = lines;

    shape.params = {
      radius1: radius1,
      radius2: radius2,
      angle: angle
    };

    shape.name = "star";

    return shape;
  };

  var makeAsterisk = function() {

    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let linesCount = 2 + Rp.bandomInt(7, 1);
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    for (let p1 = 0; p1 < linesCount; p1++) {
      lines.push(makeLine(-radius, 0, radius, 0, centre, math.pi * 2 / linesCount * p1 + angle));
    }

    shape.lines = lines;

    shape.params = {
      angle: angle
    };

    shape.name = "asterisk";

    return shape;
  };

  var makeArrow = function() {

    let shape = {};

    var centre = {
      x: 0,
      y: 0
    };

    let radius = math.random(0, 1);
    let angle = math.random(0, 2 * math.pi);

    let lines = [];

    // stem
    lines.push(makeLine(-radius, 0, radius, 0, centre, angle));

    // arrow
    lines.push(makeLine(radius / 2, radius / 2, radius, 0, centre, angle));
    lines.push(makeLine(radius / 2, -radius / 2, radius, 0, centre, angle));

    shape.lines = lines;

    shape.params = {
      angle: angle
    };

    shape.name = "arrow";

    return shape;
  };

  //---

  exports.shapers = [
    {
      fn: function() {

        return {
          name: "polygon",
          make: () => {

            return makePolygon();
          }
        };
      },
      weight: 4,
    },
    {
      fn: function() {

        return {
          name: "crosshatch",
          make: () => {

            return makeCrosshatch();
          }
        };
      },
      weight: 1,
    },
    {
      fn: function() {

        return {
          name: "asterisk",
          make: () => {

            return makeAsterisk();
          }
        };
      },
      weight: 1,
    },
    {
      fn: function() {

        return {
          name: "arrow",
          make: () => {

            return makeArrow();
          }
        };
      },
      weight: 1,
    },
    {
      fn: function() {

        return {
          name: "zigzag",
          make: () => {

            return makeZigzag();
          }
        };
      },
      weight: 1
    },
    {
      fn: function() {

        return {
          name: "wavy",
          make: () => {

            return makeWavy();
          }
        };
      },
      weight: 4
    },
    {
      fn: function() {

        return {
          name: "crescent",
          make: () => {

            return makeCrescent();
          }
        };
      },
      weight: 1
    },
    {
      fn: function() {

        return {
          name: "ellipse",
          make: () => {

            return makeEllipse();
          }
        };
      },
      weight: 1
    },
    {
      fn: function() {

        return {
          name: "star",
          make: () => {

            return makeStar();
          }
        };
      },
      weight: 1
    }
  ];
}());
<|endoftext|>


<commit_before>import type { Server } from 'http';
import type { Socket } from 'net';

declare type express$RouterOptions = {
  caseSensitive?: boolean,
  mergeParams?: boolean,
  strict?: boolean
};

declare class express$RequestResponseBase {
  app: express$Application;
  get(field: string): string | void;
}

declare class express$Request extends http$IncomingMessage mixins express$RequestResponseBase {
  baseUrl: string;
  body: any;
  cookies: {[cookie: string]: string};
  connection: Socket;
  fresh: boolean;
  hostname: string;
  ip: string;
  ips: Array<string>;
  method: string;
  originalUrl: string;
  params: {[param: string]: string};
  path: string;
  protocol: 'https' | 'http';
  query: {[name: string]: string};
  route: string;
  secure: boolean;
  signedCookies: {[signedCookie: string]: string};
  stale: boolean;
  subdomains: Array<string>;
  xhr: boolean;
  accepts(types: string): string | false;
  acceptsCharsets(...charsets: Array<string>): string | false;
  acceptsEncodings(...encoding: Array<string>): string | false;
  acceptsLanguages(...lang: Array<string>): string | false;
  header(field: string): string | void;
  is(type: string): boolean;
  param(name: string, defaultValue?: string): string | void;
}

declare type express$CookieOptions = {
  domain?: string,
  encode?: (value: string) => string,
  expires?: Date,
  httpOnly?: boolean,
  maxAge?: number,
  path?: string,
  secure?: boolean,
  signed?: boolean
};

declare type express$RenderCallback = (err: Error | null, html?: string) => mixed;

declare type express$SendFileOptions = {
  maxAge?: number,
  root?: string,
  lastModified?: boolean,
  headers?: {[name: string]: string},
  dotfiles?: 'allow' | 'deny' | 'ignore'
};

declare class express$Response extends http$ServerResponse mixins express$RequestResponseBase {
  headersSent: boolean;
  locals: {[name: string]: mixed};
  append(field: string, value?: string): this;
  attachment(filename?: string): this;
  cookie(name: string, value: string, options?: express$CookieOptions): this;
  clearCookie(name: string, options?: express$CookieOptions): this;
  download(path: string, filename?: string, callback?: (err?: ?Error) => void): this;
  format(typesObject: {[type: string]: Function}): this;
  json(body?: mixed): this;
  jsonp(body?: mixed): this;
  links(links: {[name: string]: string}): this;
  location(path: string): this;
  redirect(url: string, ...args: Array<void>): this;
  redirect(status: number, url: string, ...args: Array<void>): this;
  render(view: string, locals?: {[name: string]: mixed}, callback?: express$RenderCallback): this;
  send(body?: mixed): this;
  sendFile(path: string, options?: express$SendFileOptions, callback?: (err?: ?Error) => mixed): this;
  sendStatus(statusCode: number): this;
  header(field: string, value?: string): this;
  header(headers: {[name: string]: string}): this;
  set(field: string, value?: string|string[]): this;
  set(headers: {[name: string]: string}): this;
  status(statusCode: number): this;
  type(type: string): this;
  vary(field: string): this;
}

declare type express$NextFunction = (err?: ?Error | 'route') => mixed;
declare type express$Middleware =
  ((req: express$Request, res: express$Response, next: express$NextFunction) => mixed) |
  ((error: ?Error, req: express$Request, res: express$Response, next: express$NextFunction) => mixed);
declare interface express$RouteMethodType<T> {
  (middleware: express$Middleware): T;
  (...middleware: Array<express$Middleware>): T;
  (path: string|RegExp|string[], ...middleware: Array<express$Middleware>): T;
}
declare class express$Route {
  all: express$RouteMethodType<this>;
  get: express$RouteMethodType<this>;
  post: express$RouteMethodType<this>;
  put: express$RouteMethodType<this>;
  head: express$RouteMethodType<this>;
  delete: express$RouteMethodType<this>;
  options: express$RouteMethodType<this>;
  trace: express$RouteMethodType<this>;
  copy: express$RouteMethodType<this>;
  lock: express$RouteMethodType<this>;
  mkcol: express$RouteMethodType<this>;
  move: express$RouteMethodType<this>;
  purge: express$RouteMethodType<this>;
  propfind: express$RouteMethodType<this>;
  proppatch: express$RouteMethodType<this>;
  unlock: express$RouteMethodType<this>;
  report: express$RouteMethodType<this>;
  mkactivity: express$RouteMethodType<this>;
  checkout: express$RouteMethodType<this>;
  merge: express$RouteMethodType<this>;

  // @TODO Missing 'm-search' but get flow illegal name error.

  notify: express$RouteMethodType<this>;
  subscribe: express$RouteMethodType<this>;
  unsubscribe: express$RouteMethodType<this>;
  patch: express$RouteMethodType<this>;
  search: express$RouteMethodType<this>;
  connect: express$RouteMethodType<this>;
}

declare class express$Router extends express$Route {
  constructor(options?: express$RouterOptions): void;
  route(path: string): express$Route;
  static (options?: express$RouterOptions): express$Router;
  use(middleware: express$Middleware): this;
  use(...middleware: Array<express$Middleware>): this;
  use(path: string|RegExp|string[], ...middleware: Array<express$Middleware>): this;
  use(path: string, router: express$Router): this;
  handle(req: http$IncomingMessage, res: http$ServerResponse, next: express$NextFunction): void;

  // Can't use regular callable signature syntax due to https://github.com/facebook/flow/issues/3084
  $call: (req: http$IncomingMessage, res: http$ServerResponse, next?: ?express$NextFunction) => void;
}

declare class express$Application extends express$Router mixins events$EventEmitter {
  constructor(): void;
  locals: {[name: string]: mixed};
  mountpath: string;
  listen(port: number, hostname?: string, backlog?: number, callback?: (err?: ?Error) => mixed): Server;
  listen(port: number, hostname?: string, callback?: (err?: ?Error) => mixed): Server;
  listen(port: number, callback?: (err?: ?Error) => mixed): Server;
  listen(path: string, callback?: (err?: ?Error) => mixed): Server;
  listen(handle: Object, callback?: (err?: ?Error) => mixed): Server;
  disable(name: string): void;
  disabled(name: string): boolean;
  enable(name: string): express$Application;
  enabled(name: string): boolean;
  engine(name: string, callback: Function): void;
  /**
   * Mixed will not be taken as a value option. Issue around using the GET http method name and the get for settings.
   */
  //   get(name: string): mixed;
  set(name: string, value: mixed): mixed;
  render(name: string, optionsOrFunction: {[name: string]: mixed}, callback: express$RenderCallback): void;
  handle(req: http$IncomingMessage, res: http$ServerResponse, next?: ?express$NextFunction): void;
}

declare module 'express' {
  declare function serveStatic(root: string, options?: Object): express$Middleware;

  declare export type RouterOptions = express$RouterOptions;
  declare export type CookieOptions = express$CookieOptions;
  declare export type Middleware = express$Middleware;
  declare export type NextFunction = express$NextFunction;
  declare export type $Response = express$Response;
  declare export type $Request = express$Request;
  declare export type $Application = express$Application;

  declare module.exports: {
    (): express$Application, // If you try to call like a function, it will use this signature
    static: serveStatic, // `static` property on the function
    Router: typeof express$Router, // `Router` property on the function
  };
}
<commit_msg>Express: Fixing static function (#1072)<commit_after>import type { Server } from 'http';
import type { Socket } from 'net';

declare type express$RouterOptions = {
  caseSensitive?: boolean,
  mergeParams?: boolean,
  strict?: boolean
};

declare class express$RequestResponseBase {
  app: express$Application;
  get(field: string): string | void;
}

declare class express$Request extends http$IncomingMessage mixins express$RequestResponseBase {
  baseUrl: string;
  body: any;
  cookies: {[cookie: string]: string};
  connection: Socket;
  fresh: boolean;
  hostname: string;
  ip: string;
  ips: Array<string>;
  method: string;
  originalUrl: string;
  params: {[param: string]: string};
  path: string;
  protocol: 'https' | 'http';
  query: {[name: string]: string};
  route: string;
  secure: boolean;
  signedCookies: {[signedCookie: string]: string};
  stale: boolean;
  subdomains: Array<string>;
  xhr: boolean;
  accepts(types: string): string | false;
  acceptsCharsets(...charsets: Array<string>): string | false;
  acceptsEncodings(...encoding: Array<string>): string | false;
  acceptsLanguages(...lang: Array<string>): string | false;
  header(field: string): string | void;
  is(type: string): boolean;
  param(name: string, defaultValue?: string): string | void;
}

declare type express$CookieOptions = {
  domain?: string,
  encode?: (value: string) => string,
  expires?: Date,
  httpOnly?: boolean,
  maxAge?: number,
  path?: string,
  secure?: boolean,
  signed?: boolean
};

declare type express$RenderCallback = (err: Error | null, html?: string) => mixed;

declare type express$SendFileOptions = {
  maxAge?: number,
  root?: string,
  lastModified?: boolean,
  headers?: {[name: string]: string},
  dotfiles?: 'allow' | 'deny' | 'ignore'
};

declare class express$Response extends http$ServerResponse mixins express$RequestResponseBase {
  headersSent: boolean;
  locals: {[name: string]: mixed};
  append(field: string, value?: string): this;
  attachment(filename?: string): this;
  cookie(name: string, value: string, options?: express$CookieOptions): this;
  clearCookie(name: string, options?: express$CookieOptions): this;
  download(path: string, filename?: string, callback?: (err?: ?Error) => void): this;
  format(typesObject: {[type: string]: Function}): this;
  json(body?: mixed): this;
  jsonp(body?: mixed): this;
  links(links: {[name: string]: string}): this;
  location(path: string): this;
  redirect(url: string, ...args: Array<void>): this;
  redirect(status: number, url: string, ...args: Array<void>): this;
  render(view: string, locals?: {[name: string]: mixed}, callback?: express$RenderCallback): this;
  send(body?: mixed): this;
  sendFile(path: string, options?: express$SendFileOptions, callback?: (err?: ?Error) => mixed): this;
  sendStatus(statusCode: number): this;
  header(field: string, value?: string): this;
  header(headers: {[name: string]: string}): this;
  set(field: string, value?: string|string[]): this;
  set(headers: {[name: string]: string}): this;
  status(statusCode: number): this;
  type(type: string): this;
  vary(field: string): this;
}

declare type express$NextFunction = (err?: ?Error | 'route') => mixed;
declare type express$Middleware =
  ((req: express$Request, res: express$Response, next: express$NextFunction) => mixed) |
  ((error: ?Error, req: express$Request, res: express$Response, next: express$NextFunction) => mixed);
declare interface express$RouteMethodType<T> {
  (middleware: express$Middleware): T;
  (...middleware: Array<express$Middleware>): T;
  (path: string|RegExp|string[], ...middleware: Array<express$Middleware>): T;
}
declare class express$Route {
  all: express$RouteMethodType<this>;
  get: express$RouteMethodType<this>;
  post: express$RouteMethodType<this>;
  put: express$RouteMethodType<this>;
  head: express$RouteMethodType<this>;
  delete: express$RouteMethodType<this>;
  options: express$RouteMethodType<this>;
  trace: express$RouteMethodType<this>;
  copy: express$RouteMethodType<this>;
  lock: express$RouteMethodType<this>;
  mkcol: express$RouteMethodType<this>;
  move: express$RouteMethodType<this>;
  purge: express$RouteMethodType<this>;
  propfind: express$RouteMethodType<this>;
  proppatch: express$RouteMethodType<this>;
  unlock: express$RouteMethodType<this>;
  report: express$RouteMethodType<this>;
  mkactivity: express$RouteMethodType<this>;
  checkout: express$RouteMethodType<this>;
  merge: express$RouteMethodType<this>;

  // @TODO Missing 'm-search' but get flow illegal name error.

  notify: express$RouteMethodType<this>;
  subscribe: express$RouteMethodType<this>;
  unsubscribe: express$RouteMethodType<this>;
  patch: express$RouteMethodType<this>;
  search: express$RouteMethodType<this>;
  connect: express$RouteMethodType<this>;
}

declare class express$Router extends express$Route {
  constructor(options?: express$RouterOptions): void;
  route(path: string): express$Route;
  static (options?: express$RouterOptions): express$Router;
  use(middleware: express$Middleware): this;
  use(...middleware: Array<express$Middleware>): this;
  use(path: string|RegExp|string[], ...middleware: Array<express$Middleware>): this;
  use(path: string, router: express$Router): this;
  handle(req: http$IncomingMessage, res: http$ServerResponse, next: express$NextFunction): void;

  // Can't use regular callable signature syntax due to https://github.com/facebook/flow/issues/3084
  $call: (req: http$IncomingMessage, res: http$ServerResponse, next?: ?express$NextFunction) => void;
}

declare class express$Application extends express$Router mixins events$EventEmitter {
  constructor(): void;
  locals: {[name: string]: mixed};
  mountpath: string;
  listen(port: number, hostname?: string, backlog?: number, callback?: (err?: ?Error) => mixed): Server;
  listen(port: number, hostname?: string, callback?: (err?: ?Error) => mixed): Server;
  listen(port: number, callback?: (err?: ?Error) => mixed): Server;
  listen(path: string, callback?: (err?: ?Error) => mixed): Server;
  listen(handle: Object, callback?: (err?: ?Error) => mixed): Server;
  disable(name: string): void;
  disabled(name: string): boolean;
  enable(name: string): express$Application;
  enabled(name: string): boolean;
  engine(name: string, callback: Function): void;
  /**
   * Mixed will not be taken as a value option. Issue around using the GET http method name and the get for settings.
   */
  //   get(name: string): mixed;
  set(name: string, value: mixed): mixed;
  render(name: string, optionsOrFunction: {[name: string]: mixed}, callback: express$RenderCallback): void;
  handle(req: http$IncomingMessage, res: http$ServerResponse, next?: ?express$NextFunction): void;
}

declare module 'express' {
  declare export type RouterOptions = express$RouterOptions;
  declare export type CookieOptions = express$CookieOptions;
  declare export type Middleware = express$Middleware;
  declare export type NextFunction = express$NextFunction;
  declare export type $Response = express$Response;
  declare export type $Request = express$Request;
  declare export type $Application = express$Application;

  declare module.exports: {
    (): express$Application, // If you try to call like a function, it will use this signature
    static: (root: string, options?: Object) => express$Middleware, // `static` property on the function
    Router: typeof express$Router, // `Router` property on the function
  };
}
<|endoftext|>


<commit_before>/*!
 * BioQL®: An efficient Query Language for interpreting genome and proteome.
 * "Everything should be made as simple as possible, but not simpler."
 *                                                          - Albert Einstein.
 * ___________________________________________________________________________
 * CBBL®
 * ~~~~~
 * Computational Biology and Bioinformatics Laboratory
 * Υπολογιστικής Βιολογίας και Βιοπληροφορικής Εργαστήριο
 * ___________________________________________________________________________
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/]
 * @copyright : Sequømics Corporation [http://sequomics.com/]
 * ___________________________________________________________________________
 */

// Invoking strict mode.
"use strict";

// Module dependencies.
var fs    = require('fs');
var path  = require('path');

// Assigning a null.
var root  = null;
// Version Object Literal.
var VERSION = {
  CONFIG:   1,
  MAJOR:    0,
  MINOR:    0,
  MICRO:    1,
  PATCH:    'alpha',
  BRANCH:   'development'
};

// Module dependencies.
const exec    = require('child_process').exec;
const util    = require('util');

const git     = require('git-state');
const Promise = require('es6-promise').Promise;

// @function to export - "version.pinned".
function pin() {
  return version().then(function (v) {
    version.pinned = v;
  });
}

// @function for "version".
function version(callback) {
  // First, find the package.json as this will be our root.
  var promise = findPackage(path.dirname(module.parent.filename))
      .then(function (dir) {
        // Now, try to load the package.
        var v = require(path.resolve(dir, 'package.json')).version;
        if (v && v !== '0.0.0') {
          return v;
        }
        root = dir;
        // else we're in development, give the commit out...
        // get the last commit and whether the working dir is -/dirty/-,
        var promises = [
          branch().catch(function () {
            return 'master';
          }),
          commit().catch(function () {
            return '<none>';
          }),
          dirty().catch(function () {
            return 0;
          }),
        ];
        // use the cached result as the export.
        return Promise.all(promises).then(function (res) {
          var branch = res[0];
          var commit = res[1];
          var dirtyCount = parseInt(res[2], 10);
          var curr = branch + ': ' + commit;
          if (dirtyCount !== 0) {
            curr += ' (' + dirtyCount + ' dirty files.)';
          }
          return curr;
        });
      }).catch(function (error) {
        console.log(error.stack);
        throw error;
      });
      if (callback) {
        promise.then(function (res) {
          callback(null, res);
        }, callback);
      }
  return promise;
}

// @function for "findPackage" ----> from -/root/-.
function findPackage(dir) {
  if (dir === '/') {
    return Promise.reject(new Error('package not found!'));
  }
  return new Promise(function (resolve) {
    fs.stat(path.resolve(dir, 'package.json'), function (error, exists) {
      if (error || !exists) {
        return resolve(findPackage(path.resolve(dir, '..')));
      }
      resolve(dir);
    });
  });
}

// @function for "command".
function command(cmd) {
  return new Promise(function (resolve, reject) {
    exec(cmd, { cwd: root }, function (err, stdout, stderr) {
      var error = stderr.trim();
      if (error) {
        return reject(new Error(error));
      }
      resolve(stdout.split('\n').join(''));
    });
  });
}

// @function for "commit".
function commit() {
  return command('git rev-parse HEAD');
}
<commit_msg>Initial commit<commit_after>/*!
 * BioQL®: An efficient Query Language for interpreting genome and proteome.
 * "Everything should be made as simple as possible, but not simpler."
 *                                                          - Albert Einstein.
 * ___________________________________________________________________________
 * CBBL®
 * ~~~~~
 * Computational Biology and Bioinformatics Laboratory
 * Υπολογιστικής Βιολογίας και Βιοπληροφορικής Εργαστήριο
 * ___________________________________________________________________________
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/]
 * @copyright : Sequømics Corporation [http://sequomics.com/]
 * ___________________________________________________________________________
 */

// Invoking strict mode.
"use strict";

// Module dependencies.
var fs    = require('fs');
var path  = require('path');

// Assigning a null.
var root  = null;
// Version Object Literal.
var VERSION = {
  CONFIG:   1,
  MAJOR:    0,
  MINOR:    0,
  MICRO:    1,
  PATCH:    'alpha',
  BRANCH:   'development'
};

// Module dependencies.
const exec    = require('child_process').exec;
const util    = require('util');

const git     = require('git-state');
const Promise = require('es6-promise').Promise;

// @function to export - "version.pinned".
function pin() {
  return version().then(function (v) {
    version.pinned = v;
  });
}

// @function for "version".
function version(callback) {
  // First, find the package.json as this will be our root.
  var promise = findPackage(path.dirname(module.parent.filename))
      .then(function (dir) {
        // Now, try to load the package.
        var v = require(path.resolve(dir, 'package.json')).version;
        if (v && v !== '0.0.0') {
          return v;
        }
        root = dir;
        // else we're in development, give the commit out...
        // get the last commit and whether the working dir is -/dirty/-,
        var promises = [
          branch().catch(function () {
            return 'master';
          }),
          commit().catch(function () {
            return '<none>';
          }),
          dirty().catch(function () {
            return 0;
          }),
        ];
        // use the cached result as the export.
        return Promise.all(promises).then(function (res) {
          var branch = res[0];
          var commit = res[1];
          var dirtyCount = parseInt(res[2], 10);
          var curr = branch + ': ' + commit;
          if (dirtyCount !== 0) {
            curr += ' (' + dirtyCount + ' dirty files.)';
          }
          return curr;
        });
      }).catch(function (error) {
        console.log(error.stack);
        throw error;
      });
      if (callback) {
        promise.then(function (res) {
          callback(null, res);
        }, callback);
      }
  return promise;
}

// @function for "findPackage" ----> from -/root/-.
function findPackage(dir) {
  if (dir === '/') {
    return Promise.reject(new Error('package not found!'));
  }
  return new Promise(function (resolve) {
    fs.stat(path.resolve(dir, 'package.json'), function (error, exists) {
      if (error || !exists) {
        return resolve(findPackage(path.resolve(dir, '..')));
      }
      resolve(dir);
    });
  });
}

// @function for "command".
function command(cmd) {
  return new Promise(function (resolve, reject) {
    exec(cmd, { cwd: root }, function (err, stdout, stderr) {
      var error = stderr.trim();
      if (error) {
        return reject(new Error(error));
      }
      resolve(stdout.split('\n').join(''));
    });
  });
}

// @function for "commit".
function commit() {
  return command('git rev-parse HEAD');
}

// @function for "branch".
function branch() {
  return command('git rev-parse --abbrev-ref HEAD');
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var async = require('async');
var readline = require('readline');

// The default version number is pulled from `package.json` which we assume is
// in the format `major.minor.build`. If it's not in this format then all we
// can do is choke and die. By default the build number is bumped by 1, but this
// can be overridden by the user.

function getDefaultVersion(repo, callback) {
    fs.readFile(repo + path.sep + 'package.json', function (err, data) {
        if (err) { callback(err); }

        var nextVersion;
        var currentVersion = JSON.parse(data).version;
        var build = currentVersion.replace(/[0-9]+\.[0-9]+\./, '');

        if (isNaN(build)) {
            callback('Invalid version number: %s' + currentVersion);
        }

        build++;
        nextVersion = currentVersion.replace(/[0-9]+$/, build);
        callback(null, nextVersion);
    });
}

// The user then gets a chance to override the derived default version number,
// which is then checked to ensure it's in the correct format.

function getVersion(defaultVersion, callback) {

    var prompt = 'Version number [' + defaultVersion + '] ';

    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    async.forever(
        function (next) {
            rl.question(prompt, function(answer) {
                if (answer === '') {
                    next(defaultVersion);
                } else if (/[0-9]+\.[0-9]+\.[0-9]+/.test(answer)) {
                    next(answer);
                } else {
                    console.log('Invalid version number: %s', answer);
                    next();
                }
            });
        },
        function (version) {
            rl.close();
            callback(null, version);
        }
    );
}

// Finally the version number is written back to the `package.json` file. This
// is done as a simple replace of the version string rather than writing out
// the whole package.json object read in when determining the default version
// number in order to avoid changing the order/layout of the rest of the file.

function setVersion(repo, version, callback) {
    var regex = /"version":\s*"[0-9]+\.[0-9]+\.[0-9]+"/;
    var replace = '"version": "' + version + '"';
    var file = repo + path.sep + 'package.json';

    fs.readFile(file, 'utf8', function(err, data) {
        if (err) { callback(err); }
        var result = data.replace(regex, replace);

        fs.writeFile(file, result, 'utf8', function(err) {
            callback(err);
        });
    });
}

module.exports.getDefaultVersion = getDefaultVersion;
module.exports.getVersion = getVersion;
module.exports.setVersion = setVersion;<commit_msg>Update docs for version.js<commit_after>var fs = require('fs');
var path = require('path');
var async = require('async');
var readline = require('readline');

// The default version number is pulled from `package.json` which we assume is
// in the format `major.minor.build`. If it's not in this format then all we
// can do is choke and die. By default the build number is bumped by 1, but this
// can be overridden by the user.

function getDefaultVersion(repo, callback) {
    fs.readFile(repo + path.sep + 'package.json', function (err, data) {
        if (err) { callback(err); }

        var nextVersion;
        var currentVersion = JSON.parse(data).version;
        var build = currentVersion.replace(/[0-9]+\.[0-9]+\./, '');

        if (isNaN(build)) {
            callback('Invalid version number: %s' + currentVersion);
        }

        build++;
        nextVersion = currentVersion.replace(/[0-9]+$/, build);
        callback(null, nextVersion);
    });
}

// The user then gets a chance to override the derived default version number,
// which is then checked to ensure it's in the correct format. There's a slight
// abuse of async.forever here which uses the feature that passing `next` a
// string exits the loop and passes the string to the callback. This is used
// to break out of the loop with the version number.

function getVersion(defaultVersion, callback) {

    var prompt = 'Version number [' + defaultVersion + '] ';

    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    async.forever(
        function (next) {
            rl.question(prompt, function(answer) {
                if (answer === '') {
                    next(defaultVersion);
                } else if (/[0-9]+\.[0-9]+\.[0-9]+/.test(answer)) {
                    next(answer);
                } else {
                    console.log('Invalid version number: %s', answer);
                    next();
                }
            });
        },
        function (version) {
            rl.close();
            callback(null, version);
        }
    );
}

// Finally the version number is written back to the `package.json` file. This
// is done as a simple replace of the version string rather than writing out
// the whole package.json object read in when determining the default version
// number in order to avoid changing the order/layout of the rest of the file.

function setVersion(repo, version, callback) {
    var regex = /"version":\s*"[0-9]+\.[0-9]+\.[0-9]+"/;
    var replace = '"version": "' + version + '"';
    var file = repo + path.sep + 'package.json';

    fs.readFile(file, 'utf8', function(err, data) {
        if (err) { callback(err); }
        var result = data.replace(regex, replace);

        fs.writeFile(file, result, 'utf8', function(err) {
            callback(err);
        });
    });
}

module.exports.getDefaultVersion = getDefaultVersion;
module.exports.getVersion = getVersion;
module.exports.setVersion = setVersion;<|endoftext|>


<commit_before>var totalPrice = 0;
var numProducts = 0;

$( document ).ready(function() {
    $("#button").click(function () {
    	$("#button").click(function(){});
    	load6Pages(1);
    });
});

// Loads six pages at a time and checks to see if he program has reached the end of the store.
// This allows the program to speed up the process by loading many pages at once instead of waiting for one to complete before starting the next one
// It also avoids the issue where the program does not know when to stop loading more pages
// This program accounts for an arbitrary amount of pages in a shopify store
function load6Pages (startingPageNum) {
	$.when(loadPage(startingPageNum),
		loadPage(startingPageNum + 1),
		loadPage(startingPageNum + 2),
		loadPage(startingPageNum + 3),
		loadPage(startingPageNum + 4),
		loadPage(startingPageNum + 5)
		)
	.done(function (pg1, pg2, pg3, pg4, pg5, pg6) {
		addPrices(pg1[0]);
		addPrices(pg2[0]);
		addPrices(pg3[0]);
		addPrices(pg4[0]);
		addPrices(pg5[0]);
		addPrices(pg6[0]);
		if (!(pg1[0].products.length != pg6[0].products.length || pg6[0].products.length == 0)) {
			load6Pages(startingPageNum + 6);
		} else {
			$("#price").text((totalPrice / 100).toFixed(2));
			$("#products").text(numProducts);
			totalPrice = 0;
			numProducts = 0;
		}
	});
}

function addPrices (pageObject, num) {
	for (var i = pageObject.products.length - 1; i >= 0; i--) {
		for (var j = pageObject.products[i].variants.length - 1; j >= 0; j--) {
			numProducts++;
			// The rounding is due to the errors found in floating numbers by making it into an integer
			totalPrice += Math.round(parseFloat(pageObject.products[i].variants[j].price) * 100);
		}
	}
}

var loadPage = function (pageNum) {
	var url = "http://shopicruit.myshopify.com/products.json?page=" + pageNum;
	return $.getJSON(url);
}<commit_msg>Added a dollar sign<commit_after>var totalPrice = 0;
var numProducts = 0;

$( document ).ready(function() {
    $("#button").click(function () {
    	$("#button").click(function(){});
    	load6Pages(1);
    });
});

// Loads six pages at a time and checks to see if he program has reached the end of the store.
// This allows the program to speed up the process by loading many pages at once instead of waiting for one to complete before starting the next one
// It also avoids the issue where the program does not know when to stop loading more pages
// This program accounts for an arbitrary amount of pages in a shopify store
function load6Pages (startingPageNum) {
	$.when(loadPage(startingPageNum),
		loadPage(startingPageNum + 1),
		loadPage(startingPageNum + 2),
		loadPage(startingPageNum + 3),
		loadPage(startingPageNum + 4),
		loadPage(startingPageNum + 5)
		)
	.done(function (pg1, pg2, pg3, pg4, pg5, pg6) {
		addPrices(pg1[0]);
		addPrices(pg2[0]);
		addPrices(pg3[0]);
		addPrices(pg4[0]);
		addPrices(pg5[0]);
		addPrices(pg6[0]);
		if (!(pg1[0].products.length != pg6[0].products.length || pg6[0].products.length == 0)) {
			load6Pages(startingPageNum + 6);
		} else {
			$("#price").text("$" + (totalPrice / 100).toFixed(2));
			$("#products").text(numProducts);
			totalPrice = 0;
			numProducts = 0;
		}
	});
}

function addPrices (pageObject, num) {
	for (var i = pageObject.products.length - 1; i >= 0; i--) {
		for (var j = pageObject.products[i].variants.length - 1; j >= 0; j--) {
			numProducts++;
			// The rounding is due to the errors found in floating numbers by making it into an integer
			totalPrice += Math.round(parseFloat(pageObject.products[i].variants[j].price) * 100);
		}
	}
}

var loadPage = function (pageNum) {
	var url = "http://shopicruit.myshopify.com/products.json?page=" + pageNum;
	return $.getJSON(url);
}<|endoftext|>


<commit_before>var priceNumRegex = new RegExp("(\\d+\.\\d+)");
var possibleIds = ["priceblock_ourprice", "priceblock_saleprice"];
var productTitleId = "productTitle";
var amznPriceElm = null;

function onError(error) {
    console.error(`AussieShopper : Error ${error}`);
}

function displayConvertedPrice(result) {
    var audRate = result.exchange_rate || 1;
    var priceArray = priceNumRegex.exec(amznPriceElm.textContent);
    var productTitleElm = document.getElementById(productTitleId);

    if (priceArray) {
        var audPrice = priceArray[0] * audRate;
        var previouslyDisplayedDiv = document.getElementById("as_price");
        var productTitle = "";

        if (previouslyDisplayedDiv) {
            previouslyDisplayedDiv.remove();
        }

        if(productTitleElm){
            productTitle = encodeURIComponent(productTitleElm.innerText);
        }

        var containingDiv = document.createElement('div');
        containingDiv.setAttribute('id', 'as_price');
        containingDiv.setAttribute('style', 'color: purple');

        // price span
        var priceSpan = document.createElement('span');
        var priceText = document.createTextNode(`AUD${audPrice.toFixed(2)}`);
        priceSpan.setAttribute('style', 'margin-right: 5px');
        priceSpan.appendChild(priceText);

        // link span and its anchor
        var linkSpan = document.createElement('span');
        var linkAnchor = document.createElement('a');
        var anchorText = document.createTextNode('Find on StaticIce');
        linkAnchor.setAttribute('href', `http://www.staticice.com.au/cgi-bin/search.cgi?q=${productTitle}`);
        linkAnchor.setAttribute('target', '_blank');
        linkAnchor.appendChild(anchorText);

        linkSpan.appendChild(linkAnchor);

        // append new elements to the price block
        containingDiv.appendChild(priceSpan);
        containingDiv.appendChild(linkSpan);
        amznPriceElm.parentElement.appendChild(containingDiv);
    }

}

function lookForPrice() {
    var priceElm = null;

    for (priceIdKey in possibleIds) {
        priceElm = document.getElementById(possibleIds[priceIdKey]);

        if (priceElm) {
            amznPriceElm = priceElm;
            break;
        }
    }

    if (priceElm) {
        var getting = browser.storage.local.get("exchange_rate");
        getting.then(displayConvertedPrice, onError);
    }
}

lookForPrice();<commit_msg>due to a bug in firefox pre 52 storage retreival, i had to hardcode in a fixed value for the exchange rate. 52 will be released in around 2 weeks so all should be good by then.<commit_after>var priceNumRegex = new RegExp("(\\d+\.\\d+)");
var possibleIds = ["priceblock_ourprice", "priceblock_saleprice"];
var productTitleId = "productTitle";
var amznPriceElm = null;

function onError(error) {
    console.error(`AussieShopper : Error ${error}`);
}

function displayConvertedPrice(result) {
    var audRate = result.exchange_rate || 1.3;
    var priceArray = priceNumRegex.exec(amznPriceElm.textContent);
    var productTitleElm = document.getElementById(productTitleId);

    if (priceArray) {
        var audPrice = priceArray[0] * audRate;
        var previouslyDisplayedDiv = document.getElementById("as_price");
        var productTitle = "";

        if (previouslyDisplayedDiv) {
            previouslyDisplayedDiv.remove();
        }

        if(productTitleElm){
            productTitle = encodeURIComponent(productTitleElm.innerText);
        }

        var containingDiv = document.createElement('div');
        containingDiv.setAttribute('id', 'as_price');
        containingDiv.setAttribute('style', 'color: purple');

        // price span
        var priceSpan = document.createElement('span');
        var priceText = document.createTextNode(`AUD${audPrice.toFixed(2)}`);
        priceSpan.setAttribute('style', 'margin-right: 5px');
        priceSpan.appendChild(priceText);

        // link span and its anchor
        var linkSpan = document.createElement('span');
        var linkAnchor = document.createElement('a');
        var anchorText = document.createTextNode('Find on StaticIce');
        linkAnchor.setAttribute('href', `http://www.staticice.com.au/cgi-bin/search.cgi?q=${productTitle}`);
        linkAnchor.setAttribute('target', '_blank');
        linkAnchor.appendChild(anchorText);

        linkSpan.appendChild(linkAnchor);

        // append new elements to the price block
        containingDiv.appendChild(priceSpan);
        containingDiv.appendChild(linkSpan);
        amznPriceElm.parentElement.appendChild(containingDiv);
    }

}

function lookForPrice() {
    var priceElm = null;

    for (priceIdKey in possibleIds) {
        priceElm = document.getElementById(possibleIds[priceIdKey]);

        if (priceElm) {
            amznPriceElm = priceElm;
            break;
        }
    }

    if (priceElm) {
        var getting = browser.storage.local.get("exchange_rate");
        getting.then(displayConvertedPrice, onError);
    }
}

lookForPrice();<|endoftext|>


<commit_before>require("videojs-quality-picker");

var attachVideojsStreamrootProvider = function (window, videojs, Hls) {
    function StreamrootProviderHLS (source, tech) {
        tech.name_ = 'streamrootHLS';

        var _video = tech.el();
        var _hls;
        var _errorCounts = {};

        _video.addEventListener('error', function(evt) {
            var errorTxt,mediaError=evt.currentTarget.error;

            switch(mediaError.code) {
                case mediaError.MEDIA_ERR_ABORTED:
                    errorTxt = "You aborted the video playback";
                    break;
                case mediaError.MEDIA_ERR_DECODE:
                    errorTxt = "The video playback was aborted due to a corruption problem or because the video used features your browser did not support";
                    _handleMediaError();
                    break;
                case mediaError.MEDIA_ERR_NETWORK:
                    errorTxt = "A network error caused the video download to fail part-way";
                    break;
                case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
                    errorTxt = "The video could not be loaded, either because the server or network failed or because the format is not supported";
                    break;
            }

            console.error("MEDIA_ERROR: ", errorTxt);
        });

        function initialize() {
            var hlsjsConfig = tech.options_.hlsjsConfig || {};

            _hls = new Hls(hlsjsConfig);
            _hls.on(Hls.Events.ERROR, function(event, data) { _onError(event, data, tech, _errorCounts) });
            _hls.on(Hls.Events.MANIFEST_PARSED, _onMetaData);

            _hls.attachMedia(_video);
        }

        this.dispose = function () {
            _hls.destroy();
        };

        function load(source) {
            _hls.loadSource(source.src);
        }

        function switchQuality(qualityId, trackType) {
            _hls.nextLevel = qualityId;
        }

        function _handleMediaError() {
            if (_errorCounts[Hls.ErrorTypes.MEDIA_ERROR] === 1) {
                console.info("trying to recover media error");
                _hls.recoverMediaError();
            } else if (_errorCounts[Hls.ErrorTypes.MEDIA_ERROR] === 2) {
                console.info("2nd try to recover media error (by swapping audio codec");
                _hls.swapAudioCodec();
                _hls.recoverMediaError();
            } else if (_errorCounts[Hls.ErrorTypes.MEDIA_ERROR] > 2) {
                console.info("bubbling media error up to VIDEOJS");
                error.code = 3;
                tech.error = function() { return error; };
                tech.trigger('error');
            }
        }

        function _onError(event, data) {
            var error = {
              message: ('HLS.js error: ' + data.type + ' - fatal: ' + data.fatal + ' - ' + data.details),
            };
            console.error(error.message);

            // increment/set error count
            _errorCounts[data.type] ? _errorCounts[data.type] += 1 : _errorCounts[data.type] = 1;

            // implement simple error handling based on hls.js documentation (https://github.com/dailymotion/hls.js/blob/master/API.md#fifth-step-error-handling)
            if (data.fatal) {
                switch (data.type) {
                    case Hls.ErrorTypes.NETWORK_ERROR:
                        console.info("bubbling network error up to VIDEOJS");
                        error.code = 2;
                        tech.error = function() { return error; };
                        tech.trigger('error');
                        break;

                    case Hls.ErrorTypes.MEDIA_ERROR:
                        _handleMediaError();
                        break;

                    default:
                        // cannot recover
                        _hls.destroy();
                        console.info("bubbling error up to VIDEOJS");
                        tech.error = function() { return error; };
                        tech.trigger('error');
                        break;
                }
            }
        }

        function _onMetaData(event, data) {
            var cleanTracklist = [];

            if (data.levels.length > 1) {
                var autoLevel = {
                    id: -1,
                    label: "auto",
                    selected: -1 === _hls.manualLevel
                };
                cleanTracklist.push(autoLevel);
            }

            data.levels.forEach(function(level, index) {
                var quality = {}; // Don't write in level (shared reference with Hls.js)
                quality.id = index;
                quality.selected = index === _hls.manualLevel;
                quality.label = _levelLabel(level);

                cleanTracklist.push(quality);
            });

            var payload = {
                qualityData: {video: cleanTracklist},
                qualitySwitchCallback: switchQuality
            };

            tech.trigger('loadedqualitydata', payload);

            function _levelLabel(level) {
                if (level.height) return level.height + "p";
                else if (level.width) return Math.round(level.width * 9 / 16) + "p";
                else if (level.bitrate) return (level.bitrate / 1000) + "kbps";
                else return 0;
            }
        }

        initialize();
        load(source);
    }

    if (Hls.isSupported()) {
        videojs.getComponent('Html5').registerSourceHandler({

            canHandleSource: function (source) {

                var hlsTypeRE = /^application\/x-mpegURL$/i;
                var hlsExtRE = /\.m3u8/i;
                var result;

                if (hlsTypeRE.test(source.type)) {
                    result = 'probably';
                } else if (hlsExtRE.test(source.src)) {
                    result = 'maybe';
                } else {
                    result = '';
                }

                return result;
            },

            handleSource: function (source, tech) {

                if (tech.hlsProvider) {
                    tech.hlsProvider.dispose();
                }

                tech.hlsProvider = new StreamrootProviderHLS(source, tech);

                return tech.hlsProvider;
            }

        }, 0);

    } else {
        console.error("Hls.js is not supported in this browser!");
    }

    videojs.StreamrootProviderHLS = StreamrootProviderHLS;
};

module.exports = attachVideojsStreamrootProvider;
<commit_msg>indentation<commit_after>require("videojs-quality-picker");

var attachVideojsStreamrootProvider = function (window, videojs, Hls) {
    function StreamrootProviderHLS (source, tech) {
        tech.name_ = 'streamrootHLS';

        var _video = tech.el();
        var _hls;
        var _errorCounts = {};

        _video.addEventListener('error', function(evt) {
            var errorTxt,mediaError=evt.currentTarget.error;

            switch(mediaError.code) {
                case mediaError.MEDIA_ERR_ABORTED:
                    errorTxt = "You aborted the video playback";
                    break;
                case mediaError.MEDIA_ERR_DECODE:
                    errorTxt = "The video playback was aborted due to a corruption problem or because the video used features your browser did not support";
                    _handleMediaError();
                    break;
                case mediaError.MEDIA_ERR_NETWORK:
                    errorTxt = "A network error caused the video download to fail part-way";
                    break;
                case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
                    errorTxt = "The video could not be loaded, either because the server or network failed or because the format is not supported";
                    break;
            }

            console.error("MEDIA_ERROR: ", errorTxt);
        });

        function initialize() {
            var hlsjsConfig = tech.options_.hlsjsConfig || {};

            _hls = new Hls(hlsjsConfig);
            _hls.on(Hls.Events.ERROR, function(event, data) { _onError(event, data, tech, _errorCounts) });
            _hls.on(Hls.Events.MANIFEST_PARSED, _onMetaData);

            _hls.attachMedia(_video);
        }

        this.dispose = function () {
            _hls.destroy();
        };

        function load(source) {
            _hls.loadSource(source.src);
        }

        function switchQuality(qualityId, trackType) {
            _hls.nextLevel = qualityId;
        }

        function _handleMediaError() {
            if (_errorCounts[Hls.ErrorTypes.MEDIA_ERROR] === 1) {
                console.info("trying to recover media error");
                _hls.recoverMediaError();
            } else if (_errorCounts[Hls.ErrorTypes.MEDIA_ERROR] === 2) {
                console.info("2nd try to recover media error (by swapping audio codec");
                _hls.swapAudioCodec();
                _hls.recoverMediaError();
            } else if (_errorCounts[Hls.ErrorTypes.MEDIA_ERROR] > 2) {
                console.info("bubbling media error up to VIDEOJS");
                error.code = 3;
                tech.error = function() { return error; };
                tech.trigger('error');
            }
        }

        function _onError(event, data) {
            var error = {
                message: ('HLS.js error: ' + data.type + ' - fatal: ' + data.fatal + ' - ' + data.details),
            };
            console.error(error.message);

            // increment/set error count
            _errorCounts[data.type] ? _errorCounts[data.type] += 1 : _errorCounts[data.type] = 1;

            // implement simple error handling based on hls.js documentation (https://github.com/dailymotion/hls.js/blob/master/API.md#fifth-step-error-handling)
            if (data.fatal) {
                switch (data.type) {
                    case Hls.ErrorTypes.NETWORK_ERROR:
                        console.info("bubbling network error up to VIDEOJS");
                        error.code = 2;
                        tech.error = function() { return error; };
                        tech.trigger('error');
                        break;

                    case Hls.ErrorTypes.MEDIA_ERROR:
                        _handleMediaError();
                        break;

                    default:
                        // cannot recover
                        _hls.destroy();
                        console.info("bubbling error up to VIDEOJS");
                        tech.error = function() { return error; };
                        tech.trigger('error');
                        break;
                }
            }
        }

        function _onMetaData(event, data) {
            var cleanTracklist = [];

            if (data.levels.length > 1) {
                var autoLevel = {
                    id: -1,
                    label: "auto",
                    selected: -1 === _hls.manualLevel
                };
                cleanTracklist.push(autoLevel);
            }

            data.levels.forEach(function(level, index) {
                var quality = {}; // Don't write in level (shared reference with Hls.js)
                quality.id = index;
                quality.selected = index === _hls.manualLevel;
                quality.label = _levelLabel(level);

                cleanTracklist.push(quality);
            });

            var payload = {
                qualityData: {video: cleanTracklist},
                qualitySwitchCallback: switchQuality
            };

            tech.trigger('loadedqualitydata', payload);

            function _levelLabel(level) {
                if (level.height) return level.height + "p";
                else if (level.width) return Math.round(level.width * 9 / 16) + "p";
                else if (level.bitrate) return (level.bitrate / 1000) + "kbps";
                else return 0;
            }
        }

        initialize();
        load(source);
    }

    if (Hls.isSupported()) {
        videojs.getComponent('Html5').registerSourceHandler({

            canHandleSource: function (source) {

                var hlsTypeRE = /^application\/x-mpegURL$/i;
                var hlsExtRE = /\.m3u8/i;
                var result;

                if (hlsTypeRE.test(source.type)) {
                    result = 'probably';
                } else if (hlsExtRE.test(source.src)) {
                    result = 'maybe';
                } else {
                    result = '';
                }

                return result;
            },

            handleSource: function (source, tech) {

                if (tech.hlsProvider) {
                    tech.hlsProvider.dispose();
                }

                tech.hlsProvider = new StreamrootProviderHLS(source, tech);

                return tech.hlsProvider;
            }

        }, 0);

    } else {
        console.error("Hls.js is not supported in this browser!");
    }

    videojs.StreamrootProviderHLS = StreamrootProviderHLS;
};

module.exports = attachVideojsStreamrootProvider;
<|endoftext|>


<commit_before>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

"use strict";

var NeuronNavigator = function()
{
  this.widgetID = this.registerInstance();
  this.registerSource();
};

NeuronNavigator.prototype = {};
$.extend(NeuronNavigator.prototype, new InstanceRegistry());
$.extend(NeuronNavigator.prototype, new SkeletonSource());

/* Implement interfaces */

NeuronNavigator.prototype.getName = function()
{
    return "Neuron Navigator " + this.widgetID;
};

NeuronNavigator.prototype.destroy = function()
{
  this.unregisterInstance();
  this.unregisterSource();
};

NeuronNavigator.prototype.append = function() {};
NeuronNavigator.prototype.clear = function(source_chain) {};
NeuronNavigator.prototype.removeSkeletons = function() {};
NeuronNavigator.prototype.updateModels = function() {};

NeuronNavigator.prototype.getSelectedSkeletons = function() {
  return [];
};

NeuronNavigator.prototype.hasSkeleton = function(skeleton_id) {
  return false;
};

NeuronNavigator.prototype.getSelectedSkeletonModels = function() {
  return {};
};

NeuronNavigator.prototype.highlight = function(skeleton_id)
{
  return;
};

/* Non-interface methods */

NeuronNavigator.prototype.init_ui = function(container)
{
  // Create a navigation bar to see the current path of nodes
  var navigation_bar = document.createElement('div');
  navigation_bar.setAttribute('id', 'navigator_navi_bar' + this.widgetID);
  navigation_bar.setAttribute('class', 'navigator_navi_bar');
  container.appendChild(navigation_bar);

  // Create a containe where all the content of every node will be placed in
  var content = document.createElement('div');
  content.setAttribute('id', 'navigatior_content' + this.widgetID);
  content.setAttribute('class', 'navigator_content');
  container.appendChild(content);

  // Add home node as starting point without any parent
  var home_node = new NeuronNavigatorHomeNode(this.widgetID);
  home_node.link(this, null);
  this.select_node(home_node);
};

NeuronNavigator.prototype.select_node = function(node)
{
  // Set the navigation bar contents
  $('#navigator_navi_bar' + this.widgetID).empty().append(
      node.create_path(this));

  // Set the actual content
  $('#navigatior_content' + this.widgetID).empty().append(
      node.create_content(this));
};

/**
 * A filter container that keeps track of either an annotation, a user or a
 * neuron to be used as filter when selection data.
 */
var NeuronNavigatorFilter = function(annotation, user, neuron)
{
  this.annotation = annotation;
  this.user = user;
  this.neuron = neuron;
};

/**
 * A class representing a node in the graph of the navigator.
 */
var NeuronNavigatorNode = function(name)
{
  this.name = name;
  this.navigator = null;
  this.filters = null;
};

NeuronNavigatorNode.prototype.link = function(navigator, parent_node)
{
  this.navigator = navigator;
  this.parent_node = parent_node;
};

NeuronNavigatorNode.prototype.collect_filters = function()
{
  // Collect filters by reference
  if (this.parent_node) {
    var path_filters = this.parent_node.collect_filters();
    if (this.filters) {
      path_filters.push(this.filters);
    }
    return path_filters;
  } else {
    // The home node will return an empty list
    return [];
  }
};

NeuronNavigatorNode.prototype.create_path = function()
{
  var path_link = document.createElement('a');
  path_link.setAttribute('href', '#');
  path_link.setAttribute('class', 'navigator_navi_bar_element');
  path_link.innerHTML = this.name;
  $(path_link).click($.proxy(function() {
    this.navigator.select_node(this);
  }, this));

  if (this.parent_node) {
    var path_elements = this.parent_node.create_path();
    path_elements.push(document.createTextNode(" > "));
    path_elements.push(path_link);
    return path_elements;
  } else {
    return [path_link];
  }
};

NeuronNavigatorNode.prototype.create_content = function()
{
  return undefined;
};

NeuronNavigatorNode.prototype.create_annotations_link = function()
{
  var annotations_link = this.create_path_link("Annotations");
  $(annotations_link).click($.proxy(function() {
      var annotations_node = new NeuronNavigatorAnnotationsNode();
      annotations_node.link(this.navigator, this);
      this.navigator.select_node(annotations_node);
  }, this));

  return annotations_link;
};

NeuronNavigatorNode.prototype.create_users_link = function()
{
  var users_link = this.create_path_link("Users");
  $(users_link).click($.proxy(function() {
      var users_node = new NeuronNavigatorUsersNode();
      users_node.link(this.navigator, this);
      this.navigator.select_node(users_node);
  }, this));

  return users_link;
};

NeuronNavigatorNode.prototype.create_neurons_link = function()
{
  var neurons_link = this.create_path_link("Neurons");
  $(neurons_link).click($.proxy(function() {
      // TODO
  }, this));

  return neurons_link
};

NeuronNavigatorNode.prototype.create_path_link = function(text)
{
  var option = document.createElement('a');
  option.setAttribute('href', '#');
  option.setAttribute('class', 'navigator_content_option');
  // Add text to option, if passed
  if (text)
  {
    option.innerHTML = text;
  }

  return option;
};

/**
 * The home node of the navigator. It links to annotation
 * and users nodes.
 */
var NeuronNavigatorHomeNode = function()
{
  // A home node acts as the root node and has therefore no parent.
  this.link(null);
};

NeuronNavigatorHomeNode.prototype = {};
$.extend(NeuronNavigatorHomeNode.prototype, new NeuronNavigatorNode("Home"));

NeuronNavigatorHomeNode.prototype.create_content = function()
{
  var content = document.createElement('div');

  var annotations_link = this.create_annotations_link();
  var users_link = this.create_users_link();
  content.appendChild(annotations_link);
  content.appendChild(users_link);

  return content;
};

/**
 * The annotations node of the navigator. It links to annotations.
 */
var NeuronNavigatorAnnotationsNode = function() {};

NeuronNavigatorAnnotationsNode.prototype = {};
$.extend(NeuronNavigatorAnnotationsNode.prototype,
    new NeuronNavigatorNode("Annotations"));

NeuronNavigatorAnnotationsNode.prototype.create_content = function()
{
  var content = document.createElement('div');
  content.setAttribute('id', 'navigator_annotations_content' +
      this.navigator.widgetID);
  content.innerHTML = "Please wait while the available annotatios are requested";

  // Make node easily accessible in created methods
  var self = this;

  // Collect all filtered annotations into post data
  var filters = this.collect_filters();
  var post_data = {
    'ignored_annotations': filters.reduce(function(o, f) {
        if (f.annotation) {
          o.push(f.annotation);
        }
        return o;
      }, [])
  };

  // Get the list of currently available annotations
  requestQueue.register(django_url + project.id + '/annotations/list',
      'POST', post_data, function(status, data, text) {
        var e = $.parseJSON(data);
        if (status != 200) {
          alert("The server returned an unexpected status (" +
            status + ") with error message:\n" + text);
        } else {
          // Create a list of annotation links
          var annotations = e.map(function(a) {
            var annotations_link = self.create_path_link(a);
            $(annotations_link).click(function() {
                var annotations_node = new NeuronNavigatorAnnotationFilterNode(a);
                annotations_node.link(self.navigator, self);
                self.navigator.select_node(annotations_node);
            });
            return annotations_link;
          });
          // Add all annotation links
          $('#navigator_annotations_content' + self.navigator.widgetID).empty().
            append(annotations);
        }
      });

  return content;
};

/**
 * The users node of the navigator. It links to users.
 */
var NeuronNavigatorUsersNode = function() {};

NeuronNavigatorUsersNode.prototype = {};
$.extend(NeuronNavigatorUsersNode.prototype,
    new NeuronNavigatorNode("Users"));

NeuronNavigatorUsersNode.prototype.create_content = function()
{
  var content = document.createElement('div');
  content.setAttribute('id', 'navigator_users_content' +
      this.navigator.widgetID);
  content.innerHTML = "Please wait while the existing users are requested";

  // Make node easily accessible in created methods
  var self = this;

  // Collect all filtered annotations into post data
  var filters = this.collect_filters();
  var post_data = {
    'ignored_users': filters.reduce(function(o, f) {
        if (f.user) {
          o.push(f.user);
        }
        return o;
      }, [])
  };

  // Get the list of currently available annotations
  requestQueue.register(django_url + 'user-list',
      'POST', post_data, function(status, data, text) {
        var e = $.parseJSON(data);
        if (status != 200) {
          alert("The server returned an unexpected status (" +
            status + ") with error message:\n" + text);
        } else {
          // Create a list of user links
          var users = e.map(function(u) {
            var user_link = self.create_path_link(u.full_name +
                " (" + u.login + ")");
            $(user_link).click(function() {
                var filter_node = new NeuronNavigatorUserFilterNode(u);
                filter_node.link(self.navigator, self);
                self.navigator.select_node(filter_node);
            });
            return user_link;
          });
          // Add all annotation links
          $('#navigator_users_content' + self.navigator.widgetID).empty().
            append(users);
        }
      });

  return content;
};

/**
 * The annotation filter node of the navigator filters output based on the
 * existence of an annotations. The content it creates lists user, neuron,
 * annotation and co-annotation links.
 */
var NeuronNavigatorAnnotationFilterNode = function(included_annotation)
{
  this.filters = new NeuronNavigatorFilter(included_annotation)
  this.name = "A: " + included_annotation;
};

NeuronNavigatorAnnotationFilterNode.prototype = {};
$.extend(NeuronNavigatorAnnotationFilterNode.prototype,
    new NeuronNavigatorNode("Empty Annotation Filter"));

NeuronNavigatorAnnotationFilterNode.prototype.create_content = function()
{
  /* An annotation filter node, will display options to add ad user filter,
   * another annotation filter or to select a neuron.
   */
  var content = document.createElement('div');

  var annotations_link = this.create_annotations_link();
  content.appendChild(annotations_link);

  // Only show the users link, if there hasn't been one before
  var filters = this.collect_filters();
  var has_user_filter = filters.some(function(f) {
    return f.user;
  });
  if (!has_user_filter) {
    var users_link = this.create_users_link();
    content.appendChild(users_link);
  }

  var neurons_link = this.create_neurons_link();
  content.appendChild(neurons_link);

  return content;
};

/**
 * The user filter node of the navigator filters output based on the
 * ownership by a particular user. The content it creates lists user, neuron,
 * annotation and co-annotation links.
 */
var NeuronNavigatorUserFilterNode = function(included_user)
{
  this.filters = new NeuronNavigatorFilter(null, included_user.id)
  this.name = "U: " + included_user.login;
};

NeuronNavigatorUserFilterNode.prototype = {};
$.extend(NeuronNavigatorUserFilterNode.prototype,
    new NeuronNavigatorNode("Empty User Filter"));

NeuronNavigatorUserFilterNode.prototype.create_content = function()
{
  var content = document.createElement('div');

  var annotations_link = this.create_annotations_link();
  var neurons_link = this.create_neurons_link();
  content.appendChild(annotations_link);
  content.appendChild(neurons_link);

  return content;
};
<commit_msg>Neuron navigator: add neuron list node<commit_after>/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */

"use strict";

var NeuronNavigator = function()
{
  this.widgetID = this.registerInstance();
  this.registerSource();
};

NeuronNavigator.prototype = {};
$.extend(NeuronNavigator.prototype, new InstanceRegistry());
$.extend(NeuronNavigator.prototype, new SkeletonSource());

/* Implement interfaces */

NeuronNavigator.prototype.getName = function()
{
    return "Neuron Navigator " + this.widgetID;
};

NeuronNavigator.prototype.destroy = function()
{
  this.unregisterInstance();
  this.unregisterSource();
};

NeuronNavigator.prototype.append = function() {};
NeuronNavigator.prototype.clear = function(source_chain) {};
NeuronNavigator.prototype.removeSkeletons = function() {};
NeuronNavigator.prototype.updateModels = function() {};

NeuronNavigator.prototype.getSelectedSkeletons = function() {
  return [];
};

NeuronNavigator.prototype.hasSkeleton = function(skeleton_id) {
  return false;
};

NeuronNavigator.prototype.getSelectedSkeletonModels = function() {
  return {};
};

NeuronNavigator.prototype.highlight = function(skeleton_id)
{
  return;
};

/* Non-interface methods */

NeuronNavigator.prototype.init_ui = function(container)
{
  // Create a navigation bar to see the current path of nodes
  var navigation_bar = document.createElement('div');
  navigation_bar.setAttribute('id', 'navigator_navi_bar' + this.widgetID);
  navigation_bar.setAttribute('class', 'navigator_navi_bar');
  container.appendChild(navigation_bar);

  // Create a containe where all the content of every node will be placed in
  var content = document.createElement('div');
  content.setAttribute('id', 'navigatior_content' + this.widgetID);
  content.setAttribute('class', 'navigator_content');
  container.appendChild(content);

  // Add home node as starting point without any parent
  var home_node = new NeuronNavigatorHomeNode(this.widgetID);
  home_node.link(this, null);
  this.select_node(home_node);
};

NeuronNavigator.prototype.select_node = function(node)
{
  // Set the navigation bar contents
  $('#navigator_navi_bar' + this.widgetID).empty().append(
      node.create_path(this));

  // Set the actual content
  $('#navigatior_content' + this.widgetID).empty().append(
      node.create_content(this));
};

/**
 * A filter container that keeps track of either an annotation, a user or a
 * neuron to be used as filter when selection data.
 */
var NeuronNavigatorFilter = function(annotation, user, neuron)
{
  this.annotation = annotation;
  this.user = user;
  this.neuron = neuron;
};

/**
 * A class representing a node in the graph of the navigator.
 */
var NeuronNavigatorNode = function(name)
{
  this.name = name;
  this.navigator = null;
  this.filters = null;
};

NeuronNavigatorNode.prototype.link = function(navigator, parent_node)
{
  this.navigator = navigator;
  this.parent_node = parent_node;
};

NeuronNavigatorNode.prototype.collect_filters = function()
{
  // Collect filters by reference
  if (this.parent_node) {
    var path_filters = this.parent_node.collect_filters();
    if (this.filters) {
      path_filters.push(this.filters);
    }
    return path_filters;
  } else {
    // The home node will return an empty list
    return [];
  }
};

NeuronNavigatorNode.prototype.create_path = function()
{
  var path_link = document.createElement('a');
  path_link.setAttribute('href', '#');
  path_link.setAttribute('class', 'navigator_navi_bar_element');
  path_link.innerHTML = this.name;
  $(path_link).click($.proxy(function() {
    this.navigator.select_node(this);
  }, this));

  if (this.parent_node) {
    var path_elements = this.parent_node.create_path();
    path_elements.push(document.createTextNode(" > "));
    path_elements.push(path_link);
    return path_elements;
  } else {
    return [path_link];
  }
};

NeuronNavigatorNode.prototype.create_content = function()
{
  return undefined;
};

NeuronNavigatorNode.prototype.create_annotations_link = function()
{
  var annotations_link = this.create_path_link("Annotations");
  $(annotations_link).click($.proxy(function() {
      var annotations_node = new NeuronNavigatorAnnotationsNode();
      annotations_node.link(this.navigator, this);
      this.navigator.select_node(annotations_node);
  }, this));

  return annotations_link;
};

NeuronNavigatorNode.prototype.create_users_link = function()
{
  var users_link = this.create_path_link("Users");
  $(users_link).click($.proxy(function() {
      var users_node = new NeuronNavigatorUsersNode();
      users_node.link(this.navigator, this);
      this.navigator.select_node(users_node);
  }, this));

  return users_link;
};

NeuronNavigatorNode.prototype.create_neurons_link = function()
{
  var neurons_link = this.create_path_link("Neurons");
  $(neurons_link).click($.proxy(function() {
      var node = new NeuronNavigatorNeuronListNode();
      node.link(this.navigator, this);
      this.navigator.select_node(node);
  }, this));

  return neurons_link
};

NeuronNavigatorNode.prototype.create_path_link = function(text)
{
  var option = document.createElement('a');
  option.setAttribute('href', '#');
  option.setAttribute('class', 'navigator_content_option');
  // Add text to option, if passed
  if (text)
  {
    option.innerHTML = text;
  }

  return option;
};

/**
 * The home node of the navigator. It links to annotation
 * and users nodes.
 */
var NeuronNavigatorHomeNode = function()
{
  // A home node acts as the root node and has therefore no parent.
  this.link(null);
};

NeuronNavigatorHomeNode.prototype = {};
$.extend(NeuronNavigatorHomeNode.prototype, new NeuronNavigatorNode("Home"));

NeuronNavigatorHomeNode.prototype.create_content = function()
{
  var content = document.createElement('div');

  var annotations_link = this.create_annotations_link();
  var users_link = this.create_users_link();
  content.appendChild(annotations_link);
  content.appendChild(users_link);

  return content;
};

/**
 * The annotations node of the navigator. It links to annotations.
 */
var NeuronNavigatorAnnotationsNode = function() {};

NeuronNavigatorAnnotationsNode.prototype = {};
$.extend(NeuronNavigatorAnnotationsNode.prototype,
    new NeuronNavigatorNode("Annotations"));

NeuronNavigatorAnnotationsNode.prototype.create_content = function()
{
  var content = document.createElement('div');
  content.setAttribute('id', 'navigator_annotations_content' +
      this.navigator.widgetID);
  content.innerHTML = "Please wait while the available annotatios are requested";

  // Make node easily accessible in created methods
  var self = this;

  // Collect all filtered annotations into post data
  var filters = this.collect_filters();
  var post_data = {
    'ignored_annotations': filters.reduce(function(o, f) {
        if (f.annotation) {
          o.push(f.annotation);
        }
        return o;
      }, [])
  };

  // Get the list of currently available annotations
  requestQueue.register(django_url + project.id + '/annotations/list',
      'POST', post_data, function(status, data, text) {
        var e = $.parseJSON(data);
        if (status != 200) {
          alert("The server returned an unexpected status (" +
            status + ") with error message:\n" + text);
        } else {
          // Create a list of annotation links
          var annotations = e.map(function(a) {
            var annotations_link = self.create_path_link(a);
            $(annotations_link).click(function() {
                var annotations_node = new NeuronNavigatorAnnotationFilterNode(a);
                annotations_node.link(self.navigator, self);
                self.navigator.select_node(annotations_node);
            });
            return annotations_link;
          });
          // Add all annotation links
          $('#navigator_annotations_content' + self.navigator.widgetID).empty().
            append(annotations);
        }
      });

  return content;
};

/**
 * The users node of the navigator. It links to users.
 */
var NeuronNavigatorUsersNode = function() {};

NeuronNavigatorUsersNode.prototype = {};
$.extend(NeuronNavigatorUsersNode.prototype,
    new NeuronNavigatorNode("Users"));

NeuronNavigatorUsersNode.prototype.create_content = function()
{
  var content = document.createElement('div');
  content.setAttribute('id', 'navigator_users_content' +
      this.navigator.widgetID);
  content.innerHTML = "Please wait while the existing users are requested";

  // Make node easily accessible in created methods
  var self = this;

  // Collect all filtered annotations into post data
  var filters = this.collect_filters();
  var post_data = {
    'ignored_users': filters.reduce(function(o, f) {
        if (f.user) {
          o.push(f.user);
        }
        return o;
      }, [])
  };

  // Get the list of currently available annotations
  requestQueue.register(django_url + 'user-list',
      'POST', post_data, function(status, data, text) {
        var e = $.parseJSON(data);
        if (status != 200) {
          alert("The server returned an unexpected status (" +
            status + ") with error message:\n" + text);
        } else {
          // Create a list of user links
          var users = e.map(function(u) {
            var user_link = self.create_path_link(u.full_name +
                " (" + u.login + ")");
            $(user_link).click(function() {
                var filter_node = new NeuronNavigatorUserFilterNode(u);
                filter_node.link(self.navigator, self);
                self.navigator.select_node(filter_node);
            });
            return user_link;
          });
          // Add all annotation links
          $('#navigator_users_content' + self.navigator.widgetID).empty().
            append(users);
        }
      });

  return content;
};

/**
 * The neuron list node of the navigator lists all neurons matching the
 * filter criteria in the path.
 */
var NeuronNavigatorNeuronListNode = function() {};

NeuronNavigatorNeuronListNode.prototype = {};
$.extend(NeuronNavigatorNeuronListNode.prototype,
    new NeuronNavigatorNode("Neurons"));

NeuronNavigatorNeuronListNode.prototype.create_content = function()
{
  var content = document.createElement('div');
  content.setAttribute('id', 'navigator_neuronlist_content' +
      this.navigator.widgetID);
  content.innerHTML = "Please wait while matching neurons are requested";

  // Make node easily accessible in created methods
  var self = this;

  // Collect all filters into post data
  var filters = this.collect_filters();
  var post_data = filters.reduce(function(o, f) {
        if (f.user) {
          // Expect only one user filter and create the
          // field in result object if one exists.
          o.neuron_query_by_annotator = f.user;
        }
        if (f.annotation) {
          o.neuron_query_by_annotation.push(f.annotation);
        }
        return o;
      }, {
        'neuron_query_by_annotation': []
      });

  // Get the list of currently available annotations
  requestQueue.register(django_url + project.id +
      '/neuron/query-by-annotations',
      'POST', post_data, function(status, data, text) {
        var e = $.parseJSON(data);
        if (status != 200) {
          alert("The server returned an unexpected status (" +
            status + ") with error message:\n" + text);
        } else {
          // Create a list of neuron links
          var neurons = e.map(function(n) {
            var neuron_link = self.create_path_link(n.name +
                " (ID: " + n.id + ", Skeleton ID: " + n.skeleton_id +
                ", Root node: " + n.root_node + ")");
            $(neuron_link).click(function() {
                // TODO: What should happen when clicking a neuron?
            });
            return neuron_link;
          });
          // Add all annotation links
          $('#navigator_neuronlist_content' + self.navigator.widgetID).empty().
            append(neurons);
        }
      });

  return content;
};

/**
 * The annotation filter node of the navigator filters output based on the
 * existence of an annotations. The content it creates lists user, neuron,
 * annotation and co-annotation links.
 */
var NeuronNavigatorAnnotationFilterNode = function(included_annotation)
{
  this.filters = new NeuronNavigatorFilter(included_annotation)
  this.name = "A: " + included_annotation;
};

NeuronNavigatorAnnotationFilterNode.prototype = {};
$.extend(NeuronNavigatorAnnotationFilterNode.prototype,
    new NeuronNavigatorNode("Empty Annotation Filter"));

NeuronNavigatorAnnotationFilterNode.prototype.create_content = function()
{
  /* An annotation filter node, will display options to add ad user filter,
   * another annotation filter or to select a neuron.
   */
  var content = document.createElement('div');

  var annotations_link = this.create_annotations_link();
  content.appendChild(annotations_link);

  // Only show the users link, if there hasn't been one before
  var filters = this.collect_filters();
  var has_user_filter = filters.some(function(f) {
    return f.user;
  });
  if (!has_user_filter) {
    var users_link = this.create_users_link();
    content.appendChild(users_link);
  }

  var neurons_link = this.create_neurons_link();
  content.appendChild(neurons_link);

  return content;
};

/**
 * The user filter node of the navigator filters output based on the
 * ownership by a particular user. The content it creates lists user, neuron,
 * annotation and co-annotation links.
 */
var NeuronNavigatorUserFilterNode = function(included_user)
{
  this.filters = new NeuronNavigatorFilter(null, included_user.id)
  this.name = "U: " + included_user.login;
};

NeuronNavigatorUserFilterNode.prototype = {};
$.extend(NeuronNavigatorUserFilterNode.prototype,
    new NeuronNavigatorNode("Empty User Filter"));

NeuronNavigatorUserFilterNode.prototype.create_content = function()
{
  var content = document.createElement('div');

  var annotations_link = this.create_annotations_link();
  var neurons_link = this.create_neurons_link();
  content.appendChild(annotations_link);
  content.appendChild(neurons_link);

  return content;
};
<|endoftext|>


<commit_before>// @flow

import React, { Component } from 'react';
import Ionicons from 'react-native-vector-icons/Ionicons';

import Run from '../components/Run';

export default class RunView extends Component {
  state = {
    run: '-KnZ1p-Vm6LzDoMnUj-t',
  };

  static navigationOptions = {
    tabBarLabel: 'Run',
    tabBarIcon: ({ tintColor, focused }) =>
      <Ionicons
        name={focused ? 'ios-flag' : 'ios-flag-outline'}
        size={32}
        style={{ color: tintColor }}
      />,
  };

  render() {
    const run = this.props.run ? this.props.run : this.state.run;
    return <Run run={run} />;
  }
}
<commit_msg>default props<commit_after>// @flow

import React, { Component } from 'react';
import Ionicons from 'react-native-vector-icons/Ionicons';

import Run from '../components/Run';

export default class RunView extends Component {
  static defaultProps = {
    run: '-KnZ1p-Vm6LzDoMnUj-t',
  };

  static navigationOptions = {
    tabBarLabel: 'Run',
    tabBarIcon: ({ tintColor, focused }) =>
      <Ionicons
        name={focused ? 'ios-flag' : 'ios-flag-outline'}
        size={32}
        style={{ color: tintColor }}
      />,
  };

  render() {
    const { run } = this.props;
    return <Run run={run} />;
  }
}
<|endoftext|>