<commit_before>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const assert = require('assert');

async function getMessageFromTile(eventTile) {
  const senderElement = await eventTile.$(".mx_SenderProfile_name");
  const bodyElement = await eventTile.$(".mx_EventTile_body");
  const sender = await(await senderElement.getProperty("innerText")).jsonValue();
  const body = await(await bodyElement.getProperty("innerText")).jsonValue();
  return {sender, body};
}

module.exports = async function receiveMessage(session, message) {
  session.log.step(`waits to receive message from ${message.sender} in room`);
  // wait for a response to come in that contains the message
  // crude, but effective
  await session.page.waitForResponse(async (response) => {
    const body = await response.text();
    return body.indexOf(message.body) !== -1;
  });

  let lastTile = await session.waitAndQuery(".mx_EventTile_last");
  let lastMessage = await getMessageFromTile(lastTile);
  assert.equal(lastMessage.body, message.body);
  assert.equal(lastMessage.sender, message.sender);
  session.log.done();
}<commit_msg>make receiving a bit more robust<commit_after>/*
Copyright 2018 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const assert = require('assert');

async function getMessageFromTile(eventTile) {
}

module.exports = async function receiveMessage(session, message) {
  session.log.step(`receives message "${message.body}" from ${message.sender} in room`);
  // wait for a response to come in that contains the message
  // crude, but effective
  await session.page.waitForResponse(async (response) => {
    const body = await response.text();
    return body.indexOf(message.body) !== -1;
  });
  // wait a bit for the incoming event to be rendered
  await session.delay(100);
  let lastTile = await session.query(".mx_EventTile_last");
  const senderElement = await lastTile.$(".mx_SenderProfile_name");
  const bodyElement = await lastTile.$(".mx_EventTile_body");
  const sender = await(await senderElement.getProperty("innerText")).jsonValue();
  const body = await(await bodyElement.getProperty("innerText")).jsonValue();

  assert.equal(body, message.body);
  assert.equal(sender, message.sender);
  session.log.done();
}<|endoftext|>


<commit_before>var ui_strings  = {}

ui_strings.VIEW_LABEL_COMPOSITE_SCRIPTS = 'Scripts';
ui_strings.VIEW_LABEL_COMPOSITE_DOM = 'DOM';
ui_strings.VIEW_LABEL_COMPOSITE_ERROR_CONSOLE = 'Error Console';
ui_strings.VIEW_LABEL_COMPOSITE_EXPORTS = 'Export';
ui_strings.VIEW_LABEL_SCRIPTS = 'Scripts';
ui_strings.VIEW_LABEL_ENVIRONMENT = 'Environment';
ui_strings.VIEW_LABEL_SOURCE = 'Source';
ui_strings.VIEW_LABEL_COMMAND_LINE = 'Command Line';
ui_strings.VIEW_LABEL_CALLSTACK = 'Call Stack';
ui_strings.VIEW_LABEL_THREAD_LOG = 'Thread Log';
ui_strings.VIEW_LABEL_FRAME_INSPECTION = 'Inspection';
ui_strings.VIEW_LABEL_OBJECT_INSPECTION = 'Object Inspection';
ui_strings.VIEW_LABEL_DOCUMENTS = 'Documents';
ui_strings.VIEW_LABEL_STYLESHEETS = 'Stylesheets';
ui_strings.VIEW_LABEL_DOM = 'DOM';
ui_strings.VIEW_LABEL_STYLESHEET = 'Stylesheet';
ui_strings.VIEW_LABEL_STYLES = 'Styles';
ui_strings.VIEW_LABEL_DOM_ATTR = 'Properties';
ui_strings.VIEW_LABEL_LAYOUT = 'Layout';
ui_strings.VIEW_LABEL_ERROR_ALL = 'All';
ui_strings.VIEW_LABEL_ERROR_SCRIPT = 'JavaScript';
ui_strings.VIEW_LABEL_ERROR_JAVA = 'Java';
ui_strings.VIEW_LABEL_ERROR_M2 = 'Mail';
ui_strings.VIEW_LABEL_ERROR_NETWORK = 'Network';
ui_strings.VIEW_LABEL_ERROR_XML = 'XML';
ui_strings.VIEW_LABEL_ERROR_HTML = 'HTML';
ui_strings.VIEW_LABEL_ERROR_CSS = 'CSS';
ui_strings.VIEW_LABEL_ERROR_XSLT = 'XSLT';
ui_strings.VIEW_LABEL_ERROR_SVG = 'SVG';
ui_strings.VIEW_LABEL_ERROR_BITTORRENT = 'Bittorrent';
ui_strings.VIEW_LABEL_ERROR_VOICE = 'Voice';
ui_strings.VIEW_LABEL_ERROR_WIDGET = 'Widget';
ui_strings.VIEW_LABEL_ERROR_DRAGONFLY = 'Dragonfly';
ui_strings.VIEW_LABEL_COMPUTED_STYLE = 'Computed Style';
ui_strings.VIEW_LABEL_STYLES = 'Styles';

ui_strings.SWITCH_SHOW_TAB_ALL = 'Show Tab All';
ui_strings.SWITCH_SHOW_TAB_SCRIPT = 'Show Tab Script';
ui_strings.SWITCH_SHOW_TAB_JAVA = 'Show Tab Java';
ui_strings.SWITCH_SHOW_TAB_M2 = 'Show Tab m2';
ui_strings.SWITCH_SHOW_TAB_NETWORK = 'Show Tab Network';
ui_strings.SWITCH_SHOW_TAB_XML = 'Show Tab XML';
ui_strings.SWITCH_SHOW_TAB_HTML = 'Show Tab HTML';
ui_strings.SWITCH_SHOW_TAB_CSS = 'Show Tab CSS';
ui_strings.SWITCH_SHOW_TAB_XSLT = 'Show Tab XSLT';
ui_strings.SWITCH_SHOW_TAB_SVG = 'Show Tab SVG';
ui_strings.SWITCH_SHOW_TAB_BITTORRENT = 'Show Tab Bittorrent';
ui_strings.SWITCH_SHOW_TAB_VOICE = 'Show Tab Voice';
ui_strings.SWITCH_SHOW_TAB_WIDGET = 'Show Tab Widget';
ui_strings.SWITCH_SHOW_TAB_DRAGONFLY = 'Show Tab Dragonfly';
ui_strings.SWITCH_UPDATE_GLOBAL_SCOPE = 'Automatically update global scope';
ui_strings.SWITCH_FIND_ELEMENT_BY_CLICKING = 'Find element by clicking';
ui_strings.SWITCH_HIGHLIGHT_BY_MOUSE_OVER = 'Highlight by mouse hover';
ui_strings.SWITCH_UPDATE_DOM_ON_NODE_REMOVE = 'Update DOM when a node is removed';
ui_strings.SWITCH_USE_LOWER_CASE_TAG_NAMES = 'Use lower case tag names';
ui_strings.SWITCH_SHOW_COMMENT_NODES = 'Show comment nodes';
ui_strings.SWITCH_SHOW_ATTRIBUTES = 'Show attributes';
ui_strings.SWITCH_SHOW_WHITE_SPACE_NODES = 'Show white space nodes';
ui_strings.SWITCH_SHOW_DOM_INTREE_VIEW = 'Show DOM in tree view';
ui_strings.SWITCH_USE_SHORTHAND_PROPERTIES = 'Use shorthand for properties';
ui_strings.SWITCH_HIDE_INITIAL_VALUES = 'Hide initial values in computed styles';
ui_strings.SWITCH_HIDE_SHORTHANDS = 'Hide shorthand for computed styles';
ui_strings.SWITCH_HIDE_EMPTY_STRINGS = 'Hide empty strings and null values';
ui_strings.SWITCH_REMOTE_DEBUG = 'Remote Debug';
ui_strings.SWITCH_SHOW_VIEWS_MENU = "Show Views menu";
ui_strings.SWITCH_RELOAD_SCRIPTS_AUTOMATICALLY = "Reload documents automatically on selecting a window"
ui_strings.SWITCH_DETACH_WINDOW = "Undock into separate window"  ;
ui_strings.SWITCH_ATTACH_WINDOW = "Dock to main window";

ui_strings.BUTTON_LABEL_HELP = 'Help';
ui_strings.BUTTON_LABEL_CONTINUE = 'Continue (F8)';
ui_strings.BUTTON_LABEL_STEP_OVER = 'Step Over (F10)';
ui_strings.BUTTON_LABEL_STEP_INTO = 'Step Into (F11)';
ui_strings.BUTTON_LABEL_STEP_OUT = 'Step Out (Shift F11)';
ui_strings.BUTTON_LABEL_STOP_AT_THREAD = 'Stop at new script';
ui_strings.BUTTON_LABEL_AT_EXCEPTION = 'Stop at exception';
ui_strings.BUTTON_LABEL_AT_ERROR = 'Stop at error';
ui_strings.BUTTON_LABEL_AT_ABORT = 'Stop at abort';
ui_strings.BUTTON_LABEL_RELOAD_HOST = 'Reload the selected window in the browser';
ui_strings.BUTTON_LABEL_SELECT_WINDOW = "Select the window you'd like to debug";
ui_strings.BUTTON_LABEL_GET_THE_WOHLE_TREE = 'Expand the DOM tree';
ui_strings.BUTTON_LABEL_EXPORT_DOM = 'Export current DOM view';
ui_strings.BUTTON_LABEL_HIDE_DEFAULT_PROPS_IN_GLOBAL_SCOPE = 'Hide default properties in global scope';
ui_strings.BUTTON_LABEL_LOG_THREADS = 'Log threads';
ui_strings.BUTTON_LABEL_CLEAR_LOG = 'Clear thread log';
ui_strings.BUTTON_LABEL_EXPORT_LOG = 'Export thread log';

ui_strings.INFO_NO_SCRIPTS_PLEASE_RELOAD = 'Click the reload button above to fetch the scripts for the selected window';
ui_strings.RUNTIME_HAS_NO_SCRIPTS = 'This document has no scripts';
ui_strings.INFO_DOCUMNENT_LOADING = 'The document is loading ...';

ui_strings.SELECT_WINDOW_EMPTY = 'Select a window';

ui_strings.INPUT_DEFAULT_TEXT_SEARCH = 'Search';
ui_strings.INPUT_DEFAULT_TEXT_FILTER = 'Quick find';

ui_strings.SETTING_LABEL_GENERAL = 'General';

ui_strings.ALERT_WRONG_START = "Dragonfly can not be used in this way.\n" +
  "Either set the current url in\n\n" +
  "   opera:config > Developer Tools > Developer Tools URL\n\n" +
  "or setup a debugger environment with a proxy and server."

<commit_msg>fix for  Bug 336724<commit_after>var ui_strings  = {}

ui_strings.VIEW_LABEL_COMPOSITE_SCRIPTS = 'Scripts';
ui_strings.VIEW_LABEL_COMPOSITE_DOM = 'DOM';
ui_strings.VIEW_LABEL_COMPOSITE_ERROR_CONSOLE = 'Error Console';
ui_strings.VIEW_LABEL_COMPOSITE_EXPORTS = 'Export';
ui_strings.VIEW_LABEL_SCRIPTS = 'Scripts';
ui_strings.VIEW_LABEL_ENVIRONMENT = 'Environment';
ui_strings.VIEW_LABEL_SOURCE = 'Source';
ui_strings.VIEW_LABEL_COMMAND_LINE = 'Command Line';
ui_strings.VIEW_LABEL_CALLSTACK = 'Call Stack';
ui_strings.VIEW_LABEL_THREAD_LOG = 'Thread Log';
ui_strings.VIEW_LABEL_FRAME_INSPECTION = 'Inspection';
ui_strings.VIEW_LABEL_OBJECT_INSPECTION = 'Object Inspection';
ui_strings.VIEW_LABEL_DOCUMENTS = 'Documents';
ui_strings.VIEW_LABEL_STYLESHEETS = 'Stylesheets';
ui_strings.VIEW_LABEL_DOM = 'DOM';
ui_strings.VIEW_LABEL_STYLESHEET = 'Stylesheet';
ui_strings.VIEW_LABEL_STYLES = 'Styles';
ui_strings.VIEW_LABEL_DOM_ATTR = 'Properties';
ui_strings.VIEW_LABEL_LAYOUT = 'Layout';
ui_strings.VIEW_LABEL_ERROR_ALL = 'All';
ui_strings.VIEW_LABEL_ERROR_SCRIPT = 'JavaScript';
ui_strings.VIEW_LABEL_ERROR_JAVA = 'Java';
ui_strings.VIEW_LABEL_ERROR_M2 = 'Mail';
ui_strings.VIEW_LABEL_ERROR_NETWORK = 'Network';
ui_strings.VIEW_LABEL_ERROR_XML = 'XML';
ui_strings.VIEW_LABEL_ERROR_HTML = 'HTML';
ui_strings.VIEW_LABEL_ERROR_CSS = 'CSS';
ui_strings.VIEW_LABEL_ERROR_XSLT = 'XSLT';
ui_strings.VIEW_LABEL_ERROR_SVG = 'SVG';
ui_strings.VIEW_LABEL_ERROR_BITTORRENT = 'Bittorrent';
ui_strings.VIEW_LABEL_ERROR_VOICE = 'Voice';
ui_strings.VIEW_LABEL_ERROR_WIDGET = 'Widget';
ui_strings.VIEW_LABEL_ERROR_DRAGONFLY = 'Dragonfly';
ui_strings.VIEW_LABEL_COMPUTED_STYLE = 'Computed Style';
ui_strings.VIEW_LABEL_STYLES = 'Styles';

ui_strings.SWITCH_SHOW_TAB_ALL = 'Show Tab All';
ui_strings.SWITCH_SHOW_TAB_SCRIPT = 'Show Tab Script';
ui_strings.SWITCH_SHOW_TAB_JAVA = 'Show Tab Java';
ui_strings.SWITCH_SHOW_TAB_M2 = 'Show Tab m2';
ui_strings.SWITCH_SHOW_TAB_NETWORK = 'Show Tab Network';
ui_strings.SWITCH_SHOW_TAB_XML = 'Show Tab XML';
ui_strings.SWITCH_SHOW_TAB_HTML = 'Show Tab HTML';
ui_strings.SWITCH_SHOW_TAB_CSS = 'Show Tab CSS';
ui_strings.SWITCH_SHOW_TAB_XSLT = 'Show Tab XSLT';
ui_strings.SWITCH_SHOW_TAB_SVG = 'Show Tab SVG';
ui_strings.SWITCH_SHOW_TAB_BITTORRENT = 'Show Tab Bittorrent';
ui_strings.SWITCH_SHOW_TAB_VOICE = 'Show Tab Voice';
ui_strings.SWITCH_SHOW_TAB_WIDGET = 'Show Tab Widget';
ui_strings.SWITCH_SHOW_TAB_DRAGONFLY = 'Show Tab Dragonfly';
ui_strings.SWITCH_UPDATE_GLOBAL_SCOPE = 'Automatically update global scope';
ui_strings.SWITCH_FIND_ELEMENT_BY_CLICKING = 'Find element by clicking';
ui_strings.SWITCH_HIGHLIGHT_BY_MOUSE_OVER = 'Highlight by mouse hover';
ui_strings.SWITCH_UPDATE_DOM_ON_NODE_REMOVE = 'Update DOM when a node is removed';
ui_strings.SWITCH_USE_LOWER_CASE_TAG_NAMES = 'Use lower case tag names';
ui_strings.SWITCH_SHOW_COMMENT_NODES = 'Show comment nodes';
ui_strings.SWITCH_SHOW_ATTRIBUTES = 'Show attributes';
ui_strings.SWITCH_SHOW_WHITE_SPACE_NODES = 'Show white space nodes';
ui_strings.SWITCH_SHOW_DOM_INTREE_VIEW = 'Show DOM in tree view';
ui_strings.SWITCH_USE_SHORTHAND_PROPERTIES = 'Use shorthand for properties';
ui_strings.SWITCH_HIDE_INITIAL_VALUES = 'Hide initial values in computed styles';
ui_strings.SWITCH_HIDE_SHORTHANDS = 'Hide shorthand for computed styles';
ui_strings.SWITCH_HIDE_EMPTY_STRINGS = 'Hide empty strings and null values';
ui_strings.SWITCH_REMOTE_DEBUG = 'Remote Debug';
ui_strings.SWITCH_SHOW_VIEWS_MENU = "Show Views menu";
ui_strings.SWITCH_RELOAD_SCRIPTS_AUTOMATICALLY = "Reload documents automatically on selecting a window"
ui_strings.SWITCH_DETACH_WINDOW = "Undock into separate window"  ;
ui_strings.SWITCH_ATTACH_WINDOW = "Dock to main window";

ui_strings.BUTTON_LABEL_HELP = 'Help';
ui_strings.BUTTON_LABEL_CONTINUE = 'Continue (F8)';
ui_strings.BUTTON_LABEL_STEP_OVER = 'Step Over (F10)';
ui_strings.BUTTON_LABEL_STEP_INTO = 'Step Into (F11)';
ui_strings.BUTTON_LABEL_STEP_OUT = 'Step Out (Shift F11)';
ui_strings.BUTTON_LABEL_STOP_AT_THREAD = 'Stop at new script';
ui_strings.BUTTON_LABEL_AT_EXCEPTION = 'Stop at exception';
ui_strings.BUTTON_LABEL_AT_ERROR = 'Stop at error';
ui_strings.BUTTON_LABEL_AT_ABORT = 'Stop at abort';
ui_strings.BUTTON_LABEL_RELOAD_HOST = 'Reload the selected window in the browser';
ui_strings.BUTTON_LABEL_SELECT_WINDOW = "Select the window you'd like to debug";
ui_strings.BUTTON_LABEL_GET_THE_WOHLE_TREE = 'Expand the DOM tree';
ui_strings.BUTTON_LABEL_EXPORT_DOM = 'Export current DOM view';
ui_strings.BUTTON_LABEL_HIDE_DEFAULT_PROPS_IN_GLOBAL_SCOPE = 'Hide default properties in global scope';
ui_strings.BUTTON_LABEL_LOG_THREADS = 'Log threads';
ui_strings.BUTTON_LABEL_CLEAR_LOG = 'Clear thread log';
ui_strings.BUTTON_LABEL_EXPORT_LOG = 'Export thread log';

ui_strings.INFO_NO_SCRIPTS_PLEASE_RELOAD = 'Click the reload button above to fetch the scripts for the selected window';
ui_strings.RUNTIME_HAS_NO_SCRIPTS = 'This document has no scripts';
ui_strings.INFO_DOCUMNENT_LOADING = 'The document is loading ...';

ui_strings.SELECT_WINDOW_EMPTY = 'Select a window';

ui_strings.INPUT_DEFAULT_TEXT_SEARCH = 'Search';
ui_strings.INPUT_DEFAULT_TEXT_FILTER = 'Quick find';

ui_strings.SETTING_LABEL_GENERAL = 'General';

ui_strings.ALERT_WRONG_START = "Dragonfly cannot be used in this way.\n" +
  "Either set the current url in\n\n" +
  "   opera:config > Developer Tools > Developer Tools URL\n\n" +
  "or setup a debugger environment with a proxy and server."

<|endoftext|>


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

const app = express();
app.use(express.static('static'));

app.listen(8080, function () {
    console.log('App started on port 8080');
});<commit_msg>Add simple api<commit_after>const express = require('express');

const app = express();
app.use(express.static('static'));

const issues = [
    {
        id: 1, status: 'Open', owner: 'Ravan',
        created: new Date('2016-08-15'), effort: 5,
        completionDate: undefined,
        title: 'Error in console when clicking Add',
    },
    {
        id: 2, status: 'Assigned', owner: 'Eddie',
        created: new Date('2016-08-16'), effort: 14,
        completionDate: new Date('2016-08-30'),
        title: 'Missing bottom border on panel',
    },
];

app.get('/api/issues', (req, res) => {
    const metadata = { total_count: issues.length };
    res.json({ _metadata: metadata, records: issues });
});

app.listen(8080, function () {
    console.log('App started on port 8080');
});<|endoftext|>


<commit_before>( function( window, Backbone, $, _, Scrivener, Scrivener_Data, undefined ) {

	"use strict";
	var document = window.document;
	var currentModalView = null;

	Scrivener.Models.Core = Backbone.Model.extend( {

		buildPreviewURL : function() {
			var post_id = document.getElementById( 'post_ID' ).value;
<<<<<<< HEAD
			return Scrivener_Data.admin_url + 'admin-post.php?action=weivrep&p=' + post_id;
=======
			return scrivener_data.admin_url + 'admin-post.php?action=weivrep&p=' + post_id;
		},

		renderNewModal : function() {
			if( currentModalView !== null ) {
				currentModalView.close();
			}

			currentModalView = new Scrivener.Views.Modal( {
				model : this
			} );
>>>>>>> ff1dd73ac1082303443351b1493f8927477b9c5e
		}

	} );

} )( window, Backbone, jQuery, _, Scrivener, Scrivener_Data );
<commit_msg>Resolve merge conflict<commit_after>( function( window, Backbone, $, _, Scrivener, Scrivener_Data, undefined ) {

	"use strict";
	var document = window.document;
	var currentModalView = null;

	Scrivener.Models.Core = Backbone.Model.extend( {

		buildPreviewURL : function() {
			var post_id = document.getElementById( 'post_ID' ).value;
			return Scrivener_Data.admin_url + 'admin-post.php?action=weivrep&p=' + post_id;
		},

		renderNewModal : function() {
			if( currentModalView !== null ) {
				currentModalView.close();
			}

			currentModalView = new Scrivener.Views.Modal( {
				model : this
			} );
		}

	} );

} )( window, Backbone, jQuery, _, Scrivener, Scrivener_Data );
<|endoftext|>


<commit_before>var WHITE = "rgb(255,255,255)";
var BLACK = "rgb(0,0,0)";
var RED = "rgb(200,0,0)";
var CELL = 5; // cell size

function chooseRandomElementFromSet(s) {
  // set s is a simple object
  var bestVal = -1;
  var bestK;
  for (var k in s) {
    var v = Math.random();
    if ( v > bestVal ) {
      bestVal = v;
      bestK = k;
    }
  }
  return bestK;
}
function randInt(max) { return Math.floor(Math.random()*max); }
function chooseRandomElementFromArray(a) {
    return a[randInt(a.length)];
}
function augmentSet(s1, s2) {
  // sets s1 and s2 are simple objects
  // return augmented set s1
  for (var k in s2) { s1[k] = 1; }
  return s1;
}
function assert(condition, message) {
  if (!condition) {
    message = message || "Assertion failed";
    if (typeof Error !== "undefined") {
       throw new Error(message);
    }
    throw message; // Fallback
  }
}
function swap (arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
function shuffle(arr) {
    for(var i = arr.length - 1; i > 0; i--) {
	swap(arr, i, randInt(i+1));
    }
    return arr;
}
function drawLine(ctx, x1, y1, dx, dy, style) {
    // console.log("drawing line");
    var oldstyle = ctx.strokeStyle;
    ctx.strokeStyle = style;
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x1+dx, y1+dy);
    ctx.stroke();
    ctx.strokeStyle = oldstyle;
}

function Maze(h, w, strategy) {
    h = parseInt(h); w = parseInt(w);
    assert(h > 0 && w > 0, "Bad dimensions.");
    this.h = h;
    this.w = w;
    this.m = new Array(h*w);
    this.timeouts = [];
    this.erase();
    this.strategy = strategy? strategy: this.dfsGraph;
    // this.creationOrder = [];
    // this.randomize();
}

Maze.prototype.erase = function() {
    if (this.timeouts) {
	this.timeouts.forEach(function(id){clearTimeout(id);});
    }
    this.timeouts = []
    for (var i = 0; i < this.h * this.w; i++) {
	this.m[i] = 0;
    }
};

Maze.prototype.openPassagexy = function(x1, y1, x2, y2){
    var w = this.w, h = this.h;
    var p1 = x1+y1*w, p2 = x1+y2*w;
    this.openPassage(p1, p2);
};

Maze.prototype.openPassage = function (p1, p2) {
    var w = this.w;
    var x1 = p1 % w, y1 = Math.floor(p1 / w);
    var x2 = p2 % w, y2 = Math.floor(p2 / w);
    assert(this.isValidCell(p1), p1+"("+x1+","+y1+") is not a valid cell.");
    assert(this.isValidCell(p2), p2+"("+x2+","+y2+") is not a valid cell.");
    assert((x1 == x2 && Math.abs(y1-y2) == 1) ||
	   (y1 == y2 && Math.abs(x1-x2) == 1),
	   "("+x1+","+y1+") is not adjacent to ("+x2+","+y2+")");
    if (x1 == x2) { // vertical
	this.m[	(y1 > y2)? p1: p2] |= 2;
    }
    else { // horizontal
	this.m[	(x1 > x2)? p1: p2] |= 1;
    }
};

Maze.prototype.randomWalk = function(start, steps) {
    // console.log("randomWalk");
    // walk around randomly, returning a list of visited nodes
    if (!start) start = 0;
    if (!steps) steps = this.w * this.h;
    var visited = [start];
    var a = start, b;
    do {
	// console.log("randomWalk: a = "+a+", steps = "+steps);
	b = this.chooseRandomNeighbor(a);
	assert(b >= 0, "Bad random neighbor "+b);
	this.openPassage(a, b);
	visited.push(a);
	a = b;
    } while (steps-- > 0);

    return visited;
};

Maze.prototype.randomPath = function(start, visited) {
    // randomly walk, avoiding visited nodes. Return path.
    if (!start) start = 0;
    if (!visited) visited = {};
    var path = [];
    var prev = -1;
    while (!visited[start]) {
	if (prev >= 0) this.openPassage(prev, start);
	visited[start] = true;
	path.push(start);
	prev = start;
	start = this.randomNeighbor(start, visited);
	if (start < 0) return path;
    }
};

Maze.prototype.randomNeighbor = function(x, exclude) {
    var ns = shuffle(this.neighbors(x));
    for (var i = 0; i < ns.length; i++) {
	var n = ns[i];
	if (!exclude || !exclude[n]) return n;
    }
    return -1;
};

Maze.prototype.isValidCell = function(x) {
  return x >= 0 && x < this.w * this.h;
};

Maze.prototype.neighbors = function(x) {
    assert(this.isValidCell(x),
           x+" is out of range (maze size is "+this.w+" by "+this.h+")");
    assert(this.w * this.h > 1, "No neighbors.");
    var ns = [];
    var w = this.w, h = this.h;
    var col = x % w;
    if (col > 0)   ns.push(x-1);
    if (col < w-1) ns.push(x+1);
    var row = Math.floor(x / w);
    if (row > 0)   ns.push(x-w);
    if (row < h-1) ns.push(x+w);
    return ns;
};
Maze.prototype.chooseRandomNeighbor = function(x) {
  var w=this.w, h=this.h, cells = this.w * this.h;
  assert(this.isValidCell(x),
         x+" is out of range (maze size is "+w+" by "+h+")");
  assert(cells > 1, "No neighbors.");
  // single col or row
  if ( this.w === 1 || this.h === 1 ) {
    return x === 0? 1:
      x === cells - 1? x-1:
      Math.random() < 0.5? x-1: x+1;
  }
  var r = Math.random();
  // handle corners, sides, then middle cells
  var n = x === 0? (r < 0.5? 1: w):
    x === w - 1? (r < 0.5? x - 1: x + w):
    x === w * (h - 1)? (r < 0.5? x - w: x+1):
    x === cells - 1? (r < 0.5? x - w: x-1):
    x < w? (r < 0.33? x-1: r < 0.66? x+1: x+w):
    x + w > cells? (r < 0.33? x-1: r < 0.66? x+1: x-w):
    x % w === 0? (r < 0.33? x-w: r < 0.66? x+1: x+w):
    x % w === w-1? (r < 0.33? x-w: r < 0.66? x-1: x+w):
    r < 0.25? x-w:
    r < 0.50? x+1:
    r < 0.75? x+w:
    x-1;
  // console.log("returning neighbor "+n+" for cell "+x);
  assert(this.isValidCell(n), n+" is an invalid neighbor");
  return n;
};

Maze.prototype.dfs = function(callback) {
    var seen = {};
    var starts = [0];
    var count = 0;
    while(starts.length > 0) {
	var x = starts.pop();
	// console.log("dfs: count = "+count+", cell = "+x);
	if (seen[x]) continue;
	seen[x] = true;
	// console.log("dfs: count = "+count+", unseen cell = "+x);
	if (callback) callback(x, count++);
	Array.prototype.push.apply(starts, this.neighborsInPath(x));
	// console.log("dfs: stack = "+starts);
    }
};

Maze.prototype.dfsPath = function(start, seen) {
    if (!start) start = 0;
    if (!seen) seen = {};
    var stack=[[-1, start]];
    while (stack.length > 0) {
	var x = stack.pop();
	if (seen[x[1]]) continue;
	seen[x[1]] = true;
	if (x[0] >= 0) this.openPassage(x[0], x[1]);
	Array.prototype.push.apply(
	    stack,
	    shuffle(this.neighbors(x[1]).map(function(x1){ return [x[1], x1]; })));
	// console.log("dfs: stack = "+stack);
	// console.log("dfs: x = "+x);

    }
};

Maze.prototype.dfsGraph = function(start, seen, minCycle) {
    if (!start) start = 0;
    if (!seen) seen = {};
    if (!minCycle) minCycle = 50;
    var cycles = 0;
    var stack=[[-1, start, 1]]; // previous cell, current cell, current count.
    while (stack.length > 0) {
	var x = stack.pop();
	if (seen[x[1]]) {
	    var dist = Math.abs(seen[x[1]] - x[2]);
	    if (dist >= minCycle && randInt(minCycle) == 1) {
		cycles++;
		// console.log("creating loop "+cycles+" at "+x[0]+" and "+x[1]+", counts are "+seen[x[1]]+" and "+x[2]+", dist = "+dist);
		this.openPassage(x[1],x[0]);
	    }
	    continue;
	}
	seen[x[1]] = x[2];
	if (x[0] >= 0) this.openPassage(x[0], x[1]);
	Array.prototype.push.apply(
	    stack,
	    shuffle(this.neighbors(x[1]).map(function(x1){ return [x[1], x1, x[2]+1]; })));
	// console.log("dfs: stack = "+stack);
	// console.log("dfs: x = "+x);

    }
};

Maze.prototype.neighborsInPath = function(x) {
    var w = this.w, h = this.h, m = this.m;
    var i = x % w, j = Math.floor(x / w);
    var ns = [];
    if (i > 0   && m[x] & 1)   ns.push(x-1);
    if (i < w-1 && m[x+1] & 1) ns.push(i+1+j*w);
    if (j > 0   && m[x] & 2)   ns.push(x-w);
    if (j < h-1 && m[x+w] & 2) ns.push(x+w);
    // console.log("neighborsInPath: maze = "+this+", x = "+x+", neighbors = "+ns);
    return ns;
};

Maze.prototype.draw = function (ctx) {
    ctx.fillStyle = WHITE;
    ctx.fillRect(0,0, this.w*CELL, this.h*CELL);
    ctx.strokeStyle = BLACK;
    ctx.strokeRect(0,0, this.w*CELL, this.h*CELL);
    var delay = parseFloat(document.getElementById("delay").value);
    var maze = this;
    var threadDelay = 50;
    this.dfs(function(x, i){
	maze.timeouts.push(
	    setTimeout(function(){
		// console.log("executing "+i+": "+x);
		maze.drawSquare(ctx, x, delay*.9);
	    }, (Math.floor(i/threadDelay) + i%threadDelay)*1000*delay));
    });
};

Maze.prototype.drawSquare = function(ctx, x, delay) {
    // console.log(this);
    var w = this.w, h = this.h;
    var i = x % this.w;
    var j = Math.floor(x / w);
    // var x = i + maze.w * j;
    var mx = this.m[x];
    // console.log("drawing "+x);
    ctx.fillStyle = RED;
    ctx.fillRect( i*CELL, j*CELL, CELL, CELL);
    var maze = this;
    maze.timeouts.push(
	setTimeout(function() {
	    // console.log("drew "+x);
	    ctx.fillStyle = WHITE;
	    ctx.fillRect( i*CELL, j*CELL, CELL, CELL);

	    ctx.save();
	    // do this for smooth walls, we don't want the white
	    // vertical lines to overwrite the dark horizontal lines
	    // or vice versa.
	    ctx.globalCompositeOperation="darken";

	    // console.log("drawing left side of "+mx+"="+(mx & 1?WHITE:BLACK) );
	    drawLine(ctx, i*CELL, j*CELL, 0, CELL,
		     (mx & 1)? WHITE: BLACK);

	    if (i < w-1) {
		// console.log("drawing right side of "+mx+" ("+maze.m[x+1]+") ="+(maze.m[x+1] & 1?WHITE:BLACK) );
		drawLine(ctx, (i+1)*CELL, j*CELL, 0, CELL,
			 (maze.m[x+1] & 1)? WHITE: BLACK);
	    }

	    // console.log("drawing top side of "+mx+"="+(mx & 2?WHITE:BLACK) );
	    drawLine(ctx, i*CELL, j*CELL, CELL, 0,
		     (mx & 2)? WHITE: BLACK);

	    if (j < h-1) {
		// console.log("drawing bottom side of "+x+" ("+maze.m[x+w]+") ="+(maze.m[x+w] & 1?WHITE:BLACK) );
		drawLine(ctx, i*CELL, (j+1)*CELL, CELL, 0,
			 (maze.m[x+w] & 2)? WHITE: BLACK);
	    }
	    ctx.restore();
	    // ctx.textBaseline="top";
	    // ctx.strokeText(mx, i*CELL, j*CELL);

	}, Math.round(delay*1000)  ));
};

Maze.prototype.redraw = function (ctx) {
    this.erase();
    this.strategy();
    this.draw(ctx);
};

var m;

function makeMaze() {
    var h = document.getElementById("height").value;
    var w = document.getElementById("width").value;
    // console.log("height "+h, "width "+w);
    m= new Maze(h,w);
    m.strategy();
    m.draw(ctx);
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function go() {
    makeMaze();
    scale();
}

function redraw() { m.redraw(ctx); }
function draw() { m.draw(ctx); }

function scale() {
    // see http://stackoverflow.com/a/5306929/268040
    if (window.devicePixelRatio > 1) {
	var canvasWidth = canvas.width;
	var canvasHeight = canvas.height;

	canvas.width = canvasWidth * window.devicePixelRatio;
	canvas.height = canvasHeight * window.devicePixelRatio;
	canvas.style.width = canvasWidth;
	canvas.style.height = canvasHeight;

	ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }
    redraw();
}
go();
<commit_msg>Adjust drawing.<commit_after>var WHITE = "rgb(255,255,255)";
var BLACK = "rgb(0,0,0)";
var RED = "rgb(200,0,0)";
var CELL = 5; // cell size

function chooseRandomElementFromSet(s) {
  // set s is a simple object
  var bestVal = -1;
  var bestK;
  for (var k in s) {
    var v = Math.random();
    if ( v > bestVal ) {
      bestVal = v;
      bestK = k;
    }
  }
  return bestK;
}
function randInt(max) { return Math.floor(Math.random()*max); }
function chooseRandomElementFromArray(a) {
    return a[randInt(a.length)];
}
function augmentSet(s1, s2) {
  // sets s1 and s2 are simple objects
  // return augmented set s1
  for (var k in s2) { s1[k] = 1; }
  return s1;
}
function assert(condition, message) {
  if (!condition) {
    message = message || "Assertion failed";
    if (typeof Error !== "undefined") {
       throw new Error(message);
    }
    throw message; // Fallback
  }
}
function swap (arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
function shuffle(arr) {
    for(var i = arr.length - 1; i > 0; i--) {
	swap(arr, i, randInt(i+1));
    }
    return arr;
}
function drawLine(ctx, x1, y1, dx, dy, style) {
    // console.log("drawing line");
    var oldstyle = ctx.strokeStyle;
    ctx.strokeStyle = style;
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x1+dx, y1+dy);
    ctx.stroke();
    ctx.strokeStyle = oldstyle;
}

function Maze(h, w, strategy) {
    h = parseInt(h); w = parseInt(w);
    assert(h > 0 && w > 0, "Bad dimensions.");
    this.h = h;
    this.w = w;
    this.m = new Array(h*w);
    this.timeouts = [];
    this.erase();
    this.strategy = strategy? strategy: this.dfsGraph;
    // this.creationOrder = [];
    // this.randomize();
}

Maze.prototype.erase = function() {
    if (this.timeouts) {
	this.timeouts.forEach(function(id){clearTimeout(id);});
    }
    this.timeouts = []
    for (var i = 0; i < this.h * this.w; i++) {
	this.m[i] = 0;
    }
};

Maze.prototype.openPassagexy = function(x1, y1, x2, y2){
    var w = this.w, h = this.h;
    var p1 = x1+y1*w, p2 = x1+y2*w;
    this.openPassage(p1, p2);
};

Maze.prototype.openPassage = function (p1, p2) {
    var w = this.w;
    var x1 = p1 % w, y1 = Math.floor(p1 / w);
    var x2 = p2 % w, y2 = Math.floor(p2 / w);
    assert(this.isValidCell(p1), p1+"("+x1+","+y1+") is not a valid cell.");
    assert(this.isValidCell(p2), p2+"("+x2+","+y2+") is not a valid cell.");
    assert((x1 == x2 && Math.abs(y1-y2) == 1) ||
	   (y1 == y2 && Math.abs(x1-x2) == 1),
	   "("+x1+","+y1+") is not adjacent to ("+x2+","+y2+")");
    if (x1 == x2) { // vertical
	this.m[	(y1 > y2)? p1: p2] |= 2;
    }
    else { // horizontal
	this.m[	(x1 > x2)? p1: p2] |= 1;
    }
};

Maze.prototype.randomWalk = function(start, steps) {
    // console.log("randomWalk");
    // walk around randomly, returning a list of visited nodes
    if (!start) start = 0;
    if (!steps) steps = this.w * this.h;
    var visited = [start];
    var a = start, b;
    do {
	// console.log("randomWalk: a = "+a+", steps = "+steps);
	b = this.chooseRandomNeighbor(a);
	assert(b >= 0, "Bad random neighbor "+b);
	this.openPassage(a, b);
	visited.push(a);
	a = b;
    } while (steps-- > 0);

    return visited;
};

Maze.prototype.randomPath = function(start, visited) {
    // randomly walk, avoiding visited nodes. Return path.
    if (!start) start = 0;
    if (!visited) visited = {};
    var path = [];
    var prev = -1;
    while (!visited[start]) {
	if (prev >= 0) this.openPassage(prev, start);
	visited[start] = true;
	path.push(start);
	prev = start;
	start = this.randomNeighbor(start, visited);
	if (start < 0) return path;
    }
};

Maze.prototype.randomNeighbor = function(x, exclude) {
    var ns = shuffle(this.neighbors(x));
    for (var i = 0; i < ns.length; i++) {
	var n = ns[i];
	if (!exclude || !exclude[n]) return n;
    }
    return -1;
};

Maze.prototype.isValidCell = function(x) {
  return x >= 0 && x < this.w * this.h;
};

Maze.prototype.neighbors = function(x) {
    assert(this.isValidCell(x),
           x+" is out of range (maze size is "+this.w+" by "+this.h+")");
    assert(this.w * this.h > 1, "No neighbors.");
    var ns = [];
    var w = this.w, h = this.h;
    var col = x % w;
    if (col > 0)   ns.push(x-1);
    if (col < w-1) ns.push(x+1);
    var row = Math.floor(x / w);
    if (row > 0)   ns.push(x-w);
    if (row < h-1) ns.push(x+w);
    return ns;
};
Maze.prototype.chooseRandomNeighbor = function(x) {
  var w=this.w, h=this.h, cells = this.w * this.h;
  assert(this.isValidCell(x),
         x+" is out of range (maze size is "+w+" by "+h+")");
  assert(cells > 1, "No neighbors.");
  // single col or row
  if ( this.w === 1 || this.h === 1 ) {
    return x === 0? 1:
      x === cells - 1? x-1:
      Math.random() < 0.5? x-1: x+1;
  }
  var r = Math.random();
  // handle corners, sides, then middle cells
  var n = x === 0? (r < 0.5? 1: w):
    x === w - 1? (r < 0.5? x - 1: x + w):
    x === w * (h - 1)? (r < 0.5? x - w: x+1):
    x === cells - 1? (r < 0.5? x - w: x-1):
    x < w? (r < 0.33? x-1: r < 0.66? x+1: x+w):
    x + w > cells? (r < 0.33? x-1: r < 0.66? x+1: x-w):
    x % w === 0? (r < 0.33? x-w: r < 0.66? x+1: x+w):
    x % w === w-1? (r < 0.33? x-w: r < 0.66? x-1: x+w):
    r < 0.25? x-w:
    r < 0.50? x+1:
    r < 0.75? x+w:
    x-1;
  // console.log("returning neighbor "+n+" for cell "+x);
  assert(this.isValidCell(n), n+" is an invalid neighbor");
  return n;
};

Maze.prototype.dfs = function(callback) {
    var seen = {};
    var starts = [0];
    var count = 0;
    while(starts.length > 0) {
	var x = starts.pop();
	// console.log("dfs: count = "+count+", cell = "+x);
	if (seen[x]) continue;
	seen[x] = true;
	// console.log("dfs: count = "+count+", unseen cell = "+x);
	if (callback) callback(x, count++);
	Array.prototype.push.apply(starts, this.neighborsInPath(x));
	// console.log("dfs: stack = "+starts);
    }
};

Maze.prototype.dfsPath = function(start, seen) {
    if (!start) start = 0;
    if (!seen) seen = {};
    var stack=[[-1, start]];
    while (stack.length > 0) {
	var x = stack.pop();
	if (seen[x[1]]) continue;
	seen[x[1]] = true;
	if (x[0] >= 0) this.openPassage(x[0], x[1]);
	Array.prototype.push.apply(
	    stack,
	    shuffle(this.neighbors(x[1]).map(function(x1){ return [x[1], x1]; })));
	// console.log("dfs: stack = "+stack);
	// console.log("dfs: x = "+x);

    }
};

Maze.prototype.dfsGraph = function(start, seen, minCycle) {
    if (!start) start = 0;
    if (!seen) seen = {};
    if (!minCycle) minCycle = 50;
    var cycles = 0;
    var stack=[[-1, start, 1]]; // previous cell, current cell, current count.
    while (stack.length > 0) {
	var x = stack.pop();
	if (seen[x[1]]) {
	    var dist = Math.abs(seen[x[1]] - x[2]);
	    if (dist >= minCycle && randInt(minCycle) == 1) {
		cycles++;
		// console.log("creating loop "+cycles+" at "+x[0]+" and "+x[1]+", counts are "+seen[x[1]]+" and "+x[2]+", dist = "+dist);
		this.openPassage(x[1],x[0]);
	    }
	    continue;
	}
	seen[x[1]] = x[2];
	if (x[0] >= 0) this.openPassage(x[0], x[1]);
	Array.prototype.push.apply(
	    stack,
	    shuffle(this.neighbors(x[1]).map(function(x1){ return [x[1], x1, x[2]+1]; })));
	// console.log("dfs: stack = "+stack);
	// console.log("dfs: x = "+x);

    }
};

Maze.prototype.neighborsInPath = function(x) {
    var w = this.w, h = this.h, m = this.m;
    var i = x % w, j = Math.floor(x / w);
    var ns = [];
    if (i > 0   && m[x] & 1)   ns.push(x-1);
    if (i < w-1 && m[x+1] & 1) ns.push(i+1+j*w);
    if (j > 0   && m[x] & 2)   ns.push(x-w);
    if (j < h-1 && m[x+w] & 2) ns.push(x+w);
    // console.log("neighborsInPath: maze = "+this+", x = "+x+", neighbors = "+ns);
    return ns;
};

Maze.prototype.draw = function (ctx) {
    ctx.fillStyle = WHITE;
    ctx.fillRect(0,0, this.w*CELL, this.h*CELL);
    ctx.strokeStyle = BLACK;
    ctx.strokeRect(0,0, this.w*CELL, this.h*CELL);
    var delay = parseFloat(document.getElementById("delay").value);
    var maze = this;
    var threadDelay = 50;
    this.dfs(function(x, i){
	maze.timeouts.push(
	    setTimeout(function(){
		// console.log("executing "+i+": "+x);
		maze.drawSquare(ctx, x, delay*.9);
	    }, ((i/threadDelay) + i%threadDelay)*1000*delay));
    });
};

Maze.prototype.drawSquare = function(ctx, x, delay) {
    // console.log(this);
    var w = this.w, h = this.h;
    var i = x % this.w;
    var j = Math.floor(x / w);
    // var x = i + maze.w * j;
    var mx = this.m[x];
    // console.log("drawing "+x);
    ctx.fillStyle = RED;
    ctx.fillRect( i*CELL, j*CELL, CELL, CELL);
    var maze = this;
    maze.timeouts.push(
	setTimeout(function() {
	    // console.log("drew "+x);
	    ctx.fillStyle = WHITE;
	    ctx.fillRect( i*CELL, j*CELL, CELL, CELL);

	    ctx.save();
	    // do this for smooth walls, we don't want the white
	    // vertical lines to overwrite the dark horizontal lines
	    // or vice versa.
	    ctx.globalCompositeOperation="darken";

	    // console.log("drawing left side of "+mx+"="+(mx & 1?WHITE:BLACK) );
	    drawLine(ctx, i*CELL, j*CELL, 0, CELL,
		     (mx & 1)? WHITE: BLACK);

	    if (i < w-1) {
		// console.log("drawing right side of "+mx+" ("+maze.m[x+1]+") ="+(maze.m[x+1] & 1?WHITE:BLACK) );
		drawLine(ctx, (i+1)*CELL, j*CELL, 0, CELL,
			 (maze.m[x+1] & 1)? WHITE: BLACK);
	    }

	    // console.log("drawing top side of "+mx+"="+(mx & 2?WHITE:BLACK) );
	    drawLine(ctx, i*CELL, j*CELL, CELL, 0,
		     (mx & 2)? WHITE: BLACK);

	    if (j < h-1) {
		// console.log("drawing bottom side of "+x+" ("+maze.m[x+w]+") ="+(maze.m[x+w] & 1?WHITE:BLACK) );
		drawLine(ctx, i*CELL, (j+1)*CELL, CELL, 0,
			 (maze.m[x+w] & 2)? WHITE: BLACK);
	    }
	    ctx.restore();
	    // ctx.textBaseline="top";
	    // ctx.strokeText(mx, i*CELL, j*CELL);

	}, Math.round(delay*1000)  ));
};

Maze.prototype.redraw = function (ctx) {
    this.erase();
    this.strategy();
    this.draw(ctx);
};

var m;

function makeMaze() {
    var h = document.getElementById("height").value;
    var w = document.getElementById("width").value;
    // console.log("height "+h, "width "+w);
    m= new Maze(h,w);
    m.strategy();
    m.draw(ctx);
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function go() {
    makeMaze();
    scale();
}

function redraw() { m.redraw(ctx); }
function draw() { m.draw(ctx); }

function scale() {
    // see http://stackoverflow.com/a/5306929/268040
    if (window.devicePixelRatio > 1) {
	var canvasWidth = canvas.width;
	var canvasHeight = canvas.height;

	canvas.width = canvasWidth * window.devicePixelRatio;
	canvas.height = canvasHeight * window.devicePixelRatio;
	canvas.style.width = canvasWidth;
	canvas.style.height = canvasHeight;

	ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }
    redraw();
}
go();
<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const cookieParser = require('cookie-parser');
const session = require('express-session');
const fbRouting = require('./server/auth/utils/facebookTokens.js');
const modelRouting = require('./server/db/routing/config.js');
const cors = require('cors');
const passportConfig = require('./server/auth/passport.js');
require('dotenv').config();

passportConfig();
// INIT APP
const app = express();

//CORS config
let corsOption = {
  origin: true,
  methods: 'GET,HEAD,PUT,POST,DELETE',
  credentials: true,
  exposedHeaders: ['x-auth-token']
};
app.use(cors(corsOption));

// MIDDLEWARE
app.use(express.static((__dirname + '/client/public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

passport.use(new FacebookStrategy({
    clientID: process.env.FB_CLIENT_ID,
    clientSecret: process.env.FB_SECRET,
    callbackURL: "/auth/facebook/callback",
    profileFields: ['id', 'photos', 'emails', 'displayName']
  },
  function(accessToken, refreshToken, profile, cb) {
    console.log('AccessToken', accessToken);
    // TODO: Add CRUD database command here
    //                                   |
    //                                   v
    // User.findOrCreate({ facebookId: profile.id }, function (err, user) {
    //   return cb(err, user);
    // });
    return cb(null, profile)
  }
));

//Add ROUTES
app.use(fbRouting);
app.use(modelRouting);

// ROUTES
app.get('*', (req, res) => {
  res.send('Server is Running');
});
// CHECK PORT AND START SERVER
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log('SERVER STARTED: Listening on port:' + port);
});

module.exports = app;
<commit_msg>removed erroneous function from index.js<commit_after>const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const cookieParser = require('cookie-parser');
const session = require('express-session');
const fbRouting = require('./server/auth/utils/facebookTokens.js');
const modelRouting = require('./server/db/routing/config.js');
const cors = require('cors');
const passportConfig = require('./server/auth/passport.js');
require('dotenv').config();

passportConfig();
// INIT APP
const app = express();

//CORS config
let corsOption = {
  origin: true,
  methods: 'GET,HEAD,PUT,POST,DELETE',
  credentials: true,
  exposedHeaders: ['x-auth-token']
};
app.use(cors(corsOption));

// MIDDLEWARE
app.use(express.static((__dirname + '/client/public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//Add ROUTES
app.use(fbRouting);
app.use(modelRouting);

// ROUTES
app.get('*', (req, res) => {
  res.send('Server is Running');
});
// CHECK PORT AND START SERVER
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log('SERVER STARTED: Listening on port:' + port);
});

module.exports = app;
<|endoftext|>


<commit_before>const Telegraf = require('../')
const { Extra, Markup } = require('../')

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.use(Telegraf.log())

bot.command('onetime', (ctx) => {
  return ctx.reply('One time keyboard', Markup
    .keyboard([
      '/simple',
      '/inline',
      '/pyramid'
    ])
    .oneTime()
    .resize()
    .extra()
  )
})

bot.command('custom', (ctx) => {
  return ctx.reply('Custom buttons keyboard', Markup
    .keyboard([
      ['🔍 Search', '😎 Popular'], // Row1 with 2 button
      ['☸ Setting', '📞 Feedback'], // Row2 with 2 button
      ['📢 Ads', '⭐ Rate us', '👥 Share'] // Row3 with 3 button
    ])
    .oneTime()
    .resize()
    .extra()
  )
})

bot.command('special', (ctx) => {
  return ctx.reply('Special buttons keyboard', Extra.markup((markup) => {
    return markup.resize()
      .keyboard([
        markup.contactRequestButton('Send contact'),
        markup.locationRequestButton('Send location')
      ])
  }))
})

bot.command('pyramid', (ctx) => {
  return ctx.reply('Keyboard wrap', Extra.markup(
    Markup.keyboard(['one', 'two', 'three', 'four', 'five', 'six'], {
      wrap: (btn, index, currentRow) => currentRow.length >= (index + 1) / 2
    })
  ))
})

bot.command('simple', (ctx) => {
  return ctx.replyWithHTML('Coke or Pepsi?', Extra.markup(
    Markup.keyboard(['Coke', 'Pepsi'])
  ))
})

bot.command('inline', (ctx) => {
  return ctx.reply('Coke or Pepsi?', Extra.HTML().markup(
    Markup.inlineKeyboard([
      Markup.callbackButton('Coke', 'Coke'),
      Markup.callbackButton('Pepsi', 'Pepsi')
    ])))
})

bot.command('random', (ctx) => {
  return ctx.reply('random example',
    Markup.inlineKeyboard([
      Markup.urlButton('Coke', 'https://www.buzzfeed.com/chrisgeidner/conservative-lawyers-take-up-the-unexpected-opportunity-of-t'),
      Markup.callbackButton('Coke', 'Coke'),
      Markup.callbackButton('Dr Pepper', 'Dr Pepper', Math.random() > 0.5),
      Markup.callbackButton('Pepsi', 'Pepsi')
    ]).extra()
  )
})

bot.hears(/\/wrap (\d+)/, (ctx) => {
  return ctx.reply('Keyboard wrap', Extra.markup(
    Markup.keyboard(['one', 'two', 'three', 'four', 'five', 'six'], {
      columns: parseInt(ctx.match[1])
    })
  ))
})

bot.action('Dr Pepper', (ctx, next) => {
  return ctx.reply('👍').then(next)
})

bot.action(/.+/, (ctx) => {
  return ctx.answerCallbackQuery(`Oh, ${ctx.match[0]}! Great choise`)
})

bot.startPolling()
<commit_msg>update example<commit_after>const Telegraf = require('../')
const { Extra, Markup } = require('../')

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.use(Telegraf.log())

bot.command('onetime', (ctx) => {
  return ctx.reply('One time keyboard', Markup
    .keyboard([
      '/simple',
      '/inline',
      '/pyramid'
    ])
    .oneTime()
    .resize()
    .extra()
  )
})

bot.command('custom', (ctx) => {
  return ctx.reply('Custom buttons keyboard', Markup
    .keyboard([
      ['🔍 Search', '😎 Popular'], // Row1 with 2 button
      ['☸ Setting', '📞 Feedback'], // Row2 with 2 button
      ['📢 Ads', '⭐ Rate us', '👥 Share'] // Row3 with 3 button
    ])
    .oneTime()
    .resize()
    .extra()
  )
})

bot.command('special', (ctx) => {
  return ctx.reply('Special buttons keyboard', Extra.markup((markup) => {
    return markup.resize()
      .keyboard([
        markup.contactRequestButton('Send contact'),
        markup.locationRequestButton('Send location')
      ])
  }))
})

bot.command('pyramid', (ctx) => {
  return ctx.reply('Keyboard wrap', Extra.markup(
    Markup.keyboard(['one', 'two', 'three', 'four', 'five', 'six'], {
      wrap: (btn, index, currentRow) => currentRow.length >= (index + 1) / 2
    })
  ))
})

bot.command('simple', (ctx) => {
  return ctx.replyWithHTML('Coke or Pepsi?', Extra.markup(
    Markup.keyboard(['Coke', 'Pepsi'])
  ))
})

bot.command('inline', (ctx) => {
  return ctx.reply('Coke or Pepsi?', Extra.HTML().markup(
    Markup.inlineKeyboard([
      Markup.callbackButton('Coke', 'Coke'),
      Markup.callbackButton('Pepsi', 'Pepsi')
    ])))
})

bot.command('random', (ctx) => {
  return ctx.reply('random example',
    Markup.inlineKeyboard([
      Markup.callbackButton('Coke', 'Coke'),
      Markup.callbackButton('Dr Pepper', 'Dr Pepper', Math.random() > 0.5),
      Markup.callbackButton('Pepsi', 'Pepsi')
    ]).extra()
  )
})

bot.hears(/\/wrap (\d+)/, (ctx) => {
  return ctx.reply('Keyboard wrap', Extra.markup(
    Markup.keyboard(['one', 'two', 'three', 'four', 'five', 'six'], {
      columns: parseInt(ctx.match[1])
    })
  ))
})

bot.action('Dr Pepper', (ctx, next) => {
  return ctx.reply('👍').then(next)
})

bot.action(/.+/, (ctx) => {
  return ctx.answerCallbackQuery(`Oh, ${ctx.match[0]}! Great choise`)
})

bot.startPolling()
<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var net = require('net');
var cbt = require('pelger-cbt')();
var _ = require('underscore');

/**
 * nfd client sdk
 */
module.exports = function() {
  var _client;
  var _stdoutCb;
  var _stderrCb;
  var doc = '';

  var token = function(token, cb) {
    cbt.trackById('token ' + token, cb);
    _client.write('token ' + token + '\n');
  };

  var connect = function(options, cb) {
    _client = net.connect(options, function() {
      if (options.token) {
        token(options.token, function() {
          cb();
        });
      } else {
        cb();
      }
    });

    _client.on('data', function(data) {
      var str = data.toString('utf8');
      var lines;
      var callback;
      var json;

      doc += str;
      lines = doc.split('\n');
      _.each(lines, function(line) {
        if (line.length > 0) {
          try {
            json = JSON.parse(line);
            if (json.responseType === 'stdout') {
              if (_stdoutCb) {
                _stdoutCb(json);
              }
            }
            else if (json.responseType === 'stderr') {
              if (_stderrCb) {
                _stderrCb(json);
              }
            }
            else if (json.responseType === 'response') {
              callback = cbt.fetch(json.request);
              callback(json.response);
            }
            doc = '';
          }
          catch (e) {
            // parse failed doc incomplete swallow exception
          }
        }
      });
    });

    _client.on('end', function() {
    });
  };

  var login = function(username, password, cb) {
    cbt.trackById('login ' + username, cb);
    _client.write('login ' + username + ' ' + password + '\n');
  };

  var githublogin = function(accessToken, cb) {
    cbt.trackById('githublogin', cb);
    _client.write('githublogin ' + accessToken + '\n');
  };

  var listSystems = function(cb) {
    cbt.trackById('list systems', cb);
    _client.write('list systems\n');
  };

  var createSystem = function(name, namespace, cb) {
    cbt.trackById('create system', cb);
    _client.write('create system ' + name + ' ' + namespace + '\n');
  };

  var getSystem = function(systemId, cb) {
    cbt.trackById('get system', cb);
    _client.write('get system ' + systemId + '\n');
  };

  var getDeployed = function(systemId, cb) {
    cbt.trackById('get deployed', cb);
    _client.write('get deployed ' + systemId + '\n');
  };

  var deleteSystem = function(systemId, cb) {
    cbt.trackById('delete system', cb);
    _client.write('delete system ' + systemId + '\n');
  };

  var putSystem = function(systemJson, cb) {
    cbt.trackById('put system', cb);
    _client.write('put system ' + '\n');
    _client.write(systemJson + '\n');
    _client.write('END\n');
  };

  var listContainers = function(systemId, cb) {
    cbt.trackById('list containers', cb);
    _client.write('list containers ' + systemId + '\n');
  };

  var addContainer = function(systemId, containerJson, cb) {
    cbt.trackById('add container', cb);
    _client.write('add container ' + systemId + '\n');
    _client.write(containerJson + '\n');
    _client.write('END\n');
  };

  var putContainer = function(systemId, containerJson, cb) {
    cbt.trackById('put container', cb);
    _client.write('put container ' + systemId + '\n');
    _client.write(containerJson + '\n');
    _client.write('END\n');
  };

  var deleteContainer = function(systemId, containerId, cb) {
    cbt.trackById('delete container', cb);
    _client.write('delete container ' + systemId + ' ' + containerId + '\n');
  };

  var buildContainer = function(systemId, containerId, cb) {
    cbt.trackById('build container', cb);
    _client.write('build container ' + systemId + ' ' + containerId + '\n');
  };

  var deploySystem = function(systemId, revisionId, cb) {
    cbt.trackById('deploy system', cb);
    _client.write('deploy system ' + systemId + ' ' + revisionId + '\n');
  };

  var previewSystemDeploy = function(systemId, revisionId, cb) {
    cbt.trackById('preview system', cb);
    _client.write('preview system ' + systemId + ' ' + revisionId + '\n');
  };

  var deployAll = function(systemId, revisionId, cb) {
    cbt.trackById('deploy all', cb);
    _client.write('deploy all ' + systemId + ' ' + revisionId + '\n');
  };

  var listRevisions = function(systemId, cb) {
    cbt.trackById('list revisions', cb);
    _client.write('list revisions ' + systemId + '\n');
  };

  var getRevision = function(systemId, revisionId, cb) {
    cbt.trackById('get revision', cb);
    _client.write('get revision ' + systemId + ' ' + revisionId + '\n');
  };

  var timeline = function(systemId, containerId, cb) {
    cbt.trackById('list timeline', cb);
    _client.write('list timeline ' + systemId + ' ' + containerId + ' ' + '\n');
  };

  var addToTimeline = function(timelineJson, cb) {
    cbt.trackById('add timeline', cb);
    _client.write('add timeline\n');
    _client.write(timelineJson + '\n');
    _client.write('END\n');
  };

  var quit = function(cb) {
    cbt.trackById('quit', cb);
    _client.write('quit\n');
  };

  var ioHandlers = function(stdoutCb, stderrCb) {
    _stdoutCb = stdoutCb;
    _stderrCb = stderrCb;
  };

  return {
    connect: connect,
    login: login,
    githublogin: githublogin,
    token: token,
    quit: quit,
    createSystem: createSystem,
    listSystems: listSystems,
    getSystem: getSystem,
    getDeployed: getDeployed,
    putSystem: putSystem,
    deleteSystem: deleteSystem,

    putContainer: putContainer,
    deleteContainer: deleteContainer,
    addContainer: addContainer,
    listContainers: listContainers,
    buildContainer: buildContainer,
    deploySystem: deploySystem,
    previewSystemDeploy: previewSystemDeploy,
    deployAll: deployAll,
    ioHandlers: ioHandlers,

    listRevisions: listRevisions,
    getRevision: getRevision,

    timeline: timeline,
    addToTimeline: addToTimeline
  };
};

<commit_msg>git integration<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var net = require('net');
var cbt = require('pelger-cbt')();
var _ = require('underscore');

/**
 * nfd client sdk
 */
module.exports = function() {
  var _client;
  var _stdoutCb;
  var _stderrCb;
  var doc = '';

  var token = function(token, cb) {
    cbt.trackById('token ' + token, cb);
    _client.write('token ' + token + '\n');
  };

  var connect = function(options, cb) {
    _client = net.connect(options, function() {
      if (options.token) {
        token(options.token, function() {
          cb();
        });
      } else {
        cb();
      }
    });

    _client.on('data', function(data) {
      var str = data.toString('utf8');
      var lines;
      var callback;
      var json;

      doc += str;
      lines = doc.split('\n');
      _.each(lines, function(line) {
        if (line.length > 0) {
          try {
            json = JSON.parse(line);
            if (json.responseType === 'stdout') {
              if (_stdoutCb) {
                _stdoutCb(json);
              }
            }
            else if (json.responseType === 'stderr') {
              if (_stderrCb) {
                _stderrCb(json);
              }
            }
            else if (json.responseType === 'response') {
              callback = cbt.fetch(json.request);
              callback(json.response);
            }
            doc = '';
          }
          catch (e) {
            // parse failed doc incomplete swallow exception
          }
        }
      });
    });

    _client.on('end', function() {
    });
  };

  var login = function(username, password, cb) {
    cbt.trackById('login ' + username, cb);
    _client.write('login ' + username + ' ' + password + '\n');
  };

  var githublogin = function(accessToken, cb) {
    cbt.trackById('githublogin', cb);
    _client.write('githublogin ' + accessToken + '\n');
  };

  var listSystems = function(cb) {
    cbt.trackById('list systems', cb);
    _client.write('list systems\n');
  };

  var createSystem = function(name, namespace, cb) {
    cbt.trackById('create system', cb);
    _client.write('create system ' + name + ' ' + namespace + '\n');
  };

  var cloneSystem = function(url, cb) {
    cbt.trackById('clone system', cb);
    _client.write('clone system ' + url + '\n');
  };

  var addRemote = function(systemId, url, cb) {
    cbt.trackById('add remote', cb);
    _client.write('add remote ' + systemId + ' ' + url + '\n');
  };

  var getSystem = function(systemId, cb) {
    cbt.trackById('get system', cb);
    _client.write('get system ' + systemId + '\n');
  };

  var syncSystem = function(systemId, cb) {
    cbt.trackById('sync system', cb);
    _client.write('sync system ' + systemId + '\n');
  };

  var getDeployed = function(systemId, cb) {
    cbt.trackById('get deployed', cb);
    _client.write('get deployed ' + systemId + '\n');
  };

  var deleteSystem = function(systemId, cb) {
    cbt.trackById('delete system', cb);
    _client.write('delete system ' + systemId + '\n');
  };

  var putSystem = function(systemJson, cb) {
    cbt.trackById('put system', cb);
    _client.write('put system ' + '\n');
    _client.write(systemJson + '\n');
    _client.write('END\n');
  };

  var listContainers = function(systemId, cb) {
    cbt.trackById('list containers', cb);
    _client.write('list containers ' + systemId + '\n');
  };

  var addContainer = function(systemId, containerJson, cb) {
    cbt.trackById('add container', cb);
    _client.write('add container ' + systemId + '\n');
    _client.write(containerJson + '\n');
    _client.write('END\n');
  };

  var putContainer = function(systemId, containerJson, cb) {
    cbt.trackById('put container', cb);
    _client.write('put container ' + systemId + '\n');
    _client.write(containerJson + '\n');
    _client.write('END\n');
  };

  var deleteContainer = function(systemId, containerId, cb) {
    cbt.trackById('delete container', cb);
    _client.write('delete container ' + systemId + ' ' + containerId + '\n');
  };

  var buildContainer = function(systemId, containerId, cb) {
    cbt.trackById('build container', cb);
    _client.write('build container ' + systemId + ' ' + containerId + '\n');
  };

  var deploySystem = function(systemId, revisionId, cb) {
    cbt.trackById('deploy system', cb);
    _client.write('deploy system ' + systemId + ' ' + revisionId + '\n');
  };

  var previewSystemDeploy = function(systemId, revisionId, cb) {
    cbt.trackById('preview system', cb);
    _client.write('preview system ' + systemId + ' ' + revisionId + '\n');
  };

  var deployAll = function(systemId, revisionId, cb) {
    cbt.trackById('deploy all', cb);
    _client.write('deploy all ' + systemId + ' ' + revisionId + '\n');
  };

  var listRevisions = function(systemId, cb) {
    cbt.trackById('list revisions', cb);
    _client.write('list revisions ' + systemId + '\n');
  };

  var getRevision = function(systemId, revisionId, cb) {
    cbt.trackById('get revision', cb);
    _client.write('get revision ' + systemId + ' ' + revisionId + '\n');
  };

  var timeline = function(systemId, cb) {
    cbt.trackById('list timeline', cb);
    _client.write('list timeline ' + systemId + '\n');
  };

  var addToTimeline = function(timelineJson, cb) {
    cbt.trackById('add timeline', cb);
    _client.write('add timeline\n');
    _client.write(timelineJson + '\n');
    _client.write('END\n');
  };

  var quit = function(cb) {
    cbt.trackById('quit', cb);
    _client.write('quit\n');
  };

  var ioHandlers = function(stdoutCb, stderrCb) {
    _stdoutCb = stdoutCb;
    _stderrCb = stderrCb;
  };

  return {
    connect: connect,
    login: login,
    githublogin: githublogin,
    token: token,
    quit: quit,
    createSystem: createSystem,
    cloneSystem: cloneSystem,
    addRemote: addRemote,
    listSystems: listSystems,
    getSystem: getSystem,
    syncSystem: syncSystem,
    getDeployed: getDeployed,
    putSystem: putSystem,
    deleteSystem: deleteSystem,

    putContainer: putContainer,
    deleteContainer: deleteContainer,
    addContainer: addContainer,
    listContainers: listContainers,
    buildContainer: buildContainer,
    deploySystem: deploySystem,
    previewSystemDeploy: previewSystemDeploy,
    deployAll: deployAll,
    ioHandlers: ioHandlers,

    listRevisions: listRevisions,
    getRevision: getRevision,

    timeline: timeline,
    addToTimeline: addToTimeline
  };
};

<|endoftext|>


<commit_before><commit_msg>Added check to see if we need to call init<commit_after><|endoftext|>


<commit_before>'use strict';

const moment = require('moment');
const inherits = require('util').inherits;
const Router = require('./index');
const middleware = require('storj-service-middleware');
const errors = require('storj-service-error-types');

function PaymentProcessorsRouter(options) {
  if (!(this instanceof PaymentProcessorsRouter)) {
    return new PaymentProcessorsRouter(options);
  }

  Router.apply(this, arguments);

  this.models = options.storage.models;
  this.authenticate = middleware.authenticate(options.storage);
}

inherits(PaymentProcessorsRouter, Router);

PaymentProcessorsRouter.prototype.addPP = function(req, res, next) {
  console.log('hai', req.body);
  const PaymentProcessor = this.models.PaymentProcessor;

  const pp = new PaymentProcessor({
    user: req.user.id,
    name: req.body.processor.name,
    default: req.body.processor.default
  });

  pp.adapter
    .register(req.body.data, req.user.id)
    .then((result) => {
      console.log('result from pp', result);
      pp.data = result;
      pp.save()
        .then((pp) => {
          console.log('pppp', pp);
          res.status(200).send(pp.toObject());
        })
        .catch((err) => res.status(500).send(err));
    });
    // still need to convert user if successful
    // and then verify if there are more, and then addPaymentMethod if needed
};

PaymentProcessorsRouter.prototype.removePP = function(req, res, next) {

};

PaymentProcessorsRouter.prototype.getDefaultPP = function(req, res, next) {
  const PaymentProcessor = this.models.PaymentProcessor;

  PaymentProcessor
    .findOne({ user: req.user.id, default: true })
    .then((result) => res.status(200).send(result.toObject()))
    .catch((err) => res.status(500).send(err));
};

/**
 * Export definitions
 * @private
 */
PaymentProcessorsRouter.prototype._definitions = function() {
  return [
    ['POST', '/pp/add',
      this.authenticate,
      this.addPP
    ],
    ['POST','/pp/remove',
      this.authenticate,
      this.removePP
    ],
    ['GET', '/pp/default',
      this.authenticate,
      this.getDefaultPP
    ]
  ];
};

module.exports = PaymentProcessorsRouter;
<commit_msg>Change url and method name to be more descriptive for remove payment method; write more method<commit_after>'use strict';

const moment = require('moment');
const inherits = require('util').inherits;
const Router = require('./index');
const middleware = require('storj-service-middleware');
const errors = require('storj-service-error-types');
const Promise = require('bluebird');

function PaymentProcessorsRouter(options) {
  if (!(this instanceof PaymentProcessorsRouter)) {
    return new PaymentProcessorsRouter(options);
  }

  Router.apply(this, arguments);

  this.models = options.storage.models;
  this.authenticate = middleware.authenticate(options.storage);
}

inherits(PaymentProcessorsRouter, Router);

PaymentProcessorsRouter.prototype.addPP = function(req, res, next) {
  console.log('hai', req.body);
  const PaymentProcessor = this.models.PaymentProcessor;

  const pp = new PaymentProcessor({
    user: req.user.id,
    name: req.body.processor.name,
    default: req.body.processor.default
  });

  pp.adapter
    .register(req.body.data, req.user.id)
    .then((result) => {
      console.log('result from pp', result);
      pp.data = result;
      pp.save()
        .then((pp) => {
          console.log('pppp', pp);
          res.status(200).send(pp.toObject());
        })
        .catch((err) => res.status(500).send(err));
    });
    // still need to convert user if successful
    // and then verify if there are more, and then addPaymentMethod if needed
};

PaymentProcessorsRouter.prototype.removePaymentMethod = function(req, res, next) {
  const PaymentProcessor = this.models.PaymentProcessor;
  const User = this.models.User;
  const ppId = req.body.ppId;
  const methodId = req.body.methodId;

  Promise.coroutine(function* () {
    const currentPP = yield PaymentProcessor.findOne({ _id: ppId });

    if (pp.paymentMethods.length <= 0) {
      console.log('No payment methods to remove');
      return res.status(200).send(
        `No payment processor with ${ppId} id`
      );
    }

    yield pp.adapter.removePaymentMethod(methodId)

    const user = req.user;
    user.isFreeTier = true;

    const savedUser = yield user.save();
    const newPP = yield PaymentProcessor.findOne({ _id: ppId });

    res.status(200).send({ user, pp: newPP });
  })().catch((err) => res.status(err.status || 500).send(err));

  // PaymentProcessor.findOne({ _id: ppId }).then((pp) => {
  //   if (pp.paymentMethods.length <= 0) {
  //     console.log('No payment methods to remove');
  //     return res.status(200).send(
  //       `No payment processor with ${ppId} id`
  //     );
  //   }
  //
  //   pp.adapter.removePaymentMethod(methodId).then(() => {
  //     const user = req.user;
  //     user.isFreeTier = true;
  //
  //     user.save()
  //       .then((user) => {
  //         res.status(200).send({ user }
  //     )})
  //       .catch((err) => res.status(err.status || 500).send(err));
  //   })
  //   .catch((err) => res.status(err.status || 500).send(err));
  // })
  // .catch((err) => res.status(err.status || 500).send(err));
};

PaymentProcessorsRouter.prototype.getDefaultPP = function(req, res, next) {
  const PaymentProcessor = this.models.PaymentProcessor;

  PaymentProcessor
    .findOne({ user: req.user.id, default: true })
    .then((result) => res.status(200).send(result.toObject()))
    .catch((err) => res.status(500).send(err));
};

/**
 * Export definitions
 * @private
 */
PaymentProcessorsRouter.prototype._definitions = function() {
  return [
    ['POST', '/pp/add',
      this.authenticate,
      this.addPP
    ],
    ['POST','/pp/method/remove',
      this.authenticate,
      this.removePaymentMethod
    ],
    ['GET', '/pp/default',
      this.authenticate,
      this.getDefaultPP
    ]
  ];
};

module.exports = PaymentProcessorsRouter;
<|endoftext|>


<commit_before>import _ from 'lodash';
import rq from 'request-promise';

const USERS = {
  '1': {
    name   : '佐々木 瞳',
    age    : 26,
    address: '港区',
    job    : '保育士',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/1.png'
  },
  '2': {
    name   : '山田 優',
    age    : 24,
    address: '杉並区',
    job    : '会社員',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/2.png'
  },
  '3': {
    name   : '山崎 愛',
    age    : 26,
    address: '目黒区',
    job    : 'ミュージシャン',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/3.png'
  },
  '4': {
    name   : '時田 みな',
    age    : 22,
    address: '新宿区',
    job    : '学生',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/4.png'
  },
  '5': {
    name   : '高田 まみ',
    age    : 27,
    address: '杉並区',
    job    : 'フリーター',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/5.png'
  },
  '6': {
    name   : '池田 百合',
    age    : 30,
    address: '千代田区',
    job    : 'OL',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/6.png'
  },
  '7': {
    name   : '篠田 ゆうこ',
    age    : 22,
    address: '横浜',
    job    : '専門学生',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/7.png'
  },
  '8': {
    name   : '笠井 枝理依',
    age    : 28,
    address: '新宿区',
    job    : '会社員',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/8.png'
  },
  '9': {
    name   : '横手 絵里子',
    age    : 27,
    address: '赤羽',
    job    : '事務',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/9.png'
  }
};

export default {
  getMatched(persona) {
    const options = {
      url: 'http://52.192.17.71/recommend/v1',
      qs : {
        user: persona
      },
      json: true
    };
    return rq(options)
    .then(({result}) => {
      console.log(result);
      return _.compact(_.sortByOrder(result.map(e => {
        const user = USERS[e.id];
        if (!user) {
          return null;
        }
        user.matched = e.distance;
        return user;
      }), 'matched', 'desc'));
    });
  }
};
<commit_msg>fix(recommend): バグとり<commit_after>import _ from 'lodash';
import rq from 'request-promise';

const USERS = {
  'akira': {
    name   : '佐々木 瞳',
    age    : 26,
    address: '港区',
    job    : '保育士',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/1.png'
  },
  'ami': {
    name   : '山田 優',
    age    : 24,
    address: '杉並区',
    job    : '会社員',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/2.png'
  },
  'ariana': {
    name   : '山崎 愛',
    age    : 26,
    address: '目黒区',
    job    : 'ミュージシャン',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/3.png'
  },
  'arison': {
    name   : '時田 みな',
    age    : 22,
    address: '新宿区',
    job    : '学生',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/4.png'
  },
  'gomaki': {
    name   : '高田 まみ',
    age    : 27,
    address: '杉並区',
    job    : 'フリーター',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/5.png'
  },
  'hirary': {
    name   : '池田 百合',
    age    : 30,
    address: '千代田区',
    job    : 'OL',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/6.png'
  },
  'kanako': {
    name   : '篠田 ゆうこ',
    age    : 22,
    address: '横浜',
    job    : '専門学生',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/7.png'
  },
  'love': {
    name   : '笠井 枝理依',
    age    : 28,
    address: '新宿区',
    job    : '会社員',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/8.png'
  },
  'taylor': {
    name   : '横手 絵里子',
    age    : 27,
    address: '赤羽',
    job    : '事務',
    image  : 'https://s3-ap-northeast-1.amazonaws.com/tc-hackathon-2015-kari/9.png'
  }
};

export default {
  getMatched(persona) {
    const options = {
      url: 'http://52.192.17.71/recommend/v1',
      qs : {
        user: JSON.stringify(persona)
      },
      json: true
    };
    return rq(options)
    .then(({result}) => {
      console.log(result);
      return _.compact(_.sortByOrder(result.map(e => {
        const user = USERS[e.id];
        if (!user) {
          return null;
        }
        user.matched = e.distance;
        return user;
      }), 'matched', 'desc')).slice(0, 4);
    });
  }
};
<|endoftext|>


<commit_before>import React from 'react'
import _ from 'lodash'
import Typeahead, {TypeaheadDefaultResult} from './core'

export default class CategoryTypeahead extends React.Component {

  static defaultProps = {
    onChooseResult: _.noop,
    itemComponent: TypeaheadDefaultResult,
    listComponent: CategoryResultList
  }

  constructor(props) {
    super(props)

  }

  render() {
    const ListComponent = this.props.listComponent || CategoryResultList
    return (
      <Typeahead
        {...this.props}
        ref="typeahead"
        listComponent={ListComponent}
        resultField={null} />
    )
  }

  clear() {
    this.refs.typeahead.clear()
  }

  hideResults() {
    this.refs.typeahead.hideResults()
  }
}

export class CategoryResultList extends React.Component {

  static propTypes = {
    results:        React.PropTypes.arrayOf(React.PropTypes.object),
    itemComponent:  React.PropTypes.element,
    onChooseResult: React.PropTypes.func
  }

  static defaultProps = {
    results:        [],
    itemComponent:  TypeaheadDefaultResult,
    onChooseResult: _.noop
  }

  render() {
    const { results, itemComponent, onChooseResult } = this.props
    const clickHandler = (r, e) => {
      e.preventDefault()
      e.stopPropagation()
      onChooseResult(r)
    }
    return (

        {_.flatMap(results, (group, name) => {
          return [

{name}
,
            ..._.map(group, item => {
              return React.createElement(itemComponent, { type: name, result: item, onClick: _.partial(clickHandler, item) })
            })
          ]
        })}

    )
  }

}
<commit_msg>Pass item type to Category Typeahead callbacks<commit_after>import React from 'react'
import _ from 'lodash'
import Typeahead, {TypeaheadDefaultResult} from './core'

export default class CategoryTypeahead extends React.Component {

  static defaultProps = {
    onChooseResult: _.noop,
    itemComponent: TypeaheadDefaultResult,
    listComponent: CategoryResultList
  }

  constructor(props) {
    super(props)

  }

  render() {
    const ListComponent = this.props.listComponent || CategoryResultList
    return (
      <Typeahead
        {...this.props}
        ref="typeahead"
        listComponent={ListComponent}
        resultField={null} />
    )
  }

  clear() {
    this.refs.typeahead.clear()
  }

  hideResults() {
    this.refs.typeahead.hideResults()
  }
}

export class CategoryResultList extends React.Component {

  static propTypes = {
    results:        React.PropTypes.arrayOf(React.PropTypes.object),
    itemComponent:  React.PropTypes.element,
    onChooseResult: React.PropTypes.func
  }

  static defaultProps = {
    results:        [],
    itemComponent:  TypeaheadDefaultResult,
    onChooseResult: _.noop
  }

  render() {
    const { results, itemComponent, onChooseResult } = this.props
    const clickHandler = (r, t, e) => {
      e.preventDefault()
      e.stopPropagation()
      onChooseResult(r, t)
    }
    return (

        {_.flatMap(results, (group, name) => {
          return [

{name}
,
            ..._.map(group, item => {
              return React.createElement(itemComponent, { type: name, result: item, onClick: _.partial(clickHandler, item, name) })
            })
          ]
        })}

    )
  }

}
<|endoftext|>


<commit_before>/*! Image Zoom - v1
 *  Copyright (c) 2016 Mattias Hinderson
 *  License: MIT
 */

(function (window, factory) {
    'use strict';

    if (typeof define == 'function' && define.amd) {
        // AMD
        define([
            './utils',
            './pubsub'
        ], function(utils, pubsub) {
            return factory(window, utils, pubsub);
        });
    } else if (typeof exports == 'object') {
        // CommonJS
        module.exports = factory(
            window,
            require('./utils'),
            require('./pubsub')
        );
    }

}(window, function factory (window, utils, pubsub) {
    'use strict';

    // Constants
    var OFFSET = 60;

    // Cached values
    var cache = {
        ticking: false,
        lastScrollY: window.pageYOffset,
        viewportWidth: window.innerWidth,
        viewportHeight: window.innerHeight
    };

    // Window events
    var resizeEvent = utils.debounce(function ( ) {
    	cache.viewportWidth = window.innerWidth;
    	cache.viewportHeight = window.innerHeight;
        cache.lastScrollY = window.pageYOffset;
    }, 250);

    var scrollEvent = function ( ) {
    	var requestTick = function ( ) {
            cache.lastScrollY = window.pageYOffset;

    		// Stop ticking
    		cache.ticking = false;
    	};

    	if (!cache.ticking) {
    		utils.requestAnimFrame.call(window, requestTick);
    		cache.ticking = true;
    	}
    };

    window.addEventListener('resize', resizeEvent);
    window.addEventListener('scroll', scrollEvent);

    // Performance helpers
    var hintBrowser = function ( ) {
        this.style.willChange = 'transform';
    };

    var removeHint = function ( ) {
        this.removeEventListener(transitionEvent, removeHint);
	    this.style.willChange = 'auto';
    };

    // Transition event helper
    var transitionEvent = utils.whichTransitionEvent();

    function calculateZoom (imageRect, thumbRect) {
        var highResImageWidth = imageRect.width;
        var highResImageHeight = imageRect.height;

        var viewportHeight = cache.viewportHeight - OFFSET;
        var viewportWidth  = cache.viewportWidth - OFFSET;

        var maxScaleFactor = highResImageWidth / thumbRect.width;

        var imageAspectRatio = thumbRect.width / thumbRect.height;
        var viewPortAspectRatio = viewportWidth / viewportHeight;

        var imgScaleFactor;
        if (highResImageWidth < viewportWidth && highResImageHeight < viewportHeight) {
            imgScaleFactor = maxScaleFactor;
        } else if (imageAspectRatio < viewPortAspectRatio) {
            imgScaleFactor = (viewportHeight / highResImageHeight) * maxScaleFactor;
        } else {
            imgScaleFactor = (viewportWidth / highResImageWidth) * maxScaleFactor;
        }

        return imgScaleFactor;
    }

    function zoomOut (e) {
        var container = (e && e.delegateTarget) ? e.delegateTarget : document.querySelector('[data-zoomable].is-zoomed');
        if (!container) { return; }

        pubsub.publish('zoomOutStart', container);

        // Reset transforms
        utils.requestAnimFrame.call(window, function ( ) {
            container.classList.remove('is-zoomed');
            container.style.msTransform = '';
            container.style.webkitTransform = '';
            container.style.transform = '';
        });

        // Wait for transition to end
        container.addEventListener(transitionEvent, function resetImage ( ) {
            container.removeEventListener(transitionEvent, resetImage);
            container.classList.remove('is-active');
            pubsub.publish('zoomOutEnd', container);
        });

        container.addEventListener(transitionEvent, removeHint);
    }

    function zoomIn (e) {
        var container = e.delegateTarget;
        var image = e.target;
        var thumbRect = image.getBoundingClientRect();
        var imageRect = {
            width: container.getAttribute('data-width'),
            height: container.getAttribute('data-height'),
        };

        pubsub.publish('zoomInStart', container);

        container.classList.add('is-active');

        // Force repaint
        var repaint = image.offsetWidth;

        // Calculate offset
        var viewportY = cache.viewportHeight / 2;
        var viewportX = cache.viewportWidth / 2;
        var imageCenterY = thumbRect.top + (thumbRect.height / 2);
        var imageCenterX = thumbRect.left + (thumbRect.width / 2);
        var translate = 'translate3d(' + (viewportX - imageCenterX) + 'px, ' + (viewportY - imageCenterY) + 'px, 0)';

        // Calculate scale ratio
        var scale = 'scale(' + calculateZoom(imageRect, thumbRect) + ')';

        // Apply transforms
        utils.requestAnimFrame.call(window, function ( ) {
            container.classList.add('is-zooming');

            // Set explicit dimensions to avoid max-width issues
            image.setAttribute('width', imageRect.width);
            image.setAttribute('height', imageRect.height);

            container.style.msTransform = translate + ' ' + scale;
            container.style.webkitTransform = translate + ' ' + scale;
            container.style.transform = translate + ' ' + scale;
        });

        // Events
        window.addEventListener('keydown', function keysPressed (e) {
            e = e || window.event;

            if (e.which === 27 || e.keyCode === 27) {
                zoomOut();
                window.removeEventListener('keydown', keysPressed);
            }
        });

        // Wait for transition to end
        container.addEventListener(transitionEvent, function activateImage ( ) {
            container.removeEventListener(transitionEvent, activateImage);

            container.classList.remove('is-zooming');
            container.classList.add('is-zoomed');

            pubsub.publish('zoomInEnd', container);

            // Load high-res image
            if (image.hasAttribute('srcset')) {
                image.removeAttribute('srcset');
            }
            if (image.hasAttribute('sizes')) {
                image.removeAttribute('sizes');
            }
            image.src = container.getAttribute('href');
            pubsub.publish('imageLoaded', image);
        });
    }

    var toggleZoom = function (e) {
        e.preventDefault();

        if (e.delegateTarget.classList.contains('is-zoomed')) {
            zoomOut(e);
        } else {
            zoomIn(e);
        }
    };

    function ImageZoom (elems, options) {
        if (!elems) return;

        // Update default options
        if (options) {
            OFFSET = options.offset;
        }

        // Export event emitter
        this.on = pubsub.subscribe;

        // Attach click event listeners to all provided elems
        var bindLink = function (elem) {
            elem.addEventListener('click', utils.delegate(utils.criteria.hasAttribute('data-zoomable'), toggleZoom));
            elem.addEventListener('mouseenter', hintBrowser);
        };

        // Accepts both a single node and a NodeList
        if (elems.length) {
            utils.forEach(elems, function (index, elem) {
                bindLink(elem);
            });
        } else {
            bindLink(elems);
        }
    }

	// Expose to interface
	if (typeof module === 'object' && typeof module.exports === 'object') {
		// CommonJS, just export
		module.exports = ImageZoom;
	} else if (typeof define === 'function' && define.amd) {
		// AMD support
		define('ImageZoom', function ( ) { return ImageZoom; } );
	}

}));
<commit_msg>Replace src attribute before removing redundant srcset and sizes attributes<commit_after>/*! Image Zoom - v1
 *  Copyright (c) 2016 Mattias Hinderson
 *  License: MIT
 */

(function (window, factory) {
    'use strict';

    if (typeof define == 'function' && define.amd) {
        // AMD
        define([
            './utils',
            './pubsub'
        ], function(utils, pubsub) {
            return factory(window, utils, pubsub);
        });
    } else if (typeof exports == 'object') {
        // CommonJS
        module.exports = factory(
            window,
            require('./utils'),
            require('./pubsub')
        );
    }

}(window, function factory (window, utils, pubsub) {
    'use strict';

    // Constants
    var OFFSET = 60;

    // Cached values
    var cache = {
        ticking: false,
        lastScrollY: window.pageYOffset,
        viewportWidth: window.innerWidth,
        viewportHeight: window.innerHeight
    };

    // Window events
    var resizeEvent = utils.debounce(function ( ) {
    	cache.viewportWidth = window.innerWidth;
    	cache.viewportHeight = window.innerHeight;
        cache.lastScrollY = window.pageYOffset;
    }, 250);

    var scrollEvent = function ( ) {
    	var requestTick = function ( ) {
            cache.lastScrollY = window.pageYOffset;

    		// Stop ticking
    		cache.ticking = false;
    	};

    	if (!cache.ticking) {
    		utils.requestAnimFrame.call(window, requestTick);
    		cache.ticking = true;
    	}
    };

    window.addEventListener('resize', resizeEvent);
    window.addEventListener('scroll', scrollEvent);

    // Performance helpers
    var hintBrowser = function ( ) {
        this.style.willChange = 'transform';
    };

    var removeHint = function ( ) {
        this.removeEventListener(transitionEvent, removeHint);
	    this.style.willChange = 'auto';
    };

    // Transition event helper
    var transitionEvent = utils.whichTransitionEvent();

    function calculateZoom (imageRect, thumbRect) {
        var highResImageWidth = imageRect.width;
        var highResImageHeight = imageRect.height;

        var viewportHeight = cache.viewportHeight - OFFSET;
        var viewportWidth  = cache.viewportWidth - OFFSET;

        var maxScaleFactor = highResImageWidth / thumbRect.width;

        var imageAspectRatio = thumbRect.width / thumbRect.height;
        var viewPortAspectRatio = viewportWidth / viewportHeight;

        var imgScaleFactor;
        if (highResImageWidth < viewportWidth && highResImageHeight < viewportHeight) {
            imgScaleFactor = maxScaleFactor;
        } else if (imageAspectRatio < viewPortAspectRatio) {
            imgScaleFactor = (viewportHeight / highResImageHeight) * maxScaleFactor;
        } else {
            imgScaleFactor = (viewportWidth / highResImageWidth) * maxScaleFactor;
        }

        return imgScaleFactor;
    }

    function zoomOut (e) {
        var container = (e && e.delegateTarget) ? e.delegateTarget : document.querySelector('[data-zoomable].is-zoomed');
        if (!container) { return; }

        pubsub.publish('zoomOutStart', container);

        // Reset transforms
        utils.requestAnimFrame.call(window, function ( ) {
            container.classList.remove('is-zoomed');
            container.style.msTransform = '';
            container.style.webkitTransform = '';
            container.style.transform = '';
        });

        // Wait for transition to end
        container.addEventListener(transitionEvent, function resetImage ( ) {
            container.removeEventListener(transitionEvent, resetImage);
            container.classList.remove('is-active');
            pubsub.publish('zoomOutEnd', container);
        });

        container.addEventListener(transitionEvent, removeHint);
    }

    function zoomIn (e) {
        var container = e.delegateTarget;
        var image = e.target;
        var thumbRect = image.getBoundingClientRect();
        var imageRect = {
            width: container.getAttribute('data-width'),
            height: container.getAttribute('data-height'),
        };

        pubsub.publish('zoomInStart', container);

        container.classList.add('is-active');

        // Force repaint
        var repaint = image.offsetWidth;

        // Calculate offset
        var viewportY = cache.viewportHeight / 2;
        var viewportX = cache.viewportWidth / 2;
        var imageCenterY = thumbRect.top + (thumbRect.height / 2);
        var imageCenterX = thumbRect.left + (thumbRect.width / 2);
        var translate = 'translate3d(' + (viewportX - imageCenterX) + 'px, ' + (viewportY - imageCenterY) + 'px, 0)';

        // Calculate scale ratio
        var scale = 'scale(' + calculateZoom(imageRect, thumbRect) + ')';

        // Apply transforms
        utils.requestAnimFrame.call(window, function ( ) {
            container.classList.add('is-zooming');

            // Set explicit dimensions to avoid max-width issues
            image.setAttribute('width', imageRect.width);
            image.setAttribute('height', imageRect.height);

            container.style.msTransform = translate + ' ' + scale;
            container.style.webkitTransform = translate + ' ' + scale;
            container.style.transform = translate + ' ' + scale;
        });

        // Events
        window.addEventListener('keydown', function keysPressed (e) {
            e = e || window.event;

            if (e.which === 27 || e.keyCode === 27) {
                zoomOut();
                window.removeEventListener('keydown', keysPressed);
            }
        });

        // Wait for transition to end
        container.addEventListener(transitionEvent, function activateImage ( ) {
            container.removeEventListener(transitionEvent, activateImage);

            container.classList.remove('is-zooming');
            container.classList.add('is-zoomed');

            pubsub.publish('zoomInEnd', container);

            // Load high-res image
            image.src = container.getAttribute('href');

            // Remove redundant attributes
            if (image.hasAttribute('srcset')) {
                image.removeAttribute('srcset');
            }
            if (image.hasAttribute('sizes')) {
                image.removeAttribute('sizes');
            }

            pubsub.publish('imageLoaded', image);
        });
    }

    var toggleZoom = function (e) {
        e.preventDefault();

        if (e.delegateTarget.classList.contains('is-zoomed')) {
            zoomOut(e);
        } else {
            zoomIn(e);
        }
    };

    function ImageZoom (elems, options) {
        if (!elems) return;

        // Update default options
        if (options) {
            OFFSET = options.offset;
        }

        // Export event emitter
        this.on = pubsub.subscribe;

        // Attach click event listeners to all provided elems
        var bindLink = function (elem) {
            elem.addEventListener('click', utils.delegate(utils.criteria.hasAttribute('data-zoomable'), toggleZoom));
            elem.addEventListener('mouseenter', hintBrowser);
        };

        // Accepts both a single node and a NodeList
        if (elems.length) {
            utils.forEach(elems, function (index, elem) {
                bindLink(elem);
            });
        } else {
            bindLink(elems);
        }
    }

	// Expose to interface
	if (typeof module === 'object' && typeof module.exports === 'object') {
		// CommonJS, just export
		module.exports = ImageZoom;
	} else if (typeof define === 'function' && define.amd) {
		// AMD support
		define('ImageZoom', function ( ) { return ImageZoom; } );
	}

}));
<|endoftext|>


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

var express = require('express');

var app = express();

app.get('/', function (req, res) {
	  res.send('Hello World!')
})

app.listen(3000, function () {
	  console.log('Example app listening on port 3000!')
})
<commit_msg>add deps<commit_after>#!/usr/bin/env node

var express = require('express');
var pug = require('pug');

var app = express();

app.get('/', function (req, res) {
	  res.send('Hello World!')
})

app.listen(3000, function () {
	  console.log('Example app listening on port 3000!')
})
<|endoftext|>


<commit_before><commit_msg>added the `buildPreviewURL` function for @tlovett1 to build out<commit_after>( function( window, Backbone, $, _, Scrivener, undefined ) {

	"use strict";
	var document = window.document;

	Scrivener.Models.Core = Backbone.Model.extend( {

		buildPreviewURL : function() {
			//
		}

	} );

} )( window, Backbone, jQuery, _, Scrivener);<|endoftext|>


<commit_before>console.log("Welcome to OpenZombie");

const gridSize = {x: 10, y: 10};
var gameTable = document.getElementById("gameTable");
var grid = [];

function initGrid (x, y) {
  var row;
  for (var i = 0; i < y; i++) {
    row = gameTable.insertRow(0);
    grid[i] = [];
    for (var j = 0; j < x; j++) {
      grid[i][j] = row.insertCell(-1);
    }
  }
}

initGrid(gridSize.x, gridSize.y);

console.log(grid);

class Entity {
	constructor(x,y) {
		this.x = x;
		this.y = y;
	}

	move(x, y) {
		this.x += x;
		this.y += y;
	}
}

class Player extends Entity {

}
<commit_msg>Added constructor<commit_after>console.log("Welcome to OpenZombie");

const gridSize = {x: 10, y: 10};
var gameTable = document.getElementById("gameTable");
var grid = [];

function initGrid (x, y) {
  var row;
  for (var i = 0; i < y; i++) {
    row = gameTable.insertRow(0);
    grid[i] = [];
    for (var j = 0; j < x; j++) {
      grid[i][j] = row.insertCell(-1);
    }
  }
}

initGrid(gridSize.x, gridSize.y);

console.log(grid);

class Entity {
	constructor(x,y) {
		this.x = x;
		this.y = y;
	}

	move(x, y) {
		this.x += x;
		this.y += y;
	}
}

class Player extends Entity {
	constructor(x,y) {
		super(x,y);
	}
}
<|endoftext|>


<commit_before>var h = require('hyperscript')
var u = require('./util')
var each = u.each
var find = u.find

function displayable (el) {
  return el.style.display !== 'none'
}

function toggle_focus(el) {
  if(el.style.display === 'none')
    focus(el)
  else
    blur(el)
}

function focus(el) {
  if(el.style.display !== 'flex') {
    el.style.display = 'flex'
    el.dispatchEvent(new CustomEvent('focus', {target: el}))
  }
}

function blur (el) {
  if(el.style.display !== 'none') {
    el.style.display = 'none'
    el.dispatchEvent(new CustomEvent('blur', {target: el}))
  }
}

function moveTo(el, list, i) {
  if(!list.children.length || i >= list.children.length)
    list.appendChild(el)
  else
    list.insertBefore(el, list.children[i])
}

module.exports = function (list, onSelect) {
  var menu = h('div.row.hypertabs__tabs')
  var selection

  function tab_button (el, onclick) {
    var link = h('a', {href: '#', onclick: function (ev) {
      if(ev.shiftKey) toggle_focus(el)
      else {
        each(list.children, function (tab) {
          if(tab == el) focus(tab)
          else blur(tab)
        })
      }
      ev.preventDefault()
      ev.stopPropagation()
    }}, el.title || el.id || el.tagName)
    var rm = h('a', {href: '#', onclick: function (ev) {
      el.parentNode.removeChild(el)
      menu.removeChild(wrap)
    }}, 'x')

    var wrap = h('div.hypertabs__tab', link, rm)

    function isSelected () {
      if(displayable(el))
        link.classList.add('hypertabs--selected')
      else
        link.classList.remove('hypertabs--selected')

      if(el.classList.contains('hypertabs--notify')) {
        link.classList.add('hypertabs--notify')
      } else
        link.classList.remove('hypertabs--notify')
    }

    new MutationObserver(function (changes) {
      if(el.title !== link.innerText)
        link.innerText = el.title || el.id || el.tagName
      isSelected()
      onSelect && onSelect()
    }).observe(el, {attributes: true, attributeFilter: ['title', 'style', 'class']})

    isSelected()
    wrap.follows = el
    return wrap
  }

  new MutationObserver(function (changes) {
    //iterate over the list, and check that menu is in same order,
    //add any which do not exist, remove any which no longer exist.

    //check if a tab represented by a menu item has been removed.
    each(menu.children, function (btn) {
      if(btn.follows.parentNode != list) {
        menu.removeChild(btn)
      }
    })

    //check if each thing in the list has a tab.
    each(list.children, function (tab, i) {
      var j
      if(menu.children[i] && menu.children[i].follows === tab) {
        //already set, and in correct place. do nothing
      } else if(~(j = find(menu, function (btn) { return btn.follows === tab }))) {
        moveTo(menu[j], list, i)
      } else {
        menu.appendChild(tab_button(tab))
      }
    })

  }).observe(list, {childList: true})
  return menu
}

<commit_msg>double check that unused tabs are removed<commit_after>var h = require('hyperscript')
var u = require('./util')
var each = u.each
var find = u.find

function displayable (el) {
  return el.style.display !== 'none'
}

function toggle_focus(el) {
  if(el.style.display === 'none')
    focus(el)
  else
    blur(el)
}

function focus(el) {
  if(el.style.display !== 'flex') {
    el.style.display = 'flex'
    el.dispatchEvent(new CustomEvent('focus', {target: el}))
  }
}

function blur (el) {
  if(el.style.display !== 'none') {
    el.style.display = 'none'
    el.dispatchEvent(new CustomEvent('blur', {target: el}))
  }
}

function moveTo(el, list, i) {
  if(!list.children.length || i >= list.children.length)
    list.appendChild(el)
  else
    list.insertBefore(el, list.children[i])
}

module.exports = function (list, onSelect) {
  var menu = h('div.row.hypertabs__tabs')
  var selection

  function tab_button (el, onclick) {
    var link = h('a', {href: '#', onclick: function (ev) {
      if(ev.shiftKey) toggle_focus(el)
      else {
        each(list.children, function (tab) {
          if(tab == el) focus(tab)
          else blur(tab)
        })
      }
      ev.preventDefault()
      ev.stopPropagation()
    }}, el.title || el.id || el.tagName)
    var rm = h('a', {href: '#', onclick: function (ev) {
      el.parentNode.removeChild(el)
      menu.removeChild(wrap)
    }}, 'x')

    var wrap = h('div.hypertabs__tab', link, rm)

    function isSelected () {
      if(displayable(el))
        link.classList.add('hypertabs--selected')
      else
        link.classList.remove('hypertabs--selected')

      if(el.classList.contains('hypertabs--notify')) {
        link.classList.add('hypertabs--notify')
      } else
        link.classList.remove('hypertabs--notify')
    }

    new MutationObserver(function (changes) {
      if(el.title !== link.innerText)
        link.innerText = el.title || el.id || el.tagName
      isSelected()
      onSelect && onSelect()
    }).observe(el, {attributes: true, attributeFilter: ['title', 'style', 'class']})

    isSelected()
    wrap.follows = el
    return wrap
  }

  new MutationObserver(function (changes) {
    //iterate over the list, and check that menu is in same order,
    //add any which do not exist, remove any which no longer exist.

    //check if a tab represented by a menu item has been removed.
    each(menu.children, function (btn) {
      if(btn.follows.parentNode != list) menu.removeChild(btn)
    })

    //check if each thing in the list has a tab.
    each(list.children, function (tab, i) {
      var j
      if(menu.children[i] && menu.children[i].follows === tab) {
        //already set, and in correct place. do nothing
      } else if(~(j = find(menu, function (btn) { return btn.follows === tab }))) {
        moveTo(menu[j], list, i)
      } else {
        menu.appendChild(tab_button(tab))
      }
    })

    //check if a tab represented by a menu item has been removed.
    each(menu.children, function (btn) {
      if(btn.follows.parentNode != list) menu.removeChild(btn)
    })

  }).observe(list, {childList: true})
  return menu
}

<|endoftext|>