<commit_before>'use strict';

var Cursor = require('../../util/Cursor'),
    ClickTrap = require('../../util/ClickTrap'),
    substract = require('../../util/Math').substract,
    domEvent = require('min-dom/lib/event'),
    domClosest = require('min-dom/lib/closest'),
    EventUtil = require('../../util/Event');

function length(point) {
  return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
}

var THRESHOLD = 15;

function MoveCanvas(eventBus, canvas) {

  var container = canvas._container,
      context;

  function handleMove(event) {

    var start = context.start,
        position = EventUtil.toPoint(event),
        delta = substract(position, start);

    if (!context.dragging && length(delta) > THRESHOLD) {
      context.dragging = true;

      // prevent mouse click in this
      // interaction sequence
      ClickTrap.install();

      Cursor.set('grab');
    }

    if (context.dragging) {

      var lastPosition = context.last || context.start;

      delta = substract(position, lastPosition);

      canvas.scroll({
        dx: delta.x,
        dy: delta.y
      });

      context.last = position;
    }

    // prevent select
    event.preventDefault();
  }

  function handleEnd(event) {
    domEvent.unbind(document, 'mousemove', handleMove);
    domEvent.unbind(document, 'mouseup', handleEnd);

    context = null;

    Cursor.unset();

    // prevent select
    EventUtil.stopEvent(event);
  }

  function handleStart(event) {
    // event is already handled by '.djs-draggable'
    if (domClosest(event.target, '.djs-draggable')) {
      return;
    }

    // reject non-left left mouse button or modifier key
    if (event.button || event.ctrlKey || event.shiftKey || event.altKey) {
      return;
    }

    context = {
      start: EventUtil.toPoint(event)
    };

    domEvent.bind(document, 'mousemove', handleMove);
    domEvent.bind(document, 'mouseup', handleEnd);

    // prevent select
    EventUtil.stopEvent(event);
  }

  domEvent.bind(container, 'mousedown', handleStart);
}

MoveCanvas.$inject = [ 'eventBus', 'canvas' ];

module.exports = MoveCanvas;
<commit_msg>fix(movecanvas): do not stop event propagation<commit_after>'use strict';

var Cursor = require('../../util/Cursor'),
    ClickTrap = require('../../util/ClickTrap'),
    substract = require('../../util/Math').substract,
    domEvent = require('min-dom/lib/event'),
    domClosest = require('min-dom/lib/closest'),
    EventUtil = require('../../util/Event');

function length(point) {
  return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
}

var THRESHOLD = 15;

function MoveCanvas(eventBus, canvas) {

  var container = canvas._container,
      context;

  function handleMove(event) {

    var start = context.start,
        position = EventUtil.toPoint(event),
        delta = substract(position, start);

    if (!context.dragging && length(delta) > THRESHOLD) {
      context.dragging = true;

      // prevent mouse click in this
      // interaction sequence
      ClickTrap.install();

      Cursor.set('grab');
    }

    if (context.dragging) {

      var lastPosition = context.last || context.start;

      delta = substract(position, lastPosition);

      canvas.scroll({
        dx: delta.x,
        dy: delta.y
      });

      context.last = position;
    }

    // prevent select
    event.preventDefault();
  }

  function handleEnd(event) {
    domEvent.unbind(document, 'mousemove', handleMove);
    domEvent.unbind(document, 'mouseup', handleEnd);

    context = null;

    Cursor.unset();
  }

  function handleStart(event) {
    // event is already handled by '.djs-draggable'
    if (domClosest(event.target, '.djs-draggable')) {
      return;
    }

    // reject non-left left mouse button or modifier key
    if (event.button || event.ctrlKey || event.shiftKey || event.altKey) {
      return;
    }

    context = {
      start: EventUtil.toPoint(event)
    };

    domEvent.bind(document, 'mousemove', handleMove);
    domEvent.bind(document, 'mouseup', handleEnd);
  }

  domEvent.bind(container, 'mousedown', handleStart);
}

MoveCanvas.$inject = [ 'eventBus', 'canvas' ];

module.exports = MoveCanvas;
<|endoftext|>


<commit_before>// core
var url = require('url');

// npm
var send = require('send');

module.exports = function(hostname, site, req, res, log) {
    // if this is a static site, serve using ...
    if ( site.type === 'static' ) {
        var path = url.parse(req.url).pathname;
        log(hostname + ' :: ' + site.dir + path);

        send(req, path)
            .root(site.dir)
            .on('error', function(err) {
                res.statusCode = err.status || 500;
                res.end(err.code === 'ENOENT' ? '404 - Not Found\r\n' : err.message);
            })
            .on('file', function(path, stat) {
                log('wanting a file ' + path);
            })
            .on('directory', function() {
                res.statusCode = 301;
                res.setHeader('Location', req.url + '/');
                res.end('Redirecting to ' + req.url + '/');
            })
            .pipe(res)
        ;
        return;
    }
};
<commit_msg>root is now an option for send()<commit_after>// core
var url = require('url');

// npm
var send = require('send');

module.exports = function(hostname, site, req, res, log) {
    // if this is a static site, serve using ...
    if ( site.type === 'static' ) {
        var path = url.parse(req.url).pathname;
        log(hostname + ' :: ' + site.dir + path);

        send(req, path, { root : site.dir })
            .on('error', function(err) {
                res.statusCode = err.status || 500;
                res.end(err.code === 'ENOENT' ? '404 - Not Found\r\n' : err.message);
            })
            .on('file', function(path, stat) {
                log('wanting a file ' + path);
            })
            .on('directory', function() {
                res.statusCode = 301;
                res.setHeader('Location', req.url + '/');
                res.end('Redirecting to ' + req.url + '/');
            })
            .pipe(res)
        ;
        return;
    }
};
<|endoftext|>


<commit_before>// requestCSV:
// param: 	file 	- File name to be provided
// param: 	fn		- Callback function to receive the data.
function requestCSV(file, fn)
{
	// jQuery request of file.
	$.get(file,
		function(data) {
			fn(data);
		});
}

// CSVtoJSON
// param: 	data - CSV Data to be converted into an object
// return:  Object with all of the CSV values in the *.vals location as a Key/Value array, where the third column is the key.
function CSVtoJSON(data)
{
	// Rows are split off of new lines in simple CSV
	rows = data.split("\n");

	ret = new Object();
	ret.vals = new Array();
    var header = new Array();

	// iterate over all of the rows to build the object(must start a 0 so heading is avalible downstream)
	for (i = 0; i < rows.length; i++)
	{
		// Split on ", " in CSV data we received
		cols = rows[i].split(",", rows[0].split("\",\"").length);

		// Remove quotes out of all underlying elements
		for (j = 0; j < cols.length; j++)
			cols[j] = cols[j].replace(/\"/g, "");

		// Skip over undefined values for data integrity
		if (cols[2] != undefined)
        {
            //changed to add k/v pairs instead of indexed array
            if(i==0)
            {
                header = cols;
            }
            else
            {
                var student = new array();
                for (var k=0; k<cols.length;k++)
                    student[header[k]] = col[k];
                ret.vals[cols[2]] = student;
            }
        }
	}
	return ret;
}

//student object constructor
//Param: student is array of student data.
//Param: types is the types row from import (must be score,note,lettergrade,section or $TYPE(only repo cell))
//Param: catagory row from csv (assingemtn groupings can include anything)
var Student(student,types,catagories)
{
    var catagoriesList = getCatagories(catagories);
    for(data in student.keys)
    this.scores = ;
    this.letterGrade = ;
    this.notes = ;
    this.totalGrade = ;
    this.section = ;
    this.repo;
}

//Parses data into students  (should this be incoperated into csvtojson function?)
//Param: data - required for the passthrough object
//returns: Students object with socres array in key/val array where key is repo and  the value is an array. each student array is key/val where key
//is header(assingment neme) and value is score recieved. Contains a row where the headings repo where the headings are equal to the values
function getSection (data)
{
    var section = new Object();
    section.students = new Array();

    var json = CSVtoJSON(data);
    for (var repo in json.vals )
        section.students[repo] = new Student(json[repo],json["$TYPES"],json["$CATAGORIES"]);

    /*#test build loop
    for (student in student.sscores)
    {
        for (score in students.scores[student])
            console.log(score +" "+students.scores[student][score]);
    }*/
    return section;

}
//return array of catagories
function getCatagories(catagoriesArray)
{
    var catagoriesList = new Array();
    for (item in catagoiesArray.values)
        if(item != "$TYPE")
            catagoriesList[item] = item;
    return catagoriesList;
}

<commit_msg>updated some arrays to objects<commit_after>// requestCSV:
// param: 	file 	- File name to be provided
// param: 	fn		- Callback function to receive the data.
function requestCSV(file, fn)
{
	// jQuery request of file.
	$.get(file,
		function(data) {
			fn(data);
		});
}

// CSVtoJSON
// param: 	data - CSV Data to be converted into an object
// return:  Object with all of the CSV values in the *.vals location as a Key/Value array, where the third column is the key.
function CSVtoJSON(data)
{
	// Rows are split off of new lines in simple CSV
	rows = data.split("\n");

	ret = new Object();
	ret.vals = new Object();
    var header = new Array();

	// iterate over all of the rows to build the object(must start a 0 so heading is avalible downstream)
	for (i = 0; i < rows.length; i++)
	{
		// Split on ", " in CSV data we received
		cols = rows[i].split(",", rows[0].split("\",\"").length);

		// Remove quotes out of all underlying elements
		for (j = 0; j < cols.length; j++)
			cols[j] = cols[j].replace(/\"/g, "");

		// Skip over undefined values for data integrity
		if (cols[2] != undefined)
        {
            //changed to add k/v object instead of array
            if(i==0)
            {
                header = cols;
            }
            else
            {
                var student = {};
                for (var k=0; k<cols.length;k++)
                    student[header[k]] = col[k];
                ret.vals[cols[2]] = student;
            }
        }
	}
	return ret;
}

var Score()
{
    ;
}
//student object constructor
//Param: student is object map of student data.
//Param: the types row from import (must be score,note,lettergrade,section or $TYPE(only repo cell))
//Param: catagories row from csv (assingemtn groupings can include anything)
var Student(student,types,catagories)
{
    var catagoriesList = getCatagories(catagories);
    this.scores = ;
    for(key in Object.Keys(student))
    {

    }
    this.letterGrade = ;
    this.notes = ;
    this.totalGrade = ;
    this.section = ;
    this.repo;
}

//Parses data into students  (should this be incoperated into csvtojson function?)
//Param: data - required for the passthrough object
//returns: Students object with socres array in key/val array where key is repo and  the value is an array. each student array is key/val where key
//is header(assingment neme) and value is score recieved. Contains a row where the headings repo where the headings are equal to the values
function getSection (data)
{
    var section = {};
    section.students = {};

    var json = CSVtoJSON(data);
    for (var repo in json.vals )
        section.students[repo] = new Student(json[repo],json["$TYPES"],json["$CATAGORIES"]);

    return section;

}
//return object of catagories
function getCatagories(catagoriesObj)
{
    var catagoriesList = {};
    for (item in catagoiesObj.values)
        if(item != "$TYPE")
            catagoriesList[item] = {};
    return catagoriesList;
}

<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';

foam.CLASS({
  package: 'org.chromium.webidl',
  name: 'ParserRunner',
  extends: 'org.chromium.webidl.PipelineRunner',

  requires: ['org.chromium.webidl.BaseParser'],

  documentation: 'Runnable Box that parsers IDLFileContents into ASTs.',

  methods: [
    function run(message) {
      if (this.validateMessage(message)) return;

      // Verify all required arguments are present.
      if (!message.idlFile || !message.parserClass)
        return this.error(this.fmtErrorMsg(this.MISSING_PROPS));

      var file = message.idlFile;
      var parserClass = message.parserClass;
      // Prepare metadata to be injected by parser.
      var metadata = file.cls_.create({id: file.id});

      // Load appropriate parser depending on configuration.
      // TODO: Replace injected string with a safer method, such as a
      // helper method that chooses parser based on URL.
      var parser = parserClass.create();
      foam.assert(this.BaseParser.isInstance(parser),
        'The class provided is not an instance of BaseParser.');

      var results = parser.parseString(file.contents, metadata);

      // Determine if parse of entire file was successful.
      if (!Array.isArray(results.value) ||
          file.contents.length !== results.pos) {
        this.error(new Error(`Incomplete parse on file.
            Metadata: ${foam.json.Pretty.stringify(metadata)}`));
      } else {
        message.ast = results.value;
        this.output(message);
      }
    }
  ],
});
<commit_msg>Changing metadata to sourceId in ParserRunner<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';

foam.CLASS({
  package: 'org.chromium.webidl',
  name: 'ParserRunner',
  extends: 'org.chromium.webidl.PipelineRunner',

  requires: ['org.chromium.webidl.BaseParser'],

  documentation: 'Runnable Box that parsers IDLFileContents into ASTs.',

  methods: [
    function run(message) {
      if (this.validateMessage(message)) return;

      // Verify all required arguments are present.
      if (!message.idlFile || !message.parserClass)
        return this.error(this.fmtErrorMsg(this.MISSING_PROPS));

      var file = message.idlFile;
      var parserClass = message.parserClass;
      // Prepare metadata to be injected by parser.
      var sourceId = file.cls_.create({id: file.id});

      // Load appropriate parser depending on configuration.
      // TODO: Replace injected string with a safer method, such as a
      // helper method that chooses parser based on URL.
      var parser = parserClass.create();
      foam.assert(this.BaseParser.isInstance(parser),
        'The class provided is not an instance of BaseParser.');

      var results = parser.parseString(file.contents, sourceId);

      // Determine if parse of entire file was successful.
      if (!Array.isArray(results.value) ||
          file.contents.length !== results.pos) {
        this.error(new Error(`Incomplete parse on file.
            Source: ${foam.json.Pretty.stringify(sourceId)}`));
      } else {
        message.ast = results.value;
        this.output(message);
      }
    }
  ],
});
<|endoftext|>


<commit_before>test("backbutton.navigate()", function(pass, fail) {
  var fragmentTest = randomString();
  backbutton.navigate(fragmentTest);
  location.href.indexOf(fragmentTest) > 0 ? pass() : fail();
});

test("backbutton.current()", function(pass, fail) {
  var fragmentTest = randomString();
  location.hash = "#" + fragmentTest;
  backbutton.current() == fragmentTest ? pass() : fail();
});

test("backbutton.observe()", function(pass, fail) {
  var fragmentTest = randomString(),
    unobserve = backbutton.observe(observe),
    timer = setTimeout(resolve, 500);

  function observe(fragmentString) {
    resolve(fragmentString == fragmentTest);
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve();
    passed ? pass() : fail();
  }

  backbutton.navigate(fragmentTest);
});

test("backbutton.observe(), unregister", function(pass, fail) {
  var fragmentTest = randomString(),
    unobserve1 = backbutton.observe(observe1),
    unobserve2 = backbutton.observe(observe2),
    timer = setTimeout(resolve, 500),
    visit1 = 0,
    visit2 = 0;

  function observe1(fragmentString) {
    if (fragmentString == fragmentTest) {
      visit1++;
      unobserve1();
    }
  }

  function observe2(fragmentString) {
    if (fragmentString == fragmentTest) {
      visit2++;
      if (visit2 < 3) {
        backbutton.refresh();
      } else {
        resolve(visit1 === 1);
      }
    }
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve1();
    unobserve2();
    passed ? pass() : fail();
  }

  backbutton.navigate(fragmentTest);
});

test("backbutton.observe(), this keyword", function(pass, fail) {
  var unobserve = backbutton.observe(observe),
    timer = setTimeout(resolve, 500);

  function observe() {
    resolve(this === backbutton);
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve();
    passed ? pass() : fail();
  }

  backbutton.navigate(randomString());
});

test("backbutton.refresh()", function(pass, fail) {
  var fragmentTest = randomString(),
    unobserve = backbutton.observe(observe),
    timer = setTimeout(resolve, 500),
    visits = 0;

  function observe(fragmentString) {
    if (fragmentString == fragmentTest) {
      visits++;
      if (visits === 1) {
        backbutton.refresh();
      } else if (visits === 2) {
        resolve(true);
      }
    }
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve();
    passed ? pass() : fail();
  }

  backbutton.navigate(fragmentTest);
});

test("backbutton.routes(), auto start", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    current = backbutton.current(),
    routes = [
      /(.*)/,
      function(path) {
        resolve(path === current);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes);
});

test("backbutton.routes(), manual start", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    fragmentTest = randomString(),
    routes = [
      /(.*)/,
      function(path) {
        resolve(path === fragmentTest);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(fragmentTest);
});

test("backbutton.routes(), basic route", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    routes = [/^(navigate)$/, resolve];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed === "navigate" ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("navigate");
});

test("backbutton.routes(), parameters", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    randomData = randomString(),
    randomDigits = randomData.replace(/\D/g, "").slice(-4),
    routes = [/^(\w+):(\d)/, resolve];

  function resolve(arg1, arg2) {
    clearTimeout(timer);
    routes.length = 0;
    arg1 === randomData && arg2 === randomDigits.charAt(0) ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(randomData + ":" + randomDigits);
});

test("backbutton.routes(), this keyword", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    routes = [
      /(.*)/,
      function() {
        resolve(this === backbutton);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(randomString());
});

test("backbutton.routes(), catch-all", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    fragmentTest,
    routes = [
      /^navigateToThisFirst$/,
      function() {
        backbutton.navigate((fragmentTest = randomString()));
      },
      /(.*)/,
      function(fragmentString) {
        resolve(fragmentString === fragmentTest);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("navigateToThisFirst");
});

test("backbutton.routes(), return true", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    fragmentTest = randomString(),
    visited = 0,
    routes = [
      /(.+)/,
      function(fragmentString) {
        if (fragmentString != fragmentTest) resolve();
        visited++;
        return true;
      },
      /(.+)/,
      function(fragmentString) {
        resolve(fragmentString == fragmentTest && visited === 1);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(fragmentTest);
});

test("backbutton.routes(), redirect", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    visited = 0,
    routes = [
      /^hitThisFirst$/,
      function() {
        visited++;
        if (visited === 1) {
          backbutton.refresh();
        } else {
          return "hitThisLast";
        }
      },
      /^hitThisLast$/,
      function() {
        resolve(visited === 2);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("hitThisFirst");
});

test("backbutton.routes(), remove route", function(pass, fail) {
  var timer = setTimeout(resolve, 5000),
    visited = [],
    routes = [
      /^firstRoute$/,
      function() {
        return visited.push(1);
      },
      /(.*)/,
      function() {
        return visited.push(2);
      },
      /(.*)/,
      function() {
        visited.push(3);
        if (visited.length === 3) {
          routes.splice(2, 2);
          backbutton.refresh();
        } else {
          resolve("" + visited === "" + [1, 2, 3, 1, 3]);
        }
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("firstRoute");
});

test("backbutton.routes(), conditional routing", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    log = [],
    activated = false,
    routes = [
      /^activate:(0|1)$/,
      function(value) {
        activated = +value;
        log.push(activated ? "activated" : "deactivated");
        backbutton.navigate("conditionalRoute");
      },

      /(.*)/,
      function(path) {
        log.push("access " + (activated ? "granted" : "denied"));
        return activated ? true : "404:" + path;
      },

      /^conditionalRoute$/,
      function(path) {
        log.push("conditionalRoute accessed");
        backbutton.navigate("activate:0");
      },

      /^404:(.*)/,
      function(path) {
        log.push(path + " cannot be accessed");
        if (path === "conditionalRoute") {
          if (log.length === 2) {
            backbutton.navigate("activate:1");
          } else {
            resolve(
              "" + log ===
                "access denied," +
                  "conditionalRoute cannot be accessed," +
                  "activated," +
                  "access granted," +
                  "conditionalRoute accessed," +
                  "deactivated," +
                  "access denied," +
                  "conditionalRoute cannot be accessed" && activated === 0
            );
          }
        }
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("conditionalRoute");
});

test("backbutton.routes(), router swap", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
      log = [],
   routes1 = [
      /(.*)/, function() {
        log.push(1);
        if(log.length === 1){
          previousRouter = backbutton.routes(routes2)
        }else{
          previousRouter = backbutton.routes(previousRouter)
        }
      }
    ],
    routes2 = [
      /(.*)/, function() {
        log.push(2);
        if(log.length < 4){
          previousRouter = backbutton.routes(previousRouter)
        }else{
          resolve('' + log === '' + [1, 2, 1, 2]);
        }
      }
    ],
      previousRouter;

  function resolve(passed) {
    clearTimeout(timer);
    routes1.length = routes2.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes1);
});

test("respond to browser back button", function(pass, fail) {
  var timer,
    visits = 0,
    routes = [
      /^goingBackAgain$/,
      function() {
        visits++;
        if (visits === 1) {
          backbutton.navigate("goingForward");
        } else {
          resolve(true);
        }
      },
      /^goingForward$/,
      function() {
        alert(
          "Close this alert and click browser back button to complete testing."
        );
        timer = setTimeout(resolve, 6000);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    backbutton.navigate('');
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("goingBackAgain");
});

/* helper functions */

function randomString() {
  return +new Date() + ((Math.random() * 0x100000000) >>> 0).toString(36);
}

/* test runner functions */

function test(name, fun) {
  var tests = (window["tests"] = window["tests"] || []);
  tests.push(name, fun);
}

function run(report) {
  var tests = (window["tests"] = window["tests"] || []);
  var results = [];
  var index = -2;
  function next() {
    index += 2;
    if (tests[index]) {
      results[index] = tests[index];
      tests[index + 1](callback(index, "passed"), callback(index, "failed"));
    } else {
      report(results);
    }
  }
  function callback(index, result) {
    return function() {
      results[index + 1] = result;
      setTimeout(next);
    };
  }
  next();
}

/* test control */

(function runTests(){
    run(function(results){
        var i, unobserve;
        showResults(results);
        for(i = 1; i < results.length; i += 2){
            if(results[i] !== 'passed'){
                break;
            }
        }
        if(results.length + 1 === i){
            history.go(-21);
        }
    });
})();

function showResults(results) {
  var str =
    "
backbutton.js, version " + backbutton.version + "
";
  str += "
Tested in " + navigator.userAgent + "
";
  str += "
";
  for (var i = 0, p = 0; i < results.length; i += 2) {
    if (results[i + 1] === "passed") p++;
    str +=
      "
" +
      results[i] +
      '	' +
      results[i + 1] +
      "
";
  }
  str += "
";
  document.getElementById("results").innerHTML =
    "
Test results (" + p + "/" + (i >> 1) + ")
" + str;
}
<commit_msg>Update tests.js<commit_after>test("backbutton.navigate()", function(pass, fail) {
  var fragmentTest = randomString();
  backbutton.navigate(fragmentTest);
  location.href.indexOf(fragmentTest) > 0 ? pass() : fail();
});

test("backbutton.current()", function(pass, fail) {
  var fragmentTest = randomString();
  location.hash = "#" + fragmentTest;
  backbutton.current() == fragmentTest ? pass() : fail();
});

test("backbutton.observe()", function(pass, fail) {
  var fragmentTest = randomString(),
    unobserve = backbutton.observe(observe),
    timer = setTimeout(resolve, 500);

  function observe(fragmentString) {
    resolve(fragmentString == fragmentTest);
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve();
    passed ? pass() : fail();
  }

  backbutton.navigate(fragmentTest);
});

test("backbutton.observe(), unregister", function(pass, fail) {
  var fragmentTest = randomString(),
    unobserve1 = backbutton.observe(observe1),
    unobserve2 = backbutton.observe(observe2),
    timer = setTimeout(resolve, 500),
    visit1 = 0,
    visit2 = 0;

  function observe1(fragmentString) {
    if (fragmentString == fragmentTest) {
      visit1++;
      unobserve1();
    }
  }

  function observe2(fragmentString) {
    if (fragmentString == fragmentTest) {
      visit2++;
      if (visit2 < 3) {
        backbutton.refresh();
      } else {
        resolve(visit1 === 1);
      }
    }
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve1();
    unobserve2();
    passed ? pass() : fail();
  }

  backbutton.navigate(fragmentTest);
});

test("backbutton.observe(), this keyword", function(pass, fail) {
  var unobserve = backbutton.observe(observe),
    timer = setTimeout(resolve, 500);

  function observe() {
    resolve(this === backbutton);
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve();
    passed ? pass() : fail();
  }

  backbutton.navigate(randomString());
});

test("backbutton.refresh()", function(pass, fail) {
  var fragmentTest = randomString(),
    unobserve = backbutton.observe(observe),
    timer = setTimeout(resolve, 500),
    visits = 0;

  function observe(fragmentString) {
    if (fragmentString == fragmentTest) {
      visits++;
      if (visits === 1) {
        backbutton.refresh();
      } else if (visits === 2) {
        resolve(true);
      }
    }
  }

  function resolve(passed) {
    clearTimeout(timer);
    unobserve();
    passed ? pass() : fail();
  }

  backbutton.navigate(fragmentTest);
});

test("backbutton.routes(), auto start", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    current = backbutton.current(),
    routes = [
      /(.*)/,
      function(path) {
        resolve(path === current);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes);
});

test("backbutton.routes(), manual start", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    fragmentTest = randomString(),
    routes = [
      /(.*)/,
      function(path) {
        resolve(path === fragmentTest);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(fragmentTest);
});

test("backbutton.routes(), basic route", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    routes = [/^(navigate)$/, resolve];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed === "navigate" ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("navigate");
});

test("backbutton.routes(), parameters", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    randomData = randomString(),
    randomDigits = randomData.replace(/\D/g, "").slice(-4),
    routes = [/^(\w+):(\d)/, resolve];

  function resolve(arg1, arg2) {
    clearTimeout(timer);
    routes.length = 0;
    arg1 === randomData && arg2 === randomDigits.charAt(0) ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(randomData + ":" + randomDigits);
});

test("backbutton.routes(), this keyword", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    routes = [
      /(.*)/,
      function() {
        resolve(this === backbutton);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(randomString());
});

test("backbutton.routes(), catch-all", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    fragmentTest,
    routes = [
      /^navigateToThisFirst$/,
      function() {
        backbutton.navigate((fragmentTest = randomString()));
      },
      /(.*)/,
      function(fragmentString) {
        resolve(fragmentString === fragmentTest);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("navigateToThisFirst");
});

test("backbutton.routes(), return true", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    fragmentTest = randomString(),
    visited = 0,
    routes = [
      /(.+)/,
      function(fragmentString) {
        if (fragmentString != fragmentTest) resolve();
        visited++;
        return true;
      },
      /(.+)/,
      function(fragmentString) {
        resolve(fragmentString == fragmentTest && visited === 1);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate(fragmentTest);
});

test("backbutton.routes(), redirect", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    visited = 0,
    routes = [
      /^hitThisFirst$/,
      function() {
        visited++;
        if (visited === 1) {
          backbutton.refresh();
        } else {
          return "hitThisLast";
        }
      },
      /^hitThisLast$/,
      function() {
        resolve(visited === 2);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("hitThisFirst");
});

test("backbutton.routes(), remove route", function(pass, fail) {
  var timer = setTimeout(resolve, 5000),
    visited = [],
    routes = [
      /^firstRoute$/,
      function() {
        return visited.push(1);
      },
      /(.*)/,
      function() {
        return visited.push(2);
      },
      /(.*)/,
      function() {
        visited.push(3);
        if (visited.length === 3) {
          routes.splice(2, 2);
          backbutton.refresh();
        } else {
          resolve("" + visited === "" + [1, 2, 3, 1, 3]);
        }
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("firstRoute");
});

test("backbutton.routes(), conditional routing", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
    log = [],
    activated = false,
    routes = [
      /^activate:(0|1)$/,
      function(value) {
        activated = +value;
        log.push(activated ? "activated" : "deactivated");
        backbutton.navigate("conditionalRoute");
      },

      /(.*)/,
      function(path) {
        log.push("access " + (activated ? "granted" : "denied"));
        return activated ? true : "404:" + path;
      },

      /^conditionalRoute$/,
      function(path) {
        log.push("conditionalRoute accessed");
        backbutton.navigate("activate:0");
      },

      /^404:(.*)/,
      function(path) {
        log.push(path + " cannot be accessed");
        if (path === "conditionalRoute") {
          if (log.length === 2) {
            backbutton.navigate("activate:1");
          } else {
            resolve(
              "" + log ===
                "access denied," +
                  "conditionalRoute cannot be accessed," +
                  "activated," +
                  "access granted," +
                  "conditionalRoute accessed," +
                  "deactivated," +
                  "access denied," +
                  "conditionalRoute cannot be accessed" && activated === 0
            );
          }
        }
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("conditionalRoute");
});

test("backbutton.routes(), router swap", function(pass, fail) {
  var timer = setTimeout(resolve, 500),
      log = [],
   routes1 = [
      /(.*)/, function() {
        log.push(1);
        if(log.length === 1){
          previousRouter = backbutton.routes(routes2)
        }else{
          previousRouter = backbutton.routes(previousRouter)
        }
      }
    ],
    routes2 = [
      /(.*)/, function() {
        log.push(2);
        if(log.length < 4){
          previousRouter = backbutton.routes(previousRouter)
        }else{
          resolve('' + log === '' + [1, 2, 1, 2]);
        }
      }
    ],
      previousRouter;

  function resolve(passed) {
    clearTimeout(timer);
    routes1.length = routes2.length = 0;
    passed ? pass() : fail();
  }

  backbutton.routes(routes1);
});

test("respond to browser back button", function(pass, fail) {
  var timer,
    visits = 0,
    routes = [
      /^goingBackAgain$/,
      function() {
        visits++;
        if (visits === 1) {
          backbutton.navigate("goingForward");
        } else {
          resolve(true);
        }
      },
      /^goingForward$/,
      function() {
        alert(
          "Close this alert and click browser back button to complete testing."
        );
        timer = setTimeout(resolve, 6000);
      }
    ];

  function resolve(passed) {
    clearTimeout(timer);
    routes.length = 0;
    backbutton.navigate('');
    passed ? pass() : fail();
  }

  backbutton.routes(routes, false);
  backbutton.navigate("goingBackAgain");
});

/* helper functions */

function randomString() {
  return +new Date() + ((Math.random() * 0x100000000) >>> 0).toString(36);
}

/* test runner functions */

function test(name, fun) {
  var tests = (window["tests"] = window["tests"] || []);
  tests.push(name, fun);
}

function run(report) {
  var tests = (window["tests"] = window["tests"] || []);
  var results = [];
  var index = -2;
  function next() {
    index += 2;
    if (tests[index]) {
      results[index] = tests[index];
      tests[index + 1](callback(index, "passed"), callback(index, "failed"));
    } else {
      report(results);
    }
  }
  function callback(index, result) {
    return function() {
      results[index + 1] = result;
      setTimeout(next);
    };
  }
  next();
}

/* test control */

(function runTests(){
    run(function(results){
        var i, unobserve;
        showResults(results);
        for(i = 1; i < results.length; i += 2){
            if(results[i] !== 'passed'){
                break;
            }
        }
        if(results.length + 1 === i){
            history.go(-20);
        }
    });
})();

function showResults(results) {
  var str =
    "
backbutton.js, version " + backbutton.version + "
";
  str += "
Tested in " + navigator.userAgent + "
";
  str += "
";
  for (var i = 0, p = 0; i < results.length; i += 2) {
    if (results[i + 1] === "passed") p++;
    str +=
      "
" +
      results[i] +
      '	' +
      results[i + 1] +
      "
";
  }
  str += "
";
  document.getElementById("results").innerHTML =
    "
Test results (" + p + "/" + (i >> 1) + ")
" + str;
}
<|endoftext|>


<commit_before>var ScheduledAsync = require("pid-async-class").ScheduledAsync;
var nEw = require("pid-async-class").nEw;
var BaseAsync = require("pid-async-class").BaseAsync;
var yahooFinance = require('yahoo-finance');
var System = require("pid-system")
var stats = require("simple-statistics");

class Stocks extends ScheduledAsync {
    constructor() {
        super(true);
        this.symbols = [];
        this.concurrency = 1;
        this.scheduled = 900000;
        this.fields = [];

        Promise.resolve(this._init())
            .then(() => {
                this.__completeConstruction();
            })
            .catch((err) => {
                console.log(err)
            })

    }

    async _init() {
        var configurator = await this.resolve("configuration");
        var dailyStorage = await this.resolve("daily-storage");
        var realtimeStorage = await this.resolve("realtime-storage");
        this.symbols = (await realtimeStorage.get("symbols")).symbols;

        this.concurrency = parseInt((await configurator.getConfiguration()).realtimeConcurrency) || 1;
        this.dailySchedule = (await configurator.getConfiguration()).dailySchedule || "* 24 * * * *";
        this.sampleSchedule = (await configurator.getConfiguration()).realtimeSchedule || 900000;
        this.sampledFields = (await realtimeStorage.get("fields")).fields;
        this.dailyFields = (await dailyStorage.get("fields")).fields;

        this.schedule(this.sampleSchedule, "getStocks", [this.sampledFields, "realtime-storage"])
        this.a(["getStocks", this.sampledFields, "realtime-storage"]);
        this.schedule(this.dailySchedule, "getStocks", [this.dailyFields, "daily-storage"])
        this.a(["getStocks", this.dailyFields, "daily-storage"]);
    }

    async getStocks(fields, storageKey) {
        var workers = [];

        var db = await this.resolve(storageKey)

        for (var i = 0; i < this.concurrency; i++) {
            workers.push(await nEw(StockWorker, i));
        }

        this.symbols.map((val, idx) => {
            workers[idx % this.concurrency].a(["getStock", val, fields, db])
        });

        for (var i = 0; i < this.concurrency; i++) {
            workers[i].a(["__destroy"]);
        }

    }

}

module.exports = Stocks;

class StockWorker extends BaseAsync {
    constructor(idx) {
        super();
        this.idx = idx;
    }

    getStock(symbol, fields, db) {
        return new Promise((res, rej) => {
                yahooFinance.snapshot({
                        symbol: symbol,
                        fields: fields || ['s', 'a', 'b', 'a5', 'b6', 'a2', 'd1', 'l1'],
                    }, {
                        timeout: 10000
                    }, (err, snapshot) => {
                        if (err) {
                            rej(err);
                            return;
                        }
                        snapshot.date = new Date().toISOString();

                        if (db === "daily-storage") {
                            historical(symbol, "SPY", new Date(Date.now() - 1000 * 60 * 60 * 24 * (365 / 2)).toISOString())
                                .then((beta) => {
                                    snapshot.SPYbeta = beta;
                                    db.a(["upsert", this.collation(symbol, snapshot.date), snapshot]);
                                    res(snapshot);
                                })
                                .catch((err) => {
                                    db.a(["upsert", this.collation(symbol, snapshot.date), snapshot]);
                                    res(snapshot);
                                });

                        return;
                    }
                    db.a(["upsert", this.collation(symbol, snapshot.date), snapshot]); res(snapshot);
                });
        });
}

collation(symbol, dateStr) {
    return symbol + "/" + dateStr;
}
}

function percentChange(s1, s2) {
    return (s2 - s1) / s1;
}

function historical(stock1, stock2, from, to) {
    return new Promise((res, rej) => {
        yahooFinance.historical({
            symbols: [stock1, stock2],
            from: from,
            to: to || new Date().toISOString()
        }, (err, snapshot) => {
            if (err) {
                rej(err);
                return;
            }
            var stocks1 = snapshot[stock1];
            var stocks2 = snapshot[stock2];

            var s1Deltas = stocks1.reduce(function(red, s, idx) {

                if (idx === 0) {
                    return red;
                }

                red.push(percentChange(stocks1[idx - 1].close, s.close));
                return red;
            }, []);

            var s2Deltas = stocks2.reduce(function(red, s, idx) {
                if (idx === 0) {
                    return red;
                }
                red.push(percentChange(stocks2[idx - 1].close, s.close));
                return red;
            }, []);

            res(stats.sampleCovariance(s1Deltas, s2Deltas) / stats.sampleVariance(s2Deltas));
        });
    });
}
<commit_msg>fix params<commit_after>var ScheduledAsync = require("pid-async-class").ScheduledAsync;
var nEw = require("pid-async-class").nEw;
var BaseAsync = require("pid-async-class").BaseAsync;
var yahooFinance = require('yahoo-finance');
var System = require("pid-system")
var stats = require("simple-statistics");

class Stocks extends ScheduledAsync {
    constructor() {
        super(true);
        this.symbols = [];
        this.concurrency = 1;
        this.scheduled = 900000;
        this.fields = [];

        Promise.resolve(this._init())
            .then(() => {
                this.__completeConstruction();
            })
            .catch((err) => {
                console.log(err)
            })

    }

    async _init() {
        var configurator = await this.resolve("configuration");
        var dailyStorage = await this.resolve("daily-storage");
        var realtimeStorage = await this.resolve("realtime-storage");
        this.symbols = (await realtimeStorage.get("symbols")).symbols;

        this.concurrency = parseInt((await configurator.getConfiguration()).realtimeConcurrency) || 1;
        this.dailySchedule = (await configurator.getConfiguration()).dailySchedule || "* 24 * * * *";
        this.sampleSchedule = (await configurator.getConfiguration()).realtimeSchedule || 900000;
        this.sampledFields = (await realtimeStorage.get("fields")).fields;
        this.dailyFields = (await dailyStorage.get("fields")).fields;

        this.schedule(this.sampleSchedule, "getStocks", [this.sampledFields, "realtime-storage"])
        this.a(["getStocks", this.sampledFields, "realtime-storage"]);
        this.schedule(this.dailySchedule, "getStocks", [this.dailyFields, "daily-storage"])
        this.a(["getStocks", this.dailyFields, "daily-storage"]);
    }

    async getStocks(fields, storageKey) {
        var workers = [];

        var db = await this.resolve(storageKey)

        for (var i = 0; i < this.concurrency; i++) {
            workers.push(await nEw(StockWorker, i));
        }

        this.symbols.map((val, idx) => {
            workers[idx % this.concurrency].a(["getStock", val, fields, db, storageKey])
        });

        for (var i = 0; i < this.concurrency; i++) {
            workers[i].a(["__destroy"]);
        }

    }

}

module.exports = Stocks;

class StockWorker extends BaseAsync {
    constructor(idx) {
        super();
        this.idx = idx;
    }

    getStock(symbol, fields, db, storageKey) {
        return new Promise((res, rej) => {
            yahooFinance.snapshot({
                symbol: symbol,
                fields: fields || ['s', 'a', 'b', 'a5', 'b6', 'a2', 'd1', 'l1'],
            }, {
                timeout: 10000
            }, (err, snapshot) => {
                if (err) {
                    rej(err);
                    return;
                }
                snapshot.date = new Date().toISOString();

                if (storageKey === "daily-storage") {
                    historical(symbol, "SPY", new Date(Date.now() - 1000 * 60 * 60 * 24 * (365 / 2)).toISOString())
                        .then((beta) => {
                            snapshot.SPYbeta = beta;
                            db.a(["upsert", this.collation(symbol, snapshot.date), snapshot]);
                            console.log(snapshot)
                            res(snapshot);
                        })
                        .catch((err) => {
                          console.log(err)
                            db.a(["upsert", this.collation(symbol, snapshot.date), snapshot]);
                            res(snapshot);
                        });

                    return;
                }
                db.a(["upsert", this.collation(symbol, snapshot.date), snapshot]);
                res(snapshot);
            });
        });
    }

    collation(symbol, dateStr) {
        return symbol + "/" + dateStr;
    }
}

function percentChange(s1, s2) {
    return (s2 - s1) / s1;
}

function historical(stock1, stock2, from, to) {
    return new Promise((res, rej) => {
        yahooFinance.historical({
            symbols: [stock1, stock2],
            from: from,
            to: to || new Date().toISOString()
        }, (err, snapshot) => {
            if (err) {
                rej(err);
                return;
            }
            var stocks1 = snapshot[stock1];
            var stocks2 = snapshot[stock2];

            var s1Deltas = stocks1.reduce(function(red, s, idx) {

                if (idx === 0) {
                    return red;
                }

                red.push(percentChange(stocks1[idx - 1].close, s.close));
                return red;
            }, []);

            var s2Deltas = stocks2.reduce(function(red, s, idx) {
                if (idx === 0) {
                    return red;
                }
                red.push(percentChange(stocks2[idx - 1].close, s.close));
                return red;
            }, []);

            res(stats.sampleCovariance(s1Deltas, s2Deltas) / stats.sampleVariance(s2Deltas));
        });
    });
}
<|endoftext|>


<commit_before>'use strict';
const http = require('http');
const https = require('https');
const log = require('intel');
const Promise = require('bluebird');
const graphiteUtil = require('./util');

module.exports = {
  send(options, group, url, baseDir, pagePath) {

    // The tags make it possible for the dashboard to use the
    // templates to choose which annotations that will be showed.
    // That's why we need to send tags that matches the template
    // variables in Grafana.
    const connectivity = graphiteUtil.getConnectivity(options);
    const browser = options.browser;
    const namespace = options.graphite.namespace.split('.').join(',');
    const urlAndGroup = graphiteUtil.getURLAndGroup(options, group, url, options.graphite.includeQueryParams).split('.').join(',');
    const tags =  `${connectivity},${browser},${namespace},${urlAndGroup}`;
    const message = `<a href='${options.resultBaseURL}${baseDir}/${pagePath}' target='_blank'>Result ${options.browsertime.iterations} run(s)</a>`;

    const postData =
      `{"what": "Sitespeed.io", "tags": "${tags}", "data": "${message}"}`;
    const postOptions = {
      hostname: options.graphite.host,
      port: options.graphite.httpPort || 8080,
      path: '/events/',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    // If Graphite is behind auth, use it!
    if (options.graphite.auth) {
      postOptions.auth = options.graphite.auth;
    }

    return new Promise((resolve, reject) => {
      log.trace('Send annotation to Graphite: %j', postData);
      // not perfect but maybe work for us
      const lib = options.graphite.httpPort === 443 ? https : http;
      const req = lib.request(postOptions, (res) => {
        if (res.statusCode !== 200) {
          log.error('Got %s from Graphite when sending annotation', res.statusCode);
          reject();
        } else {
        res.setEncoding('utf8');
        log.info('Sent annotation to Graphite');
        resolve();
      }
      });
      req.on('error', (err) => {
        log.error('Got error from Graphite when sending annotation', err);
        reject(err)
      });
      req.write(postData);
      req.end();
    })
  }
}
<commit_msg>adding that missing slash<commit_after>'use strict';
const http = require('http');
const https = require('https');
const log = require('intel');
const Promise = require('bluebird');
const graphiteUtil = require('./util');

module.exports = {
  send(options, group, url, baseDir, pagePath) {

    // The tags make it possible for the dashboard to use the
    // templates to choose which annotations that will be showed.
    // That's why we need to send tags that matches the template
    // variables in Grafana.
    const connectivity = graphiteUtil.getConnectivity(options);
    const browser = options.browser;
    const namespace = options.graphite.namespace.split('.').join(',');
    const urlAndGroup = graphiteUtil.getURLAndGroup(options, group, url, options.graphite.includeQueryParams).split('.').join(',');
    const tags =  `${connectivity},${browser},${namespace},${urlAndGroup}`;
    const message = `<a href='${options.resultBaseURL}/${baseDir}/${pagePath}' target='_blank'>Result ${options.browsertime.iterations} run(s)</a>`;

    const postData =
      `{"what": "Sitespeed.io", "tags": "${tags}", "data": "${message}"}`;
    const postOptions = {
      hostname: options.graphite.host,
      port: options.graphite.httpPort || 8080,
      path: '/events/',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    // If Graphite is behind auth, use it!
    if (options.graphite.auth) {
      postOptions.auth = options.graphite.auth;
    }

    return new Promise((resolve, reject) => {
      log.trace('Send annotation to Graphite: %j', postData);
      // not perfect but maybe work for us
      const lib = options.graphite.httpPort === 443 ? https : http;
      const req = lib.request(postOptions, (res) => {
        if (res.statusCode !== 200) {
          log.error('Got %s from Graphite when sending annotation', res.statusCode);
          reject();
        } else {
        res.setEncoding('utf8');
        log.info('Sent annotation to Graphite');
        resolve();
      }
      });
      req.on('error', (err) => {
        log.error('Got error from Graphite when sending annotation', err);
        reject(err)
      });
      req.write(postData);
      req.end();
    })
  }
}
<|endoftext|>


<commit_before>var Stream = require('stream');

// writable
exports.Event = function (options) {

    options = options || {};
    if (typeof options.objectMode === 'undefined') {
        options.objectMode = true;
    }

    var sequence = Stream.Transform({
        objectMode: options.objectMode ? true : false,
        transform: function (chunk, enc, next) {

            var push;
            var pos = -1;
            var handler;
            var runSeq = function (err, data) {

                if (err && data) {
                    data = err;
                    err = null;
                    push = true;
                } else {
                    push = false;
                }

                // emit error
                if (err) {
                    return next(err);
                };

                // just push data to readable if data and error is true
                if (push) {
                    return sequence.push(data);
                }

                // get handler
                if (!(handler = sequence.seq[++pos])) {
                    return next(null, data);
                }

                // call next data handler
                if (!handler[4]) {

                    // once handler
                    if (handler[3]) {
                        handler[4] = true;
                    }

                    handler[0].call(handler[2], handler[1], data, runSeq);
                } else {
                    runSeq(null, data);
                }
            };

            if (!sequence.seq) {
                sequence.once('sequence', runSeq.bind(this, null, chunk));
                return;
            }

            runSeq(null, chunk);
        }
    });
    sequence.resume();
    return sequence;
};
<commit_msg>export a pass through stream for linking to net-streams<commit_after>var Stream = require('stream');

exports.Net = Stream.PassThrough;

// writable
exports.Event = function (options) {

    options = options || {};
    if (typeof options.objectMode === 'undefined') {
        options.objectMode = true;
    }

    var sequence = Stream.Transform({
        objectMode: options.objectMode ? true : false,
        transform: function (chunk, enc, next) {

            var push;
            var pos = -1;
            var handler;
            var runSeq = function (err, data) {

                if (err && data) {
                    data = err;
                    err = null;
                    push = true;
                } else {
                    push = false;
                }

                // emit error
                if (err) {
                    return next(err);
                };

                // just push data to readable if data and error is true
                if (push) {
                    return sequence.push(data);
                }

                // get handler
                if (!(handler = sequence.seq[++pos])) {
                    return next(null, data);
                }

                // call next data handler
                if (!handler[4]) {

                    // once handler
                    if (handler[3]) {
                        handler[4] = true;
                    }

                    handler[0].call(handler[2], handler[1], data, runSeq);
                } else {
                    runSeq(null, data);
                }
            };

            if (!sequence.seq) {
                sequence.once('sequence', runSeq.bind(this, null, chunk));
                return;
            }

            runSeq(null, chunk);
        }
    });
    sequence.resume();
    return sequence;
};
<|endoftext|>


<commit_before>const express = require('express')

let app = express()

let env = process.env.NODE_ENV || 'development'
let config = require('./server/config/config')[env]

require('./server/config/database')(config)
require('./server/config/express')(config, app)
require('./server/config/routes')(app)
require('./server/config/passport')()

app.listen(config.port)
console.log('Express ready!')
<commit_msg>Changes to listen in index<commit_after>const express = require('express')

let app = express()

let env = process.env.NODE_ENV || 'development'
let config = require('./server/config/config')[env]

require('./server/config/database')(config)
require('./server/config/express')(config, app)
require('./server/config/routes')(app)
require('./server/config/passport')()

app.listen(process.env.port || 1337)
console.log('Express ready!')
<|endoftext|>


<commit_before>require('../extensions.js')

var should = require('should');

describe('Date.prototype', function() {
  var date = new Date(2000, 0, 1),
      date2 = new Date(2000, 0, 4);

  it('should return 1 equals 1', function() { (1).should.equal(1); });
  //////////////////////////////////////
  // Checks that date functions exist //
  //////////////////////////////////////

  it('.isDate should return function for all types', function() {
    var dateIsDateCode   = new Date().isDate
      , objectIsDateCode = {}.isDate
      , arrayIsDateCode  = [].isDate
      , stringIsDateCode = "".isDate;

    ( dateIsDateCode ).should.be.ok;
    ( typeof dateIsDateCode ).should.equal( "function" );

    ( objectIsDateCode ).should.be.ok;
    ( typeof objectIsDateCode ).should.equal( "function" );

    ( arrayIsDateCode ).should.be.ok;
    ( typeof arrayIsDateCode ).should.equal( "function" );

    ( stringIsDateCode ).should.be.ok;
    ( typeof stringIsDateCode ).should.equal( "function" );
  });

  it('.getLabel should return function', function() {
    var getLabelCode = new Date().getLabel;

    ( getLabelCode ).should.be.ok;
    ( typeof getLabelCode ).should.equal( "function" );
  });

  it('.getDelta should return function', function() {
    var getDeltaCode = new Date().getDelta;

    ( getDeltaCode ).should.be.ok;
    ( typeof getDeltaCode ).should.equal( "function" );
  });

  ///////////////////////////////////////////////
  // Verifies Date extensions work as should //
  ///////////////////////////////////////////////

  it('.isDate() should return true for actual dates', function() {
    ( date.isDate()  ).should.equal( true );
    ( date2.isDate() ).should.equal( true );
  });

  it('.isDate() should return false for non-valid types/ values', function() {
    ( new Date('Malformed Date String').isDate() ).should.not.be.ok;
    ( {}                               .isDate() ).should.not.be.ok;
    ( ("")                             .isDate() ).should.not.be.ok;
    ( (55)                             .isDate() ).should.not.be.ok;
  });

  it('.getLabel() should return expected string', function() {
    (  date.getLabel() ).should.equal( 'Jan 01 2000' );
    ( date2.getLabel() ).should.equal( 'Jan 04 2000' );
  });

  it('.getDelta() should equal expected deltas', function() {
    ( date.getDelta( date2 ) ).should.eql({ days : 3, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 });
    ( date2.getDelta( date ) ).should.eql({ days : 3, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 });
  });

  it('.getDelta() for invalid dates should return empty Object', function() {
    var invalidDateDelta = date.getDelta( new Date('Invalid Date String')  );

    ( typeof invalidDateDelta            ).should.equal( "object" );
    ( JSON.stringify( invalidDateDelta ) ).should.equal( "{}" );
  });

});

describe('Array.prototype', function() {

  it('.merge should return function', function() {
    var merge = [].merge;

    ( merge ).should.be.ok;
    ( typeof merge ).should.equal( "function" );
  });

  it('.merge() should return merged array', function() {
    var arr1 = [1,2,3],
        arr2 = [4,5,6];

    ( arr1.merge(arr2) ).should.eql([1, 2, 3, 4, 5, 6]);
  });

  it('.merge() alter original array', function() {
    var arr1 = [1,2,3]
      , arr2 = [4,5,6];

    arr1.merge(arr2);
    arr1.should.eql([1, 2, 3, 4, 5, 6]);
  });
});

describe('Object.prototype', function() {

  it('.get should return function', function() {
    var getFunction = {}.get;

    ( getFunction ).should.be.ok;
    ( typeof getFunction ).should.equal( "function" );
  });

  it('.get() on obj.key should work', function() {
    var obj = { foo : "bar" };

    ( obj.get("foo") ).should.equal('bar');
    ( typeof obj.get("name") ).should.equal( "undefined" );
  });

  it('.get() o obj.key[i] should work', function() {
    var obj = { arr : [ "string"] };

    ( obj.get("arr[0]") ).should.equal( "string" );
    ( typeof obj.get("arr[2]") ).should.equal( "undefined" );
  });

  it('.get() should work on arrays too!', function() {
    var obj = { arr : [ ]}
    var arrObj = [ "string", { name : 'Jim' } ];

    ( arrObj.get('[0]') ).should.equal( "string" );
    ( arrObj.get('[1]') ).should.eql( { name : "Jim" } );
    ( typeof arrObj.get('[3]') ).should.equal( "undefined" );
  });

  /*
    TODO: Handle more edgey-cases.
     - dot syntax for arrays:  obj.arr.0.someOtherProperty
     - syntax-mix?:  obj.arr[0].anotherArr.0
  */
});

describe('String.prototype', function() {

  it('.formatPhone should return function', function() {
    var formatPhone = "".formatPhone;

    ( formatPhone ).should.be.ok;
    ( typeof formatPhone ).should.equal( 'function' );
  });

  it('.trim should return function', function() {
    var trim = "".trim;

    ( trim ).should.be.ok;
    ( typeof trim ).should.equal( "function" );
  });

  it('.formatPhone() should return expected format', function() {
    var formattedPhone = "737-4844832 x58"
      , shortPhone = "33322200";

    ( formattedPhone.formatPhone() ).should.equal( "(737) 484-4832 x58" );
    ( shortPhone.formatPhone() ).should.equal( "(333) 222-00__" );
  });

  it('.trim should remove whitespace from both sides of string', function() {
    var str = "   No more spaces!          ";

    ( str.trim() ).should.equal( 'No more spaces!' );
  });
});<commit_msg>Added mongoose<commit_after>require('../extensions.js')

var should = require('should');
// var mongoose = require('mongoose');

describe('Date.prototype', function() {
  var date = new Date(2000, 0, 1),
      date2 = new Date(2000, 0, 4);

  it('should return 1 equals 1', function() { (1).should.equal(1); });
  //////////////////////////////////////
  // Checks that date functions exist //
  //////////////////////////////////////

  it('.isDate should return function for all types', function() {
    var dateIsDateCode   = new Date().isDate
      , objectIsDateCode = {}.isDate
      , arrayIsDateCode  = [].isDate
      , stringIsDateCode = "".isDate;

    ( dateIsDateCode ).should.be.ok;
    ( typeof dateIsDateCode ).should.equal( "function" );

    ( objectIsDateCode ).should.be.ok;
    ( typeof objectIsDateCode ).should.equal( "function" );

    ( arrayIsDateCode ).should.be.ok;
    ( typeof arrayIsDateCode ).should.equal( "function" );

    ( stringIsDateCode ).should.be.ok;
    ( typeof stringIsDateCode ).should.equal( "function" );
  });

  it('.getLabel should return function', function() {
    var getLabelCode = new Date().getLabel;

    ( getLabelCode ).should.be.ok;
    ( typeof getLabelCode ).should.equal( "function" );
  });

  it('.getDelta should return function', function() {
    var getDeltaCode = new Date().getDelta;

    ( getDeltaCode ).should.be.ok;
    ( typeof getDeltaCode ).should.equal( "function" );
  });

  ///////////////////////////////////////////////
  // Verifies Date extensions work as should //
  ///////////////////////////////////////////////

  it('.isDate() should return true for actual dates', function() {
    ( date.isDate()  ).should.equal( true );
    ( date2.isDate() ).should.equal( true );
  });

  it('.isDate() should return false for non-valid types/ values', function() {
    ( new Date('Malformed Date String').isDate() ).should.not.be.ok;
    ( {}                               .isDate() ).should.not.be.ok;
    ( ("")                             .isDate() ).should.not.be.ok;
    ( (55)                             .isDate() ).should.not.be.ok;
  });

  it('.getLabel() should return expected string', function() {
    (  date.getLabel() ).should.equal( 'Jan 01 2000' );
    ( date2.getLabel() ).should.equal( 'Jan 04 2000' );
  });

  it('.getDelta() should equal expected deltas', function() {
    ( date.getDelta( date2 ) ).should.eql({ days : 3, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 });
    ( date2.getDelta( date ) ).should.eql({ days : 3, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 });
  });

  it('.getDelta() for invalid dates should return empty Object', function() {
    var invalidDateDelta = date.getDelta( new Date('Invalid Date String')  );

    ( typeof invalidDateDelta            ).should.equal( "object" );
    ( JSON.stringify( invalidDateDelta ) ).should.equal( "{}" );
  });

});

describe('Array.prototype', function() {

  it('.merge should return function', function() {
    var merge = [].merge;

    ( merge ).should.be.ok;
    ( typeof merge ).should.equal( "function" );
  });

  it('.merge() should return merged array', function() {
    var arr1 = [1,2,3],
        arr2 = [4,5,6];

    ( arr1.merge(arr2) ).should.eql([1, 2, 3, 4, 5, 6]);
  });

  it('.merge() alter original array', function() {
    var arr1 = [1,2,3]
      , arr2 = [4,5,6];

    arr1.merge(arr2);
    arr1.should.eql([1, 2, 3, 4, 5, 6]);
  });
});

describe('Object.prototype', function() {

  it('.get should return function', function() {
    var getFunction = {}.get;

    ( getFunction ).should.be.ok;
    ( typeof getFunction ).should.equal( "function" );
  });

  it('.get() on obj.key should work', function() {
    var obj = { foo : "bar" };

    ( obj.get("foo") ).should.equal('bar');
    ( typeof obj.get("name") ).should.equal( "undefined" );
  });

  it('.get() o obj.key[i] should work', function() {
    var obj = { arr : [ "string"] };

    ( obj.get("arr[0]") ).should.equal( "string" );
    ( typeof obj.get("arr[2]") ).should.equal( "undefined" );
  });

  it('.get() should work on arrays too!', function() {
    var obj = { arr : [ ]}
    var arrObj = [ "string", { name : 'Jim' } ];

    ( arrObj.get('[0]') ).should.equal( "string" );
    ( arrObj.get('[1]') ).should.eql( { name : "Jim" } );
    ( typeof arrObj.get('[3]') ).should.equal( "undefined" );
  });

  /*
    TODO: Handle more edgey-cases.
     - dot syntax for arrays:  obj.arr.0.someOtherProperty
     - syntax-mix?:  obj.arr[0].anotherArr.0
  */
});

describe('String.prototype', function() {

  it('.formatPhone should return function', function() {
    var formatPhone = "".formatPhone;

    ( formatPhone ).should.be.ok;
    ( typeof formatPhone ).should.equal( 'function' );
  });

  it('.trim should return function', function() {
    var trim = "".trim;

    ( trim ).should.be.ok;
    ( typeof trim ).should.equal( "function" );
  });

  it('.formatPhone() should return expected format', function() {
    var formattedPhone = "737-4844832 x58"
      , shortPhone = "33322200";

    ( formattedPhone.formatPhone() ).should.equal( "(737) 484-4832 x58" );
    ( shortPhone.formatPhone() ).should.equal( "(333) 222-00__" );
  });

  it('.trim should remove whitespace from both sides of string', function() {
    var str = "   No more spaces!          ";

    ( str.trim() ).should.equal( 'No more spaces!' );
  });
});<|endoftext|>


<commit_before>/* ======= Instance Methods ======= */

var hasConsole = typeof window.console !== undefined;

/**
* Logs a Message
* @param {String} msg
*/
Moon.prototype.log = function(msg) {
  if(!config.silent && hasConsole) console.log(msg);
}

/**
* Throws an Error
* @param {String} msg
*/
Moon.prototype.error = function(msg) {
  if(hasConsole) console.error("[Moon] ERR: " + msg);
}

/**
* Sets Value in Data
* @param {String} key
* @param {String} val
*/
Moon.prototype.set = function(key, val) {
  this.$data[key] = val;
  if(!this.$destroyed) this.build(this.$el.childNodes, this.$dom.children);
  this.$hooks.updated();
}

/**
* Gets Value in Data
* @param {String} key
* @return {String} Value of key in data
*/
Moon.prototype.get = function(key) {
  return this.$data[key];
}

/**
* Calls a method
* @param {String} method
*/
Moon.prototype.method = function(method) {
  this.$methods[method]();
}

/**
* Destroys Moon Instance
*/
Moon.prototype.destroy = function() {
  Object.defineProperty(this, '$data', {
    set: function(value) {
      _data = value;
    }
  });
  this.$destroyed = true;
  this.$hooks.destroyed();
}

/**
* Builds the DOM With Data
* @param {Array} children
*/
Moon.prototype.build = function(children, vdom) {
  for(var i = 0; i < children.length; i++) {
    var vnode = vdom[i];
    var child = children[i];

    if(child.nodeName === "#text") {
      child.textContent = compileTemplate(vnode.val, this.$data);
    } else if(vnode.props) {
      for(var attr in vnode.props) {

      }
    }

    this.build(child.childNodes, vnode.children);
  }
}

/**
* Initializes Moon
*/
Moon.prototype.init = function() {
  this.log("======= Moon =======");
  this.$hooks.created();
  setInitialElementValue(this.$el, this.$template);
  this.$dom = createVirtualDOM(this.$el);
  this.build(this.$el.childNodes, this.$dom.children);
  this.$hooks.mounted();
}
<commit_msg>compile attributes<commit_after>/* ======= Instance Methods ======= */

var hasConsole = typeof window.console !== undefined;

/**
* Logs a Message
* @param {String} msg
*/
Moon.prototype.log = function(msg) {
  if(!config.silent && hasConsole) console.log(msg);
}

/**
* Throws an Error
* @param {String} msg
*/
Moon.prototype.error = function(msg) {
  if(hasConsole) console.error("[Moon] ERR: " + msg);
}

/**
* Sets Value in Data
* @param {String} key
* @param {String} val
*/
Moon.prototype.set = function(key, val) {
  this.$data[key] = val;
  if(!this.$destroyed) this.build(this.$el.childNodes, this.$dom.children);
  this.$hooks.updated();
}

/**
* Gets Value in Data
* @param {String} key
* @return {String} Value of key in data
*/
Moon.prototype.get = function(key) {
  return this.$data[key];
}

/**
* Calls a method
* @param {String} method
*/
Moon.prototype.method = function(method) {
  this.$methods[method]();
}

/**
* Destroys Moon Instance
*/
Moon.prototype.destroy = function() {
  Object.defineProperty(this, '$data', {
    set: function(value) {
      _data = value;
    }
  });
  this.$destroyed = true;
  this.$hooks.destroyed();
}

/**
* Builds the DOM With Data
* @param {Array} children
*/
Moon.prototype.build = function(children, vdom) {
  for(var i = 0; i < children.length; i++) {
    var vnode = vdom[i];
    var child = children[i];

    if(child.nodeName === "#text") {
      child.textContent = compileTemplate(vnode.val, this.$data);
    } else if(vnode.props) {
      for(var attr in vnode.props) {
        child.setAttribute(attr, compileTemplate(vnode.props[attr], this.$data));
      }
    }

    this.build(child.childNodes, vnode.children);
  }
}

/**
* Initializes Moon
*/
Moon.prototype.init = function() {
  this.log("======= Moon =======");
  this.$hooks.created();
  setInitialElementValue(this.$el, this.$template);
  this.$dom = createVirtualDOM(this.$el);
  this.build(this.$el.childNodes, this.$dom.children);
  this.$hooks.mounted();
}
<|endoftext|>


<commit_before>const ZERO_DECIMAL_CURRENCIES = [
  'BIF',
  'CLP',
  'DJF',
  'GNF',
  'JPY',
  'KMF',
  'KRW',
  'MGA',
  'PYG',
  'RWF',
  'VND',
  'VUV',
  'XAF',
  'XOF',
  'XPF'
];

// Config
var Habitat = require('habitat');
Habitat.load();

var stripe = require('stripe')(process.env.STRIPE_API_KEY);
var oxr = require('open-exchange-rates');
var money = require('money');
var moment = require('moment');

oxr.set({ app_id: process.env.OXR_APP_ID });

function update_money(done) {
  if (!done) {
    done = function() {};
  }

  return function() {
    money.rates = oxr.rates;
    money.base = oxr.base;
    done();
  };
}

function update_exchange_rates(date, done) {
  done = update_money(done);

  if (date) {
    return oxr.historical(date, done);
  }

  oxr.latest(done);
}

update_exchange_rates();

// update exchange rates every hour
setInterval(update_exchange_rates, 1000 * 60 * 60);

var pg;
try {
  pg = require('pg').native;
} catch (ignore_error) {
  pg = require('pg');
}

var insert_query = 'INSERT INTO stripe (id, timestamp, amount, settle_amount, ' +
                   'refunded, currency, status, country_code, name, email ) ' +
                   'SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10';
var update_query = 'UPDATE stripe SET timestamp=$2, amount=$3, settle_amount=$4, ' +
                   'refunded=$5, currency=$6, status=$7, country_code=$8, ' +
                   ' name=$9, email=$10 WHERE id=$1';
var upsert_query = `WITH upsert AS (${update_query} RETURNING *) ${insert_query}` +
                   ' WHERE NOT EXISTS (SELECT * FROM upsert);';

function process_charge(charge, callback) {
  if (!callback) {
    callback = function() {};
  }

  pg.connect(process.env.STRIPE_DB_CONNECTION_STRING, function(err, client, done) {
    if (err) {
      console.error(`Error while connecting to db: ${err.toString()}`);
      done();
      return callback(err);
    }

    var adjusted_amount = charge.amount;
    var adjusted_amount_refunded = charge.amount_refunded;
    var currency = charge.currency.toUpperCase();

    if (ZERO_DECIMAL_CURRENCIES.indexOf(currency) === -1) {
      adjusted_amount = adjusted_amount / 100;
      // don't divide with 0 :)
      if (adjusted_amount_refunded) {
        adjusted_amount_refunded = adjusted_amount_refunded / 100;
      }
    }

    var settle_amount = money(adjusted_amount).from(currency).to('USD');

    client.query(upsert_query, [
      charge.id,
      moment.unix(charge.created).toISOString(),
      adjusted_amount,
      settle_amount,
      adjusted_amount_refunded,
      currency,
      charge.status,
      charge.source.address_country,
      charge.source.name,
      charge.metadata.email
    ], function(err, result) {
      done();
      if (err) {
        console.error(`Error while upserting charge: ${err.toString()}`);
        return callback(err);
      }
      callback();
    });
  });
}

module.exports = {
  process_charge,
  stripe,
  update_exchange_rates
};
<commit_msg>Use country code instead of country name<commit_after>const ZERO_DECIMAL_CURRENCIES = [
  'BIF',
  'CLP',
  'DJF',
  'GNF',
  'JPY',
  'KMF',
  'KRW',
  'MGA',
  'PYG',
  'RWF',
  'VND',
  'VUV',
  'XAF',
  'XOF',
  'XPF'
];

// Config
var Habitat = require('habitat');
Habitat.load();

var stripe = require('stripe')(process.env.STRIPE_API_KEY);
var oxr = require('open-exchange-rates');
var money = require('money');
var moment = require('moment');

oxr.set({ app_id: process.env.OXR_APP_ID });

function update_money(done) {
  if (!done) {
    done = function() {};
  }

  return function() {
    money.rates = oxr.rates;
    money.base = oxr.base;
    done();
  };
}

function update_exchange_rates(date, done) {
  done = update_money(done);

  if (date) {
    return oxr.historical(date, done);
  }

  oxr.latest(done);
}

update_exchange_rates();

// update exchange rates every hour
setInterval(update_exchange_rates, 1000 * 60 * 60);

var pg;
try {
  pg = require('pg').native;
} catch (ignore_error) {
  pg = require('pg');
}

var insert_query = 'INSERT INTO stripe (id, timestamp, amount, settle_amount, ' +
                   'refunded, currency, status, country_code, name, email ) ' +
                   'SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10';
var update_query = 'UPDATE stripe SET timestamp=$2, amount=$3, settle_amount=$4, ' +
                   'refunded=$5, currency=$6, status=$7, country_code=$8, ' +
                   ' name=$9, email=$10 WHERE id=$1';
var upsert_query = `WITH upsert AS (${update_query} RETURNING *) ${insert_query}` +
                   ' WHERE NOT EXISTS (SELECT * FROM upsert);';

function process_charge(charge, callback) {
  if (!callback) {
    callback = function() {};
  }

  pg.connect(process.env.STRIPE_DB_CONNECTION_STRING, function(err, client, done) {
    if (err) {
      console.error(`Error while connecting to db: ${err.toString()}`);
      done();
      return callback(err);
    }

    var adjusted_amount = charge.amount;
    var adjusted_amount_refunded = charge.amount_refunded;
    var currency = charge.currency.toUpperCase();

    if (ZERO_DECIMAL_CURRENCIES.indexOf(currency) === -1) {
      adjusted_amount = adjusted_amount / 100;
      // don't divide with 0 :)
      if (adjusted_amount_refunded) {
        adjusted_amount_refunded = adjusted_amount_refunded / 100;
      }
    }

    var settle_amount = money(adjusted_amount).from(currency).to('USD');

    client.query(upsert_query, [
      charge.id,
      moment.unix(charge.created).toISOString(),
      adjusted_amount,
      settle_amount,
      adjusted_amount_refunded,
      currency,
      charge.status,
      charge.source.country,
      charge.source.name,
      charge.metadata.email
    ], function(err, result) {
      done();
      if (err) {
        console.error(`Error while upserting charge: ${err.toString()}`);
        return callback(err);
      }
      callback();
    });
  });
}

module.exports = {
  process_charge,
  stripe,
  update_exchange_rates
};
<|endoftext|>


<commit_before>const shelljs = require('shelljs');
const ProcessWrapper = require('../../process/processWrapper');
const constants = require('../../constants');

let swarmProcess;

class SwarmProcess extends ProcessWrapper {
  constructor(options) {
    super();
    this.storageConfig = options.storageConfig;
  }

  startSwarmDaemon() {
    console.log(this.storageConfig);
    if (!this.storageConfig.account || !this.storageConfig.account.address || !this.storageConfig.account.password) {
      return 'Account address and password are needed in the storage config to start the Swarm process';
    }
    shelljs.exec(
      `${this.storageConfig.swarmPath || 'swarm'} --bzzaccount ${this.storageConfig.account.address} --password ${this.storageConfig.account.password} --corsdomain http://localhost:8000 --ens-api ''`,
      {silent: true}, (err, _stdout, _stderr) =>
    {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      process.exit();
    });
  }
}

process.on('message', (msg) => {
  if (msg.action === constants.storage.init) {
    swarmProcess = new SwarmProcess(msg.options);
    const error = swarmProcess.startSwarmDaemon();

    swarmProcess.send({result: constants.storage.initiated, error});
  }
});
<commit_msg>detect swarm started signal<commit_after>const shelljs = require('shelljs');
const ProcessWrapper = require('../../process/processWrapper');
const constants = require('../../constants');

let swarmProcess;

class SwarmProcess extends ProcessWrapper {
  constructor(options) {
    super();
    this.storageConfig = options.storageConfig;
  }

  startSwarmDaemon() {
    console.log(this.storageConfig);
    if (!this.storageConfig.account || !this.storageConfig.account.address || !this.storageConfig.account.password) {
      return 'Account address and password are needed in the storage config to start the Swarm process';
    }
    const child = shelljs.exec(
      `${this.storageConfig.swarmPath || 'swarm'} --bzzaccount ${this.storageConfig.account.address} --password ${this.storageConfig.account.password} --corsdomain http://localhost:8000 --ens-api ''`,
      {silent: true}, (err, _stdout, _stderr) =>
    {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      process.exit();
    });
    let lastMessage;
    child.stdout.on('data', (data) => {
      if (!self.readyCalled && data.indexOf('Swarm http proxy started') > -1) {
        self.readyCalled = true;
        self.send({result: constants.storage.initiated});
      }
      lastMessage = data;
      console.log('Swarm: ' + data);
    });
    child.on('exit', (code) => {
      if (code) {
        console.error('Swarm exited with error code ' + code);
        console.error(lastMessage);
      }
    });
  }
}

process.on('message', (msg) => {
  if (msg.action === constants.storage.init) {
    swarmProcess = new SwarmProcess(msg.options);
    const error = swarmProcess.startSwarmDaemon();

    if (error) {
      swarmProcess.send({result: constants.storage.initiated, error});
    }
  }
});
<|endoftext|>


<commit_before>if (typeof(Alchemy) === 'undefined') {
	var Alchemy = {};
}

(function($) {

	var ElementEditorSelector = {};
	$.extend(Alchemy, ElementEditorSelector);

	Alchemy.ElementEditorSelector = {

		init : function() {
			var $elements = $('#element_area .element_editor');
			var self = Alchemy.ElementEditorSelector;
			self.reinit($elements);
		},

		reinit : function(elements) {
			var self = Alchemy.ElementEditorSelector;
			var $elements = $(elements);
			$elements.each(function () {
				self.bindEvent(this, $elements);
			});
			$elements.find('.element_head').click(self.onClickElement);
			$elements.find('.element_head').dblclick(function() {
				var id = $(this).parent().attr('id').replace(/\D/g,'');
				self.foldElement(id);
			});
		},

		onClickElement : function(e) {
			var self = Alchemy.ElementEditorSelector;
			var $element = $(this).parent('.element_editor');
			var id = $element.attr('id').replace(/\D/g,'');
			var $frame_elements, $selected_element;
			e.preventDefault();
			$('#element_area .element_editor').removeClass('selected');
			$element.addClass('selected');
			self.scrollToElement(this);
			$frame_elements = document.getElementById('alchemyPreviewWindow').contentWindow.jQuery('[data-alchemy-element]');
			$selected_element = $frame_elements.closest('[data-alchemy-element="'+id+'"]');
			$selected_element.trigger('Alchemy.SelectElement');
		},

		bindEvent : function (element) {
			var self = Alchemy.ElementEditorSelector;
			$(element).bind('Alchemy.SelectElementEditor', self.selectElement);
		},

		selectElement : function (e) {
			var self = Alchemy.ElementEditorSelector;
			var id = this.id.replace(/\D/g,'');
			var $element = $(this);
			var $elements = $('#element_area .element_editor');
			var $cells = $('#cells .sortable_cell');
			var $cell;
			e.preventDefault();
			$elements.removeClass('selected');
			$element.addClass('selected');
			if ($cells.size() > 0) {
				$cell = $element.parent('.sortable_cell');
				$('#cells').tabs('select', $cell.attr('id'));
			}
			if ($element.hasClass('folded')) {
				self.foldElement(id);
			} else {
				self.scrollToElement(this);
			}
		},

		scrollToElement : function(el) {
			$('#alchemyElementWindow').scrollTo(el, {duration: 400, offset: -10});
		},

		foldElement : function(id) {
			var self = Alchemy.ElementEditorSelector;
			$('#element_'+id+'_folder').hide();
			$('#element_'+id+'_folder_spinner').show();
			$.post('/admin/elements/fold?id='+id, function() {
				$('#element_'+id+'_folder').show();
				$('#element_'+id+'_folder_spinner').hide();
				self.scrollToElement('#element_'+id);
			});
		}

	}

})(jQuery);
<commit_msg>Fixes unfolding of element while clicking on element in preview<commit_after>if (typeof(Alchemy) === 'undefined') {
	var Alchemy = {};
}

(function($) {

	var ElementEditorSelector = {};
	$.extend(Alchemy, ElementEditorSelector);

	Alchemy.ElementEditorSelector = {

		init : function() {
			var $elements = $('#element_area .element_editor');
			var self = Alchemy.ElementEditorSelector;
			self.reinit($elements);
		},

		reinit : function(elements) {
			var self = Alchemy.ElementEditorSelector;
			var $elements = $(elements);
			$elements.each(function () {
				self.bindEvent(this, $elements);
			});
			$elements.find('.element_head').click(self.onClickElement);
			$elements.find('.element_head').dblclick(function() {
				var id = $(this).parent().attr('id').replace(/\D/g,'');
				self.foldElement(id);
			});
		},

		onClickElement : function(e) {
			var self = Alchemy.ElementEditorSelector;
			var $element = $(this).parent('.element_editor');
			var id = $element.attr('id').replace(/\D/g,'');
			var $frame_elements, $selected_element;
			e.preventDefault();
			$('#element_area .element_editor').removeClass('selected');
			$element.addClass('selected');
			self.scrollToElement(this);
			$frame_elements = document.getElementById('alchemyPreviewWindow').contentWindow.jQuery('[data-alchemy-element]');
			$selected_element = $frame_elements.closest('[data-alchemy-element="'+id+'"]');
			$selected_element.trigger('Alchemy.SelectElement');
		},

		bindEvent : function (element) {
			var self = Alchemy.ElementEditorSelector;
			$(element).bind('Alchemy.SelectElementEditor', self.selectElement);
		},

		selectElement : function (e) {
			var self = Alchemy.ElementEditorSelector;
			var id = this.id.replace(/\D/g,'');
			var $element = $(this);
			var $elements = $('#element_area .element_editor');
			var $cells = $('#cells .sortable_cell');
			var $cell;
			e.preventDefault();
			$elements.removeClass('selected');
			$element.addClass('selected');
			if ($cells.size() > 0) {
				$cell = $element.parent('.sortable_cell');
				$('#cells').tabs('select', $cell.attr('id'));
			}
			if ($element.hasClass('folded')) {
				self.foldElement(id);
			} else {
				self.scrollToElement(this);
			}
		},

		scrollToElement : function(el) {
			$('#alchemyElementWindow').scrollTo(el, {duration: 400, offset: -10});
		},

		foldElement : function(id) {
			var self = Alchemy.ElementEditorSelector;
			$('#element_'+id+'_folder').hide();
			$('#element_'+id+'_folder_spinner').show();
			$.post('/admin/elements/'+id+'/fold', function() {
				$('#element_'+id+'_folder').show();
				$('#element_'+id+'_folder_spinner').hide();
				self.scrollToElement('#element_'+id);
			});
		}

	}

})(jQuery);
<|endoftext|>


<commit_before>window.poma = (function() {

  var poma = function() {}

  var _metafunc = function(node) {
    return (node instanceof Node) ? '_execute' : '_executes'
  }

  poma._execute = function(node, fn) {
    var args = [].slice.call(arguments, 2)
    node[fn].apply(node, args)
    return node
  }

  poma._executes = function(nodes, fn) {
    var args = [].slice.call(arguments, 2)
    for (var i = 0, len = nodes.length; i < len; i += 1) {
      nodes[i][fn].apply(nodes[i], args)
    }
    return nodes
  }

// ## PUBLIC ##

  poma.on = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'addEventListener', type, fn, false)
  }

  poma.off = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'removeEventListener', type, fn, false)
  }

  poma.once = function(node, type, fn) {
    var handler = function(e) {
      poma.off(node, type, handler)
      fn(e)
    }
    poma.on(node, type, handler)
    return node
  }

  poma.event = function(type, data, target) {
    var e = document.createEvent('HTMLEvents')
    e.initEvent(type, true, true)
    e.eventName = type
    e.target = target || document
    e.data = data || {}
    return e
  }

  poma.trigger = function(node, type, data) {
    var e = (typeof type === 'string') ? poma.event(type, data, node) : type
    var f = _metafunc(node)
    return poma[f](node, 'dispatchEvent', e)
  }

  poma.matches = (function() {
    var b = document.body
    return b.matches || b.webkitMatchesSelector || b.mozMatchesSelector || b.msMatchesSelector
  })();

  poma.parentSelector = function(node, selector) {
    node = node.parentNode
    while (node && node !== document) {
      if (poma.matches.bind(node)(selector)) {
        return node
      } else {
        node = node.parentNode
      }
    }
    return false
  }

  poma.parentSelectorAll = function(node, selector) {
    var nodes = []
    node = node.parentNode
    while (node !== document) {
      if (poma.matches.bind(node)(selector)) {
        nodes.push(node)
      }
      node = node.parentNode
    }
    return (nodes.length) ? nodes : false
  }

  poma.remove = function(node) {
    return node.parentNode.removeChild(node)
  }

  poma.plugin = function(object, fn) {
    if (typeof poma[fn] === 'function')
      return console.error('The "' + fn + '" function already exists on poma');
    poma[fn] = object[fn]
    return poma[fn]
  }

  return poma

})();

<commit_msg>Add strict<commit_after>window.poma = (function() {
  'use strict';

  var poma = function() {}

  var _metafunc = function(node) {
    return (node instanceof Node) ? '_execute' : '_executes'
  }

  poma._execute = function(node, fn) {
    var args = [].slice.call(arguments, 2)
    node[fn].apply(node, args)
    return node
  }

  poma._executes = function(nodes, fn) {
    var args = [].slice.call(arguments, 2)
    for (var i = 0, len = nodes.length; i < len; i += 1) {
      nodes[i][fn].apply(nodes[i], args)
    }
    return nodes
  }

// ## PUBLIC ##

  poma.on = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'addEventListener', type, fn, false)
  }

  poma.off = function(node, type, fn) {
    var f = _metafunc(node)
    return poma[f](node, 'removeEventListener', type, fn, false)
  }

  poma.once = function(node, type, fn) {
    var handler = function(e) {
      poma.off(node, type, handler)
      fn(e)
    }
    poma.on(node, type, handler)
    return node
  }

  poma.event = function(type, data, target) {
    var e = document.createEvent('HTMLEvents')
    e.initEvent(type, true, true)
    e.eventName = type
    e.target = target || document
    e.data = data || {}
    return e
  }

  poma.trigger = function(node, type, data) {
    var e = (typeof type === 'string') ? poma.event(type, data, node) : type
    var f = _metafunc(node)
    return poma[f](node, 'dispatchEvent', e)
  }

  poma.matches = (function() {
    var b = document.body
    return b.matches || b.webkitMatchesSelector || b.mozMatchesSelector || b.msMatchesSelector
  })();

  poma.parentSelector = function(node, selector) {
    node = node.parentNode
    while (node && node !== document) {
      if (poma.matches.bind(node)(selector)) {
        return node
      } else {
        node = node.parentNode
      }
    }
    return false
  }

  poma.parentSelectorAll = function(node, selector) {
    var nodes = []
    node = node.parentNode
    while (node !== document) {
      if (poma.matches.bind(node)(selector)) {
        nodes.push(node)
      }
      node = node.parentNode
    }
    return (nodes.length) ? nodes : false
  }

  poma.remove = function(node) {
    return node.parentNode.removeChild(node)
  }

  poma.plugin = function(object, fn) {
    if (typeof poma[fn] === 'function')
      return console.error('The "' + fn + '" function already exists on poma');
    poma[fn] = object[fn]
    return poma[fn]
  }

  return poma

})();

<|endoftext|>