<commit_before>var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");
var imageData = context.createImageData(canvas.width, canvas.height);

var Convert = {
  //TODO separate this into module? acts like Math.
  ft_mm : function(ft) {
    //1 ft = 304.8 mm
    return ft * 304.8; }
};

function setIntervalX(callback, delay, repetitions, finished) {
  // Helper function to call a given no of timers.
  // delay is in milliseconds.

  var i = 0;
  var intervalId = window.setInterval( function () {

    callback();
    i += 1;

    if (i === repetitions) {
      window.clearInterval(intervalId);
      if (typeof(finished) !== 'undefined') { finished(); }
    }
  }, delay);
}

var WallRobot = function(opts) {
  //all working units are in MM! MM is "native".

  // stepDelta tracks steps from the origin position.
  // Negative values retract the string, positive values extend the string
  // stepDelta[0] is left stepper, and stepDelta[1] is right stepper.
  this.stepDelta = [0, 0];

  // horizontal distance from motors to side of board in mm
  this.MOTOR_SIDE_OFFSET = opts.MOTOR_SIDE_OFFSET;

  // height of motors above top of drawing area in mm
  this.MOTOR_HEIGHT = opts.MOTOR_HEIGHT;

  this.DRAW_AREA_WIDTH = opts.DRAW_AREA_WIDTH;
  this.DRAW_AREA_HEIGHT = opts.DRAW_AREA_HEIGHT;

  this.STRING_LEN_PER_STEP = opts.STRING_LEN_PER_STEP;

  // TODO
  this.DEFAULT_SPEED = opts.DEFAULT_SPEED;

  this.vectorLen = function(x, y) {
    return Math.sqrt( Math.pow(x,2) + Math.pow(y,2) );
  };

  // Derivative values:
  this.INITIAL_STR_LEN_LEFT = this.vectorLen(this.MOTOR_SIDE_OFFSET, this.MOTOR_HEIGHT);
  this.INITIAL_STR_LEN_RIGHT = this.vectorLen(this.MOTOR_SIDE_OFFSET + this.DRAW_AREA_WIDTH, this.MOTOR_HEIGHT);

  this.MOTOR_TO_MOTOR_DIST = this.DRAW_AREA_WIDTH + 2*this.MOTOR_SIDE_OFFSET;

  this.initSanityCheck = function () {
    // Make sure all the constants are sane and consistent.

    //allow for rounding errors and general JS floating point errors
    var TOLERANCE_AMT = 0.00000000001;

    //constant scalars that should be > 0
    _.forEach([
      "MOTOR_SIDE_OFFSET",
      "MOTOR_HEIGHT",
      "DRAW_AREA_WIDTH",
      "DRAW_AREA_HEIGHT",
      "INITIAL_STR_LEN_LEFT",
      "INITIAL_STR_LEN_RIGHT",
      "MOTOR_TO_MOTOR_DIST",
      "DEFAULT_SPEED"
      ],
      function(param) {

      if (this[param] <= 0) {
        throw new Error(
          param + " must be > 0."
        );
      }
    }, this);

  };

  // Call for sanity check upon initialization
  this.initSanityCheck();
};

    //r_p is the only vector that should always have a <= 0 x component
  //   if(this.r_p.x > 0) {
  //     throw new Error("r_p should not have an x component > 0");
  //   }
  //
  //   if(this.L_R.y !== 0) {
  //     throw new Error("L_R should not have a horizontal component.");
  //   }
  //
  //   if(this.l_p.y !== this.r_p.y) {
  //     throw new Error("l_p and r_p should have the same y value.");
  //   }
  //
  //   if(Math.abs(this.l_p.length() - this.string_len_left) > TOLERANCE_AMT) {
  //     throw new Error("l_p's length should ~equal string_len_left.");
  //   }
  //
  //   if(Math.abs(this.r_p.length() - this.string_len_right) > TOLERANCE_AMT) {
  //   throw new Error("r_p's length should ~equal string_len_right.");
  //   }
  //

// Getters (and setters, if you make any)
Object.defineProperties(WallRobot.prototype, {

  string_len_left : {
    get: function() {
      return this.stepDelta[0]*this.STRING_LEN_PER_STEP + this.INITIAL_STR_LEN_LEFT;
    }
  },

  string_len_right : {
    get: function() {
      return this.stepDelta[1]*this.STRING_LEN_PER_STEP + this.INITIAL_STR_LEN_RIGHT;
    }
  },

  x : {
    get: function() {
      return (( Math.pow(this.string_len_left,2) - Math.pow(this.string_len_right,2) +
        Math.pow(this.MOTOR_TO_MOTOR_DIST,2) ) / (2 * this.MOTOR_TO_MOTOR_DIST) - this.MOTOR_SIDE_OFFSET);
    }
  },

  y : {
    get: function() {
      //TODO: this can probably be more efficient (not calling x.get()...)
      return (Math.sqrt(Math.pow(this.string_len_left, 2) - Math.pow(this.x + this.MOTOR_SIDE_OFFSET, 2)) - this.MOTOR_HEIGHT);
    }
  },

});

// Rest of methods

WallRobot.prototype.checkPosition = function(x, y) {
  // You can pass x and y values if you want to test them without changing
  // the stepDelta. If you don't specify, this.x and this.y are used,
  // which are calculated using this.stepDelta
  if (typeof(x)==='undefined') x = this.x;
  if (typeof(y)==='undefined') y = this.y;

  if (x < 0) { throw new Error("x should not be negative"); }
  if (y < 0) { throw new Error("y should not be negative"); }
  if (x > this.DRAW_AREA_WIDTH) { throw new Error("x should not be greater than DRAW_AREA_WIDTH"); }
  if (y > this.DRAW_AREA_HEIGHT) { throw new Error("y should not be greater than DRAW_AREA_HEIGHT"); }

  return true;
};

WallRobot.prototype.setStepDelta = function(left, right) {
  // TODO: Check if the resulting x,y is valid as well!
  this.nextStepDelta = [Math.round(left), Math.round(right)];

  console.log(this.nextStepDelta);
};

WallRobot.prototype.setDeltaByCoords = function(x, y) {
  // dx and dy are the components of the vector from the left stepper shaft
  // to the gondola's xy position.
  var dx = x + this.MOTOR_SIDE_OFFSET;
  var dy = y + this.MOTOR_HEIGHT;

  var new_left_len = this.vectorLen(dx, dy);
  var new_right_len = this.vectorLen(this.MOTOR_TO_MOTOR_DIST - dx, dy);

  this.setDeltaByLengths(new_left_len, new_right_len);
};

WallRobot.prototype.setDeltaByLengths = function(left_len, right_len) {
  // Use given string lengths to set a new delta
  this.setStepDelta( (left_len - this.INITIAL_STR_LEN_LEFT) / this.STRING_LEN_PER_STEP,
    (right_len - this.INITIAL_STR_LEN_RIGHT) / this.STRING_LEN_PER_STEP);
};

WallRobot.prototype.drawToBoard = function () {
  // instead of calling setPixel directly, this is kind of a hook.
  // later I will implement colors etc

  //round off floating point values so you can plot them
  x = Math.round(this.x);
  y = Math.round(this.y);
  setPixel(imageData, x, y, 255, 0, 0, 255);
  //console.log("drew to board (" + x + "," + y + ").");
  context.putImageData(imageData, 0,0);
};

WallRobot.prototype.gotoStepDelta = function (maxSpeed) {
  // actuate the steppers here, or at least simulate it

  throw new Error("broken fn. TODO.")

  if (typeof(this.nextStepDelta) === 'undefined') {
    throw new Error("No next step! nextStepDelta is undefined.");
  }
  if (typeof(maxSpeed) === 'undefined') { maxSpeed  = this.DEFAULT_SPEED; }

  var left_steps = this.nextStepDelta[0] - this.stepDelta[0];
  var right_steps = this.nextStepDelta[1] - this.stepDelta[1];
  var fastTimerId;
  var slowTimerId;
  var fastIndex;
  var slowIndex;
  var fast_steps;
  var slow_steps;
  var fastDir;
  var slowDir;

  if (left_steps > 0 || right_steps > 0) {
    if (left_steps > right_steps) {
      // left_stepper has more steps to make, so it moves at the given speed
      // while right_stepper moves at a fraction of that speed
      // so they both finish at the same time, hopefully!

      fastIndex = 0;
      slowIndex = 1;
      fast_steps = left_steps;
      slow_steps = right_steps;

      // JOHNNY-FIVE CODE
      // left_stepper.rpm(maxSpeed).cw().step(left_steps, cb);
      // right_stepper.rpm(maxSpeed*right_steps/left_steps).ccw().step(right_steps, cb);
    } else {
      //visa versa, since right_steps > left_steps

      fastIndex = 1;
      slowIndex = 0;
      fast_steps = right_steps;
      slow_steps = left_steps;

      // JOHNNY-FIVE CODE
      // left_stepper.rpm(maxSpeed*left_steps/right_steps).cw().step(left_steps, cb);
      // right_stepper.rpm(maxSpeed).ccw().step(right_steps, cb);
    }

    slowDir = slow_steps > 1 ? 1 : -1;
    fastDir = fast_steps > 1 ? 1 : -1;

    slowTimerId = window.setInterval( function () {
      this.stepDelta[slowIndex] += slowDir;
    }.bind(this), maxSpeed*slow_steps/fast_steps);

    fastTimerId = window.setInterval( function () {
      this.stepDelta[fastIndex] += fastDir;
      if (this.stepDelta[fastIndex] === this.nextStepDelta[fastIndex]) {
        console.log("done stepping to new delta!");
        window.clearInterval(slowTimerId);
        window.clearInterval(fastTimerId);

        // update the stepDelta to its new position
        this.stepDelta = this.nextStepDelta.slice();
      }
      this.drawToBoard();
    }.bind(this), maxSpeed);
  } else {
    console.log("Didn't move, nextStepDelta is the same as current stepDelta.");
  }

};

// ===============================================

function setPixel(imageData, x, y, r, g , b, a) {
  var index = (x+y*imageData.width)*4;
  imageData.data[index+0] = r;
  imageData.data[index+1] = g;
  imageData.data[index+2] = b;
  imageData.data[index+3] = a; //255 is opaque, 0 is transparent
}

function randomNoise() {
//just for fun
  var x = Math.floor(Math.random()*imageData.width);
  var y = Math.floor(Math.random()*imageData.height);
  setPixel(imageData,
    x, y, 255,0,0,255);
  // console.log(x,y);
  context.putImageData(imageData, 0, 0);
}

// randomNoise with setIntervalX
// setIntervalX(randomNoise, 1, 1000,
//   function () { console.log("done"); } );

// start!!!
var robot = new WallRobot({
  MOTOR_SIDE_OFFSET: Convert.ft_mm(2),
  MOTOR_HEIGHT: Convert.ft_mm(2),
  DRAW_AREA_WIDTH: Convert.ft_mm(8),
  DRAW_AREA_HEIGHT: Convert.ft_mm(4),
  STRING_LEN_PER_STEP: 1.5, //??? dunno! TODO measure.
  DEFAULT_SPEED: 10, // ??? what units is this even in?? steps/ms? mm/ms?
});

//test update and draw!
robot.setDeltaByCoords(100,200);
//robot.gotoStepDelta();
<commit_msg>can draw, but inaccurate, not synched up<commit_after>var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");
var imageData = context.createImageData(canvas.width, canvas.height);

var Convert = {
  //TODO separate this into module? acts like Math.
  ft_mm : function(ft) {
    //1 ft = 304.8 mm
    return ft * 304.8; }
};

function setIntervalX(callback, delay, repetitions, finished) {
  // Helper function to call a given no of timers.
  // delay is in milliseconds.

  var i = 0;
  var intervalId = window.setInterval( function () {

    callback();
    i += 1;

    if (i === repetitions) {
      window.clearInterval(intervalId);
      if (typeof(finished) !== 'undefined') { finished(); }
    }
  }, delay);
}

var WallRobot = function(opts) {
  //all working units are in MM! MM is "native".

  // stepDelta tracks steps from the origin position.
  // Negative values retract the string, positive values extend the string
  // stepDelta[0] is left stepper, and stepDelta[1] is right stepper.
  this.stepDelta = [0, 0];

  // horizontal distance from motors to side of board in mm
  this.MOTOR_SIDE_OFFSET = opts.MOTOR_SIDE_OFFSET;

  // height of motors above top of drawing area in mm
  this.MOTOR_HEIGHT = opts.MOTOR_HEIGHT;

  this.DRAW_AREA_WIDTH = opts.DRAW_AREA_WIDTH;
  this.DRAW_AREA_HEIGHT = opts.DRAW_AREA_HEIGHT;

  this.STRING_LEN_PER_STEP = opts.STRING_LEN_PER_STEP;

  // TODO
  this.DEFAULT_SPEED = opts.DEFAULT_SPEED;

  this.vectorLen = function(x, y) {
    return Math.sqrt( Math.pow(x,2) + Math.pow(y,2) );
  };

  // Derivative values:
  this.INITIAL_STR_LEN_LEFT = this.vectorLen(this.MOTOR_SIDE_OFFSET, this.MOTOR_HEIGHT);
  this.INITIAL_STR_LEN_RIGHT = this.vectorLen(this.MOTOR_SIDE_OFFSET + this.DRAW_AREA_WIDTH, this.MOTOR_HEIGHT);

  this.MOTOR_TO_MOTOR_DIST = this.DRAW_AREA_WIDTH + 2*this.MOTOR_SIDE_OFFSET;

  this.initSanityCheck = function () {
    // Make sure all the constants are sane and consistent.

    //allow for rounding errors and general JS floating point errors
    var TOLERANCE_AMT = 0.00000000001;

    //constant scalars that should be > 0
    _.forEach([
      "MOTOR_SIDE_OFFSET",
      "MOTOR_HEIGHT",
      "DRAW_AREA_WIDTH",
      "DRAW_AREA_HEIGHT",
      "INITIAL_STR_LEN_LEFT",
      "INITIAL_STR_LEN_RIGHT",
      "MOTOR_TO_MOTOR_DIST",
      "DEFAULT_SPEED"
      ],
      function(param) {

      if (this[param] <= 0) {
        throw new Error(
          param + " must be > 0."
        );
      }
    }, this);

  };

  // Call for sanity check upon initialization
  this.initSanityCheck();
};

    //r_p is the only vector that should always have a <= 0 x component
  //   if(this.r_p.x > 0) {
  //     throw new Error("r_p should not have an x component > 0");
  //   }
  //
  //   if(this.L_R.y !== 0) {
  //     throw new Error("L_R should not have a horizontal component.");
  //   }
  //
  //   if(this.l_p.y !== this.r_p.y) {
  //     throw new Error("l_p and r_p should have the same y value.");
  //   }
  //
  //   if(Math.abs(this.l_p.length() - this.string_len_left) > TOLERANCE_AMT) {
  //     throw new Error("l_p's length should ~equal string_len_left.");
  //   }
  //
  //   if(Math.abs(this.r_p.length() - this.string_len_right) > TOLERANCE_AMT) {
  //   throw new Error("r_p's length should ~equal string_len_right.");
  //   }
  //

// Getters (and setters, if you make any)
Object.defineProperties(WallRobot.prototype, {

  string_len_left : {
    get: function() {
      return this.stepDelta[0]*this.STRING_LEN_PER_STEP + this.INITIAL_STR_LEN_LEFT;
    }
  },

  string_len_right : {
    get: function() {
      return this.stepDelta[1]*this.STRING_LEN_PER_STEP + this.INITIAL_STR_LEN_RIGHT;
    }
  },

  x : {
    get: function() {
      return (( Math.pow(this.string_len_left,2) - Math.pow(this.string_len_right,2) +
        Math.pow(this.MOTOR_TO_MOTOR_DIST,2) ) / (2 * this.MOTOR_TO_MOTOR_DIST) - this.MOTOR_SIDE_OFFSET);
    }
  },

  y : {
    get: function() {
      //TODO: this can probably be more efficient (not calling x.get()...)
      return (Math.sqrt(Math.pow(this.string_len_left, 2) - Math.pow(this.x + this.MOTOR_SIDE_OFFSET, 2)) - this.MOTOR_HEIGHT);
    }
  },

});

// Rest of methods

WallRobot.prototype.checkPosition = function(x, y) {
  // You can pass x and y values if you want to test them without changing
  // the stepDelta. If you don't specify, this.x and this.y are used,
  // which are calculated using this.stepDelta
  if (typeof(x)==='undefined') x = this.x;
  if (typeof(y)==='undefined') y = this.y;

  if (x < 0) { throw new Error("x should not be negative"); }
  if (y < 0) { throw new Error("y should not be negative"); }
  if (x > this.DRAW_AREA_WIDTH) { throw new Error("x should not be greater than DRAW_AREA_WIDTH"); }
  if (y > this.DRAW_AREA_HEIGHT) { throw new Error("y should not be greater than DRAW_AREA_HEIGHT"); }

  return true;
};

WallRobot.prototype.setStepDelta = function(left, right) {
  // TODO: Check if the resulting x,y is valid as well!
  this.nextStepDelta = [Math.round(left), Math.round(right)];

  console.log(this.nextStepDelta);
};

WallRobot.prototype.setDeltaByCoords = function(x, y) {
  // dx and dy are the components of the vector from the left stepper shaft
  // to the gondola's xy position.
  var dx = x + this.MOTOR_SIDE_OFFSET;
  var dy = y + this.MOTOR_HEIGHT;

  var new_left_len = this.vectorLen(dx, dy);
  var new_right_len = this.vectorLen(this.MOTOR_TO_MOTOR_DIST - dx, dy);

  this.setDeltaByLengths(new_left_len, new_right_len);
};

WallRobot.prototype.setDeltaByLengths = function(left_len, right_len) {
  // Use given string lengths to set a new delta
  this.setStepDelta( (left_len - this.INITIAL_STR_LEN_LEFT) / this.STRING_LEN_PER_STEP,
    (right_len - this.INITIAL_STR_LEN_RIGHT) / this.STRING_LEN_PER_STEP);
};

WallRobot.prototype.drawToBoard = function () {
  // instead of calling setPixel directly, this is kind of a hook.
  // later I will implement colors etc

  //round off floating point values so you can plot them
  var x = Math.round(this.x);
  var y = Math.round(this.y);
  setPixel(imageData, x, y, 0, 0, 0, 255);
  // console.log(x + ", " + y);
  // console.log("THIS XY:" + this.x + "," + this.y);
  // console.log("this str_len:" + this.string_len_left + ", " + this.string_len_right);

  //context.putImageData(imageData, 0,0);
};

WallRobot.prototype.gotoStepDelta = function (maxSpeed) {
  // actuate the steppers here, or at least simulate it

  if (typeof(this.nextStepDelta) === 'undefined') {
    throw new Error("No next step! nextStepDelta is undefined.");
  }

  if (typeof(maxSpeed) === 'undefined') { maxSpeed  = this.DEFAULT_SPEED; }

  var left_steps = this.nextStepDelta[0] - this.stepDelta[0];
  var right_steps = this.nextStepDelta[1] - this.stepDelta[1];
  var fastTimerId;
  var slowTimerId;
  var fastIndex;
  var slowIndex;
  var fast_steps;
  var slow_steps;
  var fastDir;
  var slowDir;

  console.log({left_steps: left_steps, right_steps: right_steps});

  if (left_steps !== 0 || right_steps !== 0) {
    if (Math.abs(left_steps) > Math.abs(right_steps) ) {
      // left_stepper has more steps to make, so it moves at the given speed
      // while right_stepper moves at a fraction of that speed
      // so they both finish at the same time, hopefully!

      console.log("left stepper is fast!");
      fastIndex = 0;
      slowIndex = 1;
      fast_steps = left_steps;
      slow_steps = right_steps;

      // JOHNNY-FIVE CODE
      // left_stepper.rpm(maxSpeed).cw().step(left_steps, cb);
      // right_stepper.rpm(maxSpeed*right_steps/left_steps).ccw().step(right_steps, cb);
    } else {
      //visa versa, since right_steps > left_steps

      console.log("right stepper is fast!");
      fastIndex = 1;
      slowIndex = 0;
      fast_steps = right_steps;
      slow_steps = left_steps;

      // JOHNNY-FIVE CODE
      // left_stepper.rpm(maxSpeed*left_steps/right_steps).cw().step(left_steps, cb);
      // right_stepper.rpm(maxSpeed).ccw().step(right_steps, cb);
    }

    slowDir = slow_steps > 1 ? 1 : -1;
    fastDir = fast_steps > 1 ? 1 : -1;

    var stepCount = 0;

    var stepSlow = function() {
      this.stepDelta[slowIndex] += slowDir;
       console.log("boop, slow. Stepcount: " + stepCount );
    };

    var stepFast = function() {
      // console.log(stepCount + " is count");

      this.stepDelta[fastIndex] += fastDir;
      // console.log("modulous: slow=" + slow_steps + ", fast=" + fast_steps + ". " + ((slow_steps*stepCount) % fast_steps ) );
      // if ((stepCount !==0 && Error("modulus doesn't work b/c the division isn't clean. Eg -34/143, how do you work that??")) {
      //   console.log("sloooow");
      //   this.stepDelta[slowIndex] += slowDir;
      // }

      this.drawToBoard();
      // console.log("beep, fast");
      context.putImageData(imageData, 0,0);

      if (this.stepDelta[fastIndex] === this.nextStepDelta[fastIndex]) {
        console.log("done stepping to new delta!");
        window.clearInterval(slowTimerId);
        window.clearInterval(fastTimerId);
        context.putImageData(imageData, 0,0);

        // update the stepDelta to its new position
        this.stepDelta = this.nextStepDelta.slice();
      }

      stepCount += 1;
    };

    slowTimerId = window.setInterval( stepSlow.bind(this), maxSpeed*Math.abs(fast_steps/slow_steps));

    fastTimerId = window.setInterval( stepFast.bind(this), maxSpeed);
  } else {
    console.log("Didn't move, nextStepDelta is the same as current stepDelta.");
  }

};

// ===============================================

function setPixel(imageData, x, y, r, g , b, a) {
  var index = (x+y*imageData.width)*4;
  imageData.data[index+0] = r;
  imageData.data[index+1] = g;
  imageData.data[index+2] = b;
  imageData.data[index+3] = a; //255 is opaque, 0 is transparent
}

function randomNoise() {
//just for fun
  var x = Math.floor(Math.random()*imageData.width);
  var y = Math.floor(Math.random()*imageData.height);
  setPixel(imageData,
    x, y, 255,0,0,255);
  // console.log(x,y);
  context.putImageData(imageData, 0, 0);
}

// randomNoise with setIntervalX
// setIntervalX(randomNoise, 1, 1000,
//   function () { console.log("done"); } );

// start!!!
var robot = new WallRobot({
  MOTOR_SIDE_OFFSET: Convert.ft_mm(2),
  MOTOR_HEIGHT: Convert.ft_mm(2),
  DRAW_AREA_WIDTH: Convert.ft_mm(8),
  DRAW_AREA_HEIGHT: Convert.ft_mm(4),
  STRING_LEN_PER_STEP: 1.5, //??? dunno! TODO measure.
  DEFAULT_SPEED: 10, // ??? what units is this even in?? steps/ms? mm/ms?
});

//test update and draw!
robot.setDeltaByCoords(100,200);
//robot.gotoStepDelta();
<|endoftext|>


<commit_before>"use strict";

// This files has a lot of overlap with rollup-pre-alias.config.js
// - should we pull some of this functionality out?

import commonjs from '@rollup/plugin-commonjs';
import resolveNode from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";

import sourcemaps from 'rollup-plugin-sourcemaps';

// We only need this for its version (we inject it into a require)
import elliptic from "elliptic";

function addUtilsReplace(plugins) {

    // Remove the buffer check from BN.js
    plugins.push(replace({
        "require('buffer')": "/*RicMoo:ethers:require(buffer)*/(null)",
        include: "**/lib/bn.js",
        delimiters: [ '', '' ]
    }));

    // Remove the util from inhjerits (forces browser inherits)
    plugins.push(replace({
        "require('util')": "/*RicMoo:ethers:require(util)*/(null)",
        include: "**/inherits/inherits.js",
        delimiters: [ '', '' ]
    }));

    return plugins;
}

function addLangReplace(plugins) {

    plugins.push(replace({
        'require("./wordlists")': 'require("./browser-wordlists")/*RicMoo:ethers:require(wordlists)*/',
        include: "**/wordlists/lib/index.js",
        delimiters: [ '', '' ]
    }));

    return plugins;
}

function addEllipticReplace(plugins) {

    // Replace the package.json in elliptic
    plugins.push(replace({
        "require('../package.json')": `/*RicMoo:ethers*/{ version: "${ elliptic.version }" }`,
        include: "**/lib/elliptic.js",
        delimiters: [ '', '' ]
    }));

    // Nuke a bunch of requires we don't need in elliptic
    const thrower = "(function() { throw new Error('unsupported'); })";
    const crash = "(null).crash()";
    [
        { name: "./edwards", filename: "curve/index.js" },
        { name: "./mont", filename: "curve/index.js" },
        { name: "./elliptic/eddsa", filename: "lib/elliptic.js" },
        { name: "brorand", filename: "ec/index.js", text: thrower },
        { name: "brorand", filename: "lib/elliptic.js", text: thrower },
        { name: "./precomputed/secp256k1", filename: "elliptic/curves.js", text: crash },
    ].forEach(({ name, filename, text }) => {
        if (text == null) { text = "(null)"; }
        const replacement = {
            include: `**/${ filename }`,
            delimiters: [ '', '' ]
        };
        replacement[`require('${ name }')`] = `/*RicMoo:ethers:require(${ name })*/${ text }`,
        plugins.push(replace(replacement));
    });

    return plugins;
}

function getUmdConfig() {
    const plugins = [ ];

    plugins.push(sourcemaps());

    addUtilsReplace(plugins);
    addEllipticReplace(plugins);
    addLangReplace(plugins);

    plugins.push(resolveNode({
        mainFields: [ "browser", "main" ]
    }));
    plugins.push(commonjs({ }));

    return {
        input: `packages/ethers/lib/index.js`,
        output: {
            file: `packages/ethers/dist/ethers.umd.js`,
            format: "umd",
            name: "ethers",
            sourcemap: true
        },
        context: "window",
        treeshake: false,
        plugins
    };
}

function getEsmConfig() {
    const plugins = [ ];

    plugins.push(sourcemaps());

    addUtilsReplace(plugins);

    // Note: We do not need to replace the elliptic problems because they
    //       were addressed when aliasing (in rollup-pre-alias.config.js)

    plugins.push(resolveNode({ }));
    plugins.push(commonjs({ }));

    return {
        input: `packages/ethers/lib.esm/index.js`,
        output: {
            file: `packages/ethers/dist/ethers.esm.js`,
            format: "esm",
            sourcemap: true
        },
        context: "window",
        treeshake: false,
        plugins
    };
}

/*
function getConfig() {
    const plugins = [ ];

    // Remove the buffer check from BN.js
    plugins.push(replace({
        "require('buffer')": "/ * RicMoo:ethers * /(null)",
        include: "* * / lib/bn.js",
        delimiters: [ '', '' ]
    }));
    plugins.push(resolveNode({
        preferBuiltins: true
    }));
    plugins.push(commonjs({ }));

    return {
        input: `packages/ethers/lib.esm/index.js`,
        output: {
            file: `packages/ethers/dist/test-esm.js`,
            //preserveModules: true,
            format: "esm",
            //name: `ethers`,
            sourcemap: true,
            exports: "named"
        },
        context: "window",
        treeshake: false,
        //external,
        plugins
    };
}
*/
const configs = [
    getEsmConfig(),
    getUmdConfig()
];

export default configs;
<commit_msg>Fix WebWorker support in rollup files (#2976).<commit_after>"use strict";

// This files has a lot of overlap with rollup-pre-alias.config.js
// - should we pull some of this functionality out?

import commonjs from '@rollup/plugin-commonjs';
import resolveNode from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";

import sourcemaps from 'rollup-plugin-sourcemaps';

// We only need this for its version (we inject it into a require)
import elliptic from "elliptic";

function addUtilsReplace(plugins) {

    // Remove the buffer check from BN.js
    plugins.push(replace({
        "require('buffer')": "/*RicMoo:ethers:require(buffer)*/(null)",
        include: "**/lib/bn.js",
        delimiters: [ '', '' ]
    }));

    // Remove the util from inhjerits (forces browser inherits)
    plugins.push(replace({
        "require('util')": "/*RicMoo:ethers:require(util)*/(null)",
        include: "**/inherits/inherits.js",
        delimiters: [ '', '' ]
    }));

    return plugins;
}

function addLangReplace(plugins) {

    plugins.push(replace({
        'require("./wordlists")': 'require("./browser-wordlists")/*RicMoo:ethers:require(wordlists)*/',
        include: "**/wordlists/lib/index.js",
        delimiters: [ '', '' ]
    }));

    return plugins;
}

function addEllipticReplace(plugins) {

    // Replace the package.json in elliptic
    plugins.push(replace({
        "require('../package.json')": `/*RicMoo:ethers*/{ version: "${ elliptic.version }" }`,
        include: "**/lib/elliptic.js",
        delimiters: [ '', '' ]
    }));

    // Nuke a bunch of requires we don't need in elliptic
    const thrower = "(function() { throw new Error('unsupported'); })";
    const crash = "(null).crash()";
    [
        { name: "./edwards", filename: "curve/index.js" },
        { name: "./mont", filename: "curve/index.js" },
        { name: "./elliptic/eddsa", filename: "lib/elliptic.js" },
        { name: "brorand", filename: "ec/index.js", text: thrower },
        { name: "brorand", filename: "lib/elliptic.js", text: thrower },
        { name: "./precomputed/secp256k1", filename: "elliptic/curves.js", text: crash },
    ].forEach(({ name, filename, text }) => {
        if (text == null) { text = "(null)"; }
        const replacement = {
            include: `**/${ filename }`,
            delimiters: [ '', '' ]
        };
        replacement[`require('${ name }')`] = `/*RicMoo:ethers:require(${ name })*/${ text }`,
        plugins.push(replace(replacement));
    });

    return plugins;
}

function getUmdConfig() {
    const plugins = [ ];

    plugins.push(sourcemaps());

    addUtilsReplace(plugins);
    addEllipticReplace(plugins);
    addLangReplace(plugins);

    plugins.push(resolveNode({
        mainFields: [ "browser", "main" ]
    }));
    plugins.push(commonjs({ }));

    return {
        input: `packages/ethers/lib/index.js`,
        output: {
            file: `packages/ethers/dist/ethers.umd.js`,
            format: "umd",
            name: "ethers",
            sourcemap: true
        },
        context: "commonjsGlobal",
        treeshake: false,
        plugins
    };
}

function getEsmConfig() {
    const plugins = [ ];

    plugins.push(sourcemaps());

    addUtilsReplace(plugins);

    // Note: We do not need to replace the elliptic problems because they
    //       were addressed when aliasing (in rollup-pre-alias.config.js)

    plugins.push(resolveNode({ }));
    plugins.push(commonjs({ }));

    return {
        input: `packages/ethers/lib.esm/index.js`,
        output: {
            file: `packages/ethers/dist/ethers.esm.js`,
            format: "esm",
            sourcemap: true
        },
        context: "commonjsGlobal",
        treeshake: false,
        plugins
    };
}

/*
function getConfig() {
    const plugins = [ ];

    // Remove the buffer check from BN.js
    plugins.push(replace({
        "require('buffer')": "/ * RicMoo:ethers * /(null)",
        include: "* * / lib/bn.js",
        delimiters: [ '', '' ]
    }));
    plugins.push(resolveNode({
        preferBuiltins: true
    }));
    plugins.push(commonjs({ }));

    return {
        input: `packages/ethers/lib.esm/index.js`,
        output: {
            file: `packages/ethers/dist/test-esm.js`,
            //preserveModules: true,
            format: "esm",
            //name: `ethers`,
            sourcemap: true,
            exports: "named"
        },
        context: "window",
        treeshake: false,
        //external,
        plugins
    };
}
*/
const configs = [
    getEsmConfig(),
    getUmdConfig()
];

export default configs;
<|endoftext|>


<commit_before>/**
 * rudiment - A simple CRUD resource manager
 * https://github.com/gavinhungry/rudiment
 */

(function() {
  'use strict';

  /**
   * @constructor for Rudiment objects
   *
   * Rudiment objects have prototype methods that can be overridden as needed.
   * By default, the database should support a subset of MongoDB API methods.
   *
   * The schema is a predicate function that determines the validity of a
   * candidate document. The props array is filled automatically if possible.
   *
   * @param {Object} opts
   * @param {Object} opts.db - database
   * @param {Function} [opts.schema] - predicate function for schema validation
   * @param {Array} [opts.props] - document properties to filter
   * @param {String} [opts.key] - document key in database (defaults to first prop or '_id')
   * @param {Array} [opts.uniq] - document properties to consider unique
   */
  var Rudiment = function(opts) {
    var that = this;
    opts = opts || {};

    this._db = opts.db;
    if (!this._db) {
      throw new Error('No database provided');
    }

    this._schema = opts.schema;

    // attempt to get props from the passed schema
    var schemaProps;
    if (this._schema && this._schema.toJSON) {
      var obj = this._schema.toJSON();
      if (obj && obj.properties) {
        schemaProps = Object.keys(obj.properties);
      }
    }

    this._path = opts.path;
    this._key = opts.key || (schemaProps ? schemaProps[0] : null) || '_id';
    this._props = opts.props || schemaProps;
    this._uniq = opts.uniq || [this._key];

    // allow the constructor to override any of the prototype methods
    Object.keys(Rudiment.prototype).forEach(function(method) {
      if (opts[method]) {
        that[method] = opts[method];
      }
    });
  };

  Rudiment.prototype = {
    /**
     * Remove extraneous properties from a document
     *
     * @param {Object} doc - a document to clean
     * @return {Object} a copy of the cleaned document
     */
    clean: function(doc) {
      if (!this._props) {
        return doc;
      }

      return this._props.reduce(function(obj, prop) {
        obj[prop] = doc[prop];
        return obj;
      }, {});
    },

    /**
     * Check if a document is valid
     *
     * A document is valid if it passes the schema. If no schema is defined,
     * always returns true.
     *
     * @param {Object} doc - a document to test
     * @return {Boolean}
     */
    valid: function(doc) {
      return this._schema ? this._schema(doc) : true;
    },

    /**
     * Check if a document is admissible
     *
     * A document is admissible if it passes the valid predicate, and no other
     * document in the database is already using its unique keys.
     *
     * @param {Object} doc - a document to test
     * @param {Function} callback(err, {Boolean})
     */
    admissible: function(doc, callback) {
      if (!this.valid(doc)) {
        callback(null, false);
        return;
      }

      this._db.find({
        $or: this._uniq.map(function(uniq) {
          return o(uniq, doc[uniq]);
        })
      }, function(err, docs) {
        if (err) {
          return callback(err, false);
        }

        callback(null, !docs.length);
      });
    },

    /**
     * REST handler
     *
     * @param {ServerResponse} res
     * @param {Function} [map] - map data before responding
     */
    rest: function(res, map) {
      var that = this;

      return function(err, data, method) {
        if (err) {
          return res.status(500).end();
        }

        if (typeof map === 'function') {
          data = map(data);
        }

        if (method === 'create') {
          return data ?
            res.status(201)
              .header('Location', '/' + that._path + '/' + data[that._key])
              .json(data) :
            res.status(409).end();
        }

        if (method === 'update' && data === null) {
          return res.status(409).end();
        }

        return data ?
          res.status(200).json(data) :
          res.status(404).end();
      };
    },

    /**
     * Insert a new document into the database
     *
     * @param {Object} doc - a document to insert
     * @param {Function} callback(err, {Object|null})
     */
    create: function(doc, callback) {
      var that = this;

      this.admissible(doc, function(err, ok) {
        if (!ok) {
          return callback(err, null, 'create');
        }

        doc = that.clean(doc);
        that._db.insert(doc, function(err, doc) {
          callback(err, doc, 'create');
        });
      });
    },

    /**
     * Get a document from the database by key
     *
     * @param {Mixed} id - key for document to get
     * @param {Function} callback(err, {Object|null})
     */
    read: function(id, callback) {
      this._db.findOne(o(this._key, id), callback);
    },

    /**
     * Get all documents from the database
     *
     * @param {Function} callback(err, {Array})
     */
    readAll: function(callback) {
      this._db.find({}, callback);
    },

    /**
     * Update a document in the database by key
     *
     * The key and unique values of a document cannot be updated. Remove the
     * document and create a new document instead.
     *
     * @param {Mixed} id - key for document to update
     * @param {Object} updates - updates to apply to document
     * @param {Function} callback(err, {Boolean})
     */
    update: function(id, updates, callback) {
      var that = this;
      updates = updates || {};

      this.read(id, function(err, doc) {
        if (err) {
          return callback(err, null);
        }

        if (!doc) {
          return callback(null, false);
        }

        Object.keys(doc).forEach(function(prop) {
          if (updates.hasOwnProperty(prop)) {
            doc[prop] = updates[prop];
          }
        });

        // null means the document exists but could not be updated
        if (!that.valid(doc)) {
          return callback(null, null, 'update');
        }

        // remove key and unique properties
        delete doc[that._key];
        that._uniq.forEach(function(uniq) {
          delete doc[uniq];
        });

        return that._db.update(o(that._key, id), {
          $set: doc
        }, function(err, num) {
          if (err) {
            return callback(err, null);
          }

          callback(null, num > 0);
        });
      });
    },

    /**
     * Delete a document from the database
     *
     * @param {Mixed} id - key for document to delete
     * @param {Function} callback(err, {Boolean})
     */
    delete: function(id, callback) {
      this._db.remove(o(this._key, id), function(err, num) {
        if (err) {
          return callback(err, null);
        }

        callback(null, num > 0);
      });
    }
  };

  /**
   * Create an object with a variable key
   *
   * @param {Mixed} key
   * @param {Mixed} value
   * @return {Object}
   */
  var o = function(key, value) {
    var obj = {};
    obj[key] = value;

    return obj;
  };

  module.exports = Rudiment;

})();
<commit_msg>Get method when needed from ServerResponse<commit_after>/**
 * rudiment - A simple CRUD resource manager
 * https://github.com/gavinhungry/rudiment
 */

(function() {
  'use strict';

  /**
   * @constructor for Rudiment objects
   *
   * Rudiment objects have prototype methods that can be overridden as needed.
   * By default, the database should support a subset of MongoDB API methods.
   *
   * The schema is a predicate function that determines the validity of a
   * candidate document. The props array is filled automatically if possible.
   *
   * @param {Object} opts
   * @param {Object} opts.db - database
   * @param {Function} [opts.schema] - predicate function for schema validation
   * @param {Array} [opts.props] - document properties to filter
   * @param {String} [opts.key] - document key in database (defaults to first prop or '_id')
   * @param {Array} [opts.uniq] - document properties to consider unique
   */
  var Rudiment = function(opts) {
    var that = this;
    opts = opts || {};

    this._db = opts.db;
    if (!this._db) {
      throw new Error('No database provided');
    }

    this._schema = opts.schema;

    // attempt to get props from the passed schema
    var schemaProps;
    if (this._schema && this._schema.toJSON) {
      var obj = this._schema.toJSON();
      if (obj && obj.properties) {
        schemaProps = Object.keys(obj.properties);
      }
    }

    this._path = opts.path;
    this._key = opts.key || (schemaProps ? schemaProps[0] : null) || '_id';
    this._props = opts.props || schemaProps;
    this._uniq = opts.uniq || [this._key];

    // allow the constructor to override any of the prototype methods
    Object.keys(Rudiment.prototype).forEach(function(method) {
      if (opts[method]) {
        that[method] = opts[method];
      }
    });
  };

  Rudiment.prototype = {
    /**
     * Remove extraneous properties from a document
     *
     * @param {Object} doc - a document to clean
     * @return {Object} a copy of the cleaned document
     */
    clean: function(doc) {
      if (!this._props) {
        return doc;
      }

      return this._props.reduce(function(obj, prop) {
        obj[prop] = doc[prop];
        return obj;
      }, {});
    },

    /**
     * Check if a document is valid
     *
     * A document is valid if it passes the schema. If no schema is defined,
     * always returns true.
     *
     * @param {Object} doc - a document to test
     * @return {Boolean}
     */
    valid: function(doc) {
      return this._schema ? this._schema(doc) : true;
    },

    /**
     * Check if a document is admissible
     *
     * A document is admissible if it passes the valid predicate, and no other
     * document in the database is already using its unique keys.
     *
     * @param {Object} doc - a document to test
     * @param {Function} callback(err, {Boolean})
     */
    admissible: function(doc, callback) {
      if (!this.valid(doc)) {
        callback(null, false);
        return;
      }

      this._db.find({
        $or: this._uniq.map(function(uniq) {
          return o(uniq, doc[uniq]);
        })
      }, function(err, docs) {
        if (err) {
          return callback(err, false);
        }

        callback(null, !docs.length);
      });
    },

    /**
     * REST handler
     *
     * @param {ServerResponse} res
     * @param {Function} [map] - map data before responding
     */
    rest: function(res, map) {
      var that = this;
      var method = res.req.method;

      return function(err, data) {
        if (err) {
          return res.status(500).end();
        }

        if (typeof map === 'function') {
          data = map(data);
        }

        if (method === 'GET') {
          return data ?
            res.status(201)
              .header('Location', '/' + that._path + '/' + data[that._key])
              .json(data) :
            res.status(409).end();
        }

        if (method === 'PUT' && data === null) {
          return res.status(409).end();
        }

        return data ?
          res.status(200).json(data) :
          res.status(404).end();
      };
    },

    /**
     * Insert a new document into the database
     *
     * @param {Object} doc - a document to insert
     * @param {Function} callback(err, {Object|null})
     */
    create: function(doc, callback) {
      var that = this;

      this.admissible(doc, function(err, ok) {
        if (!ok) {
          return callback(err, null);
        }

        doc = that.clean(doc);
        that._db.insert(doc, function(err, doc) {
          callback(err, doc);
        });
      });
    },

    /**
     * Get a document from the database by key
     *
     * @param {Mixed} id - key for document to get
     * @param {Function} callback(err, {Object|null})
     */
    read: function(id, callback) {
      this._db.findOne(o(this._key, id), callback);
    },

    /**
     * Get all documents from the database
     *
     * @param {Function} callback(err, {Array})
     */
    readAll: function(callback) {
      this._db.find({}, callback);
    },

    /**
     * Update a document in the database by key
     *
     * The key and unique values of a document cannot be updated. Remove the
     * document and create a new document instead.
     *
     * @param {Mixed} id - key for document to update
     * @param {Object} updates - updates to apply to document
     * @param {Function} callback(err, {Boolean})
     */
    update: function(id, updates, callback) {
      var that = this;
      updates = updates || {};

      this.read(id, function(err, doc) {
        if (err) {
          return callback(err, null);
        }

        if (!doc) {
          return callback(null, false);
        }

        Object.keys(doc).forEach(function(prop) {
          if (updates.hasOwnProperty(prop)) {
            doc[prop] = updates[prop];
          }
        });

        // null means the document exists but could not be updated
        if (!that.valid(doc)) {
          return callback(null, null);
        }

        // remove key and unique properties
        delete doc[that._key];
        that._uniq.forEach(function(uniq) {
          delete doc[uniq];
        });

        return that._db.update(o(that._key, id), {
          $set: doc
        }, function(err, num) {
          if (err) {
            return callback(err, null);
          }

          callback(null, num > 0);
        });
      });
    },

    /**
     * Delete a document from the database
     *
     * @param {Mixed} id - key for document to delete
     * @param {Function} callback(err, {Boolean})
     */
    delete: function(id, callback) {
      this._db.remove(o(this._key, id), function(err, num) {
        if (err) {
          return callback(err, null);
        }

        callback(null, num > 0);
      });
    }
  };

  /**
   * Create an object with a variable key
   *
   * @param {Mixed} key
   * @param {Mixed} value
   * @return {Object}
   */
  var o = function(key, value) {
    var obj = {};
    obj[key] = value;

    return obj;
  };

  module.exports = Rudiment;

})();
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';

import { withStyles, createStyleSheet } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';

import SelectForm from '../forms/selectForm';
import TextFieldForm from '../forms/textFieldForm';

const messages = {
  choose: 'Choose',
  labels: {
    search: 'Search',
    country: 'Country',
  },
  clear: 'clear',
};

const COUNTRY_MENU = [
  {
    value: 'pl',
    label: 'Poland',
  },
  {
    value: 'fr',
    label: 'France',
  },
  {
    value: 'it',
    label: 'Italy',
  },
];

const styleSheet = createStyleSheet('PartnerFilter', theme => ({
  filterContainer: {
    padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 3}px`,
    background: '#F6F6F6',
  },
  button: {
    display: 'flex',
    justifyContent: 'flex-end',
  },
}));

const handleSubmit = (values) => {

};

const PartnerFilter = (props) => {
  const { classes, handleSubmit, reset } = props;
  return (
    <form onSubmit={handleSubmit}>
      <Grid item xs={12} className={classes.filterContainer} >
        <Grid container direction="row" >
          <Grid item sm={4} xs={12} >
            <TextFieldForm
              label={messages.labels.search}
              placeholder={messages.labels.search}
              fieldName="organizationName"
              optional
            />
          </Grid>
          <Grid item sm={4} xs={12}>
            <SelectForm
              fieldName="country"
              label={messages.labels.country}
              values={COUNTRY_MENU}
              optional
            />
          </Grid>
          <Grid className={classes.button} item sm={4}>
            <Button
              color="accent"
              onTouchTap={reset}
            >
              {messages.clear}
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </form >
  );
};

PartnerFilter.propTypes = {
  classes: PropTypes.object.isRequired,
  handleSubmit: PropTypes.func.isRequired,
  /**
   *  reset function
   */
  reset: PropTypes.func.isRequired,
};

const formPartnerFilter = reduxForm({
  form: 'tableFilter',
  handleSubmit,
})(PartnerFilter);

export default withStyles(styleSheet)(formPartnerFilter);
<commit_msg>updated partner filter<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';

import { withStyles, createStyleSheet } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';

import SelectForm from '../forms/selectForm';
import TextFieldForm from '../forms/textFieldForm';

const messages = {
  choose: 'Choose',
  labels: {
    search: 'Search',
    country: 'Country',
    verificationStatus: 'Verification Status',
    typeOfOrganization: 'Type of Organization',
    sectorArea: 'Sector & Area of specialization',
    populations: 'Populations of concer',
  },
  clear: 'clear',
};

const VERIFICATION_MENU = [
  {
    value: 'all',
    label: 'All',
  },
  {
    value: 'pen',
    label: 'Pending',
  },
  {
    value: 'ver',
    label: 'Verified',
  },
  {
    value: 'un',
    label: 'Unverified',
  },
];

const ALL_MENU = [
  {
    value: 'all',
    label: 'All',
  },
];

const COUNTRY_MENU = [
  {
    value: 'all',
    label: 'All',
  },
  {
    value: 'pl',
    label: 'Poland',
  },
  {
    value: 'fr',
    label: 'France',
  },
  {
    value: 'it',
    label: 'Italy',
  },
];

const styleSheet = createStyleSheet('PartnerFilter', theme => ({
  filterContainer: {
    padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 3}px`,
    background: '#F6F6F6',
  },
  button: {
    display: 'flex',
    justifyContent: 'flex-end',
  },
}));

const handleSubmit = (values) => {

};

const PartnerFilter = (props) => {
  const { classes, handleSubmit, reset } = props;
  return (
    <form onSubmit={handleSubmit}>
      <Grid item xs={12} className={classes.filterContainer} >
        <Grid container direction="row" >
          <Grid item sm={4} xs={12} >
            <TextFieldForm
              label={messages.labels.search}
              placeholder={messages.labels.search}
              fieldName="organizationName"
              optional
            />
          </Grid>
          <Grid item sm={4} xs={12}>
            <SelectForm
              fieldName="verificationStatus"
              label={messages.labels.verificationStatus}
              values={VERIFICATION_MENU}
              optional
            />
          </Grid>
          <Grid item sm={4} xs={12}>
            <SelectForm
              fieldName="typeOfOrganization"
              label={messages.labels.typeOfOrganization}
              values={ALL_MENU}
              optional
            />
          </Grid>

        </Grid>
        <Grid container direction="row" >
          <Grid item sm={4} xs={12} >
            <SelectForm
              fieldName="country"
              label={messages.labels.country}
              values={COUNTRY_MENU}
              optional
            />
          </Grid>
          <Grid item sm={4} xs={12}>
            <SelectForm
              fieldName="sector"
              label={messages.labels.sectorArea}
              values={ALL_MENU}
              optional
            />
          </Grid>
          <Grid item sm={4} xs={12}>
            <SelectForm
              fieldName="populations"
              label={messages.labels.populations}
              values={ALL_MENU}
              optional
            />
          </Grid>

        </Grid>
        <Grid className={classes.button} item sm={12}>
          <Button
            color="accent"
            onTouchTap={reset}
          >
            {messages.clear}
          </Button>
        </Grid>
      </Grid>
    </form >
  );
};

PartnerFilter.propTypes = {
  classes: PropTypes.object.isRequired,
  handleSubmit: PropTypes.func.isRequired,
  /**
   *  reset function
   */
  reset: PropTypes.func.isRequired,
};

const formPartnerFilter = reduxForm({
  form: 'tableFilter',
  handleSubmit,
})(PartnerFilter);

export default withStyles(styleSheet)(formPartnerFilter);
<|endoftext|>


<commit_before>import SimpleSchema from 'simpl-schema';

import Users from "meteor/vulcan:users";
import Posts from "meteor/vulcan:posts";
import Comments from "meteor/vulcan:comments";

/**
 * @summary Vote schema
 * @type {SimpleSchema}
 */
const voteSchema = new SimpleSchema({
  itemId: {
    type: String
  },
  power: {
    type: Number,
    optional: true
  },
  votedAt: {
    type: Date,
    optional: true
  }
});

Users.addField([
  /**
    An array containing comments upvotes
  */
  {
    fieldName: 'upvotedComments',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'upvotedComments',
        type: '[Comment]',
        resolver: async (user, args, {currentUser, Users, Comments}) => {
          if (!user.upvotedComments) return [];
          const comments = await Comments.loader.loadMany(user.upvotedComments);
          return Users.restrictViewableFields(currentUser, Comments, comments);
        }
      },
    }
  },
  {
    fieldName: 'upvotedComments.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  },
  /**
    An array containing posts upvotes
  */
  {
    fieldName: 'upvotedPosts',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'upvotedPosts',
        type: '[Post]',
        resolver: async (user, args, {currentUser, Users, Posts}) => {
          if (!user.upvotedPosts) return [];
          const posts = await Posts.loader.loadMany(user.upvotedPosts);
          return Users.restrictViewableFields(currentUser, Posts, posts);
        }
      },
    }
  },
  {
    fieldName: 'upvotedPosts.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  },
  /**
    An array containing comment downvotes
  */
  {
    fieldName: 'downvotedComments',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'downvotedComments',
        type: '[Comment]',
        resolver: async (user, args, {currentUser, Users, Comments}) => {
          if (!user.downvotedComments) return [];
          const comments = await Comments.loader.loadMany(user.downvotedComments);
          return Users.restrictViewableFields(currentUser, Comments, comments);
        }
      },
    }
  },
  {
    fieldName: 'downvotedComments.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  },
  /**
    An array containing posts downvotes
  */
  {
    fieldName: 'downvotedPosts',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'downvotedPosts',
        type: '[Post]',
        resolver: async (user, args, {currentUser, Users, Posts}) => {
          if (!user.downvotedPosts) return [];
          const posts = await Posts.loader.loadMany(user.downvotedPosts);
          return Users.restrictViewableFields(currentUser, Posts, posts);
        }
      },
    }
  },
  {
    fieldName: 'downvotedPosts.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  }
]);

Posts.addField([
  /**
    How many upvotes the post has received
  */
  {
    fieldName: "upvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of the post's upvoters
  */
  {
    fieldName: "upvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName: 'upvoters',
        type: '[User]',
        resolver: async (post, args, {currentUser, Users}) => {
          if (!post.upvoters) return [];
          const upvoters = await Users.loader.loadMany(post.upvoters);
          return Users.restrictViewableFields(currentUser, Users, upvoters);
        },
      },
    }
  },
  {
    fieldName: "upvoters.$",
    fieldSchema: {
      type: String,
      optional: true
    }
  },
  /**
    How many downvotes the post has received
  */
  {
    fieldName: "downvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of the post's downvoters
  */
  {
    fieldName: "downvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName: 'downvoters',
        type: '[User]',
        resolver: async (post, args, {currentUser, Users}) => {
          if (!post.downvoters) return [];
          const downvoters = await Users.loader.loadMany(post.downvoters);
          return Users.restrictViewableFields(currentUser, Users, downvoters);
        },
      },
    }
  },
  {
    fieldName: "downvoters.$",
    fieldSchema: {
      type: String,
      optional: true,
    }
  },
  /**
    The post's base score (not factoring in the post's age)
  */
  {
    fieldName: "baseScore",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    The post's current score (factoring in age)
  */
  {
    fieldName: "score",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
]);

Comments.addField([
  /**
    The number of upvotes the comment has received
  */
  {
    fieldName: "upvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of upvoters
  */
  {
    fieldName: "upvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName: 'upvoters',
        type: '[User]',
        resolver: async (comment, args, {currentUser, Users}) => {
          if (!comment.upvoters) return [];
          const upvoters = await Users.loader.loadMany(comment.upvoters);
          return Users.restrictViewableFields(currentUser, Users, upvoters);
        },
      },
    }
  },
  {
    fieldName: "upvoters.$",
    fieldSchema: {
      type: String,
      optional: true
    }
  },
  /**
    The number of downvotes the comment has received
  */
  {
    fieldName: "downvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of downvoters
  */
  {
    fieldName: "downvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName:'downvoters',
        type: '[User]',
        resolver: async (comment, args, {currentUser, Users}) => {
          if (!comment.downvoters) return [];
          const downvoters = await Users.loader.loadMany(comment.downvoters);
          return Users.restrictViewableFields(currentUser, Users, downvoters);
        },
      },
    }
  },
  {
    fieldName: "downvoters.$",
    fieldSchema: {
      type: String,
      optional: true,
    }
  },
  /**
    The comment's base score (not factoring in the comment's age)
  */
  {
    fieldName: "baseScore",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    The comment's current score (factoring in age)
  */
  {
    fieldName: "score",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
]);

<commit_msg>fix type error<commit_after>import SimpleSchema from 'simpl-schema';

import Users from "meteor/vulcan:users";
import Posts from "meteor/vulcan:posts";
import Comments from "meteor/vulcan:comments";

/**
 * @summary Vote schema
 * @type {SimpleSchema}
 */
const voteSchema = new SimpleSchema({
  itemId: {
    type: String
  },
  power: {
    type: Number,
    optional: true
  },
  votedAt: {
    type: Date,
    optional: true
  }
});

Users.addField([
  /**
    An array containing comments upvotes
  */
  {
    fieldName: 'upvotedComments',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'upvotedComments',
        type: '[Vote]',
        resolver: async (user, args, {currentUser, Users, Comments}) => {
          if (!user.upvotedComments) return [];
          const comments = await Comments.loader.loadMany(user.upvotedComments);
          return Users.restrictViewableFields(currentUser, Comments, comments);
        }
      },
    }
  },
  {
    fieldName: 'upvotedComments.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  },
  /**
    An array containing posts upvotes
  */
  {
    fieldName: 'upvotedPosts',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'upvotedPosts',
        type: '[Vote]',
        resolver: async (user, args, {currentUser, Users, Posts}) => {
          if (!user.upvotedPosts) return [];
          const posts = await Posts.loader.loadMany(user.upvotedPosts);
          return Users.restrictViewableFields(currentUser, Posts, posts);
        }
      },
    }
  },
  {
    fieldName: 'upvotedPosts.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  },
  /**
    An array containing comment downvotes
  */
  {
    fieldName: 'downvotedComments',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'downvotedComments',
        type: '[Vote]',
        resolver: async (user, args, {currentUser, Users, Comments}) => {
          if (!user.downvotedComments) return [];
          const comments = await Comments.loader.loadMany(user.downvotedComments);
          return Users.restrictViewableFields(currentUser, Comments, comments);
        }
      },
    }
  },
  {
    fieldName: 'downvotedComments.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  },
  /**
    An array containing posts downvotes
  */
  {
    fieldName: 'downvotedPosts',
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: Users.owns,
      resolveAs: {
        fieldName: 'downvotedPosts',
        type: '[Vote]',
        resolver: async (user, args, {currentUser, Users, Posts}) => {
          if (!user.downvotedPosts) return [];
          const posts = await Posts.loader.loadMany(user.downvotedPosts);
          return Users.restrictViewableFields(currentUser, Posts, posts);
        }
      },
    }
  },
  {
    fieldName: 'downvotedPosts.$',
    fieldSchema: {
      type: voteSchema,
      optional: true
    }
  }
]);

Posts.addField([
  /**
    How many upvotes the post has received
  */
  {
    fieldName: "upvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of the post's upvoters
  */
  {
    fieldName: "upvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName: 'upvoters',
        type: '[User]',
        resolver: async (post, args, {currentUser, Users}) => {
          if (!post.upvoters) return [];
          const upvoters = await Users.loader.loadMany(post.upvoters);
          return Users.restrictViewableFields(currentUser, Users, upvoters);
        },
      },
    }
  },
  {
    fieldName: "upvoters.$",
    fieldSchema: {
      type: String,
      optional: true
    }
  },
  /**
    How many downvotes the post has received
  */
  {
    fieldName: "downvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of the post's downvoters
  */
  {
    fieldName: "downvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName: 'downvoters',
        type: '[User]',
        resolver: async (post, args, {currentUser, Users}) => {
          if (!post.downvoters) return [];
          const downvoters = await Users.loader.loadMany(post.downvoters);
          return Users.restrictViewableFields(currentUser, Users, downvoters);
        },
      },
    }
  },
  {
    fieldName: "downvoters.$",
    fieldSchema: {
      type: String,
      optional: true,
    }
  },
  /**
    The post's base score (not factoring in the post's age)
  */
  {
    fieldName: "baseScore",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    The post's current score (factoring in age)
  */
  {
    fieldName: "score",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
]);

Comments.addField([
  /**
    The number of upvotes the comment has received
  */
  {
    fieldName: "upvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of upvoters
  */
  {
    fieldName: "upvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName: 'upvoters',
        type: '[User]',
        resolver: async (comment, args, {currentUser, Users}) => {
          if (!comment.upvoters) return [];
          const upvoters = await Users.loader.loadMany(comment.upvoters);
          return Users.restrictViewableFields(currentUser, Users, upvoters);
        },
      },
    }
  },
  {
    fieldName: "upvoters.$",
    fieldSchema: {
      type: String,
      optional: true
    }
  },
  /**
    The number of downvotes the comment has received
  */
  {
    fieldName: "downvotes",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    An array containing the `_id`s of downvoters
  */
  {
    fieldName: "downvoters",
    fieldSchema: {
      type: Array,
      optional: true,
      viewableBy: ['guests'],
      resolveAs: {
        fieldName:'downvoters',
        type: '[User]',
        resolver: async (comment, args, {currentUser, Users}) => {
          if (!comment.downvoters) return [];
          const downvoters = await Users.loader.loadMany(comment.downvoters);
          return Users.restrictViewableFields(currentUser, Users, downvoters);
        },
      },
    }
  },
  {
    fieldName: "downvoters.$",
    fieldSchema: {
      type: String,
      optional: true,
    }
  },
  /**
    The comment's base score (not factoring in the comment's age)
  */
  {
    fieldName: "baseScore",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
  /**
    The comment's current score (factoring in age)
  */
  {
    fieldName: "score",
    fieldSchema: {
      type: Number,
      optional: true,
      defaultValue: 0,
      viewableBy: ['guests'],
    }
  },
]);

<|endoftext|>


<commit_before>var cp = require('child_process');
var process = require('process');
var fs = require('fs')

// Point this to a file or a tty to see adapter's debug spew
var lldb_log = fs.openSync('/dev/ttys001', 'w');
//var lldb_log = 'ignore'

var lldb = cp.spawn('lldb', ['-b', '-O', 'script import adapter; adapter.stdio(3,4)'], {
    // LLDB has readline attached to its stdin and sometimes spews debug messages to stdout,
    // all of which would interfere with debug session messaging.
    // Instead, we create two new pipes on fds 3 and 4 and connect them to launcher's stdin and stdout
    stdio: ['ignore', lldb_log, lldb_log, 'pipe', 'pipe'],
    cwd: __dirname
});
process.stdin.pipe(lldb.stdio[3]);
lldb.stdio[4].pipe(process.stdout);

// When lldb exits, we exit too
lldb.on('exit', (code) => {
    process.exit(code);
});
<commit_msg>exit events<commit_after>var cp = require('child_process');
var process = require('process');
var fs = require('fs')

// Point this to a file or a tty to see adapter's debug spew
var lldb_log = 'ignore'
var lldb_log = fs.openSync('/dev/pts/19', 'w');

var lldb = cp.spawn('lldb', ['-b', '-O', 'script import adapter; adapter.stdio(3,4)'], {
    // LLDB has readline attached to its stdin and sometimes spews debug messages to stdout,
    // all of which would interfere with debug session messaging.
    // Instead, we create two new pipes on fds 3 and 4 and connect them to launcher's stdin and stdout
    stdio: ['ignore', lldb_log, lldb_log, 'pipe', 'pipe'],
    cwd: __dirname
});
process.stdin.pipe(lldb.stdio[3]);
lldb.stdio[4].pipe(process.stdout);

// When lldb exits, we exit too
lldb.on('exit', (code) => {
    process.exit(code);
});
<|endoftext|>


<commit_before>'use strict';

let cli = require('heroku-cli-util');
let co  = require('co');

function* run (context, heroku) {
  let drains = yield heroku.request({path: `/apps/${context.app}/log-drains`});
  if (context.flags.json) {
    cli.log(JSON.stringify(drains, null, 2));
  } else {
    drains.forEach(function (drain) {
      cli.log(`${cli.color.cyan(drain.url)} (${cli.color.green(drain.token)})`);
    });
  }
}

module.exports = {
  topic: 'drains',
  description: 'display the log drains of an app',
  needsApp: true,
  needsAuth: true,
  flags: [
    {name: 'json', description: 'output in json format'},
  ],
  run: cli.command(co.wrap(run))
};
<commit_msg>added extended output<commit_after>'use strict';

let cli = require('heroku-cli-util');
let co  = require('co');

function* run (context, heroku) {
  let path = `/apps/${context.app}/log-drains`;
  if (context.flags.extended) path = path + '?extended=true';
  let drains = yield heroku.request({path});
  if (context.flags.json) {
    cli.log(JSON.stringify(drains, null, 2));
  } else {
    drains.forEach(function (drain) {
      let output = `${cli.color.cyan(drain.url)} (${cli.color.green(drain.token)})`;
      if (drain.extended) output = output + ` drain_id=${drain.extended.drain_id}`;
      cli.log(output);
    });
  }
}

module.exports = {
  topic: 'drains',
  description: 'display the log drains of an app',
  needsApp: true,
  needsAuth: true,
  flags: [
    {name: 'json', description: 'output in json format'},
    {name: 'extended', char: 'x', hidden: true},
  ],
  run: cli.command(co.wrap(run))
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

const color   = require('cli-color');
const Sitemap = require('sitemap');
const program = require('commander');
const fs      = require('fs');
const Path    = require('path');
const common  = require('./common');

program
    .version('0.2.0')
    .description('Generate sitemap.xml')
    .parse(process.argv);

const urls = [
    // path (without .html),               changefreq, priority, exclude languages
    // ==================== Section: "static" ====================
    ['home',                               'monthly', 1.00],
    ['tour',                               'monthly', 0.80],
    ['why-us',                             'monthly', 0.80],
    ['platforms',                          'monthly', 0.80],

    ['about-us',                           'monthly', 0.80],
    ['binary-in-numbers',                  'monthly', 0.80],
    ['careers',                            'monthly', 0.80],
    ['careers-for-americans',              'monthly', 0.80],
    ['contact',                            'monthly', 0.80],
    ['group-history',                      'monthly', 0.80],
    ['open-positions',                     'monthly', 0.80],
    ['open-positions/job-details',         'monthly', 0.80],

    ['affiliate/signup',                   'monthly', 0.80],
    ['charity',                            'monthly', 0.8],
    ['legal/us_patents',                   'monthly', 0.80],
    ['regulation',                         'monthly', 0.80, 'id'],
    ['responsible-trading',                'monthly', 0.80],
    ['terms-and-conditions',               'monthly', 0.80],
//    ['user/browser-support',               'monthly', 0.80],

    ['liquidity-solutions',                'monthly', 0.80],
    ['multiple-accounts-manager',          'monthly', 0.80],
    ['open-source-projects',               'monthly', 0.80],
    ['partners',                           'monthly', 0.80],
    ['payment-agent',                      'monthly', 0.80],
    ['security-testing',                   'monthly', 0.80],

    ['get-started',                        'monthly', 0.80],
    ['get-started/binary-options',         'monthly', 0.80],
    ['get-started/cfds',                   'monthly', 0.80],
    ['get-started/cryptocurrencies',       'monthly', 0.80],
    ['get-started/forex',                  'monthly', 0.80],
    ['get-started/metals',                 'monthly', 0.80],

    ['metatrader/contract-specifications', 'monthly', 0.80],
    ['metatrader/download',                'monthly', 0.80],
    ['metatrader/how-to-trade-mt5',        'monthly', 0.80],
    ['metatrader/types-of-accounts',       'monthly', 0.80],

    // ==================== Section: "app" ====================
    ['cashier',                            'monthly', 0.80],
    ['cashier/payment_agent_listws',       'monthly', 0.80],
    ['cashier/payment_methods',            'monthly', 0.80],

    ['trading',                            'monthly', 0.80],
    ['multi_barriers_trading',             'monthly', 0.80],

    ['resources/asset_indexws',            'monthly', 0.80],
    ['resources/market_timesws',           'monthly', 0.80],

    // ==================== Section: "landing_pages" ====================
    ['graduates',                          'monthly', 0.80, 'NOT-en'],
    ['hackathon',                          'monthly', 0.80, 'NOT-en'],
];

const url_prefix = 'https://www.binary.com/';
const filename   = 'sitemap.xml';
let excluded     = 0;

const createSitemap = () => {
    const sitemap = Sitemap.createSitemap({
        hostname : url_prefix,
        cacheTime: 600000,
    });

    common.languages
        .map(lang => lang.toLowerCase())
        .forEach((lang) => {
            urls.forEach((entry) => {
                if (!common.isExcluded(entry[3], lang)) {
                    sitemap.add({
                        url       : `${url_prefix}${lang}/${entry[0]}.html`,
                        changefreq: entry[1],
                        priority  : entry[2],
                    });
                } else {
                    excluded++;
                }
            });
        });

    fs.writeFileSync(Path.join(common.root_path, filename), sitemap.toString());
};

const start = Date.now();
process.stdout.write(common.messageStart(`Generating ${filename}`));
createSitemap();
process.stdout.write(common.messageEnd(Date.now() - start));

// Report details
const langs_count = common.languages.length;
const total_count = langs_count * urls.length - excluded;
console.log(`  ${color.green(total_count)} URL nodes total (${color.cyan(langs_count)} Languages ${color.yellowBright('*')} ${color.cyan(urls.length)} URLs ${color.yellowBright('-')} ${color.cyan(excluded)} Excluded)`); // eslint-disable-line no-console
<commit_msg>Update sitemap<commit_after>#!/usr/bin/env node

const color   = require('cli-color');
const Sitemap = require('sitemap');
const program = require('commander');
const fs      = require('fs');
const Path    = require('path');
const common  = require('./common');

program
    .version('0.2.0')
    .description('Generate sitemap.xml')
    .parse(process.argv);

const urls = [
    // path (without .html),               changefreq, priority, exclude languages
    // ==================== Section: "static" ====================
    ['home',                               'monthly', 1.00],
    ['tour',                               'monthly', 0.80],
    ['why-us',                             'monthly', 0.80],
    ['platforms',                          'monthly', 0.80],

    ['about-us',                           'monthly', 0.80],
    ['binary-in-numbers',                  'monthly', 0.80],
    ['careers',                            'monthly', 0.80],
    ['careers-for-americans',              'monthly', 0.80],
    ['contact',                            'monthly', 0.80],
    ['group-history',                      'monthly', 0.80],
    ['open-positions',                     'monthly', 0.80],
    ['open-positions/job-details',         'monthly', 0.80],

    ['affiliate/signup',                   'monthly', 0.80],
    ['charity',                            'monthly', 0.80],
    ['legal/us_patents',                   'monthly', 0.80],
    ['regulation',                         'monthly', 0.80, 'id'],
    ['responsible-trading',                'monthly', 0.80],
    ['terms-and-conditions',               'monthly', 0.80],
//    ['user/browser-support',               'monthly', 0.80],

    ['liquidity-solutions',                'monthly', 0.80],
    ['multiple-accounts-manager',          'monthly', 0.80],
    ['open-source-projects',               'monthly', 0.80],
    ['partners',                           'monthly', 0.80],
    ['payment-agent',                      'monthly', 0.80],
    ['security-testing',                   'monthly', 0.80],

    ['get-started',                        'monthly', 0.80],
    ['get-started/binary-options',         'monthly', 0.80],
    ['get-started/cfds',                   'monthly', 0.80],
    ['get-started/cryptocurrencies',       'monthly', 0.80],
    ['get-started/forex',                  'monthly', 0.80],
    ['get-started/metals',                 'monthly', 0.80],

    ['metatrader/contract-specifications', 'monthly', 0.80],
    ['metatrader/download',                'monthly', 0.80],
    ['metatrader/how-to-trade-mt5',        'monthly', 0.80],
    ['metatrader/types-of-accounts',       'monthly', 0.80],

    // ==================== Section: "app" ====================
    ['cashier',                            'monthly', 0.80],
    ['cashier/payment_agent_listws',       'monthly', 0.80],
    ['cashier/payment_methods',            'monthly', 0.80],

    ['trading',                            'monthly', 0.80],
    ['multi_barriers_trading',             'monthly', 0.80],

    ['resources/asset_indexws',            'monthly', 0.80],
    ['resources/market_timesws',           'monthly', 0.80],

    // ==================== Section: "landing_pages" ====================
    ['graduates',                          'monthly', 0.80, 'NOT-en'],
    ['hackathon',                          'monthly', 0.80, 'NOT-en'],
];

const url_prefix = 'https://www.binary.com/';
const filename   = 'sitemap.xml';
let excluded     = 0;

const createSitemap = () => {
    const sitemap = Sitemap.createSitemap({
        hostname : url_prefix,
        cacheTime: 600000,
    });

    common.languages
        .map(lang => lang.toLowerCase())
        .forEach((lang) => {
            urls.forEach((entry) => {
                if (!common.isExcluded(entry[3], lang)) {
                    sitemap.add({
                        url       : `${url_prefix}${lang}/${entry[0]}.html`,
                        changefreq: entry[1],
                        priority  : entry[2],
                    });
                } else {
                    excluded++;
                }
            });
        });

    fs.writeFileSync(Path.join(common.root_path, filename), sitemap.toString());
};

const start = Date.now();
process.stdout.write(common.messageStart(`Generating ${filename}`));
createSitemap();
process.stdout.write(common.messageEnd(Date.now() - start));

// Report details
const langs_count = common.languages.length;
const total_count = langs_count * urls.length - excluded;
console.log(`  ${color.green(total_count)} URL nodes total (${color.cyan(langs_count)} Languages ${color.yellowBright('*')} ${color.cyan(urls.length)} URLs ${color.yellowBright('-')} ${color.cyan(excluded)} Excluded)`); // eslint-disable-line no-console
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import injectSheet from 'react-jss';
import Webview from 'react-electron-web-view';
import { Icon } from '@meetfranz/ui';
import { defineMessages, intlShape } from 'react-intl';
import classnames from 'classnames';

import { mdiCheckAll } from '@mdi/js';
import * as environment from '../../../environment';
import Appear from '../../../components/ui/effects/Appear';
import UpgradeButton from '../../../components/ui/UpgradeButton';
import { TODOS_PARTITION_ID } from '..';

const messages = defineMessages({
  premiumInfo: {
    id: 'feature.todos.premium.info',
    defaultMessage: '!!!Franz Todos are available to premium users now!',
  },
  upgradeCTA: {
    id: 'feature.todos.premium.upgrade',
    defaultMessage: '!!!Upgrade Account',
  },
  rolloutInfo: {
    id: 'feature.todos.premium.rollout',
    defaultMessage: '!!!Everyone else will have to wait a little longer.',
  },
});

const styles = theme => ({
  root: {
    background: theme.colorBackground,
    position: 'relative',
    borderLeft: [1, 'solid', theme.todos.todosLayer.borderLeftColor],
    zIndex: 300,

    transform: ({ isVisible, width, isTodosServiceActive }) => `translateX(${isVisible || isTodosServiceActive ? 0 : width}px)`,

    '& webview': {
      height: '100%',
    },
  },
  resizeHandler: {
    position: 'absolute',
    left: 0,
    marginLeft: -5,
    width: 10,
    zIndex: 400,
    cursor: 'col-resize',
  },
  dragIndicator: {
    position: 'absolute',
    left: 0,
    width: 5,
    zIndex: 400,
    background: theme.todos.dragIndicator.background,

  },
  premiumContainer: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    width: '80%',
    maxWidth: 300,
    margin: [0, 'auto'],
    textAlign: 'center',
  },
  premiumIcon: {
    marginBottom: 40,
    background: theme.styleTypes.primary.accent,
    fill: theme.styleTypes.primary.contrast,
    padding: 10,
    borderRadius: 10,
  },
  premiumCTA: {
    marginTop: 40,
  },
  isTodosServiceActive: {
    width: 'calc(100% - 368px)',
    position: 'absolute',
    right: 0,
    zIndex: 0,
  },
});

@injectSheet(styles) @observer
class TodosWebview extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    isTodosServiceActive: PropTypes.bool.isRequired,
    isVisible: PropTypes.bool.isRequired,
    handleClientMessage: PropTypes.func.isRequired,
    setTodosWebview: PropTypes.func.isRequired,
    resize: PropTypes.func.isRequired,
    width: PropTypes.number.isRequired,
    minWidth: PropTypes.number.isRequired,
    isTodosIncludedInCurrentPlan: PropTypes.bool.isRequired,
  };

  state = {
    isDragging: false,
    width: 300,
  };

  static contextTypes = {
    intl: intlShape,
  };

  componentWillMount() {
    const { width } = this.props;

    this.setState({
      width,
    });
  }

  componentDidMount() {
    this.node.addEventListener('mousemove', this.resizePanel.bind(this));
    this.node.addEventListener('mouseup', this.stopResize.bind(this));
    this.node.addEventListener('mouseleave', this.stopResize.bind(this));
  }

  startResize = (event) => {
    this.setState({
      isDragging: true,
      initialPos: event.clientX,
      delta: 0,
    });
  };

  resizePanel(e) {
    const { minWidth } = this.props;

    const {
      isDragging,
      initialPos,
    } = this.state;

    if (isDragging && Math.abs(e.clientX - window.innerWidth) > minWidth) {
      const delta = e.clientX - initialPos;

      this.setState({
        delta,
      });
    }
  }

  stopResize() {
    const {
      resize,
      minWidth,
    } = this.props;

    const {
      isDragging,
      delta,
      width,
    } = this.state;

    if (isDragging) {
      let newWidth = width + (delta < 0 ? Math.abs(delta) : -Math.abs(delta));

      if (newWidth < minWidth) {
        newWidth = minWidth;
      }

      this.setState({
        isDragging: false,
        delta: 0,
        width: newWidth,
      });

      resize(newWidth);
    }
  }

  startListeningToIpcMessages() {
    const { handleClientMessage } = this.props;
    if (!this.webview) return;
    this.webview.addEventListener('ipc-message', (e) => {
      // console.log(e);
      handleClientMessage({ channel: e.channel, message: e.args[0] });
    });
  }

  render() {
    const {
      classes,
      isTodosServiceActive,
      isVisible,
      isTodosIncludedInCurrentPlan,
    } = this.props;

    const {
      width,
      delta,
      isDragging,
    } = this.state;

    const { intl } = this.context;

    let displayedWidth = isVisible ? width : 0;
    if (isTodosServiceActive) {
      displayedWidth = null;
    }

    return (

 this.stopResize()}
        ref={(node) => { this.node = node; }}
        id="todos-panel"
      >

 this.startResize(e)}
        />
        {isDragging && (

        )}
        {isTodosIncludedInCurrentPlan ? (
          <Webview
            className={classes.webview}
            onDidAttach={() => {
              const { setTodosWebview } = this.props;
              setTodosWebview(this.webview);
              this.startListeningToIpcMessages();
            }}
            partition={TODOS_PARTITION_ID}
            preload="./features/todos/preload.js"
            ref={(webview) => { this.webview = webview ? webview.view : null; }}
            src={environment.TODOS_FRONTEND}
          />
        ) : (
          <Appear>

              <Icon icon={mdiCheckAll} className={classes.premiumIcon} size={4} />

{intl.formatMessage(messages.premiumInfo)}

{intl.formatMessage(messages.rolloutInfo)}

              <UpgradeButton
                className={classes.premiumCTA}
                gaEventInfo={{ category: 'Todos', event: 'upgrade' }}
                short
              />

          </Appear>
        )}

    );
  }
}

export default TodosWebview;
<commit_msg>disable contextIsolation<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import injectSheet from 'react-jss';
import Webview from 'react-electron-web-view';
import { Icon } from '@meetfranz/ui';
import { defineMessages, intlShape } from 'react-intl';
import classnames from 'classnames';

import { mdiCheckAll } from '@mdi/js';
import * as environment from '../../../environment';
import Appear from '../../../components/ui/effects/Appear';
import UpgradeButton from '../../../components/ui/UpgradeButton';
import { TODOS_PARTITION_ID } from '..';

const messages = defineMessages({
  premiumInfo: {
    id: 'feature.todos.premium.info',
    defaultMessage: '!!!Franz Todos are available to premium users now!',
  },
  upgradeCTA: {
    id: 'feature.todos.premium.upgrade',
    defaultMessage: '!!!Upgrade Account',
  },
  rolloutInfo: {
    id: 'feature.todos.premium.rollout',
    defaultMessage: '!!!Everyone else will have to wait a little longer.',
  },
});

const styles = theme => ({
  root: {
    background: theme.colorBackground,
    position: 'relative',
    borderLeft: [1, 'solid', theme.todos.todosLayer.borderLeftColor],
    zIndex: 300,

    transform: ({ isVisible, width, isTodosServiceActive }) => `translateX(${isVisible || isTodosServiceActive ? 0 : width}px)`,

    '& webview': {
      height: '100%',
    },
  },
  resizeHandler: {
    position: 'absolute',
    left: 0,
    marginLeft: -5,
    width: 10,
    zIndex: 400,
    cursor: 'col-resize',
  },
  dragIndicator: {
    position: 'absolute',
    left: 0,
    width: 5,
    zIndex: 400,
    background: theme.todos.dragIndicator.background,

  },
  premiumContainer: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    width: '80%',
    maxWidth: 300,
    margin: [0, 'auto'],
    textAlign: 'center',
  },
  premiumIcon: {
    marginBottom: 40,
    background: theme.styleTypes.primary.accent,
    fill: theme.styleTypes.primary.contrast,
    padding: 10,
    borderRadius: 10,
  },
  premiumCTA: {
    marginTop: 40,
  },
  isTodosServiceActive: {
    width: 'calc(100% - 368px)',
    position: 'absolute',
    right: 0,
    zIndex: 0,
  },
});

@injectSheet(styles) @observer
class TodosWebview extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    isTodosServiceActive: PropTypes.bool.isRequired,
    isVisible: PropTypes.bool.isRequired,
    handleClientMessage: PropTypes.func.isRequired,
    setTodosWebview: PropTypes.func.isRequired,
    resize: PropTypes.func.isRequired,
    width: PropTypes.number.isRequired,
    minWidth: PropTypes.number.isRequired,
    isTodosIncludedInCurrentPlan: PropTypes.bool.isRequired,
  };

  state = {
    isDragging: false,
    width: 300,
  };

  static contextTypes = {
    intl: intlShape,
  };

  componentWillMount() {
    const { width } = this.props;

    this.setState({
      width,
    });
  }

  componentDidMount() {
    this.node.addEventListener('mousemove', this.resizePanel.bind(this));
    this.node.addEventListener('mouseup', this.stopResize.bind(this));
    this.node.addEventListener('mouseleave', this.stopResize.bind(this));
  }

  startResize = (event) => {
    this.setState({
      isDragging: true,
      initialPos: event.clientX,
      delta: 0,
    });
  };

  resizePanel(e) {
    const { minWidth } = this.props;

    const {
      isDragging,
      initialPos,
    } = this.state;

    if (isDragging && Math.abs(e.clientX - window.innerWidth) > minWidth) {
      const delta = e.clientX - initialPos;

      this.setState({
        delta,
      });
    }
  }

  stopResize() {
    const {
      resize,
      minWidth,
    } = this.props;

    const {
      isDragging,
      delta,
      width,
    } = this.state;

    if (isDragging) {
      let newWidth = width + (delta < 0 ? Math.abs(delta) : -Math.abs(delta));

      if (newWidth < minWidth) {
        newWidth = minWidth;
      }

      this.setState({
        isDragging: false,
        delta: 0,
        width: newWidth,
      });

      resize(newWidth);
    }
  }

  startListeningToIpcMessages() {
    const { handleClientMessage } = this.props;
    if (!this.webview) return;
    this.webview.addEventListener('ipc-message', (e) => {
      // console.log(e);
      handleClientMessage({ channel: e.channel, message: e.args[0] });
    });
  }

  render() {
    const {
      classes,
      isTodosServiceActive,
      isVisible,
      isTodosIncludedInCurrentPlan,
    } = this.props;

    const {
      width,
      delta,
      isDragging,
    } = this.state;

    const { intl } = this.context;

    let displayedWidth = isVisible ? width : 0;
    if (isTodosServiceActive) {
      displayedWidth = null;
    }

    return (

 this.stopResize()}
        ref={(node) => { this.node = node; }}
        id="todos-panel"
      >

 this.startResize(e)}
        />
        {isDragging && (

        )}
        {isTodosIncludedInCurrentPlan ? (
          <Webview
            className={classes.webview}
            onDidAttach={() => {
              const { setTodosWebview } = this.props;
              setTodosWebview(this.webview);
              this.startListeningToIpcMessages();
            }}
            partition={TODOS_PARTITION_ID}
            preload="./features/todos/preload.js"
            ref={(webview) => { this.webview = webview ? webview.view : null; }}
            src={environment.TODOS_FRONTEND}
            webpreferences="contextIsolation=0"
          />
        ) : (
          <Appear>

              <Icon icon={mdiCheckAll} className={classes.premiumIcon} size={4} />

{intl.formatMessage(messages.premiumInfo)}

{intl.formatMessage(messages.rolloutInfo)}

              <UpgradeButton
                className={classes.premiumCTA}
                gaEventInfo={{ category: 'Todos', event: 'upgrade' }}
                short
              />

          </Appear>
        )}

    );
  }
}

export default TodosWebview;
<|endoftext|>


<commit_before>var debug = require( 'debug' )( 'dashboard:route:home' );

module.exports = function( app ){

	/**
	 * Home page
	 * */
	app.get( '/', function( req, res, next ){
		res.render( 'home', {title: 'DCP', subtitle: 'dashboard'} );
	} );
};
<commit_msg>DCP? what is DCP?<commit_after>var debug = require( 'debug' )( 'dashboard:route:home' );

module.exports = function( app ){

	/**
	 * Home page
	 * */
	app.get( '/', function( req, res, next ){
		res.render( 'home', {title: 'Services', subtitle: 'dashboard'} );
	} );
};
<|endoftext|>


<commit_before>exports.view = function (req, res) {
    var LoginInfo = {
        "AspectName": "Login",
        "HomeButton": "../images/HomeSymbol.png",
        "HomeLink": "/Home"
    };

    res.render("login", LoginInfo);
};<commit_msg>login workssss<commit_after>exports.view = function (req, res) {
    var LoginInfo = {
        "AspectName": "Login",
        "HomeButton": "../images/HomeSymbol.png",
        "HomeLink": "/Home"
    };

    res.render("Login", LoginInfo);
};<|endoftext|>


<commit_before>exports.view = function (req, res) {
    var LoginInfo = {
        "AspectName": "Login",
        "HomeButton": "../images/HomeSymbol.png",
        "HomeLink": "/Home"
    };

    res.render("login", LoginInfo);
};<commit_msg>Fixed Login routes file.<commit_after>exports.view = function (req, res) {
    var LoginInfo = {
        "AspectName": "Login",
        "HomeButton": "../images/HomeSymbol.png",
        "HomeLink": "/Home"
    };

    res.render("Login", LoginInfo);
};<|endoftext|>


<commit_before>// --------------------------------------------------------------------------------------
// TODO
// --------------------------------------------------------------------------------------
exp.check_filter = function(query, fields)
{
  var ret = {};

  for(var field in fields) {
    if(query[fields[field]]) {
      ret[fields[field]] = query[fields[field]];    // add to result
      delete query[fields[field]];                  // delete original item
    }
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// add other operators, if defined in query
// --------------------------------------------------------------------------------------
exp.add_ops = function(aggregate_query, query)
{
  if(query.sort) {
    aggregate_query.push({ $sort : query.sort });   // sort
  }

  if(query.skip && query.limit) {   // both skip and limit
    aggregate_query.push({ $limit : query.limit + query.skip });   // limit to limit + skip
  }

  if(query.skip) {
    aggregate_query.push({ $skip : query.skip });   // skip
  }

  if(query.limit) {
    aggregate_query.push({ $limit : query.limit }); // limit
  }

  return aggregate_query;
}
// --------------------------------------------------------------------------------------
// TODO
// --------------------------------------------------------------------------------------
exp.add_cond = function(aggregate_query, cond)
{
  //console.log("before");
  //console.log(aggregate_query);

  if(Object.keys(cond).length > 0)
    aggregate_query.push({ $match : cond });    // check

  //console.log("after");
  //console.log(aggregate_query);

  return aggregate_query;
}
// --------------------------------------------------------------------------------------
module.exports = exp;
<commit_msg>update code<commit_after>// --------------------------------------------------------------------------------------
// check if any of fileds is present in query
// if so, delete it and return as dict for
// further processing
// --------------------------------------------------------------------------------------
exp.check_filter = function(query, fields)
{
  var ret = {};

  for(var field in fields) {
    if(query[fields[field]]) {
      ret[fields[field]] = query[fields[field]];    // add to result
      delete query[fields[field]];                  // delete original item
    }
  }

  return ret;
}
// --------------------------------------------------------------------------------------
// add other operators, if defined in query
// --------------------------------------------------------------------------------------
exp.add_ops = function(aggregate_query, query)
{
  if(query.sort) {
    aggregate_query.push({ $sort : query.sort });   // sort
  }

  if(query.skip && query.limit) {   // both skip and limit
    aggregate_query.push({ $limit : query.limit + query.skip });   // limit to limit + skip
  }

  if(query.skip) {
    aggregate_query.push({ $skip : query.skip });   // skip
  }

  if(query.limit) {
    aggregate_query.push({ $limit : query.limit }); // limit
  }

  return aggregate_query;
}
// --------------------------------------------------------------------------------------
// add initial removed condition to aggregation query
// --------------------------------------------------------------------------------------
exp.add_cond = function(aggregate_query, cond)
{
  if(Object.keys(cond).length > 0)
    aggregate_query.push({ $match : cond });    // check

  return aggregate_query;
}
// --------------------------------------------------------------------------------------
module.exports = exp;
<|endoftext|>