<commit_before>'use strict';

import R from 'ramda';
import xtend from 'xtend';
import { DOM } from './util';
import themeEdit from './theme/edit';
import themeStyle from './theme/style';

// Data store
import Store from './store';

// Control handlers
import Line from './handlers/line';
import Point from './handlers/point';
import Square from './handlers/square';
import Polygon from './handlers/polygon';

function Draw(options) {
  if (!(this instanceof Draw)) return new Draw(options);
  mapboxgl.util.setOptions(this, options);

  // event listeners
  this.drag = this._drag.bind(this);
  this.onClick = this._onClick.bind(this);
  this.onKeyUp = this._onKeyUp.bind(this);
  this.endDrag = this._endDrag.bind(this);
  this.initiateDrag = this._initiateDrag.bind(this);
}

Draw.prototype = xtend(mapboxgl.Control.prototype, {

  options: {
    position: 'top-left',
    keybindings: true,
    geoJSON: [],
    controls: {
      marker: true,
      line: true,
      shape: true,
      square: true
    }
  },

  onAdd(map) {
    var controlClass = this._controlClass = 'mapboxgl-ctrl-draw-btn';
    var container = this._container = DOM.create('div', 'mapboxgl-ctrl-group', map.getContainer());
    var controls = this.options.controls;
    this.options.geoJSON = new Store(this.options.geoJSON, map);

    // Build out draw controls
    if (controls.line) {
      this.lineStringCtrl = this._createButton({
        className: controlClass + ' line',
        title: `LineString tool ${this.options.keybindings && '(l)'}`,
        fn: this._drawLine.bind(this)
      });
    }

    if (controls.shape) {
      this.polygonCtrl = this._createButton({
        className: `${controlClass} shape`,
        title: `Polygon tool ${this.options.keybindings && '(p)'}`,
        fn: this._drawPolygon.bind(this)
      });
    }

    if (controls.square) {
      this.squareCtrl = this._createButton({
        className: `${controlClass} square`,
        title: `Square tool ${this.options.keybindings && '(s)'}`,
        fn: this._drawSquare.bind(this)
      });
    }

    if (controls.marker) {
      this.markerCtrl = this._createButton({
        className: `${controlClass} marker`,
        title: `Marker tool ${this.options.keybindings && '(m)'}`,
        fn: this._drawPoint.bind(this)
      });
    }

    if (this.options.keybindings) {
      map.getContainer().addEventListener('keyup', this.onKeyUp);
    }

    this._map = map;

    this._mapState();
    return container;
  },

  _onKeyUp(e) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent('click', true, false);
    switch (e.keyCode) {
      case 76: // (l) linestring
        if (!this.lineStringCtrl.classList.contains('active')) {
          this.lineStringCtrl.dispatchEvent(event);
        }
        break;
      case 77: // (m) marker
        if (!this.markerCtrl.classList.contains('active')) {
          this.markerCtrl.dispatchEvent(event);
        }
        break;
      case 80: // (p) polygon
        if (!this.polygonCtrl.classList.contains('active')) {
          this.polygonCtrl.dispatchEvent(event);
        }
        break;
      case 83: // (s) square
        if (!this.squareCtrl.classList.contains('active')) {
          this.squareCtrl.dispatchEvent(event);
        }
        break;
      case 27: // (escape) exit draw/edit mode
        if (this._control && !this.editId) { // draw mode
          this._control.completeDraw();
        } else if (this._control) {
          this._control.completeEdit(); // edit mode
        }
        break;
      case 68: // (d) delete the feature in edit mode
        if (this.editId) {
          this._destroy(this.editId);
        }
    }
  },

  /**
   * Handles clicks on the maps in a number of scenarios
   * @param {Object} e - the object passed to the callback of map.on('click', ...)
   * @private
   */
  _onClick(e) {

    this._map.featuresAt(e.point, { radius: 10, includeGeometry: true }, (err, features) => {
      if (err) throw err;

      if (features.length) { // clicked on a feature
        if (this._control && !this.editId) { // clicked on a feature while in draw mode
          return;
        } else if (this._control && this.editId) { // clicked on a feature while in edit mode
          if (features[0].properties._drawid === this.editId) { // clicked on the feature you're editing
            return;
          } else { // clicked on a different feature while in edit mode
            this._control.completeEdit();
          }
        }
      } else { // clicked not on a feature
        if (!this._control && !this.editId) { // click outside features while not drawing or editing
          return;
        } else if (this._control && !this.editId) { // clicked outside features while drawing
          return;
        } else if (this._control && this.editId) { // clicked outside features while editing
          return this._control.completeEdit();
        }
      }

      // if (clicked on a feature && ((!editing this feature && !drawing))
      this._edit(features[0]);
    });

  },

  _edit(feature) {
    if (!feature.properties._drawid) return; // for when null geometries are returned

    this.editId = feature.properties._drawid;
    feature = this.options.geoJSON.edit(this.editId);
    var c = feature.geometry.coordinates;
    var featureType = feature.geometry.type;

    if (featureType === 'Point')
      this._control = new Point(this._map, this.options.geoJSON, feature);
    else if (featureType === 'LineString')
      this._control = new Line(this._map, this.options.geoJSON, feature);
    else if (c[0][0][0] === c[0][1][0])
      this._control = new Square(this._map, this.options.geoJSON, feature);
    else
      this._control = new Polygon(this._map, this.options.geoJSON, feature);

    this._map.getContainer().addEventListener('mousedown', this.initiateDrag, true);

    this.deleteBtn = this._createButton({
      className: 'mapboxgl-ctrl-draw-btn trash',
      title: `delete ${featureType}`,
      fn: this._destroy.bind(this, this.editId)
    });
  },

  _exitEdit() {
    DOM.destroy(this.deleteBtn);
    this._map.getContainer().removeEventListener('mousedown', this.initiateDrag, true);
    this.editId = false;
    this._control = false;
  },

  _initiateDrag(e) {
    var coords = DOM.mousePos(e, this._map._container);
    this._map.featuresAt([coords.x, coords.y], { radius: 10, includeGeometry: true }, (err, features) => {
      if (err) throw err;
      else if (!features.length) return;
      else if (features[0].properties._drawid !== this.editId) return;

      e.stopPropagation();

      if (features.length > 1) {
        this.vertex = R.find(feat => feat.properties.meta === 'vertex')(features);
        this.newVertex = R.find(feat => feat.properties.meta === 'midpoint')(features);
      }

      if (this.newVertex) {
        this._control.editAddVertex(coords, this.newVertex.properties.index);
        this.vertex = this.newVertex;
      }

      this._map.getContainer().addEventListener('mousemove', this.drag, true);
      this._map.getContainer().addEventListener('mouseup', this.endDrag, true);
    });
  },

  _drag(e) {
    e.stopPropagation();

    if (!this.dragging) {
      this.dragging = true;
      this.init = DOM.mousePos(e, this._map.getContainer());
      this._map.getContainer().classList.add('mapboxgl-draw-move-activated');
    }

    var curr = DOM.mousePos(e, this._map.getContainer());

    if (this.vertex) {
      this._control.moveVertex(this.init, curr, this.vertex.properties.index);
    } else {
      this._control.translate(this.init, curr);
    }
  },

  _endDrag() {
    this._map.getContainer().removeEventListener('mousemove', this.drag, true);
    this._map.getContainer().removeEventListener('mouseup', this.endDrag, true);
    this._map.getContainer().classList.remove('mapboxgl-draw-move-activated');

    this._control.translating = false;
    this.dragging = false;

    if (this.vertex) {
      this.vertex = false;
      this._control.movingVertex = false;
    }
  },

  _drawPolygon() {
    this._control = new Polygon(this._map, this.options.geoJSON);
    this._control.startDraw();
  },

  _drawLine() {
    this._control = new Line(this._map, this.options.geoJSON);
    this._control.startDraw();
  },

  _drawSquare() {
    this._control = new Square(this._map, this.options.geoJSON);
    this._control.startDraw();
  },

  _drawPoint() {
    this._control = new Point(this._map, this.options.geoJSON);
    this._control.startDraw();
  },

  _destroy(id) {
    this._control.store.clear(); // I don't like this
    this.options.geoJSON.unset(id);
    this._exitEdit();
  },

  _createButton(opts) {
    var a = DOM.create('button', opts.className, this._container, {
      title: opts.title
    });

    a.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();

      var el = e.target;

      if (this._control && !this.editId) this._control.completeDraw();

      if (el.classList.contains('active')) {
        el.classList.remove('active');
      } else {
        DOM.removeClass(document.querySelectorAll('.' + this._controlClass), 'active');
        el.classList.add('active');
        opts.fn();
      }

    }, true);

    return a;
  },

  _mapState() {
    var controlClass = this._controlClass;

    this._map.on('load', () => {

      var drawLayer = new mapboxgl.GeoJSONSource({
        data: this.options.geoJSON.getAll()
      });

      this._map.addSource('draw', drawLayer);
      themeStyle.forEach((style) => {
        this._map.addLayer(style);
      });

      var editLayer = new mapboxgl.GeoJSONSource({
        data: []
      });

      this._map.addSource('edit', editLayer);
      themeEdit.forEach((style) => {
        this._map.addLayer(style);
      });

      this._map.on('draw.end', () => {
        DOM.removeClass(document.querySelectorAll('.' + controlClass), 'active');
        this._control = false;
      });

      this._map.on('edit.end', this._exitEdit.bind(this));

      this._map.on('edit.feature.update', (e) => {
        editLayer.setData(e.geojson);
      });

      this._map.on('draw.feature.update', (e) => {
        drawLayer.setData(e.geojson);
      });

      this._map.on('click', this.onClick);

    });

  }
});

module.exports = Draw;
<commit_msg>try draw.js again<commit_after>'use strict';

import R from 'ramda';
//import xtend from 'xtend';
import { DOM } from './util';
import themeEdit from './theme/edit';
import themeStyle from './theme/style';

// Data store
import Store from './store';

// Control handlers
import Line from './handlers/line';
import Point from './handlers/point';
import Square from './handlers/square';
import Polygon from './handlers/polygon';

/*
function Draw(options) {
  if (!(this instanceof Draw)) return new Draw(options);
  mapboxgl.util.setOptions(this, options);

  // event listeners
  this.drag = this._drag.bind(this);
  this.onClick = this._onClick.bind(this);
  this.onKeyUp = this._onKeyUp.bind(this);
  this.endDrag = this._endDrag.bind(this);
  this.initiateDrag = this._initiateDrag.bind(this);
}
*/

//Draw.prototype = xtend(mapboxgl.Control.prototype, {

export default class Draw extends mapboxgl.Control {

  constructor(options) {
    super();

    if (!(this instanceof Draw)) return new Draw(options);
    mapboxgl.util.setOptions(this, options);

    // event listeners
    this.drag = this._drag.bind(this);
    this.onClick = this._onClick.bind(this);
    this.onKeyUp = this._onKeyUp.bind(this);
    this.endDrag = this._endDrag.bind(this);
    this.initiateDrag = this._initiateDrag.bind(this);

    this.options = {
      position: 'top-left',
      keybindings: true,
      geoJSON: [],
      controls: {
        marker: true,
        line: true,
        shape: true,
        square: true
      }
    };
  }

  onAdd(map) {
    var controlClass = this._controlClass = 'mapboxgl-ctrl-draw-btn';
    var container = this._container = DOM.create('div', 'mapboxgl-ctrl-group', map.getContainer());
    var controls = this.options.controls;
    this.options.geoJSON = new Store(this.options.geoJSON, map);

    // Build out draw controls
    if (controls.line) {
      this.lineStringCtrl = this._createButton({
        className: controlClass + ' line',
        title: `LineString tool ${this.options.keybindings && '(l)'}`,
        fn: this._drawLine.bind(this)
      });
    }

    if (controls.shape) {
      this.polygonCtrl = this._createButton({
        className: `${controlClass} shape`,
        title: `Polygon tool ${this.options.keybindings && '(p)'}`,
        fn: this._drawPolygon.bind(this)
      });
    }

    if (controls.square) {
      this.squareCtrl = this._createButton({
        className: `${controlClass} square`,
        title: `Square tool ${this.options.keybindings && '(s)'}`,
        fn: this._drawSquare.bind(this)
      });
    }

    if (controls.marker) {
      this.markerCtrl = this._createButton({
        className: `${controlClass} marker`,
        title: `Marker tool ${this.options.keybindings && '(m)'}`,
        fn: this._drawPoint.bind(this)
      });
    }

    if (this.options.keybindings) {
      map.getContainer().addEventListener('keyup', this.onKeyUp);
    }

    this._map = map;

    this._mapState();
    return container;
  }

  _onKeyUp(e) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent('click', true, false);
    switch (e.keyCode) {
      case 76: // (l) linestring
        if (!this.lineStringCtrl.classList.contains('active')) {
          this.lineStringCtrl.dispatchEvent(event);
        }
        break;
      case 77: // (m) marker
        if (!this.markerCtrl.classList.contains('active')) {
          this.markerCtrl.dispatchEvent(event);
        }
        break;
      case 80: // (p) polygon
        if (!this.polygonCtrl.classList.contains('active')) {
          this.polygonCtrl.dispatchEvent(event);
        }
        break;
      case 83: // (s) square
        if (!this.squareCtrl.classList.contains('active')) {
          this.squareCtrl.dispatchEvent(event);
        }
        break;
      case 27: // (escape) exit draw/edit mode
        if (this._control && !this.editId) { // draw mode
          this._control.completeDraw();
        } else if (this._control) {
          this._control.completeEdit(); // edit mode
        }
        break;
      case 68: // (d) delete the feature in edit mode
        if (this.editId) {
          this._destroy(this.editId);
        }
    }
  }

  /**
   * Handles clicks on the maps in a number of scenarios
   * @param {Object} e - the object passed to the callback of map.on('click', ...)
   * @private
   */
  _onClick(e) {

    this._map.featuresAt(e.point, { radius: 10, includeGeometry: true }, (err, features) => {
      if (err) throw err;

      if (features.length) { // clicked on a feature
        if (this._control && !this.editId) { // clicked on a feature while in draw mode
          return;
        } else if (this._control && this.editId) { // clicked on a feature while in edit mode
          if (features[0].properties._drawid === this.editId) { // clicked on the feature you're editing
            return;
          } else { // clicked on a different feature while in edit mode
            this._control.completeEdit();
          }
        }
      } else { // clicked not on a feature
        if (!this._control && !this.editId) { // click outside features while not drawing or editing
          return;
        } else if (this._control && !this.editId) { // clicked outside features while drawing
          return;
        } else if (this._control && this.editId) { // clicked outside features while editing
          return this._control.completeEdit();
        }
      }

      // if (clicked on a feature && ((!editing this feature && !drawing))
      this._edit(features[0]);
    });

  }

  _edit(feature) {
    if (!feature.properties._drawid) return; // for when null geometries are returned

    this.editId = feature.properties._drawid;
    feature = this.options.geoJSON.edit(this.editId);
    var c = feature.geometry.coordinates;
    var featureType = feature.geometry.type;

    if (featureType === 'Point')
      this._control = new Point(this._map, this.options.geoJSON, feature);
    else if (featureType === 'LineString')
      this._control = new Line(this._map, this.options.geoJSON, feature);
    else if (c[0][0][0] === c[0][1][0])
      this._control = new Square(this._map, this.options.geoJSON, feature);
    else
      this._control = new Polygon(this._map, this.options.geoJSON, feature);

    this._map.getContainer().addEventListener('mousedown', this.initiateDrag, true);

    this.deleteBtn = this._createButton({
      className: 'mapboxgl-ctrl-draw-btn trash',
      title: `delete ${featureType}`,
      fn: this._destroy.bind(this, this.editId)
    });
  }

  _exitEdit() {
    DOM.destroy(this.deleteBtn);
    this._map.getContainer().removeEventListener('mousedown', this.initiateDrag, true);
    this.editId = false;
    this._control = false;
  }

  _initiateDrag(e) {
    var coords = DOM.mousePos(e, this._map._container);
    this._map.featuresAt([coords.x, coords.y], { radius: 10, includeGeometry: true }, (err, features) => {
      if (err) throw err;
      else if (!features.length) return;
      else if (features[0].properties._drawid !== this.editId) return;

      e.stopPropagation();

      if (features.length > 1) {
        this.vertex = R.find(feat => feat.properties.meta === 'vertex')(features);
        this.newVertex = R.find(feat => feat.properties.meta === 'midpoint')(features);
      }

      if (this.newVertex) {
        this._control.editAddVertex(coords, this.newVertex.properties.index);
        this.vertex = this.newVertex;
      }

      this._map.getContainer().addEventListener('mousemove', this.drag, true);
      this._map.getContainer().addEventListener('mouseup', this.endDrag, true);
    });
  }

  _drag(e) {
    e.stopPropagation();

    if (!this.dragging) {
      this.dragging = true;
      this.init = DOM.mousePos(e, this._map.getContainer());
      this._map.getContainer().classList.add('mapboxgl-draw-move-activated');
    }

    var curr = DOM.mousePos(e, this._map.getContainer());

    if (this.vertex) {
      this._control.moveVertex(this.init, curr, this.vertex.properties.index);
    } else {
      this._control.translate(this.init, curr);
    }
  }

  _endDrag() {
    this._map.getContainer().removeEventListener('mousemove', this.drag, true);
    this._map.getContainer().removeEventListener('mouseup', this.endDrag, true);
    this._map.getContainer().classList.remove('mapboxgl-draw-move-activated');

    this._control.translating = false;
    this.dragging = false;

    if (this.vertex) {
      this.vertex = false;
      this._control.movingVertex = false;
    }
  }

  _drawPolygon() {
    this._control = new Polygon(this._map, this.options.geoJSON);
    this._control.startDraw();
  }

  _drawLine() {
    this._control = new Line(this._map, this.options.geoJSON);
    this._control.startDraw();
  }

  _drawSquare() {
    this._control = new Square(this._map, this.options.geoJSON);
    this._control.startDraw();
  }

  _drawPoint() {
    this._control = new Point(this._map, this.options.geoJSON);
    this._control.startDraw();
  }

  _destroy(id) {
    this._control.store.clear(); // I don't like this
    this.options.geoJSON.unset(id);
    this._exitEdit();
  }

  _createButton(opts) {
    var a = DOM.create('button', opts.className, this._container, {
      title: opts.title
    });

    a.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();

      var el = e.target;

      if (this._control && !this.editId) this._control.completeDraw();

      if (el.classList.contains('active')) {
        el.classList.remove('active');
      } else {
        DOM.removeClass(document.querySelectorAll('.' + this._controlClass), 'active');
        el.classList.add('active');
        opts.fn();
      }

    }, true);

    return a;
  }

  _mapState() {
    var controlClass = this._controlClass;

    this._map.on('load', () => {

      var drawLayer = new mapboxgl.GeoJSONSource({
        data: this.options.geoJSON.getAll()
      });

      this._map.addSource('draw', drawLayer);
      themeStyle.forEach((style) => {
        this._map.addLayer(style);
      });

      var editLayer = new mapboxgl.GeoJSONSource({
        data: []
      });

      this._map.addSource('edit', editLayer);
      themeEdit.forEach((style) => {
        this._map.addLayer(style);
      });

      this._map.on('draw.end', () => {
        DOM.removeClass(document.querySelectorAll('.' + controlClass), 'active');
        this._control = false;
      });

      this._map.on('edit.end', this._exitEdit.bind(this));

      this._map.on('edit.feature.update', (e) => {
        editLayer.setData(e.geojson);
      });

      this._map.on('draw.feature.update', (e) => {
        drawLayer.setData(e.geojson);
      });

      this._map.on('click', this.onClick);

    });

  }
}

//module.exports = Draw;
<|endoftext|>


<commit_before>// Barbiche
// version: 0.6.1
// author: Manuel Baclet <manuel@eda.sarl>
// license: MIT

'use strict';

var attrs = ['if', 'alias', 'text', 'html', 'repeat', 'import', 'attr', 'class', 'global'];
var BB_IF = 0, BB_ALIAS = 1, BB_TEXT = 2, BB_HTML = 3, BB_REPEAT = 4,
		BB_IMPORT = 5, BB_ATTR = 6, BB_CLASS = 7, BB_GLOBAL = 8;

var TEMPLATE = 'TEMPLATE';

/* shared context */

var context = {
	stack: [],
	resolve: function(identifier) {
		var m = this.stack.length - 1;
		var value;
		while (value === undefined && m >= 0) {
			value = this.stack[m][identifier];
			m--;
		}
		return (value === undefined) ? window[identifier] : value;
	},
	init: function(arr) {
		this.stack = arr || [];
	},
	push: function(obj) {
		this.stack.push(obj);
	},
	pop: function() {
		return this.stack.pop();
	}
};

/* BBObj class */

function BBObj(a, b) {
	this.value = a;
	this.name = b;
}

BBObj.prototype.toString = function() {
	if (this.value && this.name != null) return this.name.toString();
	else return '';
};

/* shared Parser*/

var Parser = require('../parser.js');
Parser.parser.yy.context = context;
Parser.parser.yy.BBObj = BBObj;

/* Barbiche instance builder */

function Barbiche(opt) {
	opt = opt || {};
	var doc = opt.document || document;

	var destructive = (opt.destructive !== undefined) ? !!opt.destructive : true;

	var prefixedAttrs = attrs.map(function(str) {
		return (opt.prefix || 'bb-') + str;
	});
	var prefixedAttrsObj = {};
	prefixedAttrs.forEach(function(attr, index) {
		prefixedAttrsObj[attr] = attrs[index];
	});

	var globalAttr = prefixedAttrs[BB_GLOBAL];
	var globalAttrSel = '[' + globalAttr + ']';

	function createTemplate() {
		return doc.createElement('template');
	}

	var store = {};

	/* Compilation helpers */

	var compile_works = {};
	compile_works[Node.ELEMENT_NODE] = function(node, template) {
		if (node.hasAttribute(prefixedAttrs[BB_REPEAT]) && node.nodeName != TEMPLATE) {
			if (node.hasAttribute(prefixedAttrs[BB_TEXT]) || node.hasAttribute(prefixedAttrs[BB_HTML]))
				node.removeAttribute(prefixedAttrs[BB_REPEAT]);
			else {
				var wrapper = createTemplate();
				wrapper.setAttribute(prefixedAttrs[BB_REPEAT], node.getAttribute(prefixedAttrs[BB_REPEAT]));
				node.removeAttribute(prefixedAttrs[BB_REPEAT]);
				[prefixedAttrs[BB_IF], prefixedAttrs[BB_ALIAS]].forEach(function(attr) {
					if (node.hasAttribute(attr)) {
						wrapper.setAttribute(attr, node.getAttribute(attr));
						node.removeAttribute(attr);
					}
				});
				node.before(wrapper);
				wrapper.content.appendChild(node);
				node = wrapper;
			}
		}
		var bbAttrs = {};
		function setAttr(name, value) {
			attrFound = true;
			var parsed = Parser.parse(value);
			bbAttrs[prefixedAttrsObj[attr]] = template._addClosure(parsed);
			node.removeAttribute(attr);
		}
		var attrFound = false;
		if (node.attributes.length > attrs.length) {
			prefixedAttrs.forEach(function(attr) {
				if (node.hasAttribute(attr)) setAttr(attr, node.getAttribute(attr));
			});
		} else {
			for (var i = node.attributes.length - 1; i >= 0; i--) {
				var attr = node.attributes[i].name;
				if (attr in prefixedAttrsObj) setAttr(attr, node.attributes[i].value);
			}
		}
		if (attrFound) node.setAttribute(globalAttr, JSON.stringify(bbAttrs));
		if (node.nodeName == TEMPLATE) {
			compile(node.content, template);
			if (!attrFound) node.replaceWith(node.content);
		} else {
			Array.from(node.childNodes).forEach(function(child) {
				compile(child, template);
			});
		}
	};

	compile_works[Node.TEXT_NODE] = (function() {
		var delimiters = opt.delimiters || ['{', '}'];

		function regExpEscape(str) {
			return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		}

		var UnescapeDelimitersRegExp = new RegExp('\\\\(' +
			['\\\\', regExpEscape(delimiters[0]), regExpEscape(delimiters[1])].join('|') +
		')', 'g');
		function unescapeDelimiters(str) {
			return str.replace(UnescapeDelimitersRegExp, function() {return arguments[1];});
		}

		var regExpTemplate = [
			'aaa((?:a+f+c+d+e+b(?:a+f+c+d+e+b(?:a+f+c+d+e)))*)bbb',
			'aa((?:a+f+c+d+e+b(?:a+f+c+d+e))*)bb',
			'((?:b+f+c+d+e+a(?:b+f+c+d+e))(?:b+f+c+d+e+a(?:b+f+c+d+e))*(?:a(?!a)+b+f+c+d+e++a(?:b+f+c+d+e))+(?:a(?!a)))'
		];
		var table = {
			a: regExpEscape(delimiters[0]),
			b: regExpEscape(delimiters[1]),
			c: regExpEscape("\\" + delimiters[0]),
			d: regExpEscape("\\" + delimiters[1]),
			e: '[^' + regExpEscape(delimiters[0]) + regExpEscape(delimiters[1]) + ']',
			f: regExpEscape("\\\\")
		};

		var textNodeRegExp = new RegExp(regExpTemplate.map(function(str) {
			return '(?:' +
				str.replace(/\+/g, '|').replace(/a|b|c|d|e|f/g, function() {return table[arguments[0]];}) + ')';
		}).join('|'), 'g');

		return function(node, template) {
			var res;
			var t;
			while((res = textNodeRegExp.exec(node.nodeValue))) {
				if (res[3]) {
					t = doc.createTextNode(unescapeDelimiters(res[3]));
					node.before(t);
				} else if (res[2]) {
					t = createTemplate();
					t.setAttribute(prefixedAttrs[BB_TEXT], unescapeDelimiters(res[2]));
					node.before(t);compile(t, template);
				} else {
					t = createTemplate();
					t.setAttribute(prefixedAttrs[BB_HTML], unescapeDelimiters(res[1]));
					node.before(t); compile(t, template);
				}
			}
			node.remove();
		};
	})();

	compile_works[Node.COMMENT_NODE] = function(node, template) {};

	compile_works[Node.DOCUMENT_FRAGMENT_NODE] = function(node, template) {
		Array.from(node.childNodes).forEach(function(child) {compile(child, template);});
	};

	function compile(node, template) {
		(compile_works[node.nodeType])(node, template);
	}

	/* Merge helpers */

	var works = {};
	works[Node.ELEMENT_NODE] = function(node, template) {
		var nodeContext = {};
		var nodeContextPushed = false;
		var bbAttrs = JSON.parse(node.getAttribute(globalAttr));
		node.removeAttribute(globalAttr);
		var value;
		if (bbAttrs.if) {
			value = (template.closures[bbAttrs.if])();
			if (!value) return node.remove();
		}
		if (bbAttrs.alias) {
			value = (template.closures[bbAttrs.alias])();
			if (!Array.isArray(value)) value = [value];
			value.forEach(function(item) {
				nodeContext[item.name] = item.value;
			});
			context.push(nodeContext);
			nodeContextPushed = true;
		}
		if (bbAttrs.text) {
			value = (template.closures[bbAttrs.text])();
			if (value != null) {
				node.replaceWith(value.toString());
			} else node.remove();
		} else if (bbAttrs.html) {
			value = (template.closures[bbAttrs.html])();
			if (value != null) {
				(function(t) {
					t.innerHTML = value.toString();
					node.replaceWith(t.content);
				})(createTemplate());
			} else node.remove();
		} else if (node.nodeName == TEMPLATE) {
			if (bbAttrs.repeat) {
				if (!nodeContextPushed) {
					context.push(nodeContext);
					nodeContextPushed = true;
				}
				value = (template.closures[bbAttrs.repeat])();
				var order = value._order || 'before';
				if (!Array.isArray(value)) value = [value];

				var reduceInit = (function(str) {
					var closure = template.closures[str];
					if (closure) return function() {
						var clone = Template(closure())._clone();
						node[order](merge(clone.node.content, clone));
					}; else return function() {
						node[order](merge(node.cloneNode(true).content, template));
					};
				})(bbAttrs.import);

				//iterate on cartesian product of arrays:
				(value.reduceRight(function(accu, task) {
					var alias = task.name;
					var value = task.value;
					return function() {
						value.forEach(function(item, index) {
							nodeContext[alias] = value[index];
							nodeContext['_' + alias + '_'] = index;
							accu();
						});
					};
				}, reduceInit))();
			} else if (bbAttrs.import) {
				value = (template.closures[bbAttrs.import])();
				var clone = Template(value)._clone();
				node.before(merge(clone.node.content, clone));
			}
			node.remove();
		} else {
			if (bbAttrs.attr) {
				value = (template.closures[bbAttrs.attr])();
				if (!Array.isArray(value)) value = [value];
				value.forEach(function(item) {
					var value = item.value;
					var name = item.name && item.name.toString();
					if (name && value != null) node.setAttribute(name, value);
				});
			}
			if (bbAttrs.class) {
				value = (template.closures[bbAttrs.class])();
				if (!Array.isArray(value)) value = [value];
				value.forEach(function(item) {
					if (item != null) {
						var value = item.toString();
						if (value) node.classList.add(value);
					}
				});
			}
			var child;
			while((child = node.querySelector(globalAttrSel))) {merge(child, template);}
		}
		if (nodeContextPushed) context.pop();
	};

	works[Node.DOCUMENT_FRAGMENT_NODE] = function(node, template) {
		var child;
		while((child = node.querySelector(globalAttrSel))) {merge(child, template);}
	};

	function merge(node, template) {
		(works[node.nodeType])(node, template);
		return node;
	}

	/* Template class */

	function Template(node) {
		if (node instanceof BBObj) {
			var name = node.name;
			if (store[name]) return store[name];
			else {
				var t = createTemplate();
				t.innerHTML = node.value;
				if (name) t.id = name;
				node = t;
			}
		}
		if (typeof(node) == 'string') {
			if (store[node]) return store[node];
			else node = doc.querySelector('#' + node);
		}
		if (!(this instanceof Template)) {
			return new Template(node);
		}
		if (node) {
			if (node.id) store[node.id] = this;
			this.node = destructive ? node : node.cloneNode(true);
			this.ready = false;
		} else {
			this.node = createTemplate();
			this.ready = true;
		}
		this.closures = {};
		return this;
	}

	/* Statics */

	Template.BBObj = BBObj;

	Template.clean = function(name) {
		if (name) delete store[name];
		else {
			for (var key in store) {
				delete store[key];
			}
		}
	};

	/* Public methods */

	Template.prototype.merge = function() {
		var clone = this._clone();
		var args = new Array(arguments.length);
		for(var i = 0; i < args.length; ++i) {
			args[i] = arguments[i];
		}
		context.init(args);
		merge(clone.node.content, clone);
		context.init();
		return clone.node.content;
	};

	/* Private methods */

	Template.prototype._addClosure = (function() {
		var counter = 0;
		return function(fun) {
			counter++;
			var str = 'fun' + counter;
			this.closures[str] = fun;
			return str;
		};
	})();

	Template.prototype._compile = function() {
		compile(this.node.content, this);
		this.ready = true;
		return this;
	};

	Template.prototype._clone = function() {
		if (!this.ready) this._compile();
		var t = new Template();
		t.node = this.node.cloneNode(true);
		t.closures = this.closures;
		return t;
	};

	return Template;
}
module.exports = Barbiche;
<commit_msg>Do not do useless test<commit_after>// Barbiche
// version: 0.6.1
// author: Manuel Baclet <manuel@eda.sarl>
// license: MIT

'use strict';

var attrs = ['if', 'alias', 'text', 'html', 'repeat', 'import', 'attr', 'class', 'global'];
var BB_IF = 0, BB_ALIAS = 1, BB_TEXT = 2, BB_HTML = 3, BB_REPEAT = 4,
		BB_IMPORT = 5, BB_ATTR = 6, BB_CLASS = 7, BB_GLOBAL = 8;

var TEMPLATE = 'TEMPLATE';

/* shared context */

var context = {
	stack: [],
	resolve: function(identifier) {
		var m = this.stack.length - 1;
		var value;
		while (value === undefined && m >= 0) {
			value = this.stack[m][identifier];
			m--;
		}
		return (value === undefined) ? window[identifier] : value;
	},
	init: function(arr) {
		this.stack = arr || [];
	},
	push: function(obj) {
		this.stack.push(obj);
	},
	pop: function() {
		return this.stack.pop();
	}
};

/* BBObj class */

function BBObj(a, b) {
	this.value = a;
	this.name = b;
}

BBObj.prototype.toString = function() {
	if (this.value && this.name != null) return this.name.toString();
	else return '';
};

/* shared Parser*/

var Parser = require('../parser.js');
Parser.parser.yy.context = context;
Parser.parser.yy.BBObj = BBObj;

/* Barbiche instance builder */

function Barbiche(opt) {
	opt = opt || {};
	var doc = opt.document || document;

	var destructive = (opt.destructive !== undefined) ? !!opt.destructive : true;

	var prefixedAttrs = attrs.map(function(str) {
		return (opt.prefix || 'bb-') + str;
	});
	var prefixedAttrsObj = {};
	prefixedAttrs.forEach(function(attr, index) {
		prefixedAttrsObj[attr] = attrs[index];
	});

	var globalAttr = prefixedAttrs[BB_GLOBAL];
	var globalAttrSel = '[' + globalAttr + ']';

	function createTemplate() {
		return doc.createElement('template');
	}

	var store = {};

	/* Compilation helpers */

	var compile_works = {};
	compile_works[Node.ELEMENT_NODE] = function(node, template) {
		if (node.hasAttribute(prefixedAttrs[BB_REPEAT]) && node.nodeName != TEMPLATE) {
			if (node.hasAttribute(prefixedAttrs[BB_TEXT]) || node.hasAttribute(prefixedAttrs[BB_HTML]))
				node.removeAttribute(prefixedAttrs[BB_REPEAT]);
			else {
				var wrapper = createTemplate();
				wrapper.setAttribute(prefixedAttrs[BB_REPEAT], node.getAttribute(prefixedAttrs[BB_REPEAT]));
				node.removeAttribute(prefixedAttrs[BB_REPEAT]);
				[prefixedAttrs[BB_IF], prefixedAttrs[BB_ALIAS]].forEach(function(attr) {
					if (node.hasAttribute(attr)) {
						wrapper.setAttribute(attr, node.getAttribute(attr));
						node.removeAttribute(attr);
					}
				});
				node.before(wrapper);
				wrapper.content.appendChild(node);
				node = wrapper;
			}
		}
		var bbAttrs = {};
		function setAttr(name, value) {
			attrFound = true;
			var parsed = Parser.parse(value);
			bbAttrs[prefixedAttrsObj[attr]] = template._addClosure(parsed);
			node.removeAttribute(attr);
		}
		var attrFound = false;
		if (node.attributes.length > attrs.length) {
			prefixedAttrs.forEach(function(attr) {
				if (node.hasAttribute(attr)) setAttr(attr, node.getAttribute(attr));
			});
		} else {
			for (var i = node.attributes.length - 1; i >= 0; i--) {
				var attr = node.attributes[i].name;
				if (attr in prefixedAttrsObj) setAttr(attr, node.attributes[i].value);
			}
		}
		if (attrFound) node.setAttribute(globalAttr, JSON.stringify(bbAttrs));
		if (node.nodeName == TEMPLATE) {
			compile(node.content, template);
			if (!attrFound) node.replaceWith(node.content);
		} else {
			Array.from(node.childNodes).forEach(function(child) {
				compile(child, template);
			});
		}
	};

	compile_works[Node.TEXT_NODE] = (function() {
		var delimiters = opt.delimiters || ['{', '}'];

		function regExpEscape(str) {
			return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
		}

		var UnescapeDelimitersRegExp = new RegExp('\\\\(' +
			['\\\\', regExpEscape(delimiters[0]), regExpEscape(delimiters[1])].join('|') +
		')', 'g');
		function unescapeDelimiters(str) {
			return str.replace(UnescapeDelimitersRegExp, function() {return arguments[1];});
		}

		var regExpTemplate = [
			'aaa((?:a+f+c+d+e+b(?:a+f+c+d+e+b(?:a+f+c+d+e)))*)bbb',
			'aa((?:a+f+c+d+e+b(?:a+f+c+d+e))*)bb',
			'((?:b+f+c+d+e+a(?:b+f+c+d+e))(?:b+f+c+d+e+a(?:b+f+c+d+e))*(?:a(?!a)+b+f+c+d+e++a(?:b+f+c+d+e))+(?:a(?!a)))'
		];
		var table = {
			a: regExpEscape(delimiters[0]),
			b: regExpEscape(delimiters[1]),
			c: regExpEscape("\\" + delimiters[0]),
			d: regExpEscape("\\" + delimiters[1]),
			e: '[^' + regExpEscape(delimiters[0]) + regExpEscape(delimiters[1]) + ']',
			f: regExpEscape("\\\\")
		};

		var textNodeRegExp = new RegExp(regExpTemplate.map(function(str) {
			return '(?:' +
				str.replace(/\+/g, '|').replace(/a|b|c|d|e|f/g, function() {return table[arguments[0]];}) + ')';
		}).join('|'), 'g');

		return function(node, template) {
			var res;
			var t;
			while((res = textNodeRegExp.exec(node.nodeValue))) {
				if (res[3]) {
					t = doc.createTextNode(unescapeDelimiters(res[3]));
					node.before(t);
				} else if (res[2]) {
					t = createTemplate();
					t.setAttribute(prefixedAttrs[BB_TEXT], unescapeDelimiters(res[2]));
					node.before(t);compile(t, template);
				} else {
					t = createTemplate();
					t.setAttribute(prefixedAttrs[BB_HTML], unescapeDelimiters(res[1]));
					node.before(t); compile(t, template);
				}
			}
			node.remove();
		};
	})();

	compile_works[Node.COMMENT_NODE] = function(node, template) {};

	compile_works[Node.DOCUMENT_FRAGMENT_NODE] = function(node, template) {
		Array.from(node.childNodes).forEach(function(child) {compile(child, template);});
	};

	function compile(node, template) {
		(compile_works[node.nodeType])(node, template);
	}

	/* Merge helpers */

	var works = {};
	works[Node.ELEMENT_NODE] = function(node, template) {
		var nodeContext = {};
		var nodeContextPushed = false;
		var bbAttrs = JSON.parse(node.getAttribute(globalAttr));
		node.removeAttribute(globalAttr);
		var value;
		if (bbAttrs.if) {
			value = (template.closures[bbAttrs.if])();
			if (!value) return node.remove();
		}
		if (bbAttrs.alias) {
			value = (template.closures[bbAttrs.alias])();
			if (!Array.isArray(value)) value = [value];
			value.forEach(function(item) {
				nodeContext[item.name] = item.value;
			});
			context.push(nodeContext);
			nodeContextPushed = true;
		}
		if (bbAttrs.text) {
			value = (template.closures[bbAttrs.text])();
			if (value != null) {
				node.replaceWith(value.toString());
			} else node.remove();
		} else if (bbAttrs.html) {
			value = (template.closures[bbAttrs.html])();
			if (value != null) {
				(function(t) {
					t.innerHTML = value.toString();
					node.replaceWith(t.content);
				})(createTemplate());
			} else node.remove();
		} else if (node.nodeName == TEMPLATE) {
			if (bbAttrs.repeat) {
				if (!nodeContextPushed) {
					context.push(nodeContext);
					nodeContextPushed = true;
				}
				value = (template.closures[bbAttrs.repeat])();
				var order = value._order || 'before';
				if (!Array.isArray(value)) value = [value];

				var reduceInit = (function(str) {
					var closure = template.closures[str];
					if (closure) return function() {
						var clone = Template(closure())._clone();
						node[order](merge(clone.node.content, clone));
					}; else return function() {
						node[order](merge(node.cloneNode(true).content, template));
					};
				})(bbAttrs.import);

				//iterate on cartesian product of arrays:
				(value.reduceRight(function(accu, task) {
					var alias = task.name;
					var value = task.value;
					return function() {
						value.forEach(function(item, index) {
							nodeContext[alias] = value[index];
							nodeContext['_' + alias + '_'] = index;
							accu();
						});
					};
				}, reduceInit))();
			} else if (bbAttrs.import) {
				value = (template.closures[bbAttrs.import])();
				var clone = Template(value)._clone();
				node.before(merge(clone.node.content, clone));
			}
			node.remove();
		} else {
			if (bbAttrs.attr) {
				value = (template.closures[bbAttrs.attr])();
				if (!Array.isArray(value)) value = [value];
				value.forEach(function(item) {
					var value = item.value;
					var name = item.name && item.name.toString();
					if (name && value != null) node.setAttribute(name, value);
				});
			}
			if (bbAttrs.class) {
				value = (template.closures[bbAttrs.class])();
				if (!Array.isArray(value)) value = [value];
				value.forEach(function(item) {
					if (item != null) {
						var value = item.toString();
						if (value) node.classList.add(value);
					}
				});
			}
			var child;
			while((child = node.querySelector(globalAttrSel))) {merge(child, template);}
		}
		if (nodeContextPushed) context.pop();
	};

	works[Node.DOCUMENT_FRAGMENT_NODE] = function(node, template) {
		var child;
		while((child = node.querySelector(globalAttrSel))) {merge(child, template);}
	};

	function merge(node, template) {
		(works[node.nodeType])(node, template);
		return node;
	}

	/* Template class */

	function Template(node) {
		if (node instanceof BBObj) {
			var name = node.name;
			if (store[name]) return store[name];
			else {
				var t = createTemplate();
				t.innerHTML = node.value;
				if (name) t.id = name;
				node = t;
			}
		} else if (typeof(node) == 'string') {
			if (store[node]) return store[node];
			else node = doc.querySelector('#' + node);
		}
		if (!(this instanceof Template)) {
			return new Template(node);
		}
		if (node) {
			if (node.id) store[node.id] = this;
			this.node = destructive ? node : node.cloneNode(true);
			this.ready = false;
		} else {
			this.node = createTemplate();
			this.ready = true;
		}
		this.closures = {};
		return this;
	}

	/* Statics */

	Template.BBObj = BBObj;

	Template.clean = function(name) {
		if (name) delete store[name];
		else {
			for (var key in store) {
				delete store[key];
			}
		}
	};

	/* Public methods */

	Template.prototype.merge = function() {
		var clone = this._clone();
		var args = new Array(arguments.length);
		for(var i = 0; i < args.length; ++i) {
			args[i] = arguments[i];
		}
		context.init(args);
		merge(clone.node.content, clone);
		context.init();
		return clone.node.content;
	};

	/* Private methods */

	Template.prototype._addClosure = (function() {
		var counter = 0;
		return function(fun) {
			counter++;
			var str = 'fun' + counter;
			this.closures[str] = fun;
			return str;
		};
	})();

	Template.prototype._compile = function() {
		compile(this.node.content, this);
		this.ready = true;
		return this;
	};

	Template.prototype._clone = function() {
		if (!this.ready) this._compile();
		var t = new Template();
		t.node = this.node.cloneNode(true);
		t.closures = this.closures;
		return t;
	};

	return Template;
}
module.exports = Barbiche;
<|endoftext|>


<commit_before>/* WELCOME TO THE OSTIA TRADING PLATFORM */

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var path = require('path');
var async = require('async');
var moment = require('moment');

// Passsing in a sample config
var config = {
  liveTrading: true,
  backtestMode: false,
  strategyName: "simple-arbitrage", // exponential moving average
  exchanges: "all", // exchanges strategy will trade
  pair: "BTCUSD", // or "none" for every pair
  capital: 3000, // starting capital
  timeFrame: 4, // how long to trade
  interval: 1000,
  API_KEYS: {
    poloniex: "123XYZ",
    gdax: "123ABC"
  }
}

// Set up Trading desk and run strategy
//var runLiveTrading = require("./lib/TradingDesk.js");
//runLiveTrading(config);

io.sockets.on('connection', function (socket) {
  async.waterfall([

    /* Initialze data */
    function (callback) {
      var financialData = require('./lib/strategies/basicStrategy.js');
      var candlestickData = financialData.candlestickData;
      var indicators = financialData.indicators;
      var flags = financialData.flags;
      var backtest = financialData.backtest;
      var benchmark = financialData.benchmark;
      callback(null, candlestickData, indicators, financialData, flags, backtest, benchmark);
    },

    /* emit initialized data */
    function (candlestickData, indicators, financialData, flags, backtest, benchmark, callback) {
      socket.emit('initializedChartData', {
        candlestickData: candlestickData,
        indicators: indicators,
        flags: flags,
        backtest: backtest
      });
      socket.emit('chartFlags', {
        flags: null
      });
      socket.emit('backtest', {
        backtest: backtest,
        benchmark: benchmark
      });
      callback(null, financialData);
    },

    /* poll for live data and emit */
    function (financialData, callback) {
      // var counter = 0;
      // var eventLooper = setInterval(function () {
      //   var mostRecentTickerPrice = financialData.updatedFinanceData;
      //   socket.emit('updatedChartData', {
      //     time: new Date().getTime(),
      //     mostRecentTickerPrice: parseFloat(mostRecentTickerPrice)
      //   });
      //   console.log("### SERVER: " + Date.now() + ": live data point sent")
      // }, 5000);
    }

  ], function (err, result) {
    // result now equals 'done'
  });
});

//************************/
//        ROUTES
//* ***********************/

app.use(express.static('client'))

app.get('/1', function (req, res) {
  res.sendfile(path.join(__dirname, '/client/html/index.html'))
})

app.get('/', function (req, res) {
  res.sendfile(path.join(__dirname, '/client/pages/index.html'))
})

app.get('/test', function (req, res) {
  res.sendfile(path.join(__dirname, '/client/html/chartTest.html'))
})

// Creating Express server
server.listen(3000)
<commit_msg>Trying to fix Heroku PORT issues<commit_after>/* WELCOME TO THE OSTIA TRADING PLATFORM */

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var path = require('path');
var async = require('async');
var moment = require('moment');

// Passsing in a sample config
var config = {
  liveTrading: true,
  backtestMode: false,
  strategyName: "simple-arbitrage", // exponential moving average
  exchanges: "all", // exchanges strategy will trade
  pair: "BTCUSD", // or "none" for every pair
  capital: 3000, // starting capital
  timeFrame: 4, // how long to trade
  interval: 1000,
  API_KEYS: {
    poloniex: "123XYZ",
    gdax: "123ABC"
  }
}

// Set up Trading desk and run strategy
//var runLiveTrading = require("./lib/TradingDesk.js");
//runLiveTrading(config);

io.sockets.on('connection', function (socket) {
  async.waterfall([

    /* Initialze data */
    function (callback) {
      var financialData = require('./lib/strategies/basicStrategy.js');
      var candlestickData = financialData.candlestickData;
      var indicators = financialData.indicators;
      var flags = financialData.flags;
      var backtest = financialData.backtest;
      var benchmark = financialData.benchmark;
      callback(null, candlestickData, indicators, financialData, flags, backtest, benchmark);
    },

    /* emit initialized data */
    function (candlestickData, indicators, financialData, flags, backtest, benchmark, callback) {
      socket.emit('initializedChartData', {
        candlestickData: candlestickData,
        indicators: indicators,
        flags: flags,
        backtest: backtest
      });
      socket.emit('chartFlags', {
        flags: null
      });
      socket.emit('backtest', {
        backtest: backtest,
        benchmark: benchmark
      });
      callback(null, financialData);
    },

    /* poll for live data and emit */
    function (financialData, callback) {
      // var counter = 0;
      // var eventLooper = setInterval(function () {
      //   var mostRecentTickerPrice = financialData.updatedFinanceData;
      //   socket.emit('updatedChartData', {
      //     time: new Date().getTime(),
      //     mostRecentTickerPrice: parseFloat(mostRecentTickerPrice)
      //   });
      //   console.log("### SERVER: " + Date.now() + ": live data point sent")
      // }, 5000);
    }

  ], function (err, result) {
    // result now equals 'done'
  });
});

//************************/
//        ROUTES
//* ***********************/

app.use(express.static('client'))

app.get('/1', function (req, res) {
  res.sendfile(path.join(__dirname, '/client/html/index.html'))
})

app.get('/', function (req, res) {
  res.sendfile(path.join(__dirname, '/client/pages/index.html'))
})

app.get('/test', function (req, res) {
  res.sendfile(path.join(__dirname, '/client/html/chartTest.html'))
})

// Creating Express server
server.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>//express
//mongoose
//body-parser
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;

app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({
  extended:false
}))

app.get('/', (req, res) => {
  res.send('Server Running');
});

app.get('/notes/new', (req, res) => {
  res.render('new-note');
});

app.post('/notes', (req, res) => {
  console.log("req.body", req.body);
  res.send('thanks for your new note')
})

app.listen(3000, () => {
  console.log(`Evernode server running on port: ${PORT}`);
})
<commit_msg>saving new note to database<commit_after>//express
//mongoose
//body-parser
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 3000;
const Note = mongoose.model('Notes', mongoose.Schema({
  title: String,
  text: String
}))

app.set('view engine', 'jade');

app.use(bodyParser.urlencoded({
  extended:false
}))

app.get('/', (req, res) => {
  res.send('Server Running');
});

app.get('/notes/new', (req, res) => {
  res.render('new-note');
});

app.post('/notes', (req, res) => {
  console.log("req.body", req.body);
  Note.create(req.body, (err, note) => {
    if (err) throw err;
    console.log("note:", note);
    res.redirect('/')
  })
})

mongoose.connect('mongodb://localhost:27017/evernode', (err) => {
  if(err) throw err;
  app.listen(3000, () => {
    console.log(`Evernode server running on port: ${port}`);
  });
});
<|endoftext|>


<commit_before>var express = require( 'express' )
  , http = require( 'http' )
  , path = require( 'path' )
  , index = require( './routes/index.js' )
  , instance = require( './routes/instance.js' );

var app = express();

app.configure(function() {
  app.set( 'port', process.env.PORT || 9273 );
  app.set( 'views', __dirname + '/views' );
  app.set( 'view engine', 'ejs' );

  app.use( express.favicon( __dirname + '/public/img/favicon.ico' ) );
  app.use( express.logger( 'dev' ) );

  app.use( express.bodyParser( {
    keepExtensions: true,
    maxFieldsSize: 2 * 1024 * 1024 * 1024,
    uploadDir: __dirname + '/tmp'
  } ) );
  app.use( express.methodOverride() );
  app.use( app.router );
  app.use( require( 'less-middleware' )( { src: __dirname + '/public' } ) );
  app.use( express.static( path.join( __dirname, 'public' ) ) );
});

app.configure( 'development', function() {
  app.use( express.errorHandler() );
} );

app.get( '/', instance.workspace );
app.get( '/:id([A-Z0-9]{6})', instance.workspace );

app.get( '/marker/:id([A-Z0-9]{6})', instance.getMarkers );
app.post( '/marker/:id([A-Z0-9]{6})', instance.addMarker );

app.get( '/structure/:id([A-Z0-9]{6})', instance.getStructure );
app.post( '/structure/:id([A-Z0-9]{6})', instance.setStructure );

app.get( '/:id([A-Z0-9]{6})/:file', instance.file );
app.post( '/:id([A-Z0-9]{6})/:file', instance.attach );

http.createServer( app ).listen( app.get( 'port' ), function() {
  console.log( 'Server listening on port ' + app.get( 'port' ) );
});
<commit_msg>fixed 500 style.css not found (following http://stackoverflow.com/a/22275363/1168892)<commit_after>var express = require( 'express' )
  , http = require( 'http' )
  , index = require( './routes/index.js' )
  , instance = require( './routes/instance.js' );

var app = express();

app.configure(function() {
  app.set( 'port', process.env.PORT || 9273 );
  app.set( 'views', __dirname + '/views' );
  app.set( 'view engine', 'ejs' );

  app.use( express.favicon( __dirname + '/public/img/favicon.ico' ) );
  app.use( express.logger( 'dev' ) );

  app.use( express.bodyParser( {
    keepExtensions: true,
    maxFieldsSize: 2 * 1024 * 1024 * 1024,
    uploadDir: __dirname + '/tmp'
  } ) );
  app.use( express.methodOverride() );
  app.use( app.router );
  app.use( require( 'less-middleware' )( __dirname + '/public' ) );
  app.use( express.static( __dirname + '/public' ) );
});

app.configure( 'development', function() {
  app.use( express.errorHandler() );
} );

app.get( '/', instance.workspace );
app.get( '/:id([A-Z0-9]{6})', instance.workspace );

app.get( '/marker/:id([A-Z0-9]{6})', instance.getMarkers );
app.post( '/marker/:id([A-Z0-9]{6})', instance.addMarker );

app.get( '/structure/:id([A-Z0-9]{6})', instance.getStructure );
app.post( '/structure/:id([A-Z0-9]{6})', instance.setStructure );

app.get( '/:id([A-Z0-9]{6})/:file', instance.file );
app.post( '/:id([A-Z0-9]{6})/:file', instance.attach );

http.createServer( app ).listen( app.get( 'port' ), function() {
  console.log( 'Server listening on port ' + app.get( 'port' ) );
});
<|endoftext|>


<commit_before>const http = require("http");
const bodyParser = require('body-parser');
const app = require("express")();
const EventEmitter = require("events");
const util = require('util');
const process = require('child_process');
const fs = require("fs");
const glob = require("glob")

const server = http.createServer(app);
server.listen(3000, () => console.log(`Paths livestream server is now running on port ${server.address().port}!`));

const io = require("socket.io")(server);

const emitter = new EventEmitter();
emitter.on("attempt_connection", (stream) => console.log("A user attempted to connect to Paths livestream server!"));

app.use(bodyParser.urlencoded({ extended: false }));

app.get("/", (request, response) => {
  const error = {
    "status": "error",
    "reason": "Please connect to a socket.io room in order to use Paths livestream service."
  }
  response.header("Content-Type", "application/json")
  response.send(JSON.stringify(error));
  emitter.emit("attempt_connection");
});

io.on("connection", (socket) => {
  console.log("A user successfully connected to Paths livestream server!")

  socket.on("create", (room) => {
    socket.join(room.key);
  });

  socket.on("stream_started", (stream) => {
    const secretKey = stream.key;
    console.log(`Stream started - secret key is ${secretKey}`);
  });

  socket.on("location_update", (stream) => {
    const executeCommand = util.promisify(process.exec);

    const secretKey = stream.key;
    const latitude = stream.latitude;
    const longitude = stream.longitude;
    console.log(`Received data - Latitude: ${latitude} - Longitude: ${longitude}`)

    async function takeSnapshot() {
      const { output, error } = await executeCommand(`ffmpeg -i rtmp://35.202.142.142:1935/stream/${secretKey} -f image2 -vframes 1 snapshot-${secretKey}-%d.png`);
      console.log(`Output parsed: ${output}`);
      console.log(`Error occured: ${error}`);
    }
    takeSnapshot();
    socket.emit("recent_snapshot", {"key": secretKey};
  });

  socket.on("recent_snapshot", (stream) => {
    let secretKey = stream.key;
    glob(`snapshot-${secretKey}-*.png`, function(err, files) {
        if (!err) {
          let recentFile = files.reduce((last, current) => {
              let currentFileDate = new Date(fs.statSync(current).mtime);
              let lastFileDate = new Date(fs.statSync(last).mtime);
              return (currentFileDate.getTime() > lastFileDate.getTime()) ? current : last;
          });

          print(`Recent File: ${recentFile}`);
        }
    });
  });

  socket.on("disconnect", () => {
    const executeCommand = util.promisify(process.exec);
    console.log("A user disconnected from Paths livestream server!");

    async function endSnapshot() {
      const { output, error } = await executeCommand("sudo killall ffmpeg");
      console.log(`Output parsed: ${output}`);
      console.log(`Error occured: ${error}`);
    }
    endSnapshot();
  });
});
<commit_msg>Fix syntax<commit_after>const http = require("http");
const bodyParser = require('body-parser');
const app = require("express")();
const EventEmitter = require("events");
const util = require('util');
const process = require('child_process');
const fs = require("fs");
const glob = require("glob")

const server = http.createServer(app);
server.listen(3000, () => console.log(`Paths livestream server is now running on port ${server.address().port}!`));

const io = require("socket.io")(server);

const emitter = new EventEmitter();
emitter.on("attempt_connection", (stream) => console.log("A user attempted to connect to Paths livestream server!"));

app.use(bodyParser.urlencoded({ extended: false }));

app.get("/", (request, response) => {
  const error = {
    "status": "error",
    "reason": "Please connect to a socket.io room in order to use Paths livestream service."
  }
  response.header("Content-Type", "application/json")
  response.send(JSON.stringify(error));
  emitter.emit("attempt_connection");
});

io.on("connection", (socket) => {
  console.log("A user successfully connected to Paths livestream server!")

  socket.on("create", (room) => {
    socket.join(room.key);
  });

  socket.on("stream_started", (stream) => {
    const secretKey = stream.key;
    console.log(`Stream started - secret key is ${secretKey}`);
  });

  socket.on("location_update", (stream) => {
    const executeCommand = util.promisify(process.exec);

    const secretKey = stream.key;
    const latitude = stream.latitude;
    const longitude = stream.longitude;
    console.log(`Received data - Latitude: ${latitude} - Longitude: ${longitude}`)

    async function takeSnapshot() {
      const { output, error } = await executeCommand(`ffmpeg -i rtmp://35.202.142.142:1935/stream/${secretKey} -f image2 -vframes 1 snapshot-${secretKey}-%d.png`);
      console.log(`Output parsed: ${output}`);
      console.log(`Error occured: ${error}`);
    }
    takeSnapshot();
    socket.emit("recent_snapshot", {"key": secretKey});
  });

  socket.on("recent_snapshot", (stream) => {
    let secretKey = stream.key;
    glob(`snapshot-${secretKey}-*.png`, function(err, files) {
        if (!err) {
          let recentFile = files.reduce((last, current) => {
              let currentFileDate = new Date(fs.statSync(current).mtime);
              let lastFileDate = new Date(fs.statSync(last).mtime);
              return (currentFileDate.getTime() > lastFileDate.getTime()) ? current : last;
          });

          print(`Recent File: ${recentFile}`);
        }
    });
  });

  socket.on("disconnect", () => {
    const executeCommand = util.promisify(process.exec);
    console.log("A user disconnected from Paths livestream server!");

    async function endSnapshot() {
      const { output, error } = await executeCommand("sudo killall ffmpeg");
      console.log(`Output parsed: ${output}`);
      console.log(`Error occured: ${error}`);
    }
    endSnapshot();
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
app.set('title', 'ESPN Bowl Mania Scraper');
app.set('jsonp callback', true);

app.use(express.logger());
app.use(express.compress());
app.use(express.favicon(__dirname + '/favicon.ico', { maxAge: (86400000 * 365) }));
app.use(express.errorHandler());

var nodeio = require('node.io');
var options = {timeout: 10, max: 2, benchmark: true};
var bowlmania = {};
var year;

// heroku logging
var logfmt = require("logfmt");
app.use(logfmt.requestLogger());

app.use('/bowlmania.json', function(req, res) {

    res.header('Access-Control-Allow-Origin', 'http://kulturny.com');
    res.header('Access-Control-Allow-Methods', 'GET');

    year = parseInt(req.query.year) || 2016;

    nodeio.start(scraper, function (err, output) {

        if (err) {
            console.log('ERROR', err);
        } else {
            /*res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Expires", "0");*/
            res.setHeader("Cache-Control", "public, max-age=60");// + (10 * 60));

            res.jsonp(bowlmania);
        }
    }, true);

});

var port = (process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT) || 5000;
var host = process.env.OPENSHIFT_NODEJS_IP || null;
app.listen(port, host, function() { console.log( "Listening on " + host + ":" + port) });

var scraper = new nodeio.Job(options, {

    input: ['confidence'/*, 'straight'*/],
    run: function (entryType) {

        //console.log('JOB:', entryType);

        var self = this;

        //var url = 'http://games.espn.go.com/college-bowl-mania/' + year + '/en/format/ajax/scoresheetSnapshot?groupID=';
        var url = 'http://games.espn.go.com/college-bowl-mania/' + year + '/en/scoresheet?groupID=';
        switch(entryType) {
            case 'confidence': var e = (year >= 2015) ? 106564 : 25569; break;
            case 'straight': var e = 28172; break;
        }

        this.getHtml(url + e, function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                // TODO: Fix crash if the right DOM elements aren't found
                //if (!$('table.scoresheet tbody tr')) self.skip();

                $('table.type_entries tbody tr').each(function(listing) {

                    try {

                        var entryName = $('td.entryowner a', listing).first().fulltext;
                        var player = $('td.entryowner a', listing).last().fulltext;

                    } catch (err) {

                        // 2013: skip onto the next

 if there's no player
                        console.error("No players found");
                        return false;

                    }

                    //console.log(player + ': ' + entryName);

                    var realName = whoIsThis(player);
                    if (bowlmania[realName] === undefined) bowlmania[realName] = {};

                    bowlmania[realName][entryType] = {};
                    var obj = bowlmania[realName][entryType];

                    obj.entryName = entryName;

                    var picks = {};
                    //var picksEcho = '';

                    $('td.scoresheetmatchup', listing).each(function(pick) {

                        try {

                            var team = $('img', pick).attribs.alt;
                            var confidencePoints = $('span', pick).text;

                        } catch (err) {

                            // 2013: skip onto the next 	 if there's no pick
                            return;

                        }

                        // so brittle
                        var winLose = pick.attribs.class.split(" ")[0];

                        // There are two teams that ESPN say are 'MSU', check if it's Mississippi State (MSST)
                        if (team == 'MSU') {
                            var url = $('img', pick).attribs.src;
                            if (url.search(/344\.png/) != -1) team = 'MSST';
                        }

                        picks[team] = {};
                        if (entryType == 'confidence') picks[team].pts = parseInt(confidencePoints);
                        picks[team].win = (winLose == 'win') ? 1 : (winLose == 'loss') ? 0 : -1;

                        //picksEcho += team + ' ' + confidencePoints + ' (' + winLose + '), ';

                    });

                    obj.picks = picks;

                    //console.log(picksEcho);

                });

                //self.emit(bowlmania);
                self.skip();

            }

        });

    },
    complete: function () {

        //console.log(JSON.stringify(bowlmania));
        return (JSON.stringify(bowlmania));

    }

});

function whoIsThis(data) {

    switch(data) {
        case 'jasonthefool':       return 'jason'; break;
        case 'FightingOnInOregon': return 'akiyo'; break;
        case 'arjayw':             return 'dad'; break;
        case 'Superelf7':          return 'nathan'; break;
        case 'Meerazha':
        case 'mwray':              return 'meera'; break;
        case 'robins422003':       return 'robin'; break;

        default: return data;
    }

};
<commit_msg>Add another Meera username<commit_after>var express = require('express');
var app = express();
app.set('title', 'ESPN Bowl Mania Scraper');
app.set('jsonp callback', true);

app.use(express.logger());
app.use(express.compress());
app.use(express.favicon(__dirname + '/favicon.ico', { maxAge: (86400000 * 365) }));
app.use(express.errorHandler());

var nodeio = require('node.io');
var options = {timeout: 10, max: 2, benchmark: true};
var bowlmania = {};
var year;

// heroku logging
var logfmt = require("logfmt");
app.use(logfmt.requestLogger());

app.use('/bowlmania.json', function(req, res) {

    res.header('Access-Control-Allow-Origin', 'http://kulturny.com');
    res.header('Access-Control-Allow-Methods', 'GET');

    year = parseInt(req.query.year) || 2016;

    nodeio.start(scraper, function (err, output) {

        if (err) {
            console.log('ERROR', err);
        } else {
            /*res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Expires", "0");*/
            res.setHeader("Cache-Control", "public, max-age=60");// + (10 * 60));

            res.jsonp(bowlmania);
        }
    }, true);

});

var port = (process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT) || 5000;
var host = process.env.OPENSHIFT_NODEJS_IP || null;
app.listen(port, host, function() { console.log( "Listening on " + host + ":" + port) });

var scraper = new nodeio.Job(options, {

    input: ['confidence'/*, 'straight'*/],
    run: function (entryType) {

        //console.log('JOB:', entryType);

        var self = this;

        //var url = 'http://games.espn.go.com/college-bowl-mania/' + year + '/en/format/ajax/scoresheetSnapshot?groupID=';
        var url = 'http://games.espn.go.com/college-bowl-mania/' + year + '/en/scoresheet?groupID=';
        switch(entryType) {
            case 'confidence': var e = (year >= 2015) ? 106564 : 25569; break;
            case 'straight': var e = 28172; break;
        }

        this.getHtml(url + e, function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                // TODO: Fix crash if the right DOM elements aren't found
                //if (!$('table.scoresheet tbody tr')) self.skip();

                $('table.type_entries tbody tr').each(function(listing) {

                    try {

                        var entryName = $('td.entryowner a', listing).first().fulltext;
                        var player = $('td.entryowner a', listing).last().fulltext;

                    } catch (err) {

                        // 2013: skip onto the next

 if there's no player
                        console.error("No players found");
                        return false;

                    }

                    //console.log(player + ': ' + entryName);

                    var realName = whoIsThis(player);
                    if (bowlmania[realName] === undefined) bowlmania[realName] = {};

                    bowlmania[realName][entryType] = {};
                    var obj = bowlmania[realName][entryType];

                    obj.entryName = entryName;

                    var picks = {};
                    //var picksEcho = '';

                    $('td.scoresheetmatchup', listing).each(function(pick) {

                        try {

                            var team = $('img', pick).attribs.alt;
                            var confidencePoints = $('span', pick).text;

                        } catch (err) {

                            // 2013: skip onto the next 	 if there's no pick
                            return;

                        }

                        // so brittle
                        var winLose = pick.attribs.class.split(" ")[0];

                        // There are two teams that ESPN say are 'MSU', check if it's Mississippi State (MSST)
                        if (team == 'MSU') {
                            var url = $('img', pick).attribs.src;
                            if (url.search(/344\.png/) != -1) team = 'MSST';
                        }

                        picks[team] = {};
                        if (entryType == 'confidence') picks[team].pts = parseInt(confidencePoints);
                        picks[team].win = (winLose == 'win') ? 1 : (winLose == 'loss') ? 0 : -1;

                        //picksEcho += team + ' ' + confidencePoints + ' (' + winLose + '), ';

                    });

                    obj.picks = picks;

                    //console.log(picksEcho);

                });

                //self.emit(bowlmania);
                self.skip();

            }

        });

    },
    complete: function () {

        //console.log(JSON.stringify(bowlmania));
        return (JSON.stringify(bowlmania));

    }

});

function whoIsThis(data) {

    switch(data) {
        case 'jasonthefool':       return 'jason'; break;
        case 'FightingOnInOregon': return 'akiyo'; break;
        case 'arjayw':             return 'dad'; break;
        case 'Superelf7':          return 'nathan'; break;
        case 'Meerazha':
        case 'meera.3961179':
        case 'mwray':              return 'meera'; break;
        case 'robins422003':       return 'robin'; break;

        default: return data;
    }

};
<|endoftext|>


<commit_before>var OAuthEncryption = Package["oauth-encryption"] && Package["oauth-encryption"].OAuthEncryption;

var pinEncryptedFieldsToUser = function (serviceData, userId) {
	_.each(_.keys(serviceData), function (key) {
		var value = serviceData[key];
		if (OAuthEncryption && OAuthEncryption.isSealed(value)) {
			value = OAuthEncryption.seal(OAuthEncryption.open(value), userId);
		}
		serviceData[key] = value;
	});
};

var addOauthService = function (user, options) {
	check(options.oauth, {
		credentialToken: String,
		// When an error occurs while retrieving the access token, we store
		// the error in the pending credentials table, with a secret of
		// null. The client can call the login method with a secret of null
		// to retrieve the error.
		credentialSecret: Match.OneOf(null, String)
	});
	// Retrieve the pending credential object
	var result = OAuth.retrieveCredential(options.oauth.credentialToken, options.oauth.credentialSecret);
	if (!result) {
		// OAuth credentialToken is not recognized, which could be either
		// because the popup was closed by the user before completion, or
		// some sort of error where the oauth provider didn't talk to our
		// server correctly and closed the popup somehow.
		throw new Meteor.Error("No matching login attempt found");
	}
	if (result instanceof Error) {
		// We tried to login, but there was a fatal error. Report it back
		// to the user.
		throw result;
	}
	var serviceName = result.serviceName;
	var serviceData = result.serviceData;
	// Only allow external (oauth) services
	if (serviceName === "password" || serviceName === "resume") {
		throw new Meteor.Error("Can't use updateOrCreateUserFromExternalService with internal service " + serviceName);
	}
	// The user must not have used the service already
	if (user.services[serviceName]) {
		throw new Meteor.Error(serviceName + " already used");
	}
	// The service must provide an `id` field
	if (!_.has(serviceData, "id")) {
		throw new Meteor.Error("Service data for service " + serviceName + " must include id");
	}
	// If a user with this service user-id already exists, throw an error
	// XXX We can consider instead merging the two accounts
	var selector = {};
	var selectorKey = "services." + serviceName + ".id";
	selector[selectorKey] = serviceData.id;
	if (Meteor.users.findOne(selector)) {
		throw new Meteor.Error("User already exists");
	}

	pinEncryptedFieldsToUser(serviceData, user._id);

	// Add the service to the user object
	var modifier = {
		$set: {}
	};
	var serviceKey = "services." + serviceName;
	modifier.$set[serviceKey] = serviceData;
	Meteor.users.update(user._id, modifier);
	return user._id;
};

var addPasswordService = function (user, options) {
	// TODO
};

Meteor.methods({
	addLoginService: function (options) {
		var user = Meteor.user();
		// Ensure the user is logged in
		if (!user) {
			throw new Meteor.Error("Login required");
		}
		// Check arguments
		try {
			// Wrapping this in a try/catch block to avoid throwing
			// a Match.Error, which gets logged on the server console,
			// while a Meteor.Error doesn't
			check(options, Object);
		} catch (e) {
			throw new Meteor.Error("Match failed");
		}
		// Adding an oauth service
		if (options.oauth) {
			return addOauthService(user, options);
		}
		// Adding the password service
		if (options.password) {
			return addPasswordService(user, options);
		}
	}
});
<commit_msg>Added error case<commit_after>/////////////////////////////
// OAuth related functions //
/////////////////////////////

var OAuthEncryption = Package["oauth-encryption"] && Package["oauth-encryption"].OAuthEncryption;

var pinEncryptedFieldsToUser = function (serviceData, userId) {
	_.each(_.keys(serviceData), function (key) {
		var value = serviceData[key];
		if (OAuthEncryption && OAuthEncryption.isSealed(value)) {
			value = OAuthEncryption.seal(OAuthEncryption.open(value), userId);
		}
		serviceData[key] = value;
	});
};

var addOauthService = function (user, options) {
	check(options.oauth, {
		credentialToken: String,
		// When an error occurs while retrieving the access token, we store
		// the error in the pending credentials table, with a secret of
		// null. The client can call the login method with a secret of null
		// to retrieve the error.
		credentialSecret: Match.OneOf(null, String)
	});
	// Retrieve the pending credential object
	var result = OAuth.retrieveCredential(options.oauth.credentialToken, options.oauth.credentialSecret);
	if (!result) {
		// OAuth credentialToken is not recognized, which could be either
		// because the popup was closed by the user before completion, or
		// some sort of error where the oauth provider didn't talk to our
		// server correctly and closed the popup somehow.
		throw new Meteor.Error("No matching login attempt found");
	}
	if (result instanceof Error) {
		// We tried to login, but there was a fatal error. Report it back
		// to the user.
		throw result;
	}
	var serviceName = result.serviceName;
	var serviceData = result.serviceData;
	// Only allow external (oauth) services
	if (serviceName === "password" || serviceName === "resume") {
		throw new Meteor.Error("Can't use updateOrCreateUserFromExternalService with internal service " + serviceName);
	}
	// The user must not have used the service already
	if (user.services[serviceName]) {
		throw new Meteor.Error(serviceName + " already used");
	}
	// The service must provide an `id` field
	if (!_.has(serviceData, "id")) {
		throw new Meteor.Error("Service data for service " + serviceName + " must include id");
	}
	// If a user with this service user-id already exists, throw an error
	// XXX We can consider instead merging the two accounts
	var selector = {};
	var selectorKey = "services." + serviceName + ".id";
	selector[selectorKey] = serviceData.id;
	if (Meteor.users.findOne(selector)) {
		throw new Meteor.Error("User already exists");
	}

	pinEncryptedFieldsToUser(serviceData, user._id);

	// Add the service to the user object
	var modifier = {
		$set: {}
	};
	var serviceKey = "services." + serviceName;
	modifier.$set[serviceKey] = serviceData;
	Meteor.users.update(user._id, modifier);
	return user._id;
};

////////////////////////////////
// Password related functions //
////////////////////////////////

var addPasswordService = function (user, options) {
	// TODO wait for https://github.com/meteor/meteor/pull/2271 to resolve
};

//////////////////////////////
// `addLoginService` method //
//////////////////////////////

Meteor.methods({
	addLoginService: function (options) {
		var user = Meteor.user();
		// Ensure the user is logged in
		if (!user) {
			throw new Meteor.Error("Login required");
		}
		// Check arguments
		try {
			// Wrapping this in a try/catch block to avoid throwing
			// a Match.Error, which gets logged on the server console,
			// while a Meteor.Error doesn't
			check(options, Object);
		} catch (e) {
			throw new Meteor.Error("Match failed");
		}
		// Adding an oauth service
		if (options.oauth) {
			return addOauthService(user, options);
		}
		// Adding the password service
		if (options.password) {
			return addPasswordService(user, options);
		}
		throw new Meteor.Error("Bad request");
	}
});
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const path = require('path');
const compression = require('compression')

const forceSSL = function() {
  return function (req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
      return res.redirect(
       ['https://', req.get('Host'), req.url].join('')
      );
    }
    next();
  }
}
app.use(forceSSL());

app.use(compression());

app.use(express.static(__dirname + '/dist'));

app.listen(process.env.PORT || 8080);

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname + '/dist/index.html'));
});
<commit_msg>force SSL and add compression only on production environment<commit_after>const express = require('express');
const app = express();
const path = require('path');
const compression = require('compression')

const forceSSL = function() {
  return function (req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
      return res.redirect(
       ['https://', req.get('Host'), req.url].join('')
      );
    }
    next();
  }
}

if (process.env.PRODUCTION == "true") {
  app.use(forceSSL());
  app.use(compression());
}

app.use(express.static(__dirname + '/dist'));

app.listen(process.env.PORT || 8080);

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname + '/dist/index.html'));
});
<|endoftext|>


<commit_before>var http = require('http');

var express = require("express");
var app = express();

var port = process.env.PORT || 5000;

// //Lets define a port we want to listen to
// const PORT=8080;

// //We need a function which handles requests and send response
// function handleRequest(request, response){
//     request.render('about.html');
//     response.end('It Works!! Path Hit: ' + request.url);
// }

// //Create a server
// var server = http.createServer(handleRequest);

// //Lets start our server
// server.listen(PORT, function(){
//     //Callback triggered when server is successfully listening. Hurray!
//     console.log("Server listening on: http://localhost:%s", PORT);
// });

   app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render(index);
});
console.log('Booting..');
console.log('Here we go..');
console.log('Server is Started');

app.listen(port, '127.0.0.1')<commit_msg>Make port and server host dynamic<commit_after>var http = require('http');

var express = require("express");
var app = express();

var server_port = process.env.YOUR_PORT || process.env.PORT || 8080;
var server_host = process.env.YOUR_HOST || '127.0.0.1';

var port = process.env.PORT || 5000;

// //Lets define a port we want to listen to
// const PORT=8080;

// //We need a function which handles requests and send response
// function handleRequest(request, response){
//     request.render('about.html');
//     response.end('It Works!! Path Hit: ' + request.url);
// }

// //Create a server
// var server = http.createServer(handleRequest);

// //Lets start our server
// server.listen(PORT, function(){
//     //Callback triggered when server is successfully listening. Hurray!
//     console.log("Server listening on: http://localhost:%s", PORT);
// });

   app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.render(index);
});
console.log('Booting..');
console.log('Here we go..');
console.log('Server is Started');

app.listen(server_port, server_host, function() {
    console.log('Listening on port %d', server_port);
    console.log('Server host %d', server_host);
});

<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port', port);
});

app.use(express.static(__dirname));

let players = [];
let score = [0,0]

io.on('connection', socket => {
  //socket.on('mouse move', (data) => {
  //  console.log(data);
  //});
  socket.on('addPlayer', function(data) {
	if(players.length == 0)
	{
    socket.emit('isHost', true);
    console.log("isHost = true");
  }
  else
  {
    console.log("isHost = false");
    socket.emit('isHost', false);
  }

  players.push(
  {
    name: data,
    socket: socket
  });
  console.log("addPlayer " + data);
  socket.emit('score', score);
  });

  socket.on('connected', () => {
    console.log('connected');
  });

  socket.on('disconnect', () => {
    console.log('disconnected');
    if(players.length > 0)
    {
      if(players[0].socket === socket)
      {
        console.log("Host " + players[0].name + " is leaving");
        players.shift();
        if(players.length > 0)
        {
          players[0].socket.emit('isHost', true);
          console.log("New host is " + players[0].name)
        }
      }
      else
      {
        console.log("Player " + players[0].name + " is leaving");
        for(var i = 0; i < players.length; i++)
        if(players[i].socket === socket)
            players.splice(i,1);
        }
    }
  });

  socket.on('ballSet', function(data) {
	socket.broadcast.emit('ballSet', data);
  });

  socket.on('score', function(data) {
    if(data == 1)
      score[0] += 7;
    else
      score[1] +=7;

    socket.emit('score', score);
	  socket.broadcast.emit('score', score);
    console.log("score " + data);
  });
});
<commit_msg>added click emit<commit_after>const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log('Server listening at port', port);
});

app.use(express.static(__dirname));

let players = [];
let score = [0,0]

io.on('connection', socket => {
  //socket.on('mouse move', (data) => {
  //  console.log(data);
  //});
  socket.on('addPlayer', function(data) {
	if(players.length == 0)
	{
    socket.emit('isHost', true);
    console.log("isHost = true");
  }
  else
  {
    console.log("isHost = false");
    socket.emit('isHost', false);
  }

  players.push(
  {
    name: data,
    socket: socket
  });
  console.log("addPlayer " + data);
  socket.emit('score', score);
  });

  socket.on('connected', () => {
    console.log('connected');
  });

  socket.on('disconnect', () => {
    console.log('disconnected');
    if(players.length > 0)
    {
      if(players[0].socket === socket)
      {
        console.log("Host " + players[0].name + " is leaving");
        players.shift();
        if(players.length > 0)
        {
          players[0].socket.emit('isHost', true);
          console.log("New host is " + players[0].name)
        }
      }
      else
      {
        console.log("Player " + players[0].name + " is leaving");
        for(var i = 0; i < players.length; i++)
        if(players[i].socket === socket)
            players.splice(i,1);
        }
    }
  });

  socket.on('ballSet', function(data) {
	socket.broadcast.emit('ballSet', data);
  });

  socket.on('score', function(data) {
    if(data == 1)
      score[0] += 7;
    else
      score[1] +=7;

    socket.emit('score', score);
	  socket.broadcast.emit('score', score);
    console.log("score " + data);
  });
  socket.on('click', function(data){
    players[0].socket.emit(data);
    console.log("Click X: " data[0] + " Y: " + data[1]);
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var http = require('http');
var PORT = 8000;
var https = require('https');
var qs = require('querystring');
var config = require('./config/config.js');

var path = require('path');
var FILE = process.argv[2];
FILE = path.resolve('./', FILE);

var server = http.createServer((req, res) => {
  console.log('req url', req.url);
  console.log(req.method);
  switch (req.method) {
    case 'GET':
      if (req.url == '/') {
        console.log('dead');
        fs.readFile(`${FILE}`, (err, data) => {
          res.end(data);
        });
      } else {
        var location = path.join(__dirname, req.url) //
        console.log('loca', location);
        fs.readFile(location, (err, data) => {
          console.log('hey this is data', data);
          res.end(data);
        });
      }
      break;
    case 'POST':
      handleAPI(req, res);
      break;
    default:
      console.log('Did not handle this.');
  }
});

function handleAPI(req, res) {
  var reqBody = '';
  req.on('data', function(data) {
    reqBody += data;
    if(reqBody.length > 1e7) {
      response.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
      response.end('<!doctype html><title>413</title>413: Request Entity Too Large');
    }
  });
  req.on('end', function() {
    var formData = JSON.parse(reqBody);
    console.log('fd', formData);

    var options = {
      "method": "POST",
      "hostname": "gateway.watsonplatform.net",
      "port": null,
      "path": "/tone-analyzer/api/v3/tone?version=2016-05-19",
      "headers": {
        "content-type": "application/json",
        "authorization": config.auth,
      }
    };

    var request = https.request(options, function (response) {
      var chunks = [];

      response.on("data", function (chunk) {
        chunks.push(chunk);
      });

      response.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
        res.end(body.toString());
      });
    });

    request.write(JSON.stringify({ "text": formData.text }));
    request.end();

  });

}

server.listen(PORT, () => {
  console.log('Listening on http://localhost:%d', PORT);
});<commit_msg>Added the content header for the stylesheet from the server.<commit_after>var fs = require('fs');
var http = require('http');
var PORT = 8000;
var https = require('https');
var qs = require('querystring');
var config = require('./config/config.js');

var path = require('path');
var FILE = process.argv[2];
FILE = path.resolve('./', FILE);

var server = http.createServer((req, res) => {
  console.log('req url', req.url);
  console.log(req.method);
  switch (req.method) {
    case 'GET':
      if (req.url == '/') {
        fs.readFile(`${FILE}`, (err, data) => {
          res.end(data);
        });
      } else {
        var location = path.join(__dirname, req.url)
        fs.readFile(location, (err, data) => {
          if (location.includes('.css')) res.writeHead(200, { 'Content-Type':'text/css' });
          res.end(data);
        });
      }
      break;
    case 'POST':
      handleAPI(req, res);
      break;
    default:
      console.log('Did not handle this.');
  }
});

function handleAPI(req, res) {
  var reqBody = '';
  req.on('data', function(data) {
    reqBody += data;
    if(reqBody.length > 1e7) {
      response.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
      response.end('<!doctype html><title>413</title>413: Request Entity Too Large');
    }
  });
  req.on('end', function() {
    var formData = JSON.parse(reqBody);
    console.log('fd', formData);

    var options = {
      "method": "POST",
      "hostname": "gateway.watsonplatform.net",
      "port": null,
      "path": "/tone-analyzer/api/v3/tone?version=2016-05-19",
      "headers": {
        "content-type": "application/json",
        "authorization": config.auth,
      }
    };

    var request = https.request(options, function (response) {
      var chunks = [];

      response.on("data", function (chunk) {
        chunks.push(chunk);
      });

      response.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
        res.end(body.toString());
      });
    });

    request.write(JSON.stringify({ "text": formData.text }));
    request.end();

  });

}

server.listen(PORT, () => {
  console.log('Listening on http://localhost:%d', PORT);
});<|endoftext|>


<commit_before>'use strict';

module.exports = Edge;

function Edge(p, q) {
    this.p = p;
    this.q = q;
    this.slope = (q.y - p.y) / (q.x - p.x);
    this.mpoints = [];
}

Edge.prototype = {
    isAbove: function (point) { return orient2d(this.p, this.q, point) < 0; },
    isBelow: function (point) { return orient2d(this.p, this.q, point) > 0; }
};

function orient2d(pa, pb, pc) {
    var acx = pa.x - pc.x,
        bcx = pb.x - pc.x,
        acy = pa.y - pc.y,
        bcy = pb.y - pc.y;
    return acx * bcy - acy * bcx;
}
<commit_msg>leftover v8 optimization<commit_after>'use strict';

module.exports = Edge;

function Edge(p, q) {
    this.p = p;
    this.q = q;
    this.slope = (q.y - p.y) / (q.x - p.x);
    this.mpoints = [];
    this.below = null;
    this.above = null;
}

Edge.prototype = {
    isAbove: function (point) { return orient2d(this.p, this.q, point) < 0; },
    isBelow: function (point) { return orient2d(this.p, this.q, point) > 0; }
};

function orient2d(pa, pb, pc) {
    var acx = pa.x - pc.x,
        bcx = pb.x - pc.x,
        acy = pa.y - pc.y,
        bcy = pb.y - pc.y;
    return acx * bcy - acy * bcx;
}
<|endoftext|>