<commit_before>/**
 * Author: DUONG Dinh Cuong, cuong3ihut@gmail.com.
 *
 * 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.
 **/

module.exports = function(RED) {
	"use strict";
	var q = require('q');
	var util = require("util");
	var isReachable = require('is-reachable');
	var webdriver = require("selenium-webdriver"),
	    By = webdriver.By,
	    until = webdriver.until;
	var isUtf8 = require('is-utf8');

	function getAbsoluteXPath(driver, element) {
		return driver.executeScript("function absoluteXPath(element) {" + "var comp, comps = [];" + "var parent = null;" + "var xpath = '';" + "var getPos = function(element) {" + "var position = 1, curNode;" + "if (element.nodeType == Node.ATTRIBUTE_NODE) {" + "return null;" + "}" + "for (curNode = element.previousSibling; curNode; curNode = curNode.previousSibling){" + "if (curNode.nodeName == element.nodeName) {" + "++position;" + "}" + "}" + "return position;" + "};" + "if (element instanceof Document) {" + "return '/';" + "}" + "for (; element && !(element instanceof Document); element = element.nodeType == Node.ATTRIBUTE_NODE ? element.ownerElement : element.parentNode) {" + "comp = comps[comps.length] = {};" + "switch (element.nodeType) {" + "case Node.TEXT_NODE:" + "comp.name = 'text()';" + "break;" + "case Node.ATTRIBUTE_NODE:" + "comp.name = '@' + element.nodeName;" + "break;" + "case Node.PROCESSING_INSTRUCTION_NODE:" + "comp.name = 'processing-instruction()';" + "break;" + "case Node.COMMENT_NODE:" + "comp.name = 'comment()';" + "break;" + "case Node.ELEMENT_NODE:" + "comp.name = element.nodeName;" + "break;" + "}" + "comp.position = getPos(element);" + "}" + "for (var i = comps.length - 1; i >= 0; i--) {" + "comp = comps[i];" + "xpath += '/' + comp.name.toLowerCase();" + "if (comp.position !== null) {" + "xpath += '[' + comp.position + ']';" + "}" + "}" + "return xpath;" + "} return absoluteXPath(arguments[0]);", element);
	}

	function SeleniumServerSetup(n) {
		RED.nodes.createNode(this, n);

		this.connected = false;
		this.connecting = false;
		this.usecount = 0;
		// Config node state
		this.remoteurl = n.remoteurl;
		this.browser = n.browser;

		var node = this;
		this.register = function() {
			node.usecount += 1;
		};

		this.deregister = function() {
			node.usecount -= 1;
			if (node.usecount == 0) {
			}
		};

		this.connect = function() {
			var deferred = q.defer();
			if (!node.connected && !node.connecting) {
				node.connecting = true;
				var url = require('url').parse(node.remoteurl);
				isReachable(url.host, function(error, reachable) {
					if (!error && reachable) {
						node.driver = new webdriver.Builder().forBrowser(node.browser).usingServer(node.remoteurl);
						node.log(RED._("connected", {
							server : (node.browser ? node.browser + "@" : "") + node.remoteurl
						}));
						node.connected = true;
						node.emit('connected');
						deferred.resolve(node.driver);
					} else {
						node.connecting = false;
						node.connected = false;
						deferred.reject({
							Error : "Invalid configuration."
						});
					}
				});
			} else {
				if (node.driver)
					deferred.resolve(node.driver);
			}
			return deferred.promise;
		};

		this.on('close', function(closecomplete) {
			if (this.connected) {
				this.on('disconnected', function() {
					closecomplete();
				});
				node.driver.quit();
			} else {
				closecomplete();
			}
		});
	}

	RED.nodes.registerType("selenium-server", SeleniumServerSetup);

	function SeleniumOpenURLNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.server = n.server;
		this.weburl = n.weburl;
		this.width = n.width;
		this.height = n.height;
		this.webtitle = n.webtitle;
		this.webtimeout = n.webtimeout;
		this.maximized = n.maximized;
		this.serverObj = RED.nodes.getNode(this.server);
		var node = this;
		if (node.serverObj) {
			node.serverObj.register();
			node.serverObj.connect().then(function(webdriver) {
				node.status({
					fill : "green",
					shape : "ring",
					text : "connected"
				});
			}, function(error) {
				node.status({
					fill : "red",
					shape : "ring",
					text : "disconnected"
				});
			});
		} else {
			node.error(RED._("common.status.error"));
		}
		this.on("input", function(msg) {
			node.serverObj.connect().then(function(webdriver) {
				function setWindowSize(driver, title) {
					if (node.maximized) {
						driver.manage().window().maximize().then(function() {
							node.send({
								driver : driver,
								payload : title
							});

						});
					} else {
						driver.manage().window().setSize(parseInt(node.width), parseInt(node.height)).then(function() {
							node.send({
								driver : driver,
								payload : title
							});

						});
					}
					node.status({
						fill : "green",
						shape : "ring",
						text : "connected"
					});
				}

				var driver = webdriver.build();
				driver.get(node.weburl);
				if (node.webtitle) {
					driver.wait(until.titleIs(node.webtitle), parseInt(node.webtimeout)).catch(function(errorback) {
						node.status({
							fill : "yellow",
							shape : "ring",
							text : "unexpected"
						});
					}).then(function() {
						driver.getTitle().then(function(title) {
							setWindowSize(driver, title);
						});
					});
				} else {
					setWindowSize(driver);
				}
			}, function(error) {
				node.status({
					fill : "red",
					shape : "ring",
					text : "disconnected"
				});
			});
		});
		this.on('close', function() {
			if (node.serverConn) {
				node.serverObj.deregister();
			}
		});
	}

	RED.nodes.registerType("open-web", SeleniumOpenURLNode);

	function SeleniumCloseBrowserNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.quit();
			node.send(msg);
		});
	}

	RED.nodes.registerType("close-web", SeleniumCloseBrowserNode);

	function SeleniumFindElementNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.selector = n.selector;
		this.value = n.text;
		var node = this;
		this.on("input", function(msg) {
			msg.element = msg.driver.findElement(By[node.selector](node.value));
			node.send(msg);
		});
	}

	RED.nodes.registerType("find-object", SeleniumFindElementNode);

	function SeleniumSendKeysNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.keys = n.text;
		var node = this;
		this.on("input", function(msg) {
			msg.element.sendKeys(node.keys).then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("send-keys", SeleniumSendKeysNode);

	function SeleniumClickOnNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.element.click().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("click-on", SeleniumClickOnNode);

	function SeleniumSetValueNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.value = n.text;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.executeScript("arguments[0].setAttribute('value', '" + node.value + "')", msg.element).then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("set-value", SeleniumSetValueNode);

	function SeleniumGetValueNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.expected = n.expected;
		var node = this;
		this.on("input", function(msg) {
			msg.element.getAttribute("value").then(function(text) {
				msg.payload = text;
				if (node.expected && node.expected != "" && node.expected != text) {
					if (!msg.errors) {
						msg.errors = new Array();
					}
					getAbsoluteXPath(msg.driver, msg.element).then(function(xpath) {
						msg.errors.push({
							name : node.name,
							xpath : xpath,
							expected : node.expected,
							value : text
						});
						node.send(msg);
						node.status({
							fill : "red",
							shape : "ring",
							text : "unexpected"
						});
					});
				} else {
					node.send(msg);
					node.status({
						fill : "green",
						shape : "ring",
						text : "passed"
					});
				}
			});
		});
	}

	RED.nodes.registerType("get-value", SeleniumGetValueNode);

	function SeleniumGetTextNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.expected = n.expected;
		var node = this;
		this.on("input", function(msg) {
			msg.element.getText().then(function(text) {
				msg.payload = text;
				if (node.expected && node.expected != "" && node.expected != text) {
					if (!msg.errors) {
						msg.errors = new Array();
					}
					getAbsoluteXPath(msg.driver, msg.element).then(function(xpath) {
						msg.errors.push({
							name : node.name,
							xpath : xpath,
							expected : node.expected,
							value : text
						});
						node.send(msg);
						node.status({
							fill : "red",
							shape : "ring",
							text : "unexpected"
						});
					});
				} else {
					node.send(msg);
					node.status({
						fill : "green",
						shape : "ring",
						text : "passed"
					});
				}
			});
		});
	}

	RED.nodes.registerType("get-text", SeleniumGetTextNode);

	function SeleniumTakeScreenshotNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.element.takeScreenshot().then(function(base64PNG) {
				msg.image = base64PNG;
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("screenshot", SeleniumTakeScreenshotNode);

	function SeleniumNavToNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.url = n.url;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().to(node.url).then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-to", SeleniumNavToNode);

	function SeleniumNavBackNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().back().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-back", SeleniumNavBackNode);

	function SeleniumNavForwardNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().forward().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-forward", SeleniumNavForwardNode);

	function SeleniumNavRefreshNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().refresh().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-refresh", SeleniumNavRefreshNode);

	function SeleniumRunScriptNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.func = n.func;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.executeScript(node.func, msg.element).then(function(results) {
				msg.payload = results;
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("run-script", SeleniumRunScriptNode);
};
<commit_msg>Update status text and enhance features<commit_after>/**
 * Author: DUONG Dinh Cuong, cuong3ihut@gmail.com.
 *
 * 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.
 **/

module.exports = function(RED) {
	"use strict";
	var q = require('q');
	var util = require("util");
	var isReachable = require('is-reachable');
	var webdriver = require("selenium-webdriver"),
	    By = webdriver.By,
	    until = webdriver.until;
	var isUtf8 = require('is-utf8');

	function getAbsoluteXPath(driver, element) {
		return driver.executeScript("function absoluteXPath(element) {" + "var comp, comps = [];" + "var parent = null;" + "var xpath = '';" + "var getPos = function(element) {" + "var position = 1, curNode;" + "if (element.nodeType == Node.ATTRIBUTE_NODE) {" + "return null;" + "}" + "for (curNode = element.previousSibling; curNode; curNode = curNode.previousSibling){" + "if (curNode.nodeName == element.nodeName) {" + "++position;" + "}" + "}" + "return position;" + "};" + "if (element instanceof Document) {" + "return '/';" + "}" + "for (; element && !(element instanceof Document); element = element.nodeType == Node.ATTRIBUTE_NODE ? element.ownerElement : element.parentNode) {" + "comp = comps[comps.length] = {};" + "switch (element.nodeType) {" + "case Node.TEXT_NODE:" + "comp.name = 'text()';" + "break;" + "case Node.ATTRIBUTE_NODE:" + "comp.name = '@' + element.nodeName;" + "break;" + "case Node.PROCESSING_INSTRUCTION_NODE:" + "comp.name = 'processing-instruction()';" + "break;" + "case Node.COMMENT_NODE:" + "comp.name = 'comment()';" + "break;" + "case Node.ELEMENT_NODE:" + "comp.name = element.nodeName;" + "break;" + "}" + "comp.position = getPos(element);" + "}" + "for (var i = comps.length - 1; i >= 0; i--) {" + "comp = comps[i];" + "xpath += '/' + comp.name.toLowerCase();" + "if (comp.position !== null) {" + "xpath += '[' + comp.position + ']';" + "}" + "}" + "return xpath;" + "} return absoluteXPath(arguments[0]);", element);
	}

	function SeleniumServerSetup(n) {
		RED.nodes.createNode(this, n);

		this.connected = false;
		this.connecting = false;
		this.usecount = 0;
		// Config node state
		this.remoteurl = n.remoteurl;
		this.browser = n.browser;

		var node = this;
		this.register = function() {
			node.usecount += 1;
		};

		this.deregister = function() {
			node.usecount -= 1;
			if (node.usecount == 0) {
			}
		};

		this.connect = function() {
			var deferred = q.defer();
			if (!node.connected && !node.connecting) {
				node.connecting = true;
				var url = require('url').parse(node.remoteurl);
				isReachable(url.host, function(error, reachable) {
					if (!error && reachable) {
						node.driver = new webdriver.Builder().forBrowser(node.browser).usingServer(node.remoteurl);
						node.log(RED._("connected", {
							server : (node.browser ? node.browser + "@" : "") + node.remoteurl
						}));
						node.connected = true;
						node.emit('connected');
						deferred.resolve(node.driver);
					} else {
						node.connecting = false;
						node.connected = false;
						deferred.reject({
							Error : "Invalid configuration."
						});
					}
				});
			} else {
				if (node.driver)
					deferred.resolve(node.driver);
			}
			return deferred.promise;
		};

		this.on('close', function(closecomplete) {
			if (this.connected) {
				this.on('disconnected', function() {
					closecomplete();
				});
				node.driver.quit();
			} else {
				closecomplete();
			}
		});
	}

	RED.nodes.registerType("selenium-server", SeleniumServerSetup);

	function SeleniumOpenURLNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.server = n.server;
		this.weburl = n.weburl;
		this.width = n.width;
		this.height = n.height;
		this.webtitle = n.webtitle;
		this.webtimeout = n.webtimeout;
		this.maximized = n.maximized;
		this.serverObj = RED.nodes.getNode(this.server);
		var node = this;
		if (node.serverObj) {
			node.serverObj.register();
			node.serverObj.connect().then(function(webdriver) {
				node.status({
					fill : "green",
					shape : "ring",
					text : "connected"
				});
			}, function(error) {
				node.status({
					fill : "red",
					shape : "ring",
					text : "disconnected"
				});
			});
		} else {
			node.error(RED._("common.status.error"));
		}
		this.on("input", function(msg) {
			node.serverObj.connect().then(function(webdriver) {
				function setWindowSize(driver, title) {
					if (node.maximized) {
						driver.manage().window().maximize().then(function() {
							node.send({
								driver : driver,
								payload : title
							});
						});
					} else {
						driver.manage().window().setSize(parseInt(node.width), parseInt(node.height)).then(function() {
							node.send({
								driver : driver,
								payload : title
							});
						});
					}
					node.status({
						fill : "green",
						shape : "ring",
						text : "connected"
					});
				}

				var driver = webdriver.build();
				driver.get(node.weburl);
				if (node.webtitle) {
					driver.wait(until.titleIs(node.webtitle), parseInt(node.webtimeout)).catch(function(errorback) {
						node.status({
							fill : "yellow",
							shape : "ring",
							text : "unexpected"
						});
					}).then(function() {
						driver.getTitle().then(function(title) {
							setWindowSize(driver, title);
						});
					});
				} else {
					setWindowSize(driver);
				}
			}, function(error) {
				node.status({
					fill : "red",
					shape : "ring",
					text : "disconnected"
				});
			});
		});
		this.on('close', function() {
			if (node.serverConn) {
				node.serverObj.deregister();
			}
		});
	}

	RED.nodes.registerType("open-web", SeleniumOpenURLNode);

	function SeleniumCloseBrowserNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.quit();
			node.send(msg);
		});
	}

	RED.nodes.registerType("close-web", SeleniumCloseBrowserNode);

	function SeleniumFindElementNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.selector = n.selector;
		this.value = n.text;
		var node = this;
		this.on("input", function(msg) {
			msg.element = msg.driver.findElement(By[node.selector](node.value));
			node.send(msg);
		});
	}

	RED.nodes.registerType("find-object", SeleniumFindElementNode);

	function SeleniumSendKeysNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.keys = n.text;
		var node = this;
		this.on("input", function(msg) {
			msg.element.sendKeys(node.keys).then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("send-keys", SeleniumSendKeysNode);

	function SeleniumClickOnNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.element.click().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("click-on", SeleniumClickOnNode);

	function SeleniumSetValueNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.value = n.text;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.executeScript("arguments[0].setAttribute('value', '" + node.value + "')", msg.element).then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("set-value", SeleniumSetValueNode);

	function SeleniumGetValueNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.expected = n.expected;
		var node = this;
		this.on("input", function(msg) {
			msg.element.getAttribute("value").then(function(text) {
				msg.payload = text;
				if (node.expected && node.expected != "" && node.expected != text) {
					if (!msg.errors) {
						msg.errors = new Array();
					}
					getAbsoluteXPath(msg.driver, msg.element).then(function(xpath) {
						msg.errors.push({
							name : node.name,
							xpath : xpath,
							expected : node.expected,
							value : text
						});
						node.send(msg);
						node.status({
							fill : "red",
							shape : "ring",
							text : "unexpected"
						});
					});
				} else {
					node.send(msg);
					node.status({
						fill : "green",
						shape : "ring",
						text : "passed"
					});
				}
			});
		});
	}

	RED.nodes.registerType("get-value", SeleniumGetValueNode);

	function SeleniumGetTextNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.expected = n.expected;
		var node = this;
		this.on("input", function(msg) {
			msg.element.getText().then(function(text) {
				msg.payload = text;
				if (node.expected && node.expected != "" && node.expected != text) {
					if (!msg.errors) {
						msg.errors = new Array();
					}
					getAbsoluteXPath(msg.driver, msg.element).then(function(xpath) {
						msg.errors.push({
							name : node.name,
							xpath : xpath,
							expected : node.expected,
							value : text
						});
						node.send(msg);
						node.status({
							fill : "red",
							shape : "ring",
							text : "unexpected"
						});
					});
				} else {
					node.send(msg);
					node.status({
						fill : "green",
						shape : "ring",
						text : "passed"
					});
				}
			});
		});
	}

	RED.nodes.registerType("get-text", SeleniumGetTextNode);

	function SeleniumTakeScreenshotNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.element.takeScreenshot().then(function(base64PNG) {
				msg.image = base64PNG;
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("screenshot", SeleniumTakeScreenshotNode);

	function SeleniumNavToNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.url = n.url;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().to(node.url).then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-to", SeleniumNavToNode);

	function SeleniumNavBackNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().back().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-back", SeleniumNavBackNode);

	function SeleniumNavForwardNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().forward().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-forward", SeleniumNavForwardNode);

	function SeleniumNavRefreshNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.navigate().refresh().then(function() {
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("nav-refresh", SeleniumNavRefreshNode);

	function SeleniumRunScriptNode(n) {
		RED.nodes.createNode(this, n);
		this.name = n.name;
		this.func = n.func;
		var node = this;
		this.on("input", function(msg) {
			msg.driver.executeScript(node.func, msg.element).then(function(results) {
				msg.payload = results;
				node.send(msg);
			});
		});
	}

	RED.nodes.registerType("run-script", SeleniumRunScriptNode);
};
<|endoftext|>


<commit_before>/*
 * Author: Tyler Russell
 */
require('angular').module('ays')
  .controller('LoginController',
    ['AUTH_EVENTS', '$sails', '$scope', '$state', 'AuthService', '$rootScope',
    function (AUTH_EVENTS, $sails, $scope, $state, AuthService, $rootScope) {
      $scope.loginErrorMessage = '';
      $scope.credentials = {
        userName: '',
        password: '',
      };

      // $scope.authenticateByKey = function ($event) {
      //   console.log(response);
      //   var keyCode = $event.which || $event.keyCode;
      //   switch(keyCode) {
      //     case 13:
      //       console.log('here');
      //       break;
      //     default:
      //
      //   };
      // }

      // Scope variable linked to the actual login button. Checks for validity via
      // the HTTP response codes from the AuthService methods, which in turn gets them from
      // our backend. Its not uniform yet, so if statements will probably get updated in the future
      $scope.authenticate = function () {
        // when logging in, check if user is already authenticated
        AuthService.getUserAuthStatus().then(function callback(response) {
          // if they aren't authenticated, attempt to log them in with input credentials
          if (response.status === 401) {
            loginUser().then(function (res) {
              // if user's login attempt failed with code 422
              if (res.data.code === 422) {
                $rootScope.$broadcast(AUTH_EVENTS.loginFailed);// broadcast isn't being caught for now
                $scope.loginErrorMessage = res.data.message;
              } else if (res.status === 200) {
                $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);// broadcast isn't being caught for now
                $state.go($state.params.toState, $state.params.toParams);
              }
            });
          } else { // else the user is already authenticated
            $state.go($state.params.toState, $state.params.toParams);
          }
        })
        // catch when the user is not logged in
        .catch(function () {
          console.log('An error occurred when checking the session status of the user.');
        });
      };
      var loginUser = function () {
        return AuthService.login($scope.credentials)
          .then(function (response) {
            return response;
          })
          .catch(function () {
            console.log('An error occurred trying to log in.');
          });
      };
    }])

    .directive('ngEnter', function () {
        return function (scope, element, attrs) {
            element.bind('keydown keypress', function (event) {
                if (event.which === 13) {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngEnter, {event: event});
                    });

                    event.preventDefault();
                }
            });
        };
    });
<commit_msg>Adding temporary change for debugging purposes in Circle build<commit_after>/*
 * Author: Tyler Russell
 */
require('angular').module('ays')
  .controller('LoginController',
    ['AUTH_EVENTS', '$sails', '$scope', '$state', 'AuthService', '$rootScope',
    function (AUTH_EVENTS, $sails, $scope, $state, AuthService, $rootScope) {
      $scope.loginErrorMessage = '';
      $scope.credentials = {
        userName: '',
        password: '',
      };

      // $scope.authenticateByKey = function ($event) {
      //   console.log(response);
      //   var keyCode = $event.which || $event.keyCode;
      //   switch(keyCode) {
      //     case 13:
      //       console.log('here');
      //       break;
      //     default:
      //
      //   };
      // }

      // Scope variable linked to the actual login button. Checks for validity via
      // the HTTP response codes from the AuthService methods, which in turn gets them from
      // our backend. Its not uniform yet, so if statements will probably get updated in the future
      $scope.authenticate = function () {
        // when logging in, check if user is already authenticated
        AuthService.getUserAuthStatus().then(function callback(response) {
          // if they aren't authenticated, attempt to log them in with input credentials
          if (response.status === 401) {
            loginUser().then(function (res) {
              // if user's login attempt failed with code 422
              if (res.data.code === 422) {
                $rootScope.$broadcast(AUTH_EVENTS.loginFailed);// broadcast isn't being caught for now
                $scope.loginErrorMessage = res.data.message;
              } else if (res.status === 200) {
                  console.log("wtf" + res);
                $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);// broadcast isn't being caught for now
                $state.go($state.params.toState, $state.params.toParams);
              }
            });
          } else { // else the user is already authenticated
            $state.go($state.params.toState, $state.params.toParams);
          }
        })
        // catch when the user is not logged in
        .catch(function () {
          console.log('An error occurred when checking the session status of the user.');
        });
      };
      var loginUser = function () {
        return AuthService.login($scope.credentials)
          .then(function (response) {
            return response;
          })
          .catch(function () {
            console.log('An error occurred trying to log in.');
          });
      };
    }])

    .directive('ngEnter', function () {
        return function (scope, element, attrs) {
            element.bind('keydown keypress', function (event) {
                if (event.which === 13) {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngEnter, {event: event});
                    });

                    event.preventDefault();
                }
            });
        };
    });
<|endoftext|>


<commit_before><commit_msg>starting plugin architecture<commit_after>Tempo.solr = (function (tempo) {

    var plugin = {
        functions : {
            '{{.*}}' : function() {

            }
        }
    };

    return tempo;

}(Tempo || {}));<|endoftext|>


<commit_before>#!/usr/bin/env node -r babel-register

import 'aws-util-firecloud/lib/bootstrap';

import _ from 'lodash-firecloud';
import build from 'aws-util-firecloud/lib/cfn/build';
import env from 'aws-util-firecloud/lib/env';

let main = async function({env}) {
  let tpl = await build({
    env,
    dir: env.STACK_STEM
  });
  return _.merge(tpl, {
    Description: `${env.ENV_NAME} ${env.STACK_STEM} Stack`,
    Outputs: {
      BuildNumber: {
        Value: env.BUILD_NUMBER
      },
      S3KeyPrefix: {
        Value: env.S3_KEY_PREFIX
      }
    }
  });
};

export default main;

(async function() {
  if (!module.parent) {
    console.log(JSON.stringify(await main({env}), undefined, 2));
  }
})();
<commit_msg>generalize<commit_after>#!/usr/bin/env node -r babel-register

import 'aws-util-firecloud/lib/bootstrap';

import _ from 'lodash-firecloud';
import build from 'aws-util-firecloud/lib/cfn/build';
import env from 'aws-util-firecloud/lib/env';

let main = async function({env}) {
  let tpl = await build({
    env,
    dir: env.STACK_STEM
  });
  return tpl;
};

export default main;

(async function() {
  if (!module.parent) {
    console.log(JSON.stringify(await main({env}), undefined, 2));
  }
})();
<|endoftext|>


<commit_before>angular.module('ssHome').controller('HomeCtrl', function($scope, ssYoutubeFeed) {

    ssYoutubeFeed.getRecent(3).then(function(videos) {
        $scope.videos = videos;
    });

    $scope.contacts = [
        {
            id: 1694010657,
            name: 'Securitas Protector',
            title: 'Alliance CEO'
        },
        {
            id: 92940230,
            name: 'Xeron Vann',
            title: 'Alliance Diplomat Director'
        },
        {
            id: 93670403,
            name: 'Gav Davies',
            title: 'Military Director'
        },
        {
            id: 335025985,
            name: 'Ganja Lotus',
            title: 'Co. Military Director'
        },
        {
            id: 618402478,
            name: 'Reuben Blackfeather',
            title: 'IT Director'
        }
    ];

    $scope.corporations = [
        {
            id: 98007439,
            name: 'Ethereal Vengeance'
        },
        {
            id: 98019237,
            name: 'Gallente Volunteer Defense Forces'
        },
        {
            id: 98041262,
            name: 'Community against Justice'
        },
        {
            id: 252518756,
            name: 'The Inf1dels'
        },
        {
            id: 851230678,
            name: 'The New Era'
        },
        {
            id: 555073675,
            name: 'The Green Cross'
        },
        {
            id: 1201027318,
            name: 'Lai Dai Solutions'
        },
        {
            id: 1747096465,
            name: 'Flailing Manmeat'
        },
        {
            id: 98161636,
            name: 'Physics Says No'
        },
        {
            id: 692190945,
            name: 'Shinigami Miners'
        },
        {
            id: 98253652,
            name: 'Pony Up Freight Ltd.'
        },
        {
            id: 98097817,
            name: 'Concordiat'
        },
        {
            id: 98272369,
            name: 'Truly Transdimensional'
        },
        {
            id: 98285822,
            name: 'Anime Masters'
        },
        {
            id: 98287113,
            name: 'Space - The Final Frontier'
        },
        {
            id: 98112705,
            name: 'Unsung Heroes'
        },
        {
            id: 98124232,
            name: 'Caveat Emptor Technologies LP'
        },
        {
            id: 98309567,
            name: 'Aerospace Fencing'
        },
        {
            id: 98314963,
            name: 'Cool Kids Club'
        },
        {
            id: 98197104,
            name: 'Concordiat Industries'
        },
        {
            id: 98189045,
            name: 'Pax Capital'
        },
        {
            id: 98319878,
            name: 'Only Fools and Horses'
        },
        {
            id: 98320400,
            name: 'Discharging Demeanor Solutions'
        },
        {
            id: 98324550,
            name: 'Borealis Academy'
        },
        {
            id: 98339677,
            name: 'The Contract Bureau'
        }
    ];

});<commit_msg>Updated the Alliance Member Corporations<commit_after>angular.module('ssHome').controller('HomeCtrl', function($scope, ssYoutubeFeed) {

    ssYoutubeFeed.getRecent(3).then(function(videos) {
        $scope.videos = videos;
    });

    $scope.contacts = [
        {
            id: 1694010657,
            name: 'Securitas Protector',
            title: 'Alliance Exec.'
        },
        {
            id: 92940230,
            name: 'Xeron Vann',
            title: 'Diplomacy Director'
        },
        {
            id: 335025985,
            name: 'Ganja Lotus',
            title: 'Military Director'
        },
		{
            id: 93670403,
            name: 'Gav Davies',
            title: 'Co. Military Director'
        },
        {
            id: 618402478,
            name: 'Reuben Blackfeather',
            title: 'IT Director'
        }
    ];

    $scope.corporations = [
        {
            id: 98007439,
            name: 'Ethereal Vengeance'
        },
        {
            id: 98019237,
            name: 'Gallente Volunteer Defense Forces'
        },
        {
            id: 98161636,
            name: 'Physics Says No'
        },
        {
            id: 98041262,
            name: 'Community against Justice'
        },
        {
            id: 851230678,
            name: 'The New Era'
        },
        {
            id: 555073675,
            name: 'The Green Cross'
        },
		{
			id: 98020221,
			name: Shattered Void
		},
        {
            id: 692190945,
            name: 'Shinigami Miners'
        },
        {
            id: 98097817,
            name: 'Concordiat'
        },
        {
            id: 98285822,
            name: 'Anime Masters'
        },
        {
            id: 98124232,
            name: 'Caveat Emptor Technologies LP'
        },
        {
            id: 98309567,
            name: 'Aerospace Fencing'
        },
        {
            id: 98197104,
            name: 'Concordiat Industries'
        },
        {
            id: 98189045,
            name: 'Pax Capital'
        },
        {
            id: 98319878,
            name: 'Only Fools and Horses'
        },
        {
            id: 98320400,
            name: 'Discharging Demeanor Solutions'
        },
        {
            id: 98339677,
            name: 'The Contract Bureau'
        }
    ];

});<|endoftext|>


<commit_before>let React = require("react")
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, textarea} = React.DOM
let cx = require("classnames")

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Text"

  static defaultProps = Object.assign(require("../default_props.js"))

  _inputHtml() {
  	return Object.assign({}, this.props.inputHtml, {
  		className: `${this.props.className || ""} form-control`.trim(),
  		valueLink: this.props.valueLink,
  	})
  }

  _cx() {
    return cx({
      "form-group": true,
      "has-error": this.props.errors != null,
      "has-success": this.state.edited && this.props.errors == null,
    })
  }

  _label() {
    if (this.props.label == null) return ""
    return label(this.props.labelHtml, this.props.label)
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: this._cx()},
        this._label(),
        div({className: "controls"},
          textarea(this._inputHtml()),
        ),
        this._errorList(this.props.errors),
      ),
    )
  }

}
<commit_msg>Remove Textarea Label, Use Frig Version Instead<commit_after>let React = require("react")
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, textarea} = React.DOM
let cx = require("classnames")

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Text"

  static defaultProps = Object.assign(require("../default_props.js"))

  _inputHtml() {
  	return Object.assign({}, this.props.inputHtml, {
  		className: `${this.props.className || ""} form-control`.trim(),
  		valueLink: this.props.valueLink,
  	})
  }

  _cx() {
    return cx({
      "form-group": true,
      "has-error": this.props.errors != null,
      "has-success": this.state.edited && this.props.errors == null,
    })
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: this._cx()},
        label(this.props),
        div({className: "controls"},
          textarea(this._inputHtml()),
        ),
        errorList(this.props.errors),
      ),
    )
  }

}
<|endoftext|>


<commit_before>module.exports = ErrorPage

var http = require('http')
, CODES = http.STATUS_CODES
, util = require('util')

function ErrorPage (req, res, opts) {
  opts = opts || {}
  return error

  function error () {
    var code, er, headers, message, handler
    for (var i = 0; i < arguments.length; i ++) {
      var arg = arguments[i]
      switch (typeof arg) {
        case 'number':
          code = arg
          break

        case 'string':
          if (res.template && res.template.has &&
              res.template.has(arg)) {
            handler = arg
          } else {
            message = arg
          }
          break

        case 'function':
          handler = arg
          break

        case 'object':
          if (!arg) break
          if (arg instanceof Error) {
            er = arg
          } else {
            headers = headers || {}
            Object.keys(arg).forEach(function (k) {
              if (k === 'statusCode' ||
                  k === 'cookie' ||
                  k === 'set-cookie') return
              headers[k] = arg[k]
            })
          }
          if (arg.statusCode && !code) code = arg.statusCode
          break
      }
    }

    if (!code) code = 500

    if (!message) {
      if (er) {
        message = opts.debug && er.stack ? er.stack : er.message
      } else {
        message = CODES[code]
      }
    }

    // now we have the args we care about

    // we might have a templater or something hooked up
    var xx = Math.floor(code / 100) + 'xx'
    handler = handler ||
              opts[code] ||
              opts[xx] ||
              opts['*'] ||
              defHandler

    if (typeof handler === 'string') {
      // templar integration
      if (res.template && res.template.has &&
          res.template.has(handler)) {
        handler = (function (template) {
          return function (req, res, data) {
            res.template(template, data, code)
          }
        })(handler)
      } else {
        // just a random string.
        handler = (function (str) {
          return function (req, res, data) {
            res.end(str)
          }
        })(handler)
      }
    }

    res.statusCode = code
    if (headers) Object.keys(headers).forEach(function (k) {
      res.setHeader(k, headers[k])
    })

    var data =
      { message: message
      , code: code
      , statusCode: code
      , error: er
      , options: opts
      , request: req.method + ' ' + req.url
      , headers: req.headers
      , url: req.url
      }

    if (opts.debug) {
      data.stack = new Error(message).stack
    }

    return handler(req, res, data)
  }
}

// TODO: Maybe if there's a logger on the req/res already,
// it should use that?
function defHandler (req, res, data) {
  res.setHeader('content-type', 'text/plain')
  if (data.headers) {
    data.headers = Object.keys(data.headers).filter(function (k) {
      return k !== 'cookie' && k !== 'set-cookie'
    }).reduce(function (h, k) {
      h[k] = req.headers[k]
      return h
    }, {})
  }
  var d, m = data.code + ' ' + data.message + ' ' + req.url
  d = util.inspect(data)
  console.error(new Date().toISOString() + ' ' + m)
  if (data.options.debug) {
    m += '\n' + data.stack + '\n' + d
  }
  res.end(m + '\n')
}
<commit_msg>Remove duplication of stack in debug info<commit_after>module.exports = ErrorPage

var http = require('http')
, CODES = http.STATUS_CODES
, util = require('util')

function ErrorPage (req, res, opts) {
  opts = opts || {}
  return error

  function error () {
    var code, er, headers, message, handler
    for (var i = 0; i < arguments.length; i ++) {
      var arg = arguments[i]
      switch (typeof arg) {
        case 'number':
          code = arg
          break

        case 'string':
          if (res.template && res.template.has &&
              res.template.has(arg)) {
            handler = arg
          } else {
            message = arg
          }
          break

        case 'function':
          handler = arg
          break

        case 'object':
          if (!arg) break
          if (arg instanceof Error) {
            er = arg
          } else {
            headers = headers || {}
            Object.keys(arg).forEach(function (k) {
              if (k === 'statusCode' ||
                  k === 'cookie' ||
                  k === 'set-cookie') return
              headers[k] = arg[k]
            })
          }
          if (arg.statusCode && !code) code = arg.statusCode
          break
      }
    }

    if (!code) code = 500

    if (!message) {
      if (er) {
        message = er.message
      } else {
        message = CODES[code]
      }
    }

    // now we have the args we care about

    // we might have a templater or something hooked up
    var xx = Math.floor(code / 100) + 'xx'
    handler = handler ||
              opts[code] ||
              opts[xx] ||
              opts['*'] ||
              defHandler

    if (typeof handler === 'string') {
      // templar integration
      if (res.template && res.template.has &&
          res.template.has(handler)) {
        handler = (function (template) {
          return function (req, res, data) {
            res.template(template, data, code)
          }
        })(handler)
      } else {
        // just a random string.
        handler = (function (str) {
          return function (req, res, data) {
            res.end(str)
          }
        })(handler)
      }
    }

    res.statusCode = code
    if (headers) Object.keys(headers).forEach(function (k) {
      res.setHeader(k, headers[k])
    })

    var data =
      { message: message
      , code: code
      , statusCode: code
      , error: er
      , options: opts
      , request: req.method + ' ' + req.url
      , headers: req.headers
      , url: req.url
      }

    if (opts.debug) {
      data.stack = new Error(message).stack
    }

    return handler(req, res, data)
  }
}

// TODO: Maybe if there's a logger on the req/res already,
// it should use that?
function defHandler (req, res, data) {
  res.setHeader('content-type', 'text/plain')
  if (data.headers) {
    data.headers = Object.keys(data.headers).filter(function (k) {
      return k !== 'cookie' && k !== 'set-cookie'
    }).reduce(function (h, k) {
      h[k] = req.headers[k]
      return h
    }, {})
  }
  var d, m = data.code + ' ' + data.message + ' ' + req.url
  d = util.inspect(data)
  console.error(new Date().toISOString() + ' ' + m)
  if (data.options.debug) {
    m += '\n' + data.stack + '\n' + d
  }
  res.end(m + '\n')
}
<|endoftext|>


<commit_before>/* ============================================================
 * bootstrap-collection.js v1.0.0
 * http://bootstrap.mohrenweiserpartner.de/mopa/bootstrap/forms/extended
 * ============================================================
 * Copyright 2012 Mohrenweiser & Partner
 *
 * 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.
 * ============================================================ */

!function ($) {

    "use strict";

   /* Collection PUBLIC CLASS DEFINITION
    * ============================== */

    var Collection = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.collection.defaults, options);

        var embeddedForms = 'div' + this.options.collection_id + ' .collection-item';
        this.options.index = $(embeddedForms).length - 1;
    };

    Collection.prototype = {
        constructor: Collection,
        add: function () {
            this.options.index = this.options.index + 1;
            var index = this.options.index;
            if ($.isFunction(this.options.addcheckfunc) && !this.options.addcheckfunc()) {
                if ($.isFunction(this.options.addfailedfunc)) {
                    this.options.addfailedfunc();
                }
                return;
            }
            this.addPrototype(index);
        },
        addPrototype: function(index) {
            var rowContent = $(this.options.collection_id).attr('data-prototype').replace(/__name__/g, index);
            var row = $("<div />");
            row.html(rowContent);
            $('div' + this.options.collection_id + '> .controls').append(row);
            $(this.options.collection_id).trigger('add.mopa-collection-item', [row]);
        },
        remove: function () {
                if (this.$element.parents('.collection-item').length !== 0){
                    this.$element.closest('.collection-item').remove();
                }
        }

    };

 /* COLLECTION PLUGIN DEFINITION
  * ======================== */

  $.fn.collection = function ( option ) {
      return this.each(function () {
          var $this = $(this),
            collection_id = $this.data('collection-add-btn'),
            data = $this.data('collection'),
            options = typeof option == 'object' ? option : {};
          if(collection_id){
              options.collection_id = collection_id;
          }
          else{
        	  options.collection_id = this.id.length === 0 ? '' : '#' + this.id;
          }
          if (!data){
              $this.data('collection', (data = new Collection(this, options)));
          }
          if (option == 'add') {
              data.add();
          }
          if (option == 'remove'){
              data.remove();
          }
      });
  };

  $.fn.collection.defaults = {
    collection_id: null,
    addcheckfunc: false,
    addfailedfunc: false
  };

  $.fn.collection.Constructor = Collection;

 /* COLLECTION DATA-API
  * =============== */

  $(function () {
      $('body').on('click.collection.data-api', '[data-collection-add-btn]', function ( e ) {
        var $btn = $(e.target);
        if (!$btn.hasClass('btn')){
            $btn = $btn.closest('.btn');
        }
        $btn.collection('add');
        e.preventDefault();
      });
      $('body').on('click.collection.data-api', '[data-collection-remove-btn]', function ( e ) {
        var $btn = $(e.target);
        if (!$btn.hasClass('btn')){
            $btn = $btn.closest('.btn');
        }
        $btn.collection('remove');
        e.preventDefault();
      });
  });

} ( window.jQuery );
<commit_msg>Added an event for "remove" collection item. The event is fired against the same control group as the event for "add" collection item that is fired currently.<commit_after>/* ============================================================
 * bootstrap-collection.js v1.0.0
 * http://bootstrap.mohrenweiserpartner.de/mopa/bootstrap/forms/extended
 * ============================================================
 * Copyright 2012 Mohrenweiser & Partner
 *
 * 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.
 * ============================================================ */

!function ($) {

    "use strict";

   /* Collection PUBLIC CLASS DEFINITION
    * ============================== */

    var Collection = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.collection.defaults, options);

        var embeddedForms = 'div' + this.options.collection_id + ' .collection-item';
        this.options.index = $(embeddedForms).length - 1;
    };

    Collection.prototype = {
        constructor: Collection,
        add: function () {
            this.options.index = this.options.index + 1;
            var index = this.options.index;
            if ($.isFunction(this.options.addcheckfunc) && !this.options.addcheckfunc()) {
                if ($.isFunction(this.options.addfailedfunc)) {
                    this.options.addfailedfunc();
                }
                return;
            }
            this.addPrototype(index);
        },
        addPrototype: function(index) {
            var rowContent = $(this.options.collection_id).attr('data-prototype').replace(/__name__/g, index);
            var row = $("<div />");
            row.html(rowContent);
            $('div' + this.options.collection_id + '> .controls').append(row);
            $(this.options.collection_id).trigger('add.mopa-collection-item', [row]);
        },
        remove: function () {
                if (this.$element.parents('.collection-item').length !== 0){
                    var row = this.$element.closest('.collection-item');
                    row.remove();
                    $(this.options.collection_id).trigger('remove.mopa-collection-item', [row]);
                }
        }

    };

 /* COLLECTION PLUGIN DEFINITION
  * ======================== */

  $.fn.collection = function ( option ) {
      return this.each(function () {
          var $this = $(this),
            collection_id = $this.data('collection-add-btn'),
            data = $this.data('collection'),
            options = typeof option == 'object' ? option : {};
          if(collection_id){
              options.collection_id = collection_id;
          }
          else if($this.closest(".control-group").attr('id')){
        	  options.collection_id = '#'+$this.closest(".control-group").attr('id');
          }
          else{
        	  options.collection_id = this.id.length === 0 ? '' : '#' + this.id;
          }
          if (!data){
              $this.data('collection', (data = new Collection(this, options)));
          }
          if (option == 'add') {
              data.add();
          }
          if (option == 'remove'){
              data.remove();
          }
      });
  };

  $.fn.collection.defaults = {
    collection_id: null,
    addcheckfunc: false,
    addfailedfunc: false
  };

  $.fn.collection.Constructor = Collection;

 /* COLLECTION DATA-API
  * =============== */

  $(function () {
      $('body').on('click.collection.data-api', '[data-collection-add-btn]', function ( e ) {
        var $btn = $(e.target);
        if (!$btn.hasClass('btn')){
            $btn = $btn.closest('.btn');
        }
        $btn.collection('add');
        e.preventDefault();
      });
      $('body').on('click.collection.data-api', '[data-collection-remove-btn]', function ( e ) {
        var $btn = $(e.target);
        if (!$btn.hasClass('btn')){
            $btn = $btn.closest('.btn');
        }
        $btn.collection('remove');
        e.preventDefault();
      });
  });

} ( window.jQuery );
<|endoftext|>


<commit_before>var IE10 = (navigator.userAgent.match(/(MSIE 10.0)/g) ? true : false);
if (IE10) {
	$('html').addClass('ie10');
}
var IE11 = (navigator.userAgent.match(/(MSIE 11.0)/g) ? true : false);
if (IE11) {
	$('html').addClass('ie11');
}

$(function() {

    // Accordion
    $(".accordion:not(.accordion-open) .accordion-content").css("display", "none");
    $('.accordion-title').click(function(){
		var labelText = $(this).text() === $(this).attr('data-close')? $(this).attr('data-initial') : $(this).attr('data-close');
		$(this).parent().toggleClass('accordion-open');
        $(this).next(".accordion-content").slideToggle();
        $(this).text(labelText);
    });

    // Add the "focus" value to class attribute
    $('.block-label').focusin( function() {
        $(this).addClass('focus');
    });

    // Remove the "focus" value to class attribute
    $('.block-label').focusout( function() {
        $(this).removeClass('focus');
    });

    // Help & Feedback container
    $(".feedback-container").css("display", "none");
    $('.feedback, .feed-close').click(function(){
     	$( ".feedback-container" ).toggle();
    });

    // Mobile specific - Nav
    $('#helper-toggle').click(function(){
     	$("#sidebar").toggle();
     	$(this).toggleClass("open-helper");
        return true;
    });

    // Non JS message
    $(".js-message").css("display", "none");
    $(".feed-close").css("display", "block");

    // //add new window message aria
    //   $(document).ready(function() {
    //     $("a[rel='external']").attr("aria-label" , "This link opens in a new window");
    //   });

      //add field length contextual for screen readers
      $(function() {
        var value = $(".form-control").attr("maxlength");
        $(".form-control").attr("aria-label" ,"Maximum " + value + " characters'");
      })

    // smooth scroll
    $('a[href^="#"]').bind('click.smoothscroll', function (e) {
        e.preventDefault();
        var target = this.hash,
            $target = $(target);
        $('html, body').animate({
            scrollTop: $(target).offset().top - 40
        }, 750, 'swing', function () {
            window.location.hash = target;
        });
    });

});

$(document).ready(function() {

    if (typeof console !== 'undefined') {
        console.log("document on ready " + areCookiesEnabled() );
    }

    if (areCookiesEnabled())  {
        $('#no-cookies').toggle(false);
        $('#content').toggle(true);
    } else {
        $('#no-cookies').toggle(true);
        $('#content').toggle(false);
    }

});

function areCookiesEnabled(){

    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }

    return (cookieEnabled);

}

function trackEvent(category, action, label, value){
    ga('send', 'event', getConfigurationObject(category, action, label, value));
}

function getConfigurationObject(category, action, label, value){
    var configurationObject = {};
    if (typeof category != 'undefined') configurationObject.eventCategory = category;
    if (typeof action != 'undefined') configurationObject.eventAction = action;
    if (typeof label != 'undefined') configurationObject.eventLabel = label;
    if (typeof value != 'undefined') configurationObject.eventValue = value;
    return configurationObject;
}

function trackVirtualPageView(category){
    ga('send', 'pageview', category);
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name,value) {
    var c_value=escape(value);
    document.cookie=c_name + "=" + c_value+";path=/";
}

function trackTiming(category, variable, timemeasured){
    if (0 < timemeasured && timemeasured <  36000000) {
        ga('send', 'timing', {
          'timingCategory': category,
          'timingVar': variable,
          'timingValue': timemeasured
        });
    }
}

// Selection Buttons
(function () {
  "use strict";
  var root = this,
      $ = root.jQuery;

  if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }

  var SelectionButtons = function (elmsOrSelector, opts) {
    var $elms;

    this.selectedClass = 'selected';
    this.focusedClass = 'focused';
    if (opts !== undefined) {
      $.each(opts, function (optionName, optionObj) {
        this[optionName] = optionObj;
      }.bind(this));
    }
    if (typeof elmsOrSelector === 'string') {
      $elms = $(elmsOrSelector);
      this.selector = elmsOrSelector;
      this.setInitialState($(this.selector));
    } else {
      this.$elms = elmsOrSelector;
      this.setInitialState(this.$elms);
    }
    this.addEvents();
  };
  SelectionButtons.prototype.addEvents = function () {
    if (typeof this.$elms !== 'undefined') {
      this.addElementLevelEvents();
    } else {
      this.addDocumentLevelEvents();
    }
  };
  SelectionButtons.prototype.setInitialState = function ($elms) {
    $elms.each(function (idx, elm) {
      var $elm = $(elm);

      if ($elm.is(':checked')) {
        this.markSelected($elm);
      }
    }.bind(this));
  };
  SelectionButtons.prototype.markFocused = function ($elm, state) {
    if (state === 'focused') {
      $elm.parent('label').addClass(this.focusedClass);
    } else {
      $elm.parent('label').removeClass(this.focusedClass);
    }
  };
  SelectionButtons.prototype.markSelected = function ($elm) {
    var radioName;

    if ($elm.attr('type') === 'radio') {
      radioName = $elm.attr('name');
      $($elm[0].form).find('input[name="' + radioName + '"]')
        .parent('label')
        .removeClass(this.selectedClass);
      $elm.parent('label').addClass(this.selectedClass);
    } else { // checkbox
      if ($elm.is(':checked')) {
        $elm.parent('label').addClass(this.selectedClass);
      } else {
        $elm.parent('label').removeClass(this.selectedClass);
      }
    }
  };
  SelectionButtons.prototype.addElementLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'element' });

    this.$elms
      .on('click', this.clickHandler)
      .on('focus blur', this.focusHandler);
  };
  SelectionButtons.prototype.addDocumentLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'document' });

    $(document)
      .on('click', this.selector, this.clickHandler)
      .on('focus blur', this.selector, this.focusHandler);
  };
  SelectionButtons.prototype.getClickHandler = function () {
    return function (e) {
      this.markSelected($(e.target));
    }.bind(this);
  };
  SelectionButtons.prototype.getFocusHandler = function (opts) {
    var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';

    return function (e) {
      var state = (e.type === focusEvent) ? 'focused' : 'blurred';

      this.markFocused($(e.target), state);
    }.bind(this);
  };
  SelectionButtons.prototype.destroy = function () {
    if (typeof this.selector !== 'undefined') {
      $(document)
        .off('click', this.selector, this.clickHandler)
        .off('focus blur', this.selector, this.focusHandler);
    } else {
      this.$elms
        .off('click', this.clickHandler)
        .off('focus blur', this.focusHandler);
    }
  };

  root.GOVUK.SelectionButtons = SelectionButtons;
}).call(this);

$(document).ready(function() {

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox'], .block-checkbox input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Details/summary polyfill
  // See /javascripts/vendor/details.polyfill.js

  // Cookie Banner
  if(getCookie("seen_cookie_message") === undefined){
    $("#global-cookie-message").show();
    var d = new Date;
    d.setTime(d.getTime() + 28 * 24 * 60 * 60 * 1e3);
    setCookie("seen_cookie_message", "yes; expires=" + d.toGMTString());
  }

});<commit_msg>CADS-584 removed aria labelling due to issue<commit_after>var IE10 = (navigator.userAgent.match(/(MSIE 10.0)/g) ? true : false);
if (IE10) {
	$('html').addClass('ie10');
}
var IE11 = (navigator.userAgent.match(/(MSIE 11.0)/g) ? true : false);
if (IE11) {
	$('html').addClass('ie11');
}

$(function() {

    // Accordion
    $(".accordion:not(.accordion-open) .accordion-content").css("display", "none");
    $('.accordion-title').click(function(){
		var labelText = $(this).text() === $(this).attr('data-close')? $(this).attr('data-initial') : $(this).attr('data-close');
		$(this).parent().toggleClass('accordion-open');
        $(this).next(".accordion-content").slideToggle();
        $(this).text(labelText);
    });

    // Add the "focus" value to class attribute
    $('.block-label').focusin( function() {
        $(this).addClass('focus');
    });

    // Remove the "focus" value to class attribute
    $('.block-label').focusout( function() {
        $(this).removeClass('focus');
    });

    // Help & Feedback container
    $(".feedback-container").css("display", "none");
    $('.feedback, .feed-close').click(function(){
     	$( ".feedback-container" ).toggle();
    });

    // Mobile specific - Nav
    $('#helper-toggle').click(function(){
     	$("#sidebar").toggle();
     	$(this).toggleClass("open-helper");
        return true;
    });

    // Non JS message
    $(".js-message").css("display", "none");
    $(".feed-close").css("display", "block");

    // //add new window message aria
    //   $(document).ready(function() {
    //     $("a[rel='external']").attr("aria-label" , "This link opens in a new window");
    //   });

      // //add field length contextual for screen readers
      // $(function() {
      //   var value = $(".form-control").attr("maxlength");
      //   $(".form-control").attr("aria-label" ,"Maximum " + value + " characters'");
      // });

    // smooth scroll
    $('a[href^="#"]').bind('click.smoothscroll', function (e) {
        e.preventDefault();
        var target = this.hash,
            $target = $(target);
        $('html, body').animate({
            scrollTop: $(target).offset().top - 40
        }, 750, 'swing', function () {
            window.location.hash = target;
        });
    });

});

$(document).ready(function() {

    if (typeof console !== 'undefined') {
        console.log("document on ready " + areCookiesEnabled() );
    }

    if (areCookiesEnabled())  {
        $('#no-cookies').toggle(false);
        $('#content').toggle(true);
    } else {
        $('#no-cookies').toggle(true);
        $('#content').toggle(false);
    }

});

function areCookiesEnabled(){

    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
        document.cookie="testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }

    return (cookieEnabled);

}

function trackEvent(category, action, label, value){
    ga('send', 'event', getConfigurationObject(category, action, label, value));
}

function getConfigurationObject(category, action, label, value){
    var configurationObject = {};
    if (typeof category != 'undefined') configurationObject.eventCategory = category;
    if (typeof action != 'undefined') configurationObject.eventAction = action;
    if (typeof label != 'undefined') configurationObject.eventLabel = label;
    if (typeof value != 'undefined') configurationObject.eventValue = value;
    return configurationObject;
}

function trackVirtualPageView(category){
    ga('send', 'pageview', category);
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name,value) {
    var c_value=escape(value);
    document.cookie=c_name + "=" + c_value+";path=/";
}

function trackTiming(category, variable, timemeasured){
    if (0 < timemeasured && timemeasured <  36000000) {
        ga('send', 'timing', {
          'timingCategory': category,
          'timingVar': variable,
          'timingValue': timemeasured
        });
    }
}

// Selection Buttons
(function () {
  "use strict";
  var root = this,
      $ = root.jQuery;

  if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }

  var SelectionButtons = function (elmsOrSelector, opts) {
    var $elms;

    this.selectedClass = 'selected';
    this.focusedClass = 'focused';
    if (opts !== undefined) {
      $.each(opts, function (optionName, optionObj) {
        this[optionName] = optionObj;
      }.bind(this));
    }
    if (typeof elmsOrSelector === 'string') {
      $elms = $(elmsOrSelector);
      this.selector = elmsOrSelector;
      this.setInitialState($(this.selector));
    } else {
      this.$elms = elmsOrSelector;
      this.setInitialState(this.$elms);
    }
    this.addEvents();
  };
  SelectionButtons.prototype.addEvents = function () {
    if (typeof this.$elms !== 'undefined') {
      this.addElementLevelEvents();
    } else {
      this.addDocumentLevelEvents();
    }
  };
  SelectionButtons.prototype.setInitialState = function ($elms) {
    $elms.each(function (idx, elm) {
      var $elm = $(elm);

      if ($elm.is(':checked')) {
        this.markSelected($elm);
      }
    }.bind(this));
  };
  SelectionButtons.prototype.markFocused = function ($elm, state) {
    if (state === 'focused') {
      $elm.parent('label').addClass(this.focusedClass);
    } else {
      $elm.parent('label').removeClass(this.focusedClass);
    }
  };
  SelectionButtons.prototype.markSelected = function ($elm) {
    var radioName;

    if ($elm.attr('type') === 'radio') {
      radioName = $elm.attr('name');
      $($elm[0].form).find('input[name="' + radioName + '"]')
        .parent('label')
        .removeClass(this.selectedClass);
      $elm.parent('label').addClass(this.selectedClass);
    } else { // checkbox
      if ($elm.is(':checked')) {
        $elm.parent('label').addClass(this.selectedClass);
      } else {
        $elm.parent('label').removeClass(this.selectedClass);
      }
    }
  };
  SelectionButtons.prototype.addElementLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'element' });

    this.$elms
      .on('click', this.clickHandler)
      .on('focus blur', this.focusHandler);
  };
  SelectionButtons.prototype.addDocumentLevelEvents = function () {
    this.clickHandler = this.getClickHandler();
    this.focusHandler = this.getFocusHandler({ 'level' : 'document' });

    $(document)
      .on('click', this.selector, this.clickHandler)
      .on('focus blur', this.selector, this.focusHandler);
  };
  SelectionButtons.prototype.getClickHandler = function () {
    return function (e) {
      this.markSelected($(e.target));
    }.bind(this);
  };
  SelectionButtons.prototype.getFocusHandler = function (opts) {
    var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';

    return function (e) {
      var state = (e.type === focusEvent) ? 'focused' : 'blurred';

      this.markFocused($(e.target), state);
    }.bind(this);
  };
  SelectionButtons.prototype.destroy = function () {
    if (typeof this.selector !== 'undefined') {
      $(document)
        .off('click', this.selector, this.clickHandler)
        .off('focus blur', this.selector, this.focusHandler);
    } else {
      this.$elms
        .off('click', this.clickHandler)
        .off('focus blur', this.focusHandler);
    }
  };

  root.GOVUK.SelectionButtons = SelectionButtons;
}).call(this);

$(document).ready(function() {

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox'], .block-checkbox input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Details/summary polyfill
  // See /javascripts/vendor/details.polyfill.js

  // Cookie Banner
  if(getCookie("seen_cookie_message") === undefined){
    $("#global-cookie-message").show();
    var d = new Date;
    d.setTime(d.getTime() + 28 * 24 * 60 * 60 * 1e3);
    setCookie("seen_cookie_message", "yes; expires=" + d.toGMTString());
  }

});<|endoftext|>


<commit_before>import { compileLogger, runLogger } from "../cli.controller";
const MockExpressRequest = require("mock-express-request");
const MockExpressResponse = require("mock-express-response");
import mongoose from "mongoose";
import config from "../../../config/environment";
import { seedTestData, testLoggerMsgToBePrinted } from "../../../config/seed";
import Logger from "../../logger/logger.model";

beforeAll(() => {
  // Connect to database
  mongoose.Promise = global.Promise;
  mongoose.connect(config.mongo.uri, config.mongo.options);

  // Populate DB with sample data
  if (config.seedDB) {
    return seedTestData();
  }
});

const goodCodeCompileResponseJSON = {
  error: false,
  stdout: "",
  stderr: ""
};

const badCodeCompileResponseJSON = {
  error: true,
  stdout: "",
  stderr: expect.stringMatching(/users\/\w+\/\w+\/BadCode\.c:\d+:\d+: error: /)
};

const infiniteLoopCodeCompileResponseJSON = goodCodeCompileResponseJSON;

const goodCodeRunResponseJSON = {
  error: false,
  stdout: testLoggerMsgToBePrinted,
  stderr: ""
};

const badCodeRunResponseJSON = {
  error: true,
  stdout: "",
  stderr: expect.stringMatching(/sudo: users\/\w+\/\w+\/BadCode: command not found/)
};

const infiniteLoopCodeRunResponseJSON = {
  error: true,
  stdout: "",
  stderr: expect.stringMatching(/TimeoutError/)
};

function getMockExpressRequestForLogger(logger) {
  return new MockExpressRequest({
    user: {
      id: "testUserId"
    },
    params: {
      id: logger._id
    }
  });
}

test("Compile Logger with Good Code", async () => {
  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });

  let req = getMockExpressRequestForLogger(goodCodeLogger);
  let res = new MockExpressResponse();

  let response = await compileLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(goodCodeCompileResponseJSON);
});

test("Compile Logger with Bad Code", async () => {
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });

  let req = getMockExpressRequestForLogger(badCodeLogger);
  let res = new MockExpressResponse();

  let response = await compileLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(badCodeCompileResponseJSON);
});

test("Compile Logger with Infinite Loop Code", async () => {
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  let req = getMockExpressRequestForLogger(infiniteLoopCodeLogger);
  let res = new MockExpressResponse();

  let response = await compileLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject({
    error: false,
    stdout: "",
    stderr: ""
  });
});

test("Compile Logger Load Test", async () => {
  // Note: On average this test requires:
  // - 15 seconds to run with 2 simultaneous calls to `compileLogger`
  // - 30 seconds to run with 5 simultaneous calls to `compileLogger`
  // - 40 seconds to run with 10 simultaneous calls to `compileLogger`
  // - 100 seconds to run with 30 simultaneous calls to `compileLogger`
  // - 300 seconds to run with 100 simultaneous calls to `compileLogger`
  // Change `numberOfRequests` and `testRunTimeInSeconds` as desired.
  const numberOfRequests = 100;
  const testRunTimeInSeconds = 600;
  jest.setTimeout(testRunTimeInSeconds * 1000);

  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  const allLoggers = [goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger];
  const allCompileResponseJSONs = [goodCodeCompileResponseJSON, badCodeCompileResponseJSON, infiniteLoopCodeCompileResponseJSON];

  const outputResponsePromises = [];

  expect.assertions(numberOfRequests);

  // execute a bunch of calls to compileLogger
  for (let i = 0; i < numberOfRequests; i++) {
    let randomIndex = Math.floor(Math.random() * 3);  // random integer between 0 and 2 inclusive
    let req = getMockExpressRequestForLogger(allLoggers[randomIndex]);
    let res = new MockExpressResponse();
    outputResponsePromises[i] = compileLogger(req, res).then(response => {
      let responseJson = response._getJSON();
      expect(responseJson).toMatchObject(allCompileResponseJSONs[randomIndex]);
    }).catch(err => {
      throw err;
    });
  }

  return Promise.all(outputResponsePromises);
});

test("Run Logger with Good Code", async () => {
  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });

  let req = getMockExpressRequestForLogger(goodCodeLogger);
  let res = new MockExpressResponse();

  let compileResponse = await compileLogger(req, res);
  res = new MockExpressResponse();
  let response = await runLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(goodCodeRunResponseJSON);
});

test("Run Logger with Bad Code", async () => {
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });

  let req = getMockExpressRequestForLogger(badCodeLogger);
  let res = new MockExpressResponse();

  let compileResponse = await compileLogger(req, res);
  res = new MockExpressResponse();
  let response = await runLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(badCodeRunResponseJSON);
});

test("Run Logger with Infinite Loop Code", async () => {
  jest.setTimeout(15000);
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  let req = getMockExpressRequestForLogger(infiniteLoopCodeLogger);
  let res = new MockExpressResponse();

  let compileResponse = await compileLogger(req, res);
  res = new MockExpressResponse();
  let response = await runLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(infiniteLoopCodeRunResponseJSON);
});

test("Run Logger Load Test", async () => {
  // Note: On average this test requires:
  // - 20 seconds to run with 2 simultaneous calls to `runLogger`
  // - 40 seconds to run with 5 simultaneous calls to `runLogger`
  // - 60 seconds to run with 10 simultaneous calls to `runLogger`
  // - 200 seconds to run with 30 simultaneous calls to `runLogger`
  // - 600 seconds to run with 100 simultaneous calls to `runLogger`
  // Change `numberOfRequests` and `testRunTimeInSeconds` as desired.
  const numberOfRequests = 100;
  const testRunTimeInSeconds = 600;
  jest.setTimeout(testRunTimeInSeconds * 1000);

  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  const allLoggers = [goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger];
  const allRunResponseJSONs = [goodCodeRunResponseJSON, badCodeRunResponseJSON, infiniteLoopCodeRunResponseJSON];

  const outputResponsePromises = [];

  expect.assertions(numberOfRequests);

  // execute compileLogger for each logger in advance of calling runLogger
  for (let i = 0; i < 3; i++) {
    let req = getMockExpressRequestForLogger(allLoggers[i]);
    let res = new MockExpressResponse();
    await compileLogger(req, res);
  }

  // execute a bunch of calls to runLogger
  for (let i = 0; i < numberOfRequests; i++) {
    let randomIndex = Math.floor(Math.random() * 3);  // random integer between 0 and 2 inclusive
    let req = getMockExpressRequestForLogger(allLoggers[randomIndex]);
    let res = new MockExpressResponse();
    outputResponsePromises[i] = runLogger(req, res).then(response => {
      let responseJson = response._getJSON();
      expect(responseJson).toMatchObject(allRunResponseJSONs[randomIndex]);
    }).catch(err => {
      throw err;
    });
  }

  return Promise.all(outputResponsePromises);
});

test("Compile And Run Logger Load Test", async () => {
  // Note: On average this test requires:
  // - 20 seconds to run with 2 simultaneous calls to `runLogger`
  // - 40 seconds to run with 5 simultaneous calls to `runLogger`
  // - 60 seconds to run with 10 simultaneous calls to `runLogger`
  // - 200 seconds to run with 30 simultaneous calls to `runLogger`
  // - 600 seconds to run with 100 simultaneous calls to `runLogger`
  // Change `numberOfRequests` and `testRunTimeInSeconds` as desired.
  const numberOfRequests = 100;
  const testRunTimeInSeconds = 600;
  jest.setTimeout(testRunTimeInSeconds * 1000);

  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  const allLoggers = [goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger, goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger];
  const allResponseJSONs = [
    goodCodeCompileResponseJSON, badCodeCompileResponseJSON, infiniteLoopCodeCompileResponseJSON,
    goodCodeRunResponseJSON, badCodeRunResponseJSON, infiniteLoopCodeRunResponseJSON
  ];
  const runOrCompileFunctions = [compileLogger, runLogger];

  const outputResponsePromises = [];

  expect.assertions(numberOfRequests);

  // execute compileLogger for each logger in advance of calling runLogger
  for (let i = 0; i < 3; i++) {
    let req = getMockExpressRequestForLogger(allLoggers[i]);
    let res = new MockExpressResponse();
    await compileLogger(req, res);
  }

  let startTime = Date.now();

  // execute a bunch of calls to runLogger
  for (let i = 0; i < numberOfRequests; i++) {
    let randomIndex = Math.floor(Math.random() * 6);  // random integer between 0 and 5 inclusive
    let runOrCompileIndex = Math.floor(randomIndex / 3);  // random choice of 0 or 1
    let runOrCompile = runOrCompileFunctions[runOrCompileIndex];  // random choice of `compileLogger` or `runLogger`
    let req = getMockExpressRequestForLogger(allLoggers[randomIndex]);
    let res = new MockExpressResponse();
    outputResponsePromises[i] = runOrCompile(req, res).then(response => {
      let responseJson = response._getJSON();
      expect(responseJson).toMatchObject(allResponseJSONs[randomIndex]);
    }).catch(err => {
      throw err;
    });
  }

  return Promise.all(outputResponsePromises).then(_ => {
    let endTime = Date.now();
    let timeElapsed = (endTime - startTime) / 1000;
    console.log(`We're done! It took ${timeElapsed} seconds to complete ${numberOfRequests} calls.`);
  });
});
<commit_msg>Change loads from 100 to 50<commit_after>import { compileLogger, runLogger } from "../cli.controller";
const MockExpressRequest = require("mock-express-request");
const MockExpressResponse = require("mock-express-response");
import mongoose from "mongoose";
import config from "../../../config/environment";
import { seedTestData, testLoggerMsgToBePrinted } from "../../../config/seed";
import Logger from "../../logger/logger.model";

beforeAll(() => {
  // Connect to database
  mongoose.Promise = global.Promise;
  mongoose.connect(config.mongo.uri, config.mongo.options);

  // Populate DB with sample data
  if (config.seedDB) {
    return seedTestData();
  }
});

const goodCodeCompileResponseJSON = {
  error: false,
  stdout: "",
  stderr: ""
};

const badCodeCompileResponseJSON = {
  error: true,
  stdout: "",
  stderr: expect.stringMatching(/users\/\w+\/\w+\/BadCode\.c:\d+:\d+: error: /)
};

const infiniteLoopCodeCompileResponseJSON = goodCodeCompileResponseJSON;

const goodCodeRunResponseJSON = {
  error: false,
  stdout: testLoggerMsgToBePrinted,
  stderr: ""
};

const badCodeRunResponseJSON = {
  error: true,
  stdout: "",
  stderr: expect.stringMatching(/sudo: users\/\w+\/\w+\/BadCode: command not found/)
};

const infiniteLoopCodeRunResponseJSON = {
  error: true,
  stdout: "",
  stderr: expect.stringMatching(/TimeoutError/)
};

function getMockExpressRequestForLogger(logger) {
  return new MockExpressRequest({
    user: {
      id: "testUserId"
    },
    params: {
      id: logger._id
    }
  });
}

test("Compile Logger with Good Code", async () => {
  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });

  let req = getMockExpressRequestForLogger(goodCodeLogger);
  let res = new MockExpressResponse();

  let response = await compileLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(goodCodeCompileResponseJSON);
});

test("Compile Logger with Bad Code", async () => {
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });

  let req = getMockExpressRequestForLogger(badCodeLogger);
  let res = new MockExpressResponse();

  let response = await compileLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(badCodeCompileResponseJSON);
});

test("Compile Logger with Infinite Loop Code", async () => {
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  let req = getMockExpressRequestForLogger(infiniteLoopCodeLogger);
  let res = new MockExpressResponse();

  let response = await compileLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject({
    error: false,
    stdout: "",
    stderr: ""
  });
});

test("Compile Logger Load Test", async () => {
  // Note: On average this test requires:
  // - 15 seconds to run with 2 simultaneous calls to `compileLogger`
  // - 30 seconds to run with 5 simultaneous calls to `compileLogger`
  // - 40 seconds to run with 10 simultaneous calls to `compileLogger`
  // - 100 seconds to run with 30 simultaneous calls to `compileLogger`
  // - 300 seconds to run with 100 simultaneous calls to `compileLogger`
  // Change `numberOfRequests` and `testRunTimeInSeconds` as desired.
  const numberOfRequests = 50;
  const testRunTimeInSeconds = 600;
  jest.setTimeout(testRunTimeInSeconds * 1000);

  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  const allLoggers = [goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger];
  const allCompileResponseJSONs = [goodCodeCompileResponseJSON, badCodeCompileResponseJSON, infiniteLoopCodeCompileResponseJSON];

  const outputResponsePromises = [];

  expect.assertions(numberOfRequests);

  // execute a bunch of calls to compileLogger
  for (let i = 0; i < numberOfRequests; i++) {
    let randomIndex = Math.floor(Math.random() * 3);  // random integer between 0 and 2 inclusive
    let req = getMockExpressRequestForLogger(allLoggers[randomIndex]);
    let res = new MockExpressResponse();
    outputResponsePromises[i] = compileLogger(req, res).then(response => {
      let responseJson = response._getJSON();
      expect(responseJson).toMatchObject(allCompileResponseJSONs[randomIndex]);
    }).catch(err => {
      throw err;
    });
  }

  return Promise.all(outputResponsePromises);
});

test("Run Logger with Good Code", async () => {
  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });

  let req = getMockExpressRequestForLogger(goodCodeLogger);
  let res = new MockExpressResponse();

  let compileResponse = await compileLogger(req, res);
  res = new MockExpressResponse();
  let response = await runLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(goodCodeRunResponseJSON);
});

test("Run Logger with Bad Code", async () => {
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });

  let req = getMockExpressRequestForLogger(badCodeLogger);
  let res = new MockExpressResponse();

  let compileResponse = await compileLogger(req, res);
  res = new MockExpressResponse();
  let response = await runLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(badCodeRunResponseJSON);
});

test("Run Logger with Infinite Loop Code", async () => {
  jest.setTimeout(15000);
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  let req = getMockExpressRequestForLogger(infiniteLoopCodeLogger);
  let res = new MockExpressResponse();

  let compileResponse = await compileLogger(req, res);
  res = new MockExpressResponse();
  let response = await runLogger(req, res);
  let responseJson = response._getJSON();
  expect(responseJson).toMatchObject(infiniteLoopCodeRunResponseJSON);
});

test("Run Logger Load Test", async () => {
  // Note: On average this test requires:
  // - 20 seconds to run with 2 simultaneous calls to `runLogger`
  // - 40 seconds to run with 5 simultaneous calls to `runLogger`
  // - 60 seconds to run with 10 simultaneous calls to `runLogger`
  // - 200 seconds to run with 30 simultaneous calls to `runLogger`
  // - 600 seconds to run with 100 simultaneous calls to `runLogger`
  // Change `numberOfRequests` and `testRunTimeInSeconds` as desired.
  const numberOfRequests = 50;
  const testRunTimeInSeconds = 600;
  jest.setTimeout(testRunTimeInSeconds * 1000);

  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  const allLoggers = [goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger];
  const allRunResponseJSONs = [goodCodeRunResponseJSON, badCodeRunResponseJSON, infiniteLoopCodeRunResponseJSON];

  const outputResponsePromises = [];

  expect.assertions(numberOfRequests);

  // execute compileLogger for each logger in advance of calling runLogger
  for (let i = 0; i < 3; i++) {
    let req = getMockExpressRequestForLogger(allLoggers[i]);
    let res = new MockExpressResponse();
    await compileLogger(req, res);
  }

  // execute a bunch of calls to runLogger
  for (let i = 0; i < numberOfRequests; i++) {
    let randomIndex = Math.floor(Math.random() * 3);  // random integer between 0 and 2 inclusive
    let req = getMockExpressRequestForLogger(allLoggers[randomIndex]);
    let res = new MockExpressResponse();
    outputResponsePromises[i] = runLogger(req, res).then(response => {
      let responseJson = response._getJSON();
      expect(responseJson).toMatchObject(allRunResponseJSONs[randomIndex]);
    }).catch(err => {
      throw err;
    });
  }

  return Promise.all(outputResponsePromises);
});

test("Compile And Run Logger Load Test", async () => {
  // Note: On average this test requires:
  // - 20 seconds to run with 2 simultaneous calls to `runLogger`
  // - 40 seconds to run with 5 simultaneous calls to `runLogger`
  // - 60 seconds to run with 10 simultaneous calls to `runLogger`
  // - 200 seconds to run with 30 simultaneous calls to `runLogger`
  // - 600 seconds to run with 100 simultaneous calls to `runLogger`
  // Change `numberOfRequests` and `testRunTimeInSeconds` as desired.
  const numberOfRequests = 50;
  const testRunTimeInSeconds = 600;
  jest.setTimeout(testRunTimeInSeconds * 1000);

  let goodCodeLogger = await Logger.findOne({
    className: "GoodCode"
  });
  let badCodeLogger = await Logger.findOne({
    className: "BadCode"
  });
  let infiniteLoopCodeLogger = await Logger.findOne({
    className: "InfiniteLoopCode"
  });

  const allLoggers = [goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger, goodCodeLogger, badCodeLogger, infiniteLoopCodeLogger];
  const allResponseJSONs = [
    goodCodeCompileResponseJSON, badCodeCompileResponseJSON, infiniteLoopCodeCompileResponseJSON,
    goodCodeRunResponseJSON, badCodeRunResponseJSON, infiniteLoopCodeRunResponseJSON
  ];
  const runOrCompileFunctions = [compileLogger, runLogger];

  const outputResponsePromises = [];

  expect.assertions(numberOfRequests);

  // execute compileLogger for each logger in advance of calling runLogger
  for (let i = 0; i < 3; i++) {
    let req = getMockExpressRequestForLogger(allLoggers[i]);
    let res = new MockExpressResponse();
    await compileLogger(req, res);
  }

  let startTime = Date.now();

  // execute a bunch of calls to runLogger
  for (let i = 0; i < numberOfRequests; i++) {
    let randomIndex = Math.floor(Math.random() * 6);  // random integer between 0 and 5 inclusive
    let runOrCompileIndex = Math.floor(randomIndex / 3);  // random choice of 0 or 1
    let runOrCompile = runOrCompileFunctions[runOrCompileIndex];  // random choice of `compileLogger` or `runLogger`
    let req = getMockExpressRequestForLogger(allLoggers[randomIndex]);
    let res = new MockExpressResponse();
    outputResponsePromises[i] = runOrCompile(req, res).then(response => {
      let responseJson = response._getJSON();
      expect(responseJson).toMatchObject(allResponseJSONs[randomIndex]);
    }).catch(err => {
      throw err;
    });
  }

  return Promise.all(outputResponsePromises).then(_ => {
    let endTime = Date.now();
    let timeElapsed = (endTime - startTime) / 1000;
    console.log(`We're done! It took ${timeElapsed} seconds to complete ${numberOfRequests} calls.`);
  });
});
<|endoftext|>


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

'use strict';

require('shelljs/global');
var xpath = require('xpath'),
    dom = require('xmldom').DOMParser;

var GITHUB_HTML = 'github.html';

config.fatal = true;
config.silent = true;

var args = process.argv.slice(2);

if (args.length < 1) {
  echo('Must specify a URL');
  exit(1);
}

process.on('exit', (code) => {
  if (code)
    echo('ERROR: ' + error());
});

///////////////
// Setup
///////////////

// Clean up the url
// Of the form: https://github.com/shelljs/benchmarks/pull/6
var repoName;
var remoteName;
var urlMatch = args[0].match(/^https:\/\/github.com\/(.+)\/(.+)\/pull\/(\d+)/);
if (urlMatch) {
  var prUrl = urlMatch[0];
  var ownerName = urlMatch[1];
  repoName = urlMatch[2];
  var prNumber = 'PR_' + urlMatch[3];

  // Pull the web page, parse it, and determine the correct URLs
  echo('Pulling your URL...');
  echo(prUrl);
  var html = exec('curl ' + prUrl).output;
  echo('URL successfully fetched');

  // For parsing with xpath
  var parserArgs = {
    errorHandler:{} // silence error messages
  };
  var doc = new dom(parserArgs).parseFromString(html);
  var nodes = xpath.select('//head/title', doc);
  var page_title = nodes[0].firstChild.data.trim();
  echo(page_title);

  var re = /[\u0000-\u007F]*/g;
  var matches = page_title.match(re);
  var description = matches[0].trim();

  nodes = xpath.select('//div/div/a[@class="author pull-header-username css-truncate css-truncate-target expandable"]', doc);
  var author = nodes[0].firstChild.data.trim();

  nodes = xpath.select('//div/div/span[@class="commit-ref current-branch css-truncate user-select-contain expandable"]/span', doc);

  var branch_name;
  var upstream;
  if (nodes.length === 4) {
    // remote
    remoteName = nodes[2].firstChild.data.trim();
    branch_name = nodes[3].firstChild.data.trim();
    upstream = 'https://github.com/' + ownerName + '/' + repoName + '.git';
  } else {
    // from the same repo
    remoteName = ownerName;
    branch_name = nodes[1].firstChild.data.trim();
  }
} else if (!(urlMatch = args[0].match(/^https:\/\/github.com\/(.+)\/([^\/]+)/))) {
  console.error('URL format is incorrect');
  exit(1);
}
// Setup directories
remoteName = remoteName || urlMatch[1];
repoName = repoName || urlMatch[2];
var topDir = prNumber || 'review_' + repoName;
var name = topDir;
rm('-Rf', name);
mkdir(name);
cd(name);
name = 'node_modules/';
mkdir(name);

// Clone the person's repo
echo('Cloning the repository...');
var cloneCmd = 'git clone' +
    (branch_name ? ' -b ' + branch_name : '') +
    ' https://github.com/' +
    remoteName + '/' + repoName + '.git';
echo(cloneCmd);
exec(cloneCmd);

ls().forEach(function (dir) {
  if (dir === 'node_modules')
    return; // don't do anything
  cd(dir);
});

if (upstream) {
  echo('Adding upstream');
  exec('git remote add upstream ' + upstream);
  exec('git fetch upstream');
} else {
  exec('git fetch origin master:master');
}

config.silent = false;
echo('Installing dependencies...');
exec('npm install'); // install dependencies

cd('..');
mv(repoName, 'node_modules/');
cd('node_modules/' + repoName);

if (repoName.toLowerCase() === 'shx') {
  exec('npm run build');
}

// installs bin scripts
exec('npm install');

config.fatal = false;

// **Specific to ShellJS**
if (repoName.toLowerCase() === 'shelljs') {
  // Run interesting tests
  var bugsToFix = [];

  exec('node ./scripts/generate-docs.js');
  if (exec('git diff --quiet README.md').code !== 0) {
    bugsToFix.append('docs');
    echo('Please generate docs');
  }

  echo('Running tests');
  if (exec('npm test').code !== 0) {
    bugsToFix.append('tests');
  }

  if (bugsToFix.length > 0) {
    echo('===================');
    echo('Must fix:');
    echo(bugsToFix);
    exit(1);
  } else {
    // Output useful info
    echo('Testing out Pull Request #' + prNumber);
    echo('> ' + description);
    echo();
    echo('This PR passes initial tests!');
  }
}

echo('cd ' + topDir + '/    or');
echo('cd ' + topDir + '/node_modules/' + repoName + '/');
<commit_msg>fix crash for reviewing the master branch<commit_after>#!/usr/bin/env node

'use strict';

require('shelljs/global');
var xpath = require('xpath'),
    dom = require('xmldom').DOMParser;

var GITHUB_HTML = 'github.html';

config.fatal = true;
config.silent = true;

var args = process.argv.slice(2);

if (args.length < 1) {
  echo('Must specify a URL');
  exit(1);
}

process.on('exit', (code) => {
  if (code)
    echo('ERROR: ' + error());
});

///////////////
// Setup
///////////////

// Clean up the url
// Of the form: https://github.com/shelljs/benchmarks/pull/6
var repoName;
var remoteName;
var urlMatch = args[0].match(/^https:\/\/github.com\/(.+)\/(.+)\/pull\/(\d+)/);
if (urlMatch) {
  var prUrl = urlMatch[0];
  var ownerName = urlMatch[1];
  repoName = urlMatch[2];
  var prNumber = 'PR_' + urlMatch[3];

  // Pull the web page, parse it, and determine the correct URLs
  echo('Pulling your URL...');
  echo(prUrl);
  var html = exec('curl ' + prUrl).output;
  echo('URL successfully fetched');

  // For parsing with xpath
  var parserArgs = {
    errorHandler:{} // silence error messages
  };
  var doc = new dom(parserArgs).parseFromString(html);
  var nodes = xpath.select('//head/title', doc);
  var page_title = nodes[0].firstChild.data.trim();
  echo(page_title);

  var re = /[\u0000-\u007F]*/g;
  var matches = page_title.match(re);
  var description = matches[0].trim();

  nodes = xpath.select('//div/div/a[@class="author pull-header-username css-truncate css-truncate-target expandable"]', doc);
  var author = nodes[0].firstChild.data.trim();

  nodes = xpath.select('//div/div/span[@class="commit-ref current-branch css-truncate user-select-contain expandable"]/span', doc);

  var branch_name;
  var upstream;
  if (nodes.length === 4) {
    // remote
    remoteName = nodes[2].firstChild.data.trim();
    branch_name = nodes[3].firstChild.data.trim();
    upstream = 'https://github.com/' + ownerName + '/' + repoName + '.git';
  } else {
    // from the same repo
    remoteName = ownerName;
    branch_name = nodes[1].firstChild.data.trim();
  }
} else if (!(urlMatch = args[0].match(/^https:\/\/github.com\/(.+)\/([^\/]+)/))) {
  console.error('URL format is incorrect');
  exit(1);
}
// Setup directories
remoteName = remoteName || urlMatch[1];
repoName = repoName || urlMatch[2];
var topDir = prNumber || 'review_' + repoName;
var name = topDir;
rm('-Rf', name);
mkdir(name);
cd(name);
name = 'node_modules/';
mkdir(name);

// Clone the person's repo
echo('Cloning the repository...');
var cloneCmd = 'git clone' +
    (branch_name ? ' -b ' + branch_name : '') +
    ' https://github.com/' +
    remoteName + '/' + repoName + '.git';
echo(cloneCmd);
exec(cloneCmd);

ls().forEach(function (dir) {
  if (dir === 'node_modules')
    return; // don't do anything
  cd(dir);
});

if (upstream) {
  echo('Adding upstream');
  exec('git remote add upstream ' + upstream);
  exec('git fetch upstream');
} else if (exec('git rev-parse --abbrev-ref HEAD').stdout.trim() !== 'master') {
  exec('git fetch origin master:master');
}

config.silent = false;
echo('Installing dependencies...');
exec('npm install'); // install dependencies

cd('..');
mv(repoName, 'node_modules/');
cd('node_modules/' + repoName);

if (repoName.toLowerCase() === 'shx') {
  exec('npm run build');
}

// installs bin scripts
exec('npm install');

config.fatal = false;

// **Specific to ShellJS**
if (repoName.toLowerCase() === 'shelljs') {
  // Run interesting tests
  var bugsToFix = [];

  exec('node ./scripts/generate-docs.js');
  if (exec('git diff --quiet README.md').code !== 0) {
    bugsToFix.append('docs');
    echo('Please generate docs');
  }

  echo('Running tests');
  if (exec('npm test').code !== 0) {
    bugsToFix.append('tests');
  }

  if (bugsToFix.length > 0) {
    echo('===================');
    echo('Must fix:');
    echo(bugsToFix);
    exit(1);
  } else {
    // Output useful info
    echo('Testing out Pull Request #' + prNumber);
    echo('> ' + description);
    echo();
    echo('This PR passes initial tests!');
  }
}

echo('cd ' + topDir + '/    or');
echo('cd ' + topDir + '/node_modules/' + repoName + '/');
<|endoftext|>