<commit_before>define(['view',
        'render',
        'class'],
function(View, render, clazz) {

  // TODO: Implement support for effects.

  function Carousel(el, options) {
    options = options || {};
    Carousel.super_.call(this, el, options);
    this._listEl = this.el.find(options.listSelector || 'ul');
    this._itemSel = options.itemSelector || 'li';
    this._items = [];
    this._i = 0;

    var self = this;
    this.el.find('.next').on('click', function() {
      self._scrollto(self._i + 1, self._i);
      return false;
    });
    this.el.find('.prev').on('click', function() {
      self._scrollto(self._i - 1, self._i);
      return false;
    });

    this._listEl.on('click', function(e) {
      var iel = render.$(e.target).closest(self._itemSel);
      self.emit('click', iel, iel.index());
      iel.siblings().removeClass('active');
      iel.addClass('active');
      return false;
    });
  }
  clazz.inherits(Carousel, View);

  Carousel.prototype.item = function(el) {
    this._items.push(el);
    this._listEl.append(el);
    return this;
  };

  Carousel.prototype.active = function(i) {
    var iel = this._items[i];
    iel.siblings().removeClass('active');
    iel.addClass('active');
  }

  Carousel.prototype._scrollto = function(i, pi) {
    this._i = i;

    var pos = toFloat(this._listEl.position()['left'])
      , adj = this._adjustment(i, pi);

    if (adj === 0) return;

    var props = {};
    props['left'] = (pos + adj) + 'px';

    // TODO: Animate this transition.
    this._listEl.css(props);
  }

  Carousel.prototype._adjustment = function(i, pi) {
    var pitem = this._items[pi]
      , item = this._items[i]
      , ppos   = pitem.position()['left']
      , pos = item.position()['left'];

    // TODO: Implement center option.

    return ppos - pos;
  }

  function toFloat(val) {
    return parseFloat(val) || 0;
  };

  return Carousel;
});
<commit_msg>Guard against index out of bounds.<commit_after>define(['view',
        'render',
        'class'],
function(View, render, clazz) {

  // TODO: Implement support for effects.

  function Carousel(el, options) {
    options = options || {};
    Carousel.super_.call(this, el, options);
    this._listEl = this.el.find(options.listSelector || 'ul');
    this._itemSel = options.itemSelector || 'li';
    this._items = [];
    this._i = 0;

    var self = this;
    this.el.find('.next').on('click', function() {
      self._scrollto(self._i + 1, self._i);
      return false;
    });
    this.el.find('.prev').on('click', function() {
      self._scrollto(self._i - 1, self._i);
      return false;
    });

    this._listEl.on('click', function(e) {
      var iel = render.$(e.target).closest(self._itemSel);
      self.emit('click', iel, iel.index());
      iel.siblings().removeClass('active');
      iel.addClass('active');
      return false;
    });
  }
  clazz.inherits(Carousel, View);

  Carousel.prototype.item = function(el) {
    this._items.push(el);
    this._listEl.append(el);
    return this;
  };

  Carousel.prototype.active = function(i) {
    var iel = this._items[i];
    iel.siblings().removeClass('active');
    iel.addClass('active');
  }

  Carousel.prototype._scrollto = function(i, pi) {
    if (i < 0 || i >= this._items.length) return;

    this._i = i;
    var pos = toFloat(this._listEl.position()['left'])
      , adj = this._adjustment(i, pi);

    if (adj === 0) return;

    var props = {};
    props['left'] = (pos + adj) + 'px';

    // TODO: Animate this transition.
    this._listEl.css(props);
  }

  Carousel.prototype._adjustment = function(i, pi) {
    var pitem = this._items[pi]
      , item = this._items[i]
      , ppos   = pitem.position()['left']
      , pos = item.position()['left'];

    // TODO: Implement center option.

    return ppos - pos;
  }

  function toFloat(val) {
    return parseFloat(val) || 0;
  };

  return Carousel;
});
<|endoftext|>


<commit_before>'use strict'
const itoml = require('@iarna/toml')
const toml = require('toml')
const promisify = use('promisify')

const sync = {
  stringify: obj => {
    return itoml.stringify(obj)
  },
  parse: str => {
    try {
      return itoml.parse(str)
    } catch (_) {
      return toml.parse(str)
    }
  }
}

module.exports = {
  parse: promisify.args(sync.parse),
  stringify: promisify.args(sync.stringify),
  sync: sync
}
<commit_msg>toml: Only use my TOML<commit_after>'use strict'
const TOML = require('@iarna/toml')
const promisify = use('promisify')

module.exports = {
  parse: promisify.args(TOML.parse.async),
  stringify: promisify.args(TOML.stringify),
  sync: TOML
}
<|endoftext|>


<commit_before>// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// 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.

var request = require('request');

function NGALMClient() {
  this.sourceProperties = [
    {
      name: "ngalm_url",
      optional: false
    },
    {
      name: "client_id",
      optional: false
    },
    {
      name: "client_secret",
      optional: false
    }
  ];
  this.paramProperties = [
    {
      name: "color",
      optional: true
    },
    {
      name: "from",
      optional: false
    },
    {
      name: "message",
      optional: false
    },
    {
      name: "message_format",
      optional: true
    },
    {
      name: "notify",
      optional: true
    }
  ];
  this.validInput = true;
  this.failOnError = true;
}

NGALMClient.prototype.checkArgument = function (argumentName, argumentValue) {
  if (!argumentValue || argumentValue.length === 0) {
    console.error("Please provide a value for", argumentName);
    this.validInput = false;
  }
};

NGALMClient.prototype.connectALM = function (source, params, done) {
  //First auth so that we can perform API calls
  var requestUrl = '${source.ngalm_url}/authentication/sign_in',
    authBody = {
      client_id: source.client_id,
      client_secret: source.client_secret,
    },
    requestOptions = {
      url: requestUrl,
      method: "POST",
      json: authBody
    };

  request(requestOptions, (err, response) => {
    if (err || response.statusCode > 200) {
      return done(err || response.body)
    }

    //return done(err);
  });

  //Now let's create a CI server.  This is idempotent so we should be able to do it on every check
  var requestUrl = '${source.ngalm_url}/shared_spaces/1001/workspaces/1002/ci_servers',
    postBody = {
      instance_id: "0",
      name: "Concourse_test_sam",
      url: "http://192.168.1.100:3000",
      server_type: "Concourse server"
    },
    requestOptions = {
      url: requestUrl,
      method: "POST",
      json: {"data":[postBody]}
    };

  request(requestOptions, (err, response) => {
    if (err || response.statusCode > 200) {
      return done(err || response.body)
    }

    return done(err);
  });

};

NGALMClient.prototype.checkProperties = function (values, properties) {
  for (property of properties) {
    if (!property.optional) {
      this.checkArgument(property.name, values[property.name]);
    }
  }
};

NGALMClient.prototype.connect = function (source, params) {
  var self = this;
  if (source.fail_on_error === undefined) {
    source.fail_on_error = true;
  }

  self.failOnError = source.fail_on_error;
  self.validInput = true;

  self.checkProperties(source, this.sourceProperties);
  self.checkProperties(params, this.paramProperties);

  if (!self.validInput) {
    console.error("Please provide valid input and try again");
    return process.exit(1);
  }

  self.connectALM(source, params, (error, result) => {
    if (error) {
      console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
      console.error(error);
      if (self.failOnError) {
        process.exit(1);
      }
    }

    // Concourse expects this output from stdout, do not use console.dir
    console.log('this should work-printing out result');
    console.log(result);
    console.log(JSON.stringify({
      version: {
        ref: "none"
      }
    }));
    process.exit(0);
  });
}

module.exports = NGALMClient;<commit_msg>factoring out auth from server put<commit_after>// (c) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// 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.

var request = require('request');

function NGALMClient() {
  this.sourceProperties = [
    {
      name: "ngalm_url",
      optional: false
    },
    {
      name: "client_id",
      optional: false
    },
    {
      name: "client_secret",
      optional: false
    }
  ];
  this.paramProperties = [
    {
      name: "color",
      optional: true
    },
    {
      name: "from",
      optional: false
    },
    {
      name: "message",
      optional: false
    },
    {
      name: "message_format",
      optional: true
    },
    {
      name: "notify",
      optional: true
    }
  ];
  this.validInput = true;
  this.failOnError = true;
}

NGALMClient.prototype.checkArgument = function (argumentName, argumentValue) {
  if (!argumentValue || argumentValue.length === 0) {
    console.error("Please provide a value for", argumentName);
    this.validInput = false;
  }
};

NGALMClient.prototype.connectALM = function (source, params, done) {
  //First auth so that we can perform API calls
  var requestUrl = '${source.ngalm_url}/authentication/sign_in',
    authBody = {
      client_id: source.client_id,
      client_secret: source.client_secret,
    },
    requestOptions = {
      url: requestUrl,
      method: "POST",
      json: authBody
    };

  request(requestOptions, (err, response) => {
    if (err || response.statusCode > 200) {
      return done(err || response.body)
    }

    //return done(err);
  });

};

NGALMClient.prototype.pipelineVersion = function (source, params, done) {
//Now let's create a CI server.  This is idempotent so we should be able to do it on every check
var requestUrl = '${source.ngalm_url}/shared_spaces/1001/workspaces/1002/ci_servers',
  postBody = {
    instance_id: "0",
    name: "Concourse_test_sam",
    url: "http://192.168.1.100:3000",
    server_type: "Concourse server"
  },
  requestOptions = {
    url: requestUrl,
    method: "POST",
    json: {"data":[postBody]}
  };

request(requestOptions, (err, response) => {
  if (err || response.statusCode > 200) {
    return done(err || response.body)
  }

  return done(err);
});

};

NGALMClient.prototype.checkProperties = function (values, properties) {
  for (property of properties) {
    if (!property.optional) {
      this.checkArgument(property.name, values[property.name]);
    }
  }
};

NGALMClient.prototype.connect = function (source, params) {
  var self = this;
  if (source.fail_on_error === undefined) {
    source.fail_on_error = true;
  }

  self.failOnError = source.fail_on_error;
  self.validInput = true;

  self.checkProperties(source, this.sourceProperties);
  self.checkProperties(params, this.paramProperties);

  if (!self.validInput) {
    console.error("Please provide valid input and try again");
    return process.exit(1);
  }

  self.connectALM(source, params, (error, result) => {
    if (error) {
      console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
      console.error(error);
      if (self.failOnError) {
        process.exit(1);
      }
    }
  });
  self.pipelineVersion(source, params, (error, result) => {
  if (error) {
    console.error(`Error sending notification. Fail on error: ${self.failOnError}`);
    console.error(error);
    if (self.failOnError) {
      process.exit(1);
    }
  }
  // Concourse expects this output from stdout, do not use console.dir
  console.log('this should work-printing out result');
  console.log(result);
  console.log(JSON.stringify({
    version: {
      ref: "none"
    }
  }));
  process.exit(0);
});
}

module.exports = NGALMClient;<|endoftext|>


<commit_before>var plugins = [
	{	name: "JS Beautify",
		description: 'Cleans up the formatting of your JavaScript code using jsbeautifier.',
		versions: {
			/*"0.2 M6/M7": [
				"/m6/beautify/jsbeautify.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"
			],*/
			"0.2": [
				"/0.2/plugins/beautify/jsbeautify.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"
			],
			"0.3": [
				"/0.2/plugins/beautify/jsbeautify.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"
			]
		}
	},
	{	name: "Uglify",
		description: 'Minifies your JavaScript code using uglify-js.',
		versions: {
			/*"0.2 M6/M7": [
				"/m6/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/uglify"
			],*/
			"0.2": [
				"/0.2/plugins/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/uglify"
			],
			"0.3": [
				"/0.2/plugins/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/uglify"
			]
		}
	},
	{	name: "CSSLint",
		description: 'Provides validation and style tips on your CSS files using CSS Lint. (Included with Orion by default starting in 0.4)',
		versions: {
			"0.2": [
				"/0.2/plugins/csslint/csslintPlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/csslint",
			],
			"0.3": [
				"/0.3/plugins/csslint/csslintPlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/csslint",
			]
		}
	},
	{	name: "reverse",
		description: 'A minimal plugin example used as part of a tutorial.',
		versions: {
			/*"0.2 M6/M7": [
				"/m6/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/reverse"
			],*/
			"0.2": [
				"/0.2/plugins/reverse/reversePlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/reverse"
			],
			"0.3": [
				"/0.2/plugins/reverse/reversePlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/reverse"
			]
		}
	},
	{	name: "Bugzilla",
		description: 'A Bugzilla integration plugin for Orion.',
		versions: {
			"0.3": [
				"/0.3/plugins/bugzilla/plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/bugzilla"
			]
		}
	},
	//{	name: "language.js",
	//	description: 'Provides content assist suggestions JavaScript identifiers using language.js.',
	//	experimental: true,
	//	versions: {
	//		"0.2": [
	//			"/0.2/plugins/language/languagejsPlugin.html",
	//			"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"
	//		],
	//		"0.3": [
	//			"/0.2/plugins/language/languagejsPlugin.html",
	//			"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"
	//		]
	//	}
	//},
	{	name: "JavaScript hierarchical outline",
		description: 'Provides a simple tree view of the functions in a JavaScript file.',
		experimental: true,
		versions: {
			"0.3": [
				"http://mamacdon.github.com/outliner/outlinerPlugin.html",
				"https://github.com/mamacdon/outliner"
			]
		}
	},
	{	name: "Nonymous outline",
		description: 'Provides a tree view of JavaScript functions using the \"Function-Object Consumption\" algorithm to generate meaningful names for anonymous functions.',
		experimental: true,
		versions: {
			"0.3 M2": [
				"http://johnjbarton.github.com/outliner/nonymousPlugin.html",
				"https://github.com/johnjbarton/outliner"
			]
		}
	},
	{	name: "CodeMirror highlighting",
		description: 'Uses CodeMirror modes to highlight your code.',
		experimental: true,
		versions: {
			"0.4": [
				"http://mamacdon.github.com/orion-codemirror/codeMirrorPlugin.html",
				"https://github.com/mamacdon/orion-codemirror"
			]
		}
	},
	{	name: "HTML Outline",
		description: 'Provides a hierarchical outline of the elements in an HTML file.',
		versions: {
			"0.4": [
				"http://jarthorn.github.com/html-tools/htmlOutlinePlugin.html",
				"https://github.com/jarthorn/html-tools"
			]
		}
	},
	{	name: "Esprima outline",
		description: 'Uses the esprima JavaScript parser to provide a detailed outline of your JavaScript code.',
		versions: {
			"0.4": [
				"http://aclement.github.com/esprima-outline/esprimaOutlinerPlugin.html",
				"https://github.com/aclement/esprima-outline"
			]
		}
	}];

document.addEventListener("DOMContentLoaded", function() {
	function getVersions() {
		var versions = {};
		for (var i=0; i < plugins.length; i++) {
			var plugin = plugins[i];
			for (var prop in plugin.versions) {
				if (plugin.versions.hasOwnProperty(prop)) {
					versions[prop] = null;
				}
			}
		}
		var array = [];
		for (prop in versions) {
			array.push(prop);
		}
		return array;
	}

	function createTbody(tableId, plugins) {
		var table = document.getElementById(tableId),
		    versions = getVersions(),
		    headerRow = table.insertRow(-1),
		    th = document.createElement("th");
		th.innerHTML = "";
		headerRow.appendChild(th);
		for (var i=0; i < versions.length; i++) {
			th = document.createElement("th");
			th.innerHTML = "Orion " + versions[i];
			headerRow.appendChild(th);
		}
		plugins.sort(function(p1, p2) {
			return p1.name.toLowerCase().localeCompare(p2.name.toLowerCase());
		});
		for (i=0; i < plugins.length; i++) {
			var plugin = plugins[i];
			var row = table.insertRow(-1);
			var desc = row.insertCell(-1);
			desc.innerHTML = '
' + plugin.name + '
' + '
' + plugin.description + '
';
			for (var j=0; j < versions.length; j++) {
				var cell = row.insertCell(-1),
				    versionId = versions[j],
				    pluginVersion = plugin.versions[versionId];
				cell.className = "dl";
				if (pluginVersion) {
					var html = '
Plugin
';
					if (pluginVersion[1]) {
						html += '
Source
';
					}
					cell.innerHTML = html;
				} else {
					cell.innerHTML = "–";
					cell.title = "Not available for Orion " + versionId;
				}
			}
		}
	}

	createTbody("pluginTable", plugins);
}, false);<commit_msg>plugin list: merge 0.3M2 category with 0.3<commit_after>var plugins = [
	{	name: "JS Beautify",
		description: 'Cleans up the formatting of your JavaScript code using jsbeautifier.',
		versions: {
			/*"0.2 M6/M7": [
				"/m6/beautify/jsbeautify.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"
			],*/
			"0.2": [
				"/0.2/plugins/beautify/jsbeautify.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"
			],
			"0.3": [
				"/0.2/plugins/beautify/jsbeautify.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/beautify"
			]
		}
	},
	{	name: "Uglify",
		description: 'Minifies your JavaScript code using uglify-js.',
		versions: {
			/*"0.2 M6/M7": [
				"/m6/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/uglify"
			],*/
			"0.2": [
				"/0.2/plugins/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/uglify"
			],
			"0.3": [
				"/0.2/plugins/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/uglify"
			]
		}
	},
	{	name: "CSSLint",
		description: 'Provides validation and style tips on your CSS files using CSS Lint. (Included with Orion by default starting in 0.4)',
		versions: {
			"0.2": [
				"/0.2/plugins/csslint/csslintPlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/csslint",
			],
			"0.3": [
				"/0.3/plugins/csslint/csslintPlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/csslint",
			]
		}
	},
	{	name: "reverse",
		description: 'A minimal plugin example used as part of a tutorial.',
		versions: {
			/*"0.2 M6/M7": [
				"/m6/uglify/uglify-plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/m6/reverse"
			],*/
			"0.2": [
				"/0.2/plugins/reverse/reversePlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/reverse"
			],
			"0.3": [
				"/0.2/plugins/reverse/reversePlugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/reverse"
			]
		}
	},
	{	name: "Bugzilla",
		description: 'A Bugzilla integration plugin for Orion.',
		versions: {
			"0.3": [
				"/0.3/plugins/bugzilla/plugin.html",
				"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.3/plugins/bugzilla"
			]
		}
	},
	//{	name: "language.js",
	//	description: 'Provides content assist suggestions JavaScript identifiers using language.js.',
	//	experimental: true,
	//	versions: {
	//		"0.2": [
	//			"/0.2/plugins/language/languagejsPlugin.html",
	//			"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"
	//		],
	//		"0.3": [
	//			"/0.2/plugins/language/languagejsPlugin.html",
	//			"https://github.com/mamacdon/mamacdon.github.com/tree/master/0.2/plugins/language/"
	//		]
	//	}
	//},
	{	name: "JavaScript hierarchical outline",
		description: 'Provides a simple tree view of the functions in a JavaScript file.',
		experimental: true,
		versions: {
			"0.3": [
				"http://mamacdon.github.com/outliner/outlinerPlugin.html",
				"https://github.com/mamacdon/outliner"
			]
		}
	},
	{	name: "Nonymous outline",
		description: 'Provides a tree view of JavaScript functions using the \"Function-Object Consumption\" algorithm to generate meaningful names for anonymous functions.',
		experimental: true,
		versions: {
			"0.3": [
				"http://johnjbarton.github.com/outliner/nonymousPlugin.html",
				"https://github.com/johnjbarton/outliner"
			]
		}
	},
	{	name: "CodeMirror highlighting",
		description: 'Uses CodeMirror modes to highlight your code.',
		experimental: true,
		versions: {
			"0.4": [
				"http://mamacdon.github.com/orion-codemirror/codeMirrorPlugin.html",
				"https://github.com/mamacdon/orion-codemirror"
			]
		}
	},
	{	name: "HTML Outline",
		description: 'Provides a hierarchical outline of the elements in an HTML file.',
		versions: {
			"0.4": [
				"http://jarthorn.github.com/html-tools/htmlOutlinePlugin.html",
				"https://github.com/jarthorn/html-tools"
			]
		}
	},
	{	name: "Esprima outline",
		description: 'Uses the esprima JavaScript parser to provide a detailed outline of your JavaScript code.',
		versions: {
			"0.4": [
				"http://aclement.github.com/esprima-outline/esprimaOutlinerPlugin.html",
				"https://github.com/aclement/esprima-outline"
			]
		}
	}];

document.addEventListener("DOMContentLoaded", function() {
	function getVersions() {
		var versions = {};
		for (var i=0; i < plugins.length; i++) {
			var plugin = plugins[i];
			for (var prop in plugin.versions) {
				if (plugin.versions.hasOwnProperty(prop)) {
					versions[prop] = null;
				}
			}
		}
		var array = [];
		for (prop in versions) {
			array.push(prop);
		}
		return array;
	}

	function createTbody(tableId, plugins) {
		var table = document.getElementById(tableId),
		    versions = getVersions(),
		    headerRow = table.insertRow(-1),
		    th = document.createElement("th");
		th.innerHTML = "";
		headerRow.appendChild(th);
		for (var i=0; i < versions.length; i++) {
			th = document.createElement("th");
			th.innerHTML = "Orion " + versions[i];
			headerRow.appendChild(th);
		}
		plugins.sort(function(p1, p2) {
			return p1.name.toLowerCase().localeCompare(p2.name.toLowerCase());
		});
		for (i=0; i < plugins.length; i++) {
			var plugin = plugins[i];
			var row = table.insertRow(-1);
			var desc = row.insertCell(-1);
			desc.innerHTML = '
' + plugin.name + '
' + '
' + plugin.description + '
';
			for (var j=0; j < versions.length; j++) {
				var cell = row.insertCell(-1),
				    versionId = versions[j],
				    pluginVersion = plugin.versions[versionId];
				cell.className = "dl";
				if (pluginVersion) {
					var html = '
Plugin
';
					if (pluginVersion[1]) {
						html += '
Source
';
					}
					cell.innerHTML = html;
				} else {
					cell.innerHTML = "–";
					cell.title = "Not available for Orion " + versionId;
				}
			}
		}
	}

	createTbody("pluginTable", plugins);
}, false);<|endoftext|>


<commit_before>/**
 *
 * @source: https://github.com/dnatsvlishvili/geo-key
 *
 * @licstart  The following is the entire license notice for the
 *  JavaScript code in this page.
 *
 * The MIT License (MIT)

 * Copyright (c) 2013 David Natsvlishvili
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this page.
 *
 */

(function(window, document, undefined){
  "use strict";

  var GeoKey = function(params){
    // Fix silently
    if (!(this instanceof GeoKey)) {
      return new GeoKey(arguments[0]);
    };

    // Target set to non empty value will not work on IE6
    var defaults = {
    };

    // Provides ability to provide custom parameters
    this.params = function(input, defaults) {
      if (input) {
        for (var key in input) {
          var val = input[key];
          if (typeof val !== 'undefined') {
            defaults[key] = val;
          }
        }
      }
      return defaults;
    }(params, defaults);

    // Elements that need to be worked on
    this.elements = function(params){
      if (params.target === '') {
        return document.querySelectorAll('input[type=text],input[type=edit],textarea,div,iframe');
      } else {
        return document.getElementsByClassName(params.target);
      }
    }(this.params);

    // Track changes to inputs set
    var input, that = this;
    for (var c = 0; c < this.elements.length; c += 1) {
      input = this.elements[c];
      (function(that, input) {
        that.listen(input, 'keypress', function(event){
          GeoKey.prototype.convert(input, event);
        });
      })(that, input);
    }
  };

  // Returns [a-z] input string in Georgian
  GeoKey.prototype.translate = function(string) {
    var input = string.split('');
    var result = '', offset, chr;

    var charset = {
      a: 1, b: 1, d: 1, e: 1, i: 1, g: -3, v: -15,
      z: -18, T: 21, J: 39, f: 16, q: 6, R: 38, S: 39,
      C: 56, c: 25, Z: 35, w: 7, W: 40, x: 8, j: 23, h: 26
    };

    var scope = [67, 74, 82, 83, 84, 87, 90];
    for (var n = 96; n < 122; n += 1, scope.push(n));

    for (var i = 0; i < input.length; i += 1) {
      chr = input[i];

      offset = chr.charCodeAt();
      if (typeof charset[chr] !== 'undefined') {
        offset += charset[chr];
      }

      result += (scope.indexOf(chr.charCodeAt()) > -1) ? String.fromCharCode(4206 + offset) : chr;
    }

    return result;
  };

  GeoKey.prototype.listen = function(element, eventName, callback) {
    if (element.nodeName === 'IFRAME') {
      element = element.contentWindow.document;
    }
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
  }

  // Works on a DOM element to replace a character upon keypress
  GeoKey.prototype.convert = function(element, event) {
    var start, end;
    var character = typeof event.which === 'number' ? event.which : event.keyCode;

    console.log(element);

    if (!character || character <= 32) {
      return false;
    }

    if (['INPUT','TEXTAREA'].indexOf(element.nodeName) > -1) {
      // Text convertion for <input> and <textarea> elements
      if (typeof element.selectionStart === 'number' && typeof element.selectionEnd === 'number') {
        // For modern browsers and IE9+
        start = element.selectionStart;
        end = element.selectionEnd;
        element.value = element.value.slice(0, start) + GeoKey.prototype.translate(String.fromCharCode(character)) + element.value.slice(end);
        element.selectionStart = element.selectionEnd = start + 1;
      } else {
        // For IE6, IE7, IE8
        range = document.selection.createRange();

        charLength = element.value.length;
        normal = element.value.replace(/\r\n/g, "\n");

        // Input scope only
        textInputRange = element.createTextRange();
        textInputRange.moveToBookmark(range.getBookmark());

        // Start and end of the selection should be at the end of input
        endRange = element.createTextRange();
        endRange.collapse(false);

        if (textInputRange.compareEndPoints('StartToEnd', endRange) > -1) {
            start = end = charLength;
        } else {
            start = -textInputRange.moveStart('character', -charLength);
            start += normal.slice(0, start).split("\n").length - 1;

            if (textInputRange.compareEndPoints('EndToEnd', endRange) > -1) {
                end = charLength;
            } else {
                end = -textInputRange.moveEnd('character', -charLength);
                end += normal.slice(0, end).split("\n").length - 1;
            }
        }

        // Add computed value in the right place
        element.value = element.value.slice(0, start) + GeoKey.prototype.translate(String.fromCharCode(character)) + element.value.slice(end);
        start++;

        textInputRange = element.createTextRange();
        textInputRange.collapse(true);
        textInputRange.move('character', start - (element.value.slice(0, start).split("\r\n").length - 1));
        textInputRange.select();
      }
    } else if (['DIV','IFRAME'].indexOf(element.nodeName) > -1) {

      // Text convertion for content-editable <div> elements
      var textSelection, textInputRange, textNode;

      var contextWindow = (element.nodeName === 'IFRAME') ? element.contentWindow.window : window;
      var contextDocument = (element.nodeName === 'IFRAME') ? element.contentWindow.document : document;

      if (contextWindow.getSelection) {
        // For newer browsers
        textSelection = contextWindow.getSelection();
        if (textSelection.getRangeAt && textSelection.rangeCount) {
          // Get range and put a converted character in the appropriate place
          textInputRange = textSelection.getRangeAt(0);
          textInputRange.deleteContents();
          textNode = contextDocument.createTextNode(GeoKey.prototype.translate(String.fromCharCode(character)));
          textInputRange.insertNode(textNode);

          // Move point to last character
          textInputRange.setStart(textNode, textNode.length);
          textInputRange.setEnd(textNode, textNode.length);
          textSelection.removeAllRanges();
          textSelection.addRange(textInputRange);
        }
      } else if (contextDocument.selection && contextDocument.selection.createRange) {
        // For older IE browsers
        textInputRange = contextDocument.selection.createRange();
        textInputRange.pasteHTML(GeoKey.prototype.translate(String.fromCharCode(character)));
      }
    }

    if (event.preventDefault) {
      event.preventDefault();
    } else {
      event.returnValue = false;
      return event;
    }
  }

  /**
   *
   * Polyfills and shims for older browsers that might have a problem with GeoKey Library
   * @source: https://github.com/inexorabletash/polyfill
   *
   */

  // document.querySelectorAll
  if (!document.querySelectorAll) {
    document.querySelectorAll = function (selectors) {
      var style = document.createElement('style'), elements = [], element;
      document.documentElement.firstChild.appendChild(style);
      document._qsa = [];

      style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
      window.scrollBy(0, 0);
      style.parentNode.removeChild(style);

      while (document._qsa.length) {
        element = document._qsa.shift();
        element.style.removeAttribute('x-qsa');
        elements.push(element);
      }
      document._qsa = null;
      return elements;
    };
  }

  // document.getElementsByClassName
  if (typeof document.getElementsByClassName!='function') {
      document.getElementsByClassName = function() {
          var elms = document.getElementsByTagName('*');
          var ei = new Array();
          for (i=0;i<elms.length;i++) {
              if (elms[i].getAttribute('class')) {
                  ecl = elms[i].getAttribute('class').split(' ');
                  for (j=0;j<ecl.length;j++) {
                      if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                          ei.push(elms[i]);
                      }
                  }
              } else if (elms[i].className) {
                  ecl = elms[i].className.split(' ');
                  for (j=0;j<ecl.length;j++) {
                      if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                          ei.push(elms[i]);
                      }
                  }
              }
          }
          return ei;
      }
  }

  // [].map
  if (!Array.prototype.map) {
    Array.prototype.map = function (fun /*, thisp */) {
      "use strict";

      if (this === void 0 || this === null) { throw new TypeError(); }

      var t = Object(this);
      var len = t.length >>> 0;
      if (typeof fun !== "function") { throw new TypeError(); }

      var res = []; res.length = len;
      var thisp = arguments[1], i;
      for (i = 0; i < len; i++) {
        if (i in t) {
          res[i] = fun.call(thisp, t[i], i, t);
        }
      }

      return res;
    };
  }

  // [].indexOf
  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
      "use strict";

      if (this === void 0 || this === null) { throw new TypeError(); }

      var t = Object(this);
      var len = t.length >>> 0;
      if (len === 0) { return -1; }

      var n = 0;
      if (arguments.length > 0) {
        n = Number(arguments[1]);
        if (isNaN(n)) {
          n = 0;
        } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
          n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
      }

      if (n >= len) { return -1; }

      var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);

      for (; k < len; k++) {
        if (k in t && t[k] === searchElement) {
          return k;
        }
      }
      return -1;
    };
  }

  // Binds a function constructor to global object
  window.GeoKey = GeoKey;
})(window, document);<commit_msg>Conditional context for better cross-browser performance<commit_after>/**
 *
 * @source: https://github.com/dnatsvlishvili/geo-key
 *
 * @licstart  The following is the entire license notice for the
 *  JavaScript code in this page.
 *
 * The MIT License (MIT)

 * Copyright (c) 2013 David Natsvlishvili
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this page.
 *
 */

(function(window, document, undefined){
  "use strict";

  var GeoKey = function(params){
    // Fix silently
    if (!(this instanceof GeoKey)) {
      return new GeoKey(arguments[0]);
    };

    // Target set to non empty value will not work on IE6
    var defaults = {
    };

    // Provides ability to provide custom parameters
    this.params = function(input, defaults) {
      if (input) {
        for (var key in input) {
          var val = input[key];
          if (typeof val !== 'undefined') {
            defaults[key] = val;
          }
        }
      }
      return defaults;
    }(params, defaults);

    // Elements that need to be worked on
    this.elements = function(params){
      if (params.target === '') {
        return document.querySelectorAll('input[type=text],input[type=edit],textarea,div,iframe');
      } else {
        return document.getElementsByClassName(params.target);
      }
    }(this.params);

    // Track changes to inputs set
    var input, that = this;
    for (var c = 0; c < this.elements.length; c += 1) {
      input = this.elements[c];
      (function(that, input) {
        that.listen(input, 'keypress', function(event){
          GeoKey.prototype.convert(input, event);
        });
      })(that, input);
    }
  };

  // Returns [a-z] input string in Georgian
  GeoKey.prototype.translate = function(string) {
    var input = string.split('');
    var result = '', offset, chr;

    var charset = {
      a: 1, b: 1, d: 1, e: 1, i: 1, g: -3, v: -15,
      z: -18, T: 21, J: 39, f: 16, q: 6, R: 38, S: 39,
      C: 56, c: 25, Z: 35, w: 7, W: 40, x: 8, j: 23, h: 26
    };

    var scope = [67, 74, 82, 83, 84, 87, 90];
    for (var n = 96; n < 122; n += 1, scope.push(n));

    for (var i = 0; i < input.length; i += 1) {
      chr = input[i];

      offset = chr.charCodeAt();
      if (typeof charset[chr] !== 'undefined') {
        offset += charset[chr];
      }

      result += (scope.indexOf(chr.charCodeAt()) > -1) ? String.fromCharCode(4206 + offset) : chr;
    }

    return result;
  };

  GeoKey.prototype.listen = function(element, eventName, callback) {
    if (element.nodeName === 'IFRAME') {
      element = element.contentWindow.document;
    }
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
  }

  // Works on a DOM element to replace a character upon keypress
  GeoKey.prototype.convert = function(element, event) {
    var start, end;
    var character = typeof event.which === 'number' ? event.which : event.keyCode;

    console.log(element);

    if (!character || character <= 32) {
      return false;
    }

    if (['INPUT','TEXTAREA'].indexOf(element.nodeName) > -1) {
      // Text convertion for <input> and <textarea> elements
      if (typeof element.selectionStart === 'number' && typeof element.selectionEnd === 'number') {
        // For modern browsers and IE9+
        start = element.selectionStart;
        end = element.selectionEnd;
        element.value = element.value.slice(0, start) + GeoKey.prototype.translate(String.fromCharCode(character)) + element.value.slice(end);
        element.selectionStart = element.selectionEnd = start + 1;
      } else {
        // For IE6, IE7, IE8
        range = document.selection.createRange();

        charLength = element.value.length;
        normal = element.value.replace(/\r\n/g, "\n");

        // Input scope only
        textInputRange = element.createTextRange();
        textInputRange.moveToBookmark(range.getBookmark());

        // Start and end of the selection should be at the end of input
        endRange = element.createTextRange();
        endRange.collapse(false);

        if (textInputRange.compareEndPoints('StartToEnd', endRange) > -1) {
            start = end = charLength;
        } else {
            start = -textInputRange.moveStart('character', -charLength);
            start += normal.slice(0, start).split("\n").length - 1;

            if (textInputRange.compareEndPoints('EndToEnd', endRange) > -1) {
                end = charLength;
            } else {
                end = -textInputRange.moveEnd('character', -charLength);
                end += normal.slice(0, end).split("\n").length - 1;
            }
        }

        // Add computed value in the right place
        element.value = element.value.slice(0, start) + GeoKey.prototype.translate(String.fromCharCode(character)) + element.value.slice(end);
        start++;

        textInputRange = element.createTextRange();
        textInputRange.collapse(true);
        textInputRange.move('character', start - (element.value.slice(0, start).split("\r\n").length - 1));
        textInputRange.select();
      }
    } else if (['DIV','IFRAME'].indexOf(element.nodeName) > -1) {

      // Text convertion for content-editable <div> elements
      var textSelection, textInputRange, textNode, context;

      var context = (element.contentWindow || element.contentDocument) || null;
      var contextWindow = (element.nodeName === 'IFRAME') ? context.window : window;
      var contextDocument = (element.nodeName === 'IFRAME') ? context.document : document;

      if (contextWindow.getSelection) {
        // For newer browsers
        textSelection = contextWindow.getSelection();
        if (textSelection.getRangeAt && textSelection.rangeCount) {
          // Get range and put a converted character in the appropriate place
          textInputRange = textSelection.getRangeAt(0);
          textInputRange.deleteContents();
          textNode = contextDocument.createTextNode(GeoKey.prototype.translate(String.fromCharCode(character)));
          textInputRange.insertNode(textNode);

          // Move point to last character
          textInputRange.setStart(textNode, textNode.length);
          textInputRange.setEnd(textNode, textNode.length);
          textSelection.removeAllRanges();
          textSelection.addRange(textInputRange);
        }
      } else if (contextDocument.selection && contextDocument.selection.createRange) {
        // For older IE browsers
        textInputRange = contextDocument.selection.createRange();
        textInputRange.pasteHTML(GeoKey.prototype.translate(String.fromCharCode(character)));
      }
    }

    if (event.preventDefault) {
      event.preventDefault();
    } else {
      event.returnValue = false;
      return event;
    }
  }

  /**
   *
   * Polyfills and shims for older browsers that might have a problem with GeoKey Library
   * @source: https://github.com/inexorabletash/polyfill
   *
   */

  // document.querySelectorAll
  if (!document.querySelectorAll) {
    document.querySelectorAll = function (selectors) {
      var style = document.createElement('style'), elements = [], element;
      document.documentElement.firstChild.appendChild(style);
      document._qsa = [];

      style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
      window.scrollBy(0, 0);
      style.parentNode.removeChild(style);

      while (document._qsa.length) {
        element = document._qsa.shift();
        element.style.removeAttribute('x-qsa');
        elements.push(element);
      }
      document._qsa = null;
      return elements;
    };
  }

  // document.getElementsByClassName
  if (typeof document.getElementsByClassName!='function') {
      document.getElementsByClassName = function() {
          var elms = document.getElementsByTagName('*');
          var ei = new Array();
          for (i=0;i<elms.length;i++) {
              if (elms[i].getAttribute('class')) {
                  ecl = elms[i].getAttribute('class').split(' ');
                  for (j=0;j<ecl.length;j++) {
                      if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                          ei.push(elms[i]);
                      }
                  }
              } else if (elms[i].className) {
                  ecl = elms[i].className.split(' ');
                  for (j=0;j<ecl.length;j++) {
                      if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                          ei.push(elms[i]);
                      }
                  }
              }
          }
          return ei;
      }
  }

  // [].map
  if (!Array.prototype.map) {
    Array.prototype.map = function (fun /*, thisp */) {
      "use strict";

      if (this === void 0 || this === null) { throw new TypeError(); }

      var t = Object(this);
      var len = t.length >>> 0;
      if (typeof fun !== "function") { throw new TypeError(); }

      var res = []; res.length = len;
      var thisp = arguments[1], i;
      for (i = 0; i < len; i++) {
        if (i in t) {
          res[i] = fun.call(thisp, t[i], i, t);
        }
      }

      return res;
    };
  }

  // [].indexOf
  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
      "use strict";

      if (this === void 0 || this === null) { throw new TypeError(); }

      var t = Object(this);
      var len = t.length >>> 0;
      if (len === 0) { return -1; }

      var n = 0;
      if (arguments.length > 0) {
        n = Number(arguments[1]);
        if (isNaN(n)) {
          n = 0;
        } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
          n = (n > 0 || -1) * Math.floor(Math.abs(n));
        }
      }

      if (n >= len) { return -1; }

      var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);

      for (; k < len; k++) {
        if (k in t && t[k] === searchElement) {
          return k;
        }
      }
      return -1;
    };
  }

  // Binds a function constructor to global object
  window.GeoKey = GeoKey;
})(window, document);<|endoftext|>


<commit_before>const bot = require('./bot');
const functions = require('./functions');
const music = require('./music');
const bf2 = require('revive-stats.js').bf2;
const bf2142 = require('revive-stats.js').bf2142;
const Discord = require('discord.js')
const rank = require('./rank');
const request = require('request-promise');
const stats = require('./stats');
const math = require('mathjs');
const crypto = require('crypto');
const web = require('./web');
const help = require('./help');
const index = require('./hotline');

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    if (commands.hasOwnProperty(cmd))
        commands[cmd].exec(message);
});
var commands = {
    'ping': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function(message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function(message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function(message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function(message) {
            if (message.content.toString().includes('all')) {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else if(message.mentions.users.size !=0 ) {
		message.mentions.users.map(functions.refreshUser);
		}else{

                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function(message) {
            var nick = message.content.substring(5).trim();
            bf2.getPlayers(nick).then(plist => {
                console.log("BF2 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact,'bf2');
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i],'bf2');
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function(message) {

            let nick = message.content.substring(7).trim();
            bf2142.getPlayers(nick).then(plist => {
                console.log("BF2142 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact);
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i]);
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function(message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function(message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function(message) {
            var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd, "Description: " + commands[cmd].description + "\n" + "Syntax: " + commands[cmd].syntax);
            }
            //embed.addField('Music',"Description: Access the music bot using - as the prefix" + "\n"+ "Syntax: -help");
            message.channel.sendEmbed(embed);
        }
    },
    'play': {
        description: 'plays the youtube url specified',
        syntax: '~play <youtube_url>',
        exec: function(message) {
            url = message.content.substring(6).trim();
            music.play(url, message);
        }
    },
    'pause': {
        description: 'pauses the voice stream',
        syntax: '~pause',
        exec: function(message) {
            music.pause(message);
        }
    },
    'resume': {
        description: 'resumes the voice stream',
        syntax: '~resume',
        exec: function(message) {
            music.resume(message);
        }
    },
    'clear': {
        description: 'clears the playlist',
        syntax: '~clear',
        exec: function(message) {
            music.clear(message);
        }
    },
    'playnext': {
        description: 'plays the next song',
        syntax: '~playnext',
        exec: function(message) {
            music.playNext(message);
        }
    },
    'setvol': {
        description: 'sets the play volume',
        syntax: '~setVol',
        exec: function(message) {
            music.setVol(message.content.substring(7).trim());
        }
    },
    'queue': {
        description: 'views the queue',
        syntax: '~queue',
        exec: function(message) {
            music.queue(message);
        }
    },
    'info': {
        description: 'Gives the Battlelog Profile of a Verified User',
        syntax: '~info @usermention',
        exec: function(message) {
            rank.rank(message);
        }
    },
    'request': {
        description: 'execute a request',
        syntax: '~request <request>',
        exec: function(message) {
            if (message.guild != bot.guilds.get('256299642180861953')) {
                return;
            }
            var msg = message.content.substring(9).trim();
            var call = function(error, response, body) {
                if (error) {
                    message.reply(error);
                } else {
                    console.log(body)
                    if (body.length > 2000)
			body = body.toString().substring(0,1980)+"...";
                        message.channel.sendMessage("```Javascript\n" + body + '```');
                }
            };
            if (msg.startsWith('{')) msg = JSON.parse(msg)
				else msg = getOptions(msg);
            request(msg, call);
        }
    },
    'stats': {
        description: 'displays the guild stats',
        syntax: '~stats',
        exec: function(message) {
            stats.stats(message);
        }
    },
    'calc': {
        description: 'evalutes a mathematical expression',
        syntax: '~calc <expression>',
        exec: function(message) {
            let res = message.content.substring(6)//.match(/[ 0-9\%\(\)\^\/\+\-\*]+/);
           // res = res.join(' ');
	    res = math.eval(res);
	    console.log(res);
            message.channel.sendMessage(res);
        }
    },                                                   'hash': {                                              description: 'hashes a text.',
	  syntax: '~hash <algorithm> <text>',
	  exec: function(message) {
		  let res = message.content.trim().substring(6);
		  let algo = res.split(' ')[0];
		  res = res.substring(algo.length+1).trim();
		  if(crypto.getHashes().indexOf(algo)===-1){
			  message.channel.sendMessage('Invalid algorithm \n Valid hashing Algorithms are:\n'+crypto.getHashes().join(' , '));
			  return;}
		  res = checksum(res,algo);
		  console.log(res);                                  message.channel.sendMessage('hash of message:'+res);
		  if(message.attachments.size>0)
		  {
			  res = message.attachments.first().url;
			  request(res).then(body=> message.channel.sendMessage('Hash of file:\n'+checksum(body,algo)));
		  }
	  }
    },
     'convert': {                                           description: 'hashes a dec number to a different base.',
	 syntax: '~convert <base> <decnumber>',             exec: function(message)
	     {
		 let res = message.content.trim().substring(9);
		 let base = res.split(' ')[0];
		 res = res.substring(base.length+1).trim();
		 base = parseInt(base);
		 res = parseInt(res).toString(base);
		 console.log(res);                                  message.channel.sendMessage(res);          }
     }
}
const str = function(soldier,game)
{
	if(game=='bf2')
	{game='https://battlelog.co/bfhq.php?pid='}
	else
	{game='https://bl2142.co/bfhq.php?pid='}
	return soldier.nick+'\t'+"<"+game+soldier.pid+">";
};
const getOptions = function(URL) {
    return {
        url: URL,
        headers: {
            'User-Agent': 'GameSpyHTTP/1.0'
        }
    };
};
function checksum (str, algorithm) {
	console.log(str);
	console.log(algorithm);
	    return crypto
	        .createHash(algorithm || 'md5')
	        .update(str)
	        .digest('hex')
	}
<commit_msg>Removed Calc<commit_after>const bot = require('./bot');
const functions = require('./functions');
const music = require('./music');
const bf2 = require('revive-stats.js').bf2;
const bf2142 = require('revive-stats.js').bf2142;
const Discord = require('discord.js')
const rank = require('./rank');
const request = require('request-promise');
const stats = require('./stats');
const math = require('mathjs');
const crypto = require('crypto');
const web = require('./web');
const help = require('./help');
const index = require('./hotline');

bot.on('message', message => {
    if (!message.content.startsWith('~')) {
        return;
    } //base case
    var cmd = message.content.split(' ')[0].substring(1).toLowerCase();
    if (commands.hasOwnProperty(cmd))
        commands[cmd].exec(message);
});
var commands = {
    'ping': {
        description: 'reply with a pong',
        syntax: '~ping',
        exec: function (message) {
            message.reply('pong');
        }
    },
    'yo': {
        description: 'reply with a yo bro',
        syntax: '~yo',
        exec: function (message) {
            message.reply('yo bro');
        }
    },
    'link': {
        description: 'link revive account to this discord account',
        syntax: '~link',
        exec: function (message) {
            functions.integrate(message.author);
        }
    },
    'refresh': {
        description: 'refresh a user discord link status',
        syntax: '~refresh',
        exec: function (message) {
            if (message.content.toString().includes('all')) {
                functions.refreshAll(bot.guilds.get('184536578654339072').members.array())
            } else if (message.mentions.users.size != 0) {
                message.mentions.users.map(functions.refreshUser);
            } else {

                functions.refreshUser(message.author);
            }
        }
    },
    'bf2': {
        description: 'finds a bf2 player',
        syntax: '~bf2 <PlayerName>',
        exec: function (message) {
            var nick = message.content.substring(5).trim();
            bf2.getPlayers(nick).then(plist => {
                console.log("BF2 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact, 'bf2');
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i], 'bf2');
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'bf2142': {
        description: 'finds a bf2142 player',
        syntax: '~bf2142 <PlayerName>',
        exec: function (message) {

            let nick = message.content.substring(7).trim();
            bf2142.getPlayers(nick).then(plist => {
                console.log("BF2142 in index.js gets executed");
                if (plist == null) {
                    message.channel.sendMessage("API Down or invalid search");
                    return;
                }
                if (plist.length >= 1) {
                    //checking for exact matches
                    var exact = plist.find(o => o.nick.toUpperCase().trim() === nick.toUpperCase());
                    console.log(exact);
                    var res = "**S.no.\tName \t link**";
                }
                if (plist.length == 0) {
                    message.channel.sendMessage("Player not found");
                    return;
                }
                var start = 0;
                var past = 0;
                if (exact != null) {
                    res = res + "\n" + (1) + "\t" + "\t" + str(exact);
                    start++;
                }
                for (var i = start; i < plist.length; i++) {
                    if (exact != null && i == plist.indexOf(exact)) {
                        past++;
                        continue;
                    }
                    if (i == 26) {
                        res = res + "\n" + (plist.length - 25) +
                            " more players found to Get a full list of players \n" +
                            "<https://battlelog.co/player_search.php?q=" + nick + ">";
                        break;
                    } else {
                        res = res + " \n" + (i + 1 - past) +
                            "\t" + "\t" + str(plist[i]);
                    }
                }
                message.channel.sendMessage(res);
                console.log(res);
            });
        }
    },
    'cookie': {
        description: 'eats a cookie',
        syntax: '~cookie',
        exec: function (message) {
            message.reply('crunch crunch');
        }
    },
    'add': {
        description: 'adds a person to a role',
        syntax: '~add <UserMention> to <roleName>',
        exec: function (message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.addRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'remove': {
        description: 'removes a person to a role',
        syntax: '~remove <UserMention> from <roleName>',
        exec: function (message) {
            if (!message.member.hasPermission("MANAGE_ROLES_OR_PERMISSIONS")) {
                message.channel.sendMessage("You aren't Worthy");
                return;
            }
            var member = message.guild.member(message.mentions.users.first());
            var msg = message.content.split("to ");
            member.removeRole(message.guild.roles.find("name", msg[msg.length - 1]));
            message.reply('done');
        }
    },
    'help': {
        description: 'displays help',
        syntax: '~help',
        exec: function (message) {
            var embed = new Discord.RichEmbed().setTitle('HELP').setColor("#FF7F50");
            for (cmd in commands) {
                embed.addField(cmd, "Description: " + commands[cmd].description + "\n" + "Syntax: " + commands[cmd].syntax);
            }
            //embed.addField('Music',"Description: Access the music bot using - as the prefix" + "\n"+ "Syntax: -help");
            message.channel.sendEmbed(embed);
        }
    },
    'play': {
        description: 'plays the youtube url specified',
        syntax: '~play <youtube_url>',
        exec: function (message) {
            url = message.content.substring(6).trim();
            music.play(url, message);
        }
    },
    'pause': {
        description: 'pauses the voice stream',
        syntax: '~pause',
        exec: function (message) {
            music.pause(message);
        }
    },
    'resume': {
        description: 'resumes the voice stream',
        syntax: '~resume',
        exec: function (message) {
            music.resume(message);
        }
    },
    'clear': {
        description: 'clears the playlist',
        syntax: '~clear',
        exec: function (message) {
            music.clear(message);
        }
    },
    'playnext': {
        description: 'plays the next song',
        syntax: '~playnext',
        exec: function (message) {
            music.playNext(message);
        }
    },
    'setvol': {
        description: 'sets the play volume',
        syntax: '~setVol',
        exec: function (message) {
            music.setVol(message.content.substring(7).trim());
        }
    },
    'queue': {
        description: 'views the queue',
        syntax: '~queue',
        exec: function (message) {
            music.queue(message);
        }
    },
    'info': {
        description: 'Gives the Battlelog Profile of a Verified User',
        syntax: '~info @usermention',
        exec: function (message) {
            rank.rank(message);
        }
    },
    'request': {
        description: 'execute a request',
        syntax: '~request <request>',
        exec: function (message) {
            if (message.guild != bot.guilds.get('256299642180861953')) {
                return;
            }
            var msg = message.content.substring(9).trim();
            var call = function (error, response, body) {
                if (error) {
                    message.reply(error);
                } else {
                    console.log(body)
                    if (body.length > 2000)
                        body = body.toString().substring(0, 1980) + "...";
                    message.channel.sendMessage("```Javascript\n" + body + '```');
                }
            };
            if (msg.startsWith('{')) msg = JSON.parse(msg)
            else msg = getOptions(msg);
            request(msg, call);
        }
    },
    'stats': {
        description: 'displays the guild stats',
        syntax: '~stats',
        exec: function (message) {
            stats.stats(message);
        }
    },
    'hash': {
        description: 'hashes a text.',
        syntax: '~hash <algorithm> <text>',
        exec: function (message) {
            let res = message.content.trim().substring(6);
            let algo = res.split(' ')[0];
            res = res.substring(algo.length + 1).trim();
            if (crypto.getHashes().indexOf(algo) === -1) {
                message.channel.sendMessage('Invalid algorithm \n Valid hashing Algorithms are:\n' + crypto.getHashes().join(' , '));
                return;
            }
            res = checksum(res, algo);
            console.log(res); message.channel.sendMessage('hash of message:' + res);
            if (message.attachments.size > 0) {
                res = message.attachments.first().url;
                request(res).then(body => message.channel.sendMessage('Hash of file:\n' + checksum(body, algo)));
            }
        }
    },
    'convert': {
        description: 'hashes a dec number to a different base.',
        syntax: '~convert <base> <decnumber>', exec: function (message) {
            let res = message.content.trim().substring(9);
            let base = res.split(' ')[0];
            res = res.substring(base.length + 1).trim();
            base = parseInt(base);
            res = parseInt(res).toString(base);
            console.log(res); message.channel.sendMessage(res);
        }
    }
}
const str = function (soldier, game) {
    if (game == 'bf2')
    { game = 'https://battlelog.co/bfhq.php?pid=' }
    else
    { game = 'https://bl2142.co/bfhq.php?pid=' }
    return soldier.nick + '\t' + "<" + game + soldier.pid + ">";
};
const getOptions = function (URL) {
    return {
        url: URL,
        headers: {
            'User-Agent': 'GameSpyHTTP/1.0'
        }
    };
};
function checksum(str, algorithm) {
    console.log(str);
    console.log(algorithm);
    return crypto
        .createHash(algorithm || 'md5')
        .update(str)
        .digest('hex')
}
<|endoftext|>


<commit_before>var remoteUrl = "https://api.carpoolvote.com/live";
// var remoteUrl = "http://localhost:8000";

var driverLoggedIn = false;
var riderLoggedIn = false;

// Create a data object containing all URL query string data:
var data = tinyQuery.getAll();

if (data.uuid_driver) {
  data.uuid = data.uuid || data.uuid_driver;
  data.type = data.type || 'driver';
}
if (data.uuid_rider) {
  data.uuid = data.uuid || data.uuid_rider;
  data.type = data.type || 'rider';
}

// Cache jQuery selectors:
var $login = $('#login'),
  $manage = $('#manage'),
  $manageLogin = $('#manageLogin'),
  $info = $manage.find('#info'),
  $infoLogin = $manageLogin.find('#info')
  ;

if (data.uuid) {
  $login.find('#enter-uuid').remove();
}
if (data.type) {
  $login.find('#enter-type').remove();
}

$login.validator().on('submit', function(e) {
  if (e.isDefaultPrevented()) {
    return;
  }
  data.uuid = data.uuid || $(this).find('#inputUUID').val();
  data.type = data.type || $(this).find('#enter-type').find('input:checked').val();
  data.phone = $(this).find('#inputPhoneNumber').val();

  if (data.type === "driver") {
    driverExists();
  }
  else {
    riderExists();
  }

  // done in driver exists
  //
  // $(this).slideUp(300).attr('aria-hidden','true');
  // $manage.slideDown(300).attr('aria-hidden','false');
  // updateUI();
  e.preventDefault();
});

function updateUI(uuid, type, phone) {
  $manage.find('#btnCancelDriveOffer').toggle(data.type === 'driver');
  $manage.find('#btnCancelDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
  $manage.find('#btnPauseDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');

  $manage.find('#btnCancelRideRequest').toggle(data.type === 'rider');
  $manage.find('#btnCancelRiderMatch').toggle(data.type === 'rider' && data.score !== 'undefined');

  $manage.find('#btnAcceptDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
}

$manage
  .on('click', '#btnCancelRideRequest', cancelRideRequest)
  .on('click', '#btnCancelRiderMatch', cancelRiderMatch)
  .on('click', '#btnCancelDriveOffer', cancelDriveOffer)
  .on('click', '#btnCancelDriverMatch', cancelDriverMatch)
  .on('click', '#btnPauseDriverMatch', pauseDriverMatch)
  .on('click', '#btnAcceptDriverMatch', acceptDriverMatch)
  .on('click', '#logout', logout);

function cancelRideRequest() {
  if (!window.confirm('This will cancel your ride request. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      uuid: data.uuid,
      RiderPhone: data.phone
    },
    '/cancel-ride-request'
  );
}

function cancelRiderMatch() {
  if (!window.confirm('This will cancel your ride match. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      UUID_driver: data.uuid_driver,
      UUID_rider: data.uuid,
      Score: data.score,
      RiderPhone: data.phone
    },
    '/cancel-rider-match'
  );
}

function cancelDriveOffer() {
  if (!window.confirm('This will cancel your ride offer. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      uuid: data.uuid,
      DriverPhone: data.phone
    },
    '/cancel-drive-offer'
  );
}

function cancelDriverMatch() {
  if (!window.confirm('This will cancel your ride match. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      UUID_driver: data.uuid_driver,
      UUID_rider: data.uuid,
      Score: data.score,
      RiderPhone: data.phone
    },
    '/cancel-driver-match'
  );
}

function acceptDriverMatch() {
  sendAjaxRequest(
    {
      UUID_driver: data.uuid,
      UUID_rider: data.uuid_rider,
      Score: data.score,
      DriverPhone: data.phone
    },
    '/accept-driver-match'
  );
}

function pauseDriverMatch() {
  sendAjaxRequest(
    {
      uuid: data.uuid,
      DriverPhone: data.phone
    },
    '/pause-driver-match'
  );
}

function logout() {
  window.location.search = tinyQuery.remove(['type','uuid','uuid_driver','uuid_rider']);
}

function sendAjaxRequest(ajaxData, ajaxPath) {
  var url = tinyQuery.set(ajaxData, remoteUrl + ajaxPath);

  $info.html('⏳ Loading…');

  $.getJSON(url, function(dbInfo) {
    var keys = Object.keys(dbInfo);
    if (keys) {
      info = dbInfo[keys[0]].toString();
      $info.text('ℹ ' + info);
    }
  })
  .fail(function(err) {
    $info.text('⚠ ' + err.statusText);
  });
}

function driverExists () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-exists?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {
        info = resp[keys[0]].toString();
        // $info.text(info);
        $infoLogin.text(info);

        if (keys[0] == "driver_exists" && info === "") {
          driverLoggedIn = true;

          $(this).slideUp(300).attr('aria-hidden','true');
          $manage.slideDown(300).attr('aria-hidden','false');
          updateUI();

          driverInfo();
          driverProposedMatches();
          driverConfirmedMatches();

        }
      }
    }
  };
}

function driverInfo () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-info?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {

        if (keys[0] == "driver_info" ) {

          var driverInfo = resp[keys[0]];
          var i = 0;

$("#driverInfo ul").append('
' + driverInfo.DriverFirstName + '
');
$("#driverInfo ul").append('
' + driverInfo.DriverLastName + '
');

        }
      }
    }
  };
}

function driverProposedMatches () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-proposed-matches?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      resp.forEach(val => {

          $("#driverProposedMatches ul").append('
 UUID_driver - ' + val.driver_proposed_matches.uuid_driver + '
');
  $("#driverProposedMatches ul").append('
  UUID_rider - ' + val.driver_proposed_matches.uuid_rider + '
');
  $("#driverProposedMatches ul").append('
 Score - ' + val.driver_proposed_matches.score + '
');

      });

    }
  };
}

function driverConfirmedMatches () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-confirmed-matches?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      resp.forEach(val => {

          $("#driverConfirmedMatches ul").append('
 UUID_driver - ' + val.driver_confirmed_matches.uuid_driver + '
');
  $("#driverConfirmedMatches ul").append('
  UUID_rider - ' + val.driver_confirmed_matches.uuid_rider + '
');
  $("#driverConfirmedMatches ul").append('
 Score - ' + val.driver_confirmed_matches.score + '
');

      });

    }
  };
}

function riderExists () {
//http://localhost:8000/rider-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&RiderPhone=Test

  var url =
    remoteUrl + '/rider-exists?' +
    'UUID=' + data.uuid +
    '&RiderPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {
        info = resp[keys[0]].toString();
        // $info.text(info);
        $infoLogin.text(info);

        if (keys[0] == "rider_exists" && info === "") {
          riderLoggedIn = true;

          $(this).slideUp(300).attr('aria-hidden','true');
          $manage.slideDown(300).attr('aria-hidden','false');
          updateUI();

          riderInfo();
          riderConfirmedMatch();
        }
      }
    }
  };
}

function riderInfo () {
//http://localhost:8000/rider-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&RiderPhone=Test

  var url =
    remoteUrl + '/rider-info?' +
    'UUID=' + data.uuid +
    '&RiderPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {

        if (keys[0] == "rider_info" ) {

          var riderInfo = resp[keys[0]];
          var i = 0;

$("#riderInfo ul").append('
' + riderInfo.RiderFirstName + '
');
$("#riderInfo ul").append('
' + riderInfo.RiderLastName + '
');

        }
      }
    }
  };
}

function riderConfirmedMatch () {
//http://localhost:8000/rider-confirmed-match?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/rider-confirmed-match?' +
    'UUID=' + data.uuid +
    '&RiderPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      if (resp.rider_confirmed_match.uuid_driver !== null) {
        $("#riderConfirmedMatch ul").append('
 UUID_driver - ' + resp.rider_confirmed_match.uuid_driver + '
');
        $("#riderConfirmedMatch ul").append('
  UUID_rider - ' + resp.rider_confirmed_match.uuid_rider + '
');
        $("#riderConfirmedMatch ul").append('
 Score - ' + resp.rider_confirmed_match.score + '
');
      }
    }
  };
}

<commit_msg>extra driver,rider details<commit_after>// var remoteUrl = "https://api.carpoolvote.com/live";
var remoteUrl = "http://localhost:8000";

var driverLoggedIn = false;
var riderLoggedIn = false;

// Create a data object containing all URL query string data:
var data = tinyQuery.getAll();

if (data.uuid_driver) {
  data.uuid = data.uuid || data.uuid_driver;
  data.type = data.type || 'driver';
}
if (data.uuid_rider) {
  data.uuid = data.uuid || data.uuid_rider;
  data.type = data.type || 'rider';
}

// Cache jQuery selectors:
var $login = $('#login'),
  $manage = $('#manage'),
  $manageLogin = $('#manageLogin'),
  $info = $manage.find('#info'),
  $infoLogin = $manageLogin.find('#info')
  ;

if (data.uuid) {
  $login.find('#enter-uuid').remove();
}
if (data.type) {
  $login.find('#enter-type').remove();
}

$login.validator().on('submit', function(e) {
  if (e.isDefaultPrevented()) {
    return;
  }
  data.uuid = data.uuid || $(this).find('#inputUUID').val();
  data.type = data.type || $(this).find('#enter-type').find('input:checked').val();
  data.phone = $(this).find('#inputPhoneNumber').val();

  if (data.type === "driver") {
    driverExists();
  }
  else {
    riderExists();
  }

  // done in driver exists
  //
  // $(this).slideUp(300).attr('aria-hidden','true');
  // $manage.slideDown(300).attr('aria-hidden','false');
  // updateUI();
  e.preventDefault();
});

function updateUI(uuid, type, phone) {
  $manage.find('#btnCancelDriveOffer').toggle(data.type === 'driver');
  $manage.find('#btnCancelDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
  $manage.find('#btnPauseDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');

  $manage.find('#btnCancelRideRequest').toggle(data.type === 'rider');
  $manage.find('#btnCancelRiderMatch').toggle(data.type === 'rider' && data.score !== 'undefined');

  $manage.find('#btnAcceptDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
}

$manage
  .on('click', '#btnCancelRideRequest', cancelRideRequest)
  .on('click', '#btnCancelRiderMatch', cancelRiderMatch)
  .on('click', '#btnCancelDriveOffer', cancelDriveOffer)
  .on('click', '#btnCancelDriverMatch', cancelDriverMatch)
  .on('click', '#btnPauseDriverMatch', pauseDriverMatch)
  .on('click', '#btnAcceptDriverMatch', acceptDriverMatch)
  .on('click', '#logout', logout);

function cancelRideRequest() {
  if (!window.confirm('This will cancel your ride request. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      uuid: data.uuid,
      RiderPhone: data.phone
    },
    '/cancel-ride-request'
  );
}

function cancelRiderMatch() {
  if (!window.confirm('This will cancel your ride match. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      UUID_driver: data.uuid_driver,
      UUID_rider: data.uuid,
      Score: data.score,
      RiderPhone: data.phone
    },
    '/cancel-rider-match'
  );
}

function cancelDriveOffer() {
  if (!window.confirm('This will cancel your ride offer. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      uuid: data.uuid,
      DriverPhone: data.phone
    },
    '/cancel-drive-offer'
  );
}

function cancelDriverMatch() {
  if (!window.confirm('This will cancel your ride match. Are you sure you want to proceed?')) {
    return;
  }
  sendAjaxRequest(
    {
      UUID_driver: data.uuid_driver,
      UUID_rider: data.uuid,
      Score: data.score,
      RiderPhone: data.phone
    },
    '/cancel-driver-match'
  );
}

function acceptDriverMatch() {
  sendAjaxRequest(
    {
      UUID_driver: data.uuid,
      UUID_rider: data.uuid_rider,
      Score: data.score,
      DriverPhone: data.phone
    },
    '/accept-driver-match'
  );
}

function pauseDriverMatch() {
  sendAjaxRequest(
    {
      uuid: data.uuid,
      DriverPhone: data.phone
    },
    '/pause-driver-match'
  );
}

function logout() {
  window.location.search = tinyQuery.remove(['type','uuid','uuid_driver','uuid_rider']);
}

function sendAjaxRequest(ajaxData, ajaxPath) {
  var url = tinyQuery.set(ajaxData, remoteUrl + ajaxPath);

  $info.html('⏳ Loading…');

  $.getJSON(url, function(dbInfo) {
    var keys = Object.keys(dbInfo);
    if (keys) {
      info = dbInfo[keys[0]].toString();
      $info.text('ℹ ' + info);
    }
  })
  .fail(function(err) {
    $info.text('⚠ ' + err.statusText);
  });
}

function driverExists () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-exists?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {
        info = resp[keys[0]].toString();
        // $info.text(info);
        $infoLogin.text(info);

        if (keys[0] == "driver_exists" && info === "") {
          driverLoggedIn = true;

          $(this).slideUp(300).attr('aria-hidden','true');
          $manage.slideDown(300).attr('aria-hidden','false');
          updateUI();

          driverInfo();
          driverProposedMatches();
          driverConfirmedMatches();

        }
      }
    }
  };
}

function driverInfo () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-info?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {

        if (keys[0] == "driver_info" ) {

          var driverInfo = resp[keys[0]];
          var i = 0;

$("#driverInfo ul").append('
' + driverInfo.DriverFirstName + '
');
$("#driverInfo ul").append('
' + driverInfo.DriverLastName + '
');
$("#driverInfo ul").append('
' + driverInfo.UUID + '
');
$("#driverInfo ul").append('
' + driverInfo.DriverCollectionZIP + '
');
$("#driverInfo ul").append('
' + driverInfo.DriverEmail + '
');
$("#driverInfo ul").append('
' + driverInfo.DriverPhone + '
');
$("#driverInfo ul").append('
' + driverInfo.DriverLicenseNumber + '
');

        }
      }
    }
  };
}

function driverProposedMatches () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-proposed-matches?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      resp.forEach(val => {

          $("#driverProposedMatches ul").append('
 UUID_driver - ' + val.driver_proposed_matches.uuid_driver + '
');
  $("#driverProposedMatches ul").append('
  UUID_rider - ' + val.driver_proposed_matches.uuid_rider + '
');
  $("#driverProposedMatches ul").append('
 Score - ' + val.driver_proposed_matches.score + '
');

      });

    }
  };
}

function driverConfirmedMatches () {
//http://localhost:8000/driver-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/driver-confirmed-matches?' +
    'UUID=' + data.uuid +
    '&DriverPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      resp.forEach(val => {

          $("#driverConfirmedMatches ul").append('
 UUID_driver - ' + val.driver_confirmed_matches.uuid_driver + '
');
  $("#driverConfirmedMatches ul").append('
  UUID_rider - ' + val.driver_confirmed_matches.uuid_rider + '
');
  $("#driverConfirmedMatches ul").append('
 Score - ' + val.driver_confirmed_matches.score + '
');

      });

    }
  };
}

function riderExists () {
//http://localhost:8000/rider-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&RiderPhone=Test

  var url =
    remoteUrl + '/rider-exists?' +
    'UUID=' + data.uuid +
    '&RiderPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {
        info = resp[keys[0]].toString();
        // $info.text(info);
        $infoLogin.text(info);

        if (keys[0] == "rider_exists" && info === "") {
          riderLoggedIn = true;

          $(this).slideUp(300).attr('aria-hidden','true');
          $manage.slideDown(300).attr('aria-hidden','false');
          updateUI();

          riderInfo();
          riderConfirmedMatch();
        }
      }
    }
  };
}

function riderInfo () {
//http://localhost:8000/rider-exists?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&RiderPhone=Test

  var url =
    remoteUrl + '/rider-info?' +
    'UUID=' + data.uuid +
    '&RiderPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      var keys = Object.keys(resp);
      if (keys) {

        if (keys[0] == "rider_info" ) {

          var riderInfo = resp[keys[0]];
          var i = 0;

$("#riderInfo ul").append('
' + riderInfo.RiderFirstName + '
');
$("#riderInfo ul").append('
' + riderInfo.RiderLastName + '
');
$("#riderInfo ul").append('
' + riderInfo.UUID + '
');
$("#riderInfo ul").append('
' + riderInfo.RiderCollectionZIP + '
');
$("#riderInfo ul").append('
' + riderInfo.RiderEmail + '
');
$("#riderInfo ul").append('
' + riderInfo.RiderPhone + '
');

        }
      }
    }
  };
}

function riderConfirmedMatch () {
//http://localhost:8000/rider-confirmed-match?UUID=32e5cbd4-1342-4e1e-9076-0147e779a796&DriverPhone=Test

  var url =
    remoteUrl + '/rider-confirmed-match?' +
    'UUID=' + data.uuid +
    '&RiderPhone=' + data.phone;

  var request = new XMLHttpRequest();

  request.open("GET", url);
  request.send();

  request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
      console.log(request.responseText);

      var resp = JSON.parse(request.responseText);

      if (resp.rider_confirmed_match.uuid_driver !== null) {
        $("#riderConfirmedMatch ul").append('
 UUID_driver - ' + resp.rider_confirmed_match.uuid_driver + '
');
        $("#riderConfirmedMatch ul").append('
  UUID_rider - ' + resp.rider_confirmed_match.uuid_rider + '
');
        $("#riderConfirmedMatch ul").append('
 Score - ' + resp.rider_confirmed_match.score + '
');
      }
    }
  };
}

<|endoftext|>


<commit_before>
var ngm = angular.module(module.exports = 'datasha', [
	require('./datasha/ui'),
	require('./datasha/api'),
	require('./datasha/domain')
]);
<commit_msg>Obey config.js<commit_after>
if (!window.appConfig) {
	window.appConfig = require('../config.js');
}

var ngm = angular.module(module.exports = 'datasha', [
	require('./datasha/ui'),
	require('./datasha/api'),
	require('./datasha/domain')
]);
<|endoftext|>