<commit_before>helper = {
	isArray : function (value) {
		return (Object.prototype.toString.call(value) === '[object Array]');
	},
	isString : function (value) {
		return typeof value == "string";
	},
	merge : function (source, left, right) { // three arrays
		var merged = source;

		if (helper.isArray(left)) merged = merged.concat(left);
		else if(!left.fake) merged.push(left);

		if (helper.isArray(right)) merged = merged.concat(right);
		else if((right) && (!right.fake)) merged.push(right);

		return merged;
	}
}

irGenerator = function() {
	var self = this;
	this.parseType = function (astNode) {
		if (helper.isArray(astNode)) { // Parse as array of parsed instances
			var tuple=[];
			for (var i=0;i<astNode.length;i++) {
				var t=self.parseType(astNode[i]);
				if (helper.isArray(t)) tuple = tuple.concat(t);
				else tuple.push(t);
			}
			return tuple;
		}
		if (helper.isString(astNode) && astNode) {
			return new type.simple(astNode);
		}
		if (astNode.type==="TypedIdList") {
			var dtype, tuple = [];
			dtype = self.parseType(astNode.dtype);
			for (var i=0;i<astNode.ids.length;i++) {
				tuple.push(new port.typedName(astNode.ids[i], dtype));
			}
			return tuple;
		}
		if (astNode.type==="ArrayOf") {
			var dtype;
			dtype = self.parseType(astNode.dtype);
			return new type.array(dtype);
		}
	}

	this.parseRangeGen = function (astNode, inputs) { // Range gen is a special case because it contains scatter and dot nodes
		var nodes = self.parse(astNode, inputs);
		// add scatter for every range node
		var scatter = [];
		var outPorts = [];
		for (var i = 0; i<nodes.length; i++) {
			if (nodes[i].type!="range") continue;
			var tcolor = color.getNew();
			scatter.push(new node.scatter(new port.colored(color.getColor(nodes[i])), new port.colored(tcolor)));
			outPorts.push(new port.colored(tcolor));
		}
		var gen = new node.rangeGen(inputs, outPorts);
		gen.addNodes(scatter);
		gen.addNodes(nodes);
		self.connectColored(gen);
		return gen;
	}

	this.parseComplex = function (astNode, complex, inputs) {
		if (!astNode) return new node.fake(0);

		if (helper.isArray(astNode)) {
			for (var i=0;i<astNode.length;i++) {
				var nodes=self.parse(astNode[i], inputs);
				complex.outPorts.push(new port.colored(color.getColor(nodes)));
				complex.addNodes(nodes);
			}
			// Connect SubNodes
			self.connectColored(complex);
			return complex;
		} else {
			throw "Unexpected kind of complex node"
		}
	}

	this.parseBody = function (astNode, inputs) { // Body is special case, it conatins self-created ports as "old" values
		return self.parseComplex(astNode, new node.loopBody(inputs, []), inputs);
	}

	this.parseReturns = function (astNode, inputs) {
		return self.parseComplex(astNode.expressions, new node.loopReturn(astNode.reduction.name, inputs, []), inputs);
	}

	this.parse = function (astNode, inputs, undefined) {
		if (helper.isArray(astNode)) { // Parse as array of parsed instances
			var first=self.parse(astNode[0], inputs);
			for (var i=1;i<astNode.length;i++) {
				first.addNodes(self.parse(astNode[i], inputs));
			}
			return first;
		}
		if (helper.isString(astNode) && astNode) {
			if (helper.isArray(inputs)) {
				for (var i = 0; i<inputs.length; i++) {
					if (inputs[i].id==astNode) return new node.fake(inputs[i].color);
				}
			}
			return new node.identifier(astNode, color.getNew());
		}

		if (astNode === null) return new node.virtualComplex();

		switch (astNode.type) {
			case "Let":
				var let = new node.virtualComplex();
				var letInputs = self.parse(astNode.deflist, inputs);
				color.assign(letInputs);
				let.addNodes(letInputs);
				newInputs = self.addInputs(inputs, letInputs)
				for (var i = 0; i < astNode.body.length; i++) {
					var nodes=self.parse(astNode.body[i], newInputs);
					let.outPorts.push(port.colored(color.getColor(nodes)));
					let.addNodes(nodes);
				}

				return let;

			case "NumericLiteral":
				return new node.constant(astNode.value, color.getNew());

			case "Function":
				var fInputs=self.parseType(astNode.params);
				var fOutputs=self.parseType(astNode.returns);
				// Create SubNodes

				color.assign(fInputs);

				var func=new node.func(astNode.name, fInputs, fOutputs);

				for (var i=0;i<astNode.expressions.length;i++) {
					var nodes=self.parse(astNode.expressions[i], fInputs);
					func.addNodes(nodes);
				}
				// Connect SubNodes
				self.connectColored(func);
				self.connectOutput(func);
				func.removeFake();

				return func;

			case "If":
				var condition = new node.virtualComplex();
				var condParts = self.parse(astNode.condition, inputs);
				condition.addNodes(condParts);

				var thenbranch = self.parse(astNode.then, inputs);
				var elsebranch = new node.virtualComplex();
				elsebranch.addNodes(self.parse(astNode.else, inputs));
				var elseif = self.parse(astNode.elseif, inputs);
				var ifnode = new node.if(condition, thenbranch, elsebranch, elseif, inputs, [new port.colored(color.getNew())]);
				return ifnode;

			case "For":
				var range = self.parseRangeGen(astNode.range, inputs);
				var body = self.parseBody(astNode.body, helper.merge(range.outPorts, inputs));
				var returns = self.parseReturns(astNode.returns, helper.merge( (body ? body.outPorts : []), range.outPorts, inputs));
				return new node.forAll(range, body, returns, inputs, [new port.colored(color.getColor(returns))]);

			case "BinaryExpression":
				var left = self.parse(astNode.left, inputs);
				var right = self.parse(astNode.right, inputs);
				var op = new node.binary(astNode.operator,
					[new port.colored(color.getColor(left)), new port.colored(color.getColor(right))], [new port.colored(color.getNew())]);

				return helper.merge([op], left, right);

			case "cross":
				return helper.merge([], self.parse(astNode.left, inputs), self.parse(astNode.right, inputs));

			case "RangeTriplet":
				var left = self.parse(astNode.exp, inputs);
				var right = self.parse(astNode.exp2, inputs);
				if (astNode.exp3) throw "Step is not implemented for triplet";// TODO: add exp3 which means step
				var op = new node.range(
					[new port.colored(color.getColor(left)), new port.colored(color.getColor(right))], [new port.colored(color.getNew())]);
				return helper.merge([op], left, right);

			case "Range":
				var range = self.parse(astNode.range, inputs);
				range[0].outPorts[0].name = astNode.name; //out port comes first that's why zero
				// TODO: fix 0
				return range;

			case "Definition":
				var def = self.parse(astNode.right, inputs);
				def.outPorts[0].name = astNode.left[0]; //out port comes first that's why zero
				// TODO: fix 0
				return def;

			case "Postfix":
				var base = self.parse(astNode.base, inputs);
				var nodes = [];
				var current, prev = null;

				for (var i = astNode.opList.length-1; i>=0; i--) {
					current = self.parse(astNode.opList[i], inputs);
					nodes = helper.merge(nodes, current);
					if (prev !== null) {
						prev.inPorts[0].color = current.outPorts[0].color;
					}
					prev = current;
				}
				current[0].inPorts[0].color = color.getColor(base);
				nodes.push(base);
				return nodes;

			case "[]":
				var nodes = [new node.element([new port.empty()], [new port.colored(color.getNew())])];
				var current;
				for (var i = 0; i < astNode.exp.length; i++) {
					current = self.parse(astNode.exp[i]);
					nodes= helper.merge(nodes, current);
					nodes[0].inPorts.push(new port.colored(color.getColor(current)));
				}
				return nodes;

			case "()":
				var nodes = [new node.element([new port.empty()], [new port.colored(color.getNew())])];
				var current;
				for (var i = 0; i < astNode.exp.length; i++) {
					current = self.parse(astNode.exp[i]);
					nodes= helper.merge(nodes, current);
					nodes[0].inPorts.push(new port.colored(color.getColor(current)));
				}
				return nodes;
			default: throw "Unexpected node type: " + astNode.type;
		}
	}

	this.addInputs = function (inputs, nodes) {
		if (helper.isArray(nodes)) {
			for (var i = 0; i < nodes.length; i++) {
				var tp = new port.typedName(nodes[i].outPorts[0].name, type.simple("auto"));
				tp.color = nodes[i].outPorts[0].color;
				inputs.push(tp);
			}
		} else {
			var tp = new port.typedName(nodes.outPorts[0].name, type.simple("auto"));
			tp.color = nodes.outPorts[0].color;
			inputs.push(tp);
		}
		return inputs;
	}

	this.notConnectedOutput = function (cNode, nodeNum, outPortNum) {
		for (var i=0; i < cNode.edges.length; i++) {
			if (cNode.edges[i].nodeFrom == nodeNum && cNode.edges[i].portFrom == outPortNum)
				return false;
		}
		return true;
	}

	this.connectOutput = function (cNode) {
		var outPortNum = 0;
        for (var i = 0; i < cNode.nodes.length; i++)
        	for (var j = 0; j < cNode.nodes[i].outPorts.length; j++) {
        		if (self.notConnectedOutput(cNode, i, j)) {
        			cNode.edges.push(new edge.single(i, j, -1, outPortNum++));
        		}
        	}
        if (outPortNum != cNode.outPorts.length)
        	throw "Output parameter list mismatch " + outPortNum + " instead of " + cNode.outPorts.length
	}

	this.connectColored = function (cNode) { // input is a complex node
		if (helper.isArray(cNode.inPorts) && helper.isArray(cNode.nodes)) {
			for (var i = 0; i < cNode.inPorts.length; i++) {
				if (!cNode.inPorts[i].color) continue;
				for (var j = 0; j< cNode.nodes.length; j++) {
					for (var k = 0; k< cNode.nodes[j].inPorts.length; k++) {
						if (cNode.inPorts[i].color==cNode.nodes[j].inPorts[k].color) {
							cNode.edges.push(new edge.single(-1, i, j, k));
						}
					}
				}
			}
		}
		if (helper.isArray(cNode.inPorts) && helper.isArray(cNode.outPorts)) {
			for (var i = 0; i < cNode.inPorts.length; i++) {
				if (!cNode.inPorts[i].color) continue;
				for (var j = 0; j< cNode.outPorts.length; j++) {
					if (cNode.inPorts[i].color==cNode.outPorts[j].color) {
						cNode.edges.push(new edge.single(-1, i, -1, j));
					}
				}
			}
		}
		if (helper.isArray(cNode.outPorts) && helper.isArray(cNode.nodes)) {
			for (var i = 0; i < cNode.outPorts.length; i++) {
				if (!cNode.outPorts[i].color) continue;
				for (var j = 0; j< cNode.nodes.length; j++) {
					for (var k = 0; k< cNode.nodes[j].outPorts.length; k++) {
						if (cNode.outPorts[i].color==cNode.nodes[j].outPorts[k].color) {
							cNode.edges.push(new edge.single(j, k, -1, i));
						}
					}
				}
			}
		}
		if (helper.isArray(cNode.nodes)) {
			for (var l = 0; l < cNode.nodes.length; l++) {
				if (!helper.isArray(cNode.nodes[l].outPorts)) continue;

				for (var i = 0; i < cNode.nodes[l].outPorts.length; i++) {
					if (!cNode.nodes[l].outPorts[i].color) continue;
					for (var j = 0; j< cNode.nodes.length; j++) {
						for (var k = 0; k< cNode.nodes[j].inPorts.length; k++) {
							if (cNode.nodes[l].outPorts[i].color==cNode.nodes[j].inPorts[k].color) {
								cNode.edges.push(new edge.single(l, i, j, k));
							}
						}
						if (!cNode.nodes[l].fake && cNode.nodes[j].fake && cNode.nodes[j].color &&
							cNode.nodes[j].color==cNode.nodes[l].outPorts[i].color) {
								cNode.nodes[j].inPorts.push(new port.colored(0));
								cNode.edges.push(new edge.single(l, i, j, 0));
						}
					}
				}
			}
		}
	}
}<commit_msg>Multiple let definition fix<commit_after>helper = {
	isArray : function (value) {
		return (Object.prototype.toString.call(value) === '[object Array]');
	},
	isString : function (value) {
		return typeof value == "string";
	},
	merge : function (source, left, right) { // three arrays
		var merged = source;

		if (helper.isArray(left)) merged = merged.concat(left);
		else if(!left.fake) merged.push(left);

		if (helper.isArray(right)) merged = merged.concat(right);
		else if((right) && (!right.fake)) merged.push(right);

		return merged;
	}
}

irGenerator = function() {
	var self = this;
	this.parseType = function (astNode) {
		if (helper.isArray(astNode)) { // Parse as array of parsed instances
			var tuple=[];
			for (var i=0;i<astNode.length;i++) {
				var t=self.parseType(astNode[i]);
				if (helper.isArray(t)) tuple = tuple.concat(t);
				else tuple.push(t);
			}
			return tuple;
		}
		if (helper.isString(astNode) && astNode) {
			return new type.simple(astNode);
		}
		if (astNode.type==="TypedIdList") {
			var dtype, tuple = [];
			dtype = self.parseType(astNode.dtype);
			for (var i=0;i<astNode.ids.length;i++) {
				tuple.push(new port.typedName(astNode.ids[i], dtype));
			}
			return tuple;
		}
		if (astNode.type==="ArrayOf") {
			var dtype;
			dtype = self.parseType(astNode.dtype);
			return new type.array(dtype);
		}
	}

	this.parseRangeGen = function (astNode, inputs) { // Range gen is a special case because it contains scatter and dot nodes
		var nodes = self.parse(astNode, inputs);
		// add scatter for every range node
		var scatter = [];
		var outPorts = [];
		for (var i = 0; i<nodes.length; i++) {
			if (nodes[i].type!="range") continue;
			var tcolor = color.getNew();
			scatter.push(new node.scatter(new port.colored(color.getColor(nodes[i])), new port.colored(tcolor)));
			outPorts.push(new port.colored(tcolor));
		}
		var gen = new node.rangeGen(inputs, outPorts);
		gen.addNodes(scatter);
		gen.addNodes(nodes);
		self.connectColored(gen);
		return gen;
	}

	this.parseComplex = function (astNode, complex, inputs) {
		if (!astNode) return new node.fake(0);

		if (helper.isArray(astNode)) {
			for (var i=0;i<astNode.length;i++) {
				var nodes=self.parse(astNode[i], inputs);
				complex.outPorts.push(new port.colored(color.getColor(nodes)));
				complex.addNodes(nodes);
			}
			// Connect SubNodes
			self.connectColored(complex);
			return complex;
		} else {
			throw "Unexpected kind of complex node"
		}
	}

	this.parseBody = function (astNode, inputs) { // Body is special case, it conatins self-created ports as "old" values
		return self.parseComplex(astNode, new node.loopBody(inputs, []), inputs);
	}

	this.parseReturns = function (astNode, inputs) {
		return self.parseComplex(astNode.expressions, new node.loopReturn(astNode.reduction.name, inputs, []), inputs);
	}

	this.parse = function (astNode, inputs, undefined) {
		if (helper.isArray(astNode)) { // Parse as array of parsed instances
			var arr=[self.parse(astNode[0], inputs)];
			for (var i=1;i<astNode.length;i++) {
				arr.push(self.parse(astNode[i], inputs));
			}
			return arr;
		}
		if (helper.isString(astNode) && astNode) {
			if (helper.isArray(inputs)) {
				for (var i = 0; i<inputs.length; i++) {
					if (inputs[i].id==astNode) return new node.fake(inputs[i].color);
				}
			}
			return new node.identifier(astNode, color.getNew());
		}

		if (astNode === null) return new node.virtualComplex();

		switch (astNode.type) {
			case "Let":
				var let = new node.virtualComplex();
				var letInputs = self.parse(astNode.deflist, inputs);
				color.assign(letInputs);
				let.addNodes(letInputs);
				newInputs = self.addInputs(inputs, letInputs)
				for (var i = 0; i < astNode.body.length; i++) {
					var nodes=self.parse(astNode.body[i], newInputs);
					let.outPorts.push(port.colored(color.getColor(nodes)));
					let.addNodes(nodes);
				}

				return let;

			case "NumericLiteral":
				return new node.constant(astNode.value, color.getNew());

			case "Function":
				var fInputs=self.parseType(astNode.params);
				var fOutputs=self.parseType(astNode.returns);
				// Create SubNodes

				color.assign(fInputs);

				var func=new node.func(astNode.name, fInputs, fOutputs);

				for (var i=0;i<astNode.expressions.length;i++) {
					var nodes=self.parse(astNode.expressions[i], fInputs);
					func.addNodes(nodes);
				}
				// Connect SubNodes
				self.connectColored(func);
				self.connectOutput(func);
				func.removeFake();

				return func;

			case "If":
				var condition = new node.virtualComplex();
				var condParts = self.parse(astNode.condition, inputs);
				condition.addNodes(condParts);

				var thenbranch = self.parse(astNode.then, inputs);
				var elsebranch = new node.virtualComplex();
				elsebranch.addNodes(self.parse(astNode.else, inputs));
				var elseif = self.parse(astNode.elseif, inputs);
				var ifnode = new node.if(condition, thenbranch, elsebranch, elseif, inputs, [new port.colored(color.getNew())]);
				return ifnode;

			case "For":
				var range = self.parseRangeGen(astNode.range, inputs);
				var body = self.parseBody(astNode.body, helper.merge(range.outPorts, inputs));
				var returns = self.parseReturns(astNode.returns, helper.merge( (body ? body.outPorts : []), range.outPorts, inputs));
				return new node.forAll(range, body, returns, inputs, [new port.colored(color.getColor(returns))]);

			case "BinaryExpression":
				var left = self.parse(astNode.left, inputs);
				var right = self.parse(astNode.right, inputs);
				var op = new node.binary(astNode.operator,
					[new port.colored(color.getColor(left)), new port.colored(color.getColor(right))], [new port.colored(color.getNew())]);

				return helper.merge([op], left, right);

			case "cross":
				return helper.merge([], self.parse(astNode.left, inputs), self.parse(astNode.right, inputs));

			case "RangeTriplet":
				var left = self.parse(astNode.exp, inputs);
				var right = self.parse(astNode.exp2, inputs);
				if (astNode.exp3) throw "Step is not implemented for triplet";// TODO: add exp3 which means step
				var op = new node.range(
					[new port.colored(color.getColor(left)), new port.colored(color.getColor(right))], [new port.colored(color.getNew())]);
				return helper.merge([op], left, right);

			case "Range":
				var range = self.parse(astNode.range, inputs);
				range[0].outPorts[0].name = astNode.name; //out port comes first that's why zero
				// TODO: fix 0
				return range;

			case "Definition":
				var def = self.parse(astNode.right, inputs);
				def.outPorts[0].name = astNode.left[0]; //out port comes first that's why zero
				// TODO: fix 0
				return def;

			case "Postfix":
				var base = self.parse(astNode.base, inputs);
				var nodes = [];
				var current, prev = null;

				for (var i = astNode.opList.length-1; i>=0; i--) {
					current = self.parse(astNode.opList[i], inputs);
					nodes = helper.merge(nodes, current);
					if (prev !== null) {
						prev.inPorts[0].color = current.outPorts[0].color;
					}
					prev = current;
				}
				current[0].inPorts[0].color = color.getColor(base);
				nodes.push(base);
				return nodes;

			case "[]":
				var nodes = [new node.element([new port.empty()], [new port.colored(color.getNew())])];
				var current;
				for (var i = 0; i < astNode.exp.length; i++) {
					current = self.parse(astNode.exp[i]);
					nodes= helper.merge(nodes, current);
					nodes[0].inPorts.push(new port.colored(color.getColor(current)));
				}
				return nodes;

			case "()":
				var nodes = [new node.element([new port.empty()], [new port.colored(color.getNew())])];
				var current;
				for (var i = 0; i < astNode.exp.length; i++) {
					current = self.parse(astNode.exp[i]);
					nodes= helper.merge(nodes, current);
					nodes[0].inPorts.push(new port.colored(color.getColor(current)));
				}
				return nodes;
			default: throw "Unexpected node type: " + astNode.type;
		}
	}

	this.addInputs = function (inputs, nodes) {
		if (helper.isArray(nodes)) {
			for (var i = 0; i < nodes.length; i++) {
				var tp = new port.typedName(nodes[i].outPorts[0].name, type.simple("auto"));
				tp.color = nodes[i].outPorts[0].color;
				inputs.push(tp);
			}
		} else {
			var tp = new port.typedName(nodes.outPorts[0].name, type.simple("auto"));
			tp.color = nodes.outPorts[0].color;
			inputs.push(tp);
		}
		return inputs;
	}

	this.notConnectedOutput = function (cNode, nodeNum, outPortNum) {
		for (var i=0; i < cNode.edges.length; i++) {
			if (cNode.edges[i].nodeFrom == nodeNum && cNode.edges[i].portFrom == outPortNum)
				return false;
		}
		return true;
	}

	this.connectOutput = function (cNode) {
		var outPortNum = 0;
        for (var i = 0; i < cNode.nodes.length; i++)
        	for (var j = 0; j < cNode.nodes[i].outPorts.length; j++) {
        		if (self.notConnectedOutput(cNode, i, j)) {
        			cNode.edges.push(new edge.single(i, j, -1, outPortNum++));
        		}
        	}
        if (outPortNum != cNode.outPorts.length)
        	throw "Output parameter list mismatch " + outPortNum + " instead of " + cNode.outPorts.length
	}

	this.connectColored = function (cNode) { // input is a complex node
		if (helper.isArray(cNode.inPorts) && helper.isArray(cNode.nodes)) {
			for (var i = 0; i < cNode.inPorts.length; i++) {
				if (!cNode.inPorts[i].color) continue;
				for (var j = 0; j< cNode.nodes.length; j++) {
					for (var k = 0; k< cNode.nodes[j].inPorts.length; k++) {
						if (cNode.inPorts[i].color==cNode.nodes[j].inPorts[k].color) {
							cNode.edges.push(new edge.single(-1, i, j, k));
						}
					}
				}
			}
		}
		if (helper.isArray(cNode.inPorts) && helper.isArray(cNode.outPorts)) {
			for (var i = 0; i < cNode.inPorts.length; i++) {
				if (!cNode.inPorts[i].color) continue;
				for (var j = 0; j< cNode.outPorts.length; j++) {
					if (cNode.inPorts[i].color==cNode.outPorts[j].color) {
						cNode.edges.push(new edge.single(-1, i, -1, j));
					}
				}
			}
		}
		if (helper.isArray(cNode.outPorts) && helper.isArray(cNode.nodes)) {
			for (var i = 0; i < cNode.outPorts.length; i++) {
				if (!cNode.outPorts[i].color) continue;
				for (var j = 0; j< cNode.nodes.length; j++) {
					for (var k = 0; k< cNode.nodes[j].outPorts.length; k++) {
						if (cNode.outPorts[i].color==cNode.nodes[j].outPorts[k].color) {
							cNode.edges.push(new edge.single(j, k, -1, i));
						}
					}
				}
			}
		}
		if (helper.isArray(cNode.nodes)) {
			for (var l = 0; l < cNode.nodes.length; l++) {
				if (!helper.isArray(cNode.nodes[l].outPorts)) continue;

				for (var i = 0; i < cNode.nodes[l].outPorts.length; i++) {
					if (!cNode.nodes[l].outPorts[i].color) continue;
					for (var j = 0; j< cNode.nodes.length; j++) {
						for (var k = 0; k< cNode.nodes[j].inPorts.length; k++) {
							if (cNode.nodes[l].outPorts[i].color==cNode.nodes[j].inPorts[k].color) {
								cNode.edges.push(new edge.single(l, i, j, k));
							}
						}
						if (!cNode.nodes[l].fake && cNode.nodes[j].fake && cNode.nodes[j].color &&
							cNode.nodes[j].color==cNode.nodes[l].outPorts[i].color) {
								cNode.nodes[j].inPorts.push(new port.colored(0));
								cNode.edges.push(new edge.single(l, i, j, 0));
						}
					}
				}
			}
		}
	}
}<|endoftext|>


<commit_before>/*
 * mobile buttonMarkup tests
 */
(function($){
	module("jquery.mobile.buttonMarkup.js");

	test( "header buttons should have the header class", function() {
		var headerButton1 = $("#header-button-1"),
		    headerButton2 = $("#header-button-2");

		ok((headerButton1.hasClass("ui-btn-left") &&
		    headerButton2.hasClass("ui-btn-right")), "first header button should have class 'ui-btn-left' and the second one should have 'ui-btn-right'");
	});

	test( "control group buttons should be enhanced inside a footer", function(){
		var group, linkCount;

		group = $("#control-group-footer");
		linkCount = group.find( "a" ).length;

		same( group.find("a.ui-btn").length, linkCount, "all 4 links should be buttons");
		same( group.find("a > span.ui-corner-left").length, 1, "only 1 left cornered button");
		same( group.find("a > span.ui-corner-right").length, 1, "only 1 right cornered button");
		same( group.find("a > span:not(.ui-corner-left):not(.ui-corner-right)").length, linkCount - 2, "only 2 buttons are cornered");
	});

	test( "control group buttons should respect theme-related data attributes", function(){
		var group = $("#control-group-content");

		ok(!group.find('[data-shadow=false]').hasClass("ui-shadow"),
			 "buttons with data-shadow=false should not have the ui-shadow class");
		ok(!group.find('[data-corners=false]').hasClass("ui-btn-corner-all"),
			 "buttons with data-corners=false should not have the ui-btn-corner-all class");
		ok(!group.find('[data-iconshadow=false] .ui-icon').hasClass("ui-icon-shadow"),
			 "buttons with data-iconshadow=false should not have the ui-icon-shadow class on their icons");
	});

	// Test for issue #3046 and #3054:
	test( "mousedown on SVG elements should not throw an exception", function(){
		var svg = $("#embedded-svg"),
			success = true,
			rect;
		ok(svg.length > 0, "found embedded svg document" );
		if ( svg.length > 0 ) {
			rect = $( "rect", svg );
			ok(rect.length > 0, "found rect" );
			try {
				rect.trigger("mousedown");
			} catch ( ex ) {
				success = false;
			}
			ok( success, "mousedown executed without exception");
		}
	});

	test( "Elements with “data-mini='true'” should have “ui-mini” class attached to enhanced element.", function(){
		var $mini = $("#mini"),
			$full = $("#full"),
			$minicontrol = $('#mini-control');

		ok( $full.not('.ui-mini'), "Original element does not have data attribute, enhanced version does not recieve .ui-mini.");
		ok( $mini.is('.ui-mini'), "Original element has data attribute, enhanced version recieves .ui-mini." );
		ok( $minicontrol.is('.ui-mini'), "Controlgroup has data attribute and recieves .ui-mini.");
	});

	test( "Ensure icon positioning defaults to left, and can be overridden with “data-iconpos”", function() {
		var posdefault = $("#iconpos1"),
		    posleft = $("#iconpos2"),
			posright = $("#iconpos3");

		ok( posdefault.hasClass("ui-btn-icon-left"), "Button with unspecified icon position gets .ui-btn-icon-left" );
		ok( posleft.hasClass("ui-btn-icon-left"), "Button with left icon positioning specified .ui-btn-icon-left" );
		ok( posright.hasClass("ui-btn-icon-right"), "Button with right icon positioning specified .ui-btn-icon-right" );

	});

	asyncTest( "ui-btn-* should be applied based on a setting", function() {
		// force touch support so the timeout is set
		$.support.touch = true;

		var $btn = $( "#hover-delay" );

		$btn.trigger( "vmousedown" );

		setTimeout(function() {
				ok( $btn.attr("class").indexOf( "ui-btn-down" ) == -1, "button doesn't have the down class yet" );
		}, $.mobile.buttonMarkup.hoverDelay / 2);

		setTimeout(function() {
				ok( $btn.attr("class").indexOf( "ui-btn-down" ) >= 0, "button has the down class yet" );
				start();
		}, $.mobile.buttonMarkup.hoverDelay + 100 );
	});
})(jQuery);
<commit_msg>Fixed forcing of event type to touch<commit_after>/*
 * mobile buttonMarkup tests
 */
(function($){
	module("jquery.mobile.buttonMarkup.js");

	test( "header buttons should have the header class", function() {
		var headerButton1 = $("#header-button-1"),
		    headerButton2 = $("#header-button-2");

		ok((headerButton1.hasClass("ui-btn-left") &&
		    headerButton2.hasClass("ui-btn-right")), "first header button should have class 'ui-btn-left' and the second one should have 'ui-btn-right'");
	});

	test( "control group buttons should be enhanced inside a footer", function(){
		var group, linkCount;

		group = $("#control-group-footer");
		linkCount = group.find( "a" ).length;

		same( group.find("a.ui-btn").length, linkCount, "all 4 links should be buttons");
		same( group.find("a > span.ui-corner-left").length, 1, "only 1 left cornered button");
		same( group.find("a > span.ui-corner-right").length, 1, "only 1 right cornered button");
		same( group.find("a > span:not(.ui-corner-left):not(.ui-corner-right)").length, linkCount - 2, "only 2 buttons are cornered");
	});

	test( "control group buttons should respect theme-related data attributes", function(){
		var group = $("#control-group-content");

		ok(!group.find('[data-shadow=false]').hasClass("ui-shadow"),
			 "buttons with data-shadow=false should not have the ui-shadow class");
		ok(!group.find('[data-corners=false]').hasClass("ui-btn-corner-all"),
			 "buttons with data-corners=false should not have the ui-btn-corner-all class");
		ok(!group.find('[data-iconshadow=false] .ui-icon').hasClass("ui-icon-shadow"),
			 "buttons with data-iconshadow=false should not have the ui-icon-shadow class on their icons");
	});

	// Test for issue #3046 and #3054:
	test( "mousedown on SVG elements should not throw an exception", function(){
		var svg = $("#embedded-svg"),
			success = true,
			rect;
		ok(svg.length > 0, "found embedded svg document" );
		if ( svg.length > 0 ) {
			rect = $( "rect", svg );
			ok(rect.length > 0, "found rect" );
			try {
				rect.trigger("mousedown");
			} catch ( ex ) {
				success = false;
			}
			ok( success, "mousedown executed without exception");
		}
	});

	test( "Elements with “data-mini='true'” should have “ui-mini” class attached to enhanced element.", function(){
		var $mini = $("#mini"),
			$full = $("#full"),
			$minicontrol = $('#mini-control');

		ok( $full.not('.ui-mini'), "Original element does not have data attribute, enhanced version does not recieve .ui-mini.");
		ok( $mini.is('.ui-mini'), "Original element has data attribute, enhanced version recieves .ui-mini." );
		ok( $minicontrol.is('.ui-mini'), "Controlgroup has data attribute and recieves .ui-mini.");
	});

	test( "Ensure icon positioning defaults to left, and can be overridden with “data-iconpos”", function() {
		var posdefault = $("#iconpos1"),
		    posleft = $("#iconpos2"),
			posright = $("#iconpos3");

		ok( posdefault.hasClass("ui-btn-icon-left"), "Button with unspecified icon position gets .ui-btn-icon-left" );
		ok( posleft.hasClass("ui-btn-icon-left"), "Button with left icon positioning specified .ui-btn-icon-left" );
		ok( posright.hasClass("ui-btn-icon-right"), "Button with right icon positioning specified .ui-btn-icon-right" );

	});

	asyncTest( "ui-btn-* should be applied based on a setting", function() {
		// force touch support so the timeout is set
		$.Event.prototype.originalEvent = {
			type: "touch"
		};

		var $btn = $( "#hover-delay" );

		$btn.trigger( "vmousedown" );

		setTimeout(function() {
				ok( $btn.attr("class").indexOf( "ui-btn-down" ) == -1, "button doesn't have the down class yet" );
		}, $.mobile.buttonMarkup.hoverDelay / 2);

		setTimeout(function() {
				ok( $btn.attr("class").indexOf( "ui-btn-down" ) >= 0, "button has the down class yet" );
				start();
		}, $.mobile.buttonMarkup.hoverDelay + 100 );
	});
})(jQuery);
<|endoftext|>


<commit_before>(function() {
	var logLevels = {
		FULL: "FULL", // record all logs
		ERROR: "ERROR", // only record errors and warnings
		NONE: "NONE", // record nothing from this module
	}

	logTypes = {
		DEBUG: "DEBUG",
		WARNING: "WARNING",
		ERROR: "ERROR",
	}

	var recordFunctions = {};

	recordFunctions[logLevels.FULL] = function(name, log, type) {
		console.log(name + ": " + log);
	}

	recordFunctions[logLevels.ERROR] = function(name, logtype) {
		console.log(name + ": " + log);
	}

	recordFunctions[logLevels.NONE] = function() {}

	var currentLogs = {
		"app": logLevels.FULL,
		"TodosController": logLevels.FULL,
	}

	window.loggerInstance = function(name) {
		var recordFunction = recordFunctions[currentLogs[name]] || function(){};

		return {
			record: function(message){
				recordFunction(name, message);
			},
		};
	}
})()
<commit_msg>Logic on not recording low level logs in error logger<commit_after>(function() {
	var logLevels = {
		FULL: "FULL", // record all logs
		ERROR: "ERROR", // only record errors and warnings
		NONE: "NONE", // record nothing from this module
	}

	logTypes = {
		DEBUG: 3,
		WARNING: 2,
		ERROR: 1,
	}

	var recordFunctions = {};

	recordFunctions[logLevels.FULL] = function(name, log, type) {
		console.log(name + ": " + log);
	}

	recordFunctions[logLevels.ERROR] = function(name, log, type) {
		if (log < logtTypes.WARNING) {
			console.log(name + ": " + log);
		}
	}

	recordFunctions[logLevels.NONE] = function() {}

	var currentLogs = {
		"app": logLevels.FULL,
		"TodosController": logLevels.FULL,
	}

	window.loggerInstance = function(name) {
		var recordFunction = recordFunctions[currentLogs[name]] || function(){};

		return {
			record: function(message){
				recordFunction(name, message);
			},
		};
	}
})()
<|endoftext|>


<commit_before>function DataUpdater(allViewModels) {
    var self = this;

    self.allViewModels = allViewModels;

    self._pluginHash = undefined;
    self._configHash = undefined;

    self._connectedDeferred = undefined;

    self._throttleFactor = 1;
    self._baseProcessingLimit = 500.0;
    self._lastProcessingTimes = [];
    self._lastProcessingTimesSize = 20;

    self._safeModePopup = undefined;

    self.increaseThrottle = function() {
        self.setThrottle(self._throttleFactor + 1);
    };

    self.decreaseThrottle = function() {
        if (self._throttleFactor <= 1) {
            return;
        }
        self.setThrottle(self._throttleFactor - 1);
    };

    self.setThrottle = function(throttle) {
        self._throttleFactor = throttle;

        self._send("throttle", self._throttleFactor);
        log.debug("DataUpdater: New SockJS throttle factor:", self._throttleFactor, " new processing limit:", self._baseProcessingLimit * self._throttleFactor);
    };

    self._send = function(message, data) {
        var payload = {};
        payload[message] = data;
        self._socket.send(JSON.stringify(payload));
    };

    self.connect = function() {
        if (self._connectedDeferred) {
            self._connectedDeferred.reject();
        }
        self._connectedDeferred = $.Deferred();
        OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG});
        return self._connectedDeferred.promise();
    };

    self.reconnect = function() {
        if (self._connectedDeferred) {
            self._connectedDeferred.reject();
        }
        self._connectedDeferred = $.Deferred();
        OctoPrint.socket.reconnect();
        return self._connectedDeferred.promise();
    };

    self._onReconnectAttempt = function(trial) {
        if (trial <= 0) {
            // Only consider it a real disconnect if the trial number has exceeded our threshold.
            return;
        }

        var handled = false;
        callViewModelsIf(
            self.allViewModels,
            "onServerDisconnect",
            function() { return !handled; },
            function(method) { var result = method(); handled = (result !== undefined && !result) || handled; }
        );

        if (handled) {
            return true;
        }

        showOfflineOverlay(
            gettext("Server is offline"),
            gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below."),
            self.reconnect
        );
    };

    self._onReconnectFailed = function() {
        var handled = false;
        callViewModelsIf(
            self.allViewModels,
            "onServerDisconnect",
            function() { return !handled; },
            function(method) { var result = method(); handled = (result !== undefined && !result) || handled; }
        );

        if (handled) {
            return;
        }

        $("#offline_overlay_title").text(gettext("Server is offline"));
        $("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below."));
    };

    self._onConnected = function(event) {
        var data = event.data;

        // update version information
        var oldVersion = VERSION;
        VERSION = data["version"];
        DISPLAY_VERSION = data["display_version"];
        BRANCH = data["branch"];
        $("span.version").text(DISPLAY_VERSION);

        // update plugin hash
        var oldPluginHash = self._pluginHash;
        self._pluginHash = data["plugin_hash"];

        // update config hash
        var oldConfigHash = self._configHash;
        self._configHash = data["config_hash"];

        // process safe mode
        if (self._safeModePopup) self._safeModePopup.remove();
        if (data["safe_mode"]) {
            // safe mode is active, let's inform the user
            log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");

            self._safeModePopup = new PNotify({
                title: gettext("Safe mode is active"),
                text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
                hide: false
            });
        }

        // if the offline overlay is still showing, now's a good time to
        // hide it, plus reload the camera feed if it's currently displayed
        if ($("#offline_overlay").is(":visible")) {
            hideOfflineOverlay();
            callViewModels(self.allViewModels, "onServerReconnect");
            callViewModels(self.allViewModels, "onDataUpdaterReconnect");
        } else {
            callViewModels(self.allViewModels, "onServerConnect");
        }

        // if the version, the plugin hash or the config hash changed, we
        // want the user to reload the UI since it might be stale now
        var versionChanged = oldVersion != VERSION;
        var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
        var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
        if (versionChanged || pluginsChanged || configChanged) {
            showReloadOverlay();
        }

        log.info("Connected to the server");

        // if we have a connected promise, resolve it now
        if (self._connectedDeferred) {
            self._connectedDeferred.resolve();
            self._connectedDeferred = undefined;
        }
    };

    self._onHistoryData = function(event) {
        callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
    };

    self._onCurrentData = function(event) {
        callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
    };

    self._onSlicingProgress = function(event) {
        $("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));

        var data = event.data;
        callViewModels(self.allViewModels, "onSlicingProgress", [
            data["slicer"],
            data["model_path"],
            data["machinecode_path"],
            data["progress"]
        ]);
    };

    self._onEvent = function(event) {
        var gcodeUploadProgress = $("#gcode_upload_progress");
        var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);

        var type = event.data["type"];
        var payload = event.data["payload"];
        var html = "";

        log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));

        if (type == "PrintCancelled") {
            if (payload.firmwareError) {
                new PNotify({
                    title: gettext("Unhandled communication error"),
                    text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
                    type: "error",
                    hide: false
                });
            }
        } else if (type == "Error") {
            new PNotify({
                    title: gettext("Unhandled communication error"),
                    text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
                    type: "error",
                    hide: false
            });
        }

        var legacyEventHandlers = {
            "UpdatedFiles": "onUpdatedFiles",
            "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
            "MetadataAnalysisFinished": "onMetadataAnalysisFinished",
            "SlicingDone": "onSlicingDone",
            "SlicingCancelled": "onSlicingCancelled",
            "SlicingFailed": "onSlicingFailed"
        };
        _.each(self.allViewModels, function(viewModel) {
            if (viewModel.hasOwnProperty("onEvent" + type)) {
                viewModel["onEvent" + type](payload);
            } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
                // there might still be code that uses the old callbacks, make sure those still get called
                // but log a warning
                log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
                viewModel[legacyEventHandlers[type]](payload);
            }
        });
    };

    self._onTimelapse = function(event) {
        callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
    };

    self._onPluginMessage = function(event) {
        callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
    };

    self._onIncreaseRate = function(measurement, minimum) {
        log.debug("We are fast (" + measurement + " < " + minimum + "), increasing refresh rate");
        OctoPrint.socket.increaseRate();
    };

    self._onDecreaseRate = function(measurement, maximum) {
        log.debug("We are slow (" + measurement + " > " + maximum + "), reducing refresh rate");
        OctoPrint.socket.decreaseRate();
    };

    OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
    OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
    OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
    OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
    OctoPrint.socket
        .onMessage("connected", self._onConnected)
        .onMessage("history", self._onHistoryData)
        .onMessage("current", self._onCurrentData)
        .onMessage("slicingProgress", self._onSlicingProgress)
        .onMessage("event", self._onEvent)
        .onMessage("timelapse", self._onTimelapse)
        .onMessage("plugin", self._onPluginMessage);
}
<commit_msg>No scary message on autodetect fail<commit_after>function DataUpdater(allViewModels) {
    var self = this;

    self.allViewModels = allViewModels;

    self._pluginHash = undefined;
    self._configHash = undefined;

    self._connectedDeferred = undefined;

    self._throttleFactor = 1;
    self._baseProcessingLimit = 500.0;
    self._lastProcessingTimes = [];
    self._lastProcessingTimesSize = 20;

    self._safeModePopup = undefined;

    self.increaseThrottle = function() {
        self.setThrottle(self._throttleFactor + 1);
    };

    self.decreaseThrottle = function() {
        if (self._throttleFactor <= 1) {
            return;
        }
        self.setThrottle(self._throttleFactor - 1);
    };

    self.setThrottle = function(throttle) {
        self._throttleFactor = throttle;

        self._send("throttle", self._throttleFactor);
        log.debug("DataUpdater: New SockJS throttle factor:", self._throttleFactor, " new processing limit:", self._baseProcessingLimit * self._throttleFactor);
    };

    self._send = function(message, data) {
        var payload = {};
        payload[message] = data;
        self._socket.send(JSON.stringify(payload));
    };

    self.connect = function() {
        if (self._connectedDeferred) {
            self._connectedDeferred.reject();
        }
        self._connectedDeferred = $.Deferred();
        OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG});
        return self._connectedDeferred.promise();
    };

    self.reconnect = function() {
        if (self._connectedDeferred) {
            self._connectedDeferred.reject();
        }
        self._connectedDeferred = $.Deferred();
        OctoPrint.socket.reconnect();
        return self._connectedDeferred.promise();
    };

    self._onReconnectAttempt = function(trial) {
        if (trial <= 0) {
            // Only consider it a real disconnect if the trial number has exceeded our threshold.
            return;
        }

        var handled = false;
        callViewModelsIf(
            self.allViewModels,
            "onServerDisconnect",
            function() { return !handled; },
            function(method) { var result = method(); handled = (result !== undefined && !result) || handled; }
        );

        if (handled) {
            return true;
        }

        showOfflineOverlay(
            gettext("Server is offline"),
            gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below."),
            self.reconnect
        );
    };

    self._onReconnectFailed = function() {
        var handled = false;
        callViewModelsIf(
            self.allViewModels,
            "onServerDisconnect",
            function() { return !handled; },
            function(method) { var result = method(); handled = (result !== undefined && !result) || handled; }
        );

        if (handled) {
            return;
        }

        $("#offline_overlay_title").text(gettext("Server is offline"));
        $("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below."));
    };

    self._onConnected = function(event) {
        var data = event.data;

        // update version information
        var oldVersion = VERSION;
        VERSION = data["version"];
        DISPLAY_VERSION = data["display_version"];
        BRANCH = data["branch"];
        $("span.version").text(DISPLAY_VERSION);

        // update plugin hash
        var oldPluginHash = self._pluginHash;
        self._pluginHash = data["plugin_hash"];

        // update config hash
        var oldConfigHash = self._configHash;
        self._configHash = data["config_hash"];

        // process safe mode
        if (self._safeModePopup) self._safeModePopup.remove();
        if (data["safe_mode"]) {
            // safe mode is active, let's inform the user
            log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");

            self._safeModePopup = new PNotify({
                title: gettext("Safe mode is active"),
                text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
                hide: false
            });
        }

        // if the offline overlay is still showing, now's a good time to
        // hide it, plus reload the camera feed if it's currently displayed
        if ($("#offline_overlay").is(":visible")) {
            hideOfflineOverlay();
            callViewModels(self.allViewModels, "onServerReconnect");
            callViewModels(self.allViewModels, "onDataUpdaterReconnect");
        } else {
            callViewModels(self.allViewModels, "onServerConnect");
        }

        // if the version, the plugin hash or the config hash changed, we
        // want the user to reload the UI since it might be stale now
        var versionChanged = oldVersion != VERSION;
        var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
        var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
        if (versionChanged || pluginsChanged || configChanged) {
            showReloadOverlay();
        }

        log.info("Connected to the server");

        // if we have a connected promise, resolve it now
        if (self._connectedDeferred) {
            self._connectedDeferred.resolve();
            self._connectedDeferred = undefined;
        }
    };

    self._onHistoryData = function(event) {
        callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
    };

    self._onCurrentData = function(event) {
        callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
    };

    self._onSlicingProgress = function(event) {
        $("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));

        var data = event.data;
        callViewModels(self.allViewModels, "onSlicingProgress", [
            data["slicer"],
            data["model_path"],
            data["machinecode_path"],
            data["progress"]
        ]);
    };

    self._onEvent = function(event) {
        var gcodeUploadProgress = $("#gcode_upload_progress");
        var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);

        var type = event.data["type"];
        var payload = event.data["payload"];
        var html = "";

        log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));

        if (type == "PrintCancelled") {
            if (payload.firmwareError) {
                new PNotify({
                    title: gettext("Unhandled communication error"),
                    text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
                    type: "error",
                    hide: false
                });
            }
        } else if (type == "Error") {
            if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect"
                new PNotify({
                        title: gettext("Unhandled communication error"),
                        text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
                        type: "error",
                        hide: false
                });
            }
        }

        var legacyEventHandlers = {
            "UpdatedFiles": "onUpdatedFiles",
            "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
            "MetadataAnalysisFinished": "onMetadataAnalysisFinished",
            "SlicingDone": "onSlicingDone",
            "SlicingCancelled": "onSlicingCancelled",
            "SlicingFailed": "onSlicingFailed"
        };
        _.each(self.allViewModels, function(viewModel) {
            if (viewModel.hasOwnProperty("onEvent" + type)) {
                viewModel["onEvent" + type](payload);
            } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
                // there might still be code that uses the old callbacks, make sure those still get called
                // but log a warning
                log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
                viewModel[legacyEventHandlers[type]](payload);
            }
        });
    };

    self._onTimelapse = function(event) {
        callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
    };

    self._onPluginMessage = function(event) {
        callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
    };

    self._onIncreaseRate = function(measurement, minimum) {
        log.debug("We are fast (" + measurement + " < " + minimum + "), increasing refresh rate");
        OctoPrint.socket.increaseRate();
    };

    self._onDecreaseRate = function(measurement, maximum) {
        log.debug("We are slow (" + measurement + " > " + maximum + "), reducing refresh rate");
        OctoPrint.socket.decreaseRate();
    };

    OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
    OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
    OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
    OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
    OctoPrint.socket
        .onMessage("connected", self._onConnected)
        .onMessage("history", self._onHistoryData)
        .onMessage("current", self._onCurrentData)
        .onMessage("slicingProgress", self._onSlicingProgress)
        .onMessage("event", self._onEvent)
        .onMessage("timelapse", self._onTimelapse)
        .onMessage("plugin", self._onPluginMessage);
}
<|endoftext|>


<commit_before>(function() {

    'use strict';

    angular.module('Core')
        .service('commonService', commonService);

    commonService.$inject = ['$stateParams', '$q', '$timeout', '$window'];

    function commonService($stateParams, $q, $timeout, $window) {
        var service = this;
        service.resetForm = resetForm;
        service.getDateInDDMMMMYYYY = getDateInDDMMMMYYYY;
        service.isObjPresent = isObjPresent;
        service.getObjType = getObjType;
        service.getUUID = getUUID;
        service.isEpochTimeInMs = isEpochTimeInMs;
        service.getValInNumber = getValInNumber;
        service.loadingMode = loadingMode;
        service.goToPage = goToPage;
        service.getCurrentState = getCurrentState;
        service.getStateParam = getStateParam;

        /* ======================================== Var ==================================================== */
        service.$q = $q;
        service.$timeout = $timeout;
        service.$window = $window;

        /* ======================================== Services =============================================== */
        var stateParam = $stateParams;

        /* ======================================== Public Methods ========================================= */
        function getStateParam() {
            return stateParam.data;
        }

        function getCurrentState() {
            return $state.current;
        }

        function goToPage(stateName, hasRoot, toReload, stateParam) {
            var stateObj = {};

            if (isObjPresent(stateName)) {
                if (isObjPresent(hasRoot)) {
                    stateName = 'root.' + stateName;
                }

                if (isObjPresent(stateParam)) {
                    stateObj = $state.go(stateName, { data: stateParam });
                } else {
                    stateObj = $state.go(stateName);
                }
            } else {
                if (toReload) {
                    $state.reload();
                }
            }

            return stateObj.$$state;
        }

        function loadingMode(isLoading) {
            if(isLoading === true || isLoading === false) {
                if(isLoading == true) {
                    if(!isObjPresent(document.getElementById('loadingContainer'))) {
                        var loadingHtml = '

';
                        var body = $document.find('body').eq(0);
                        body.append(loadingHtml);

                        var opts = {
                            lines: 13, // The number of lines to draw
                            length: 28, // The length of each line
                            width: 14, // The line thickness
                            radius: 50, // The radius of the inner circle
                            scale: 1, // Scales overall size of the spinner
                            corners: 1, // Corner roundness (0..1)
                            color: '#FFF', // #rgb or #rrggbb or array of colors
                            opacity: 0, // Opacity of the lines
                            rotate: 0, // The rotation offset
                            direction: 1, // 1: clockwise, -1: counterclockwise
                            speed: 1, // Rounds per second
                            trail: 100, // Afterglow percentage
                            fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
                            zIndex: 2e9, // The z-index (defaults to 2000000000)
                            className: 'spinner', // The CSS class to assign to the spinner
                            top: '50%', // Top position relative to parent
                            left: '50%', // Left position relative to parent
                            shadow: false, // Whether to render a shadow
                            hwaccel: false, // Whether to use hardware acceleration
                            position: 'absolute' // Element positioning
                        }
                        var target = document.getElementById('spinner')
                        spinner = new Spinner(opts).spin(target);
                    }
                } else {
                    if(isObjPresent(spinner)) {
                        spinner.stop();
                        angular.element(document.getElementById('loadingContainer')).remove();
                    }
                }
            } else {
                throw new Error ('Parameter can only be TRUE or FALSE');
            }
        }

        // This function will return the following:
        //      - 111 => return 100
        //      - 1111 => return 1000
        //      - 53 => 50
        //      - 9987 => 9000
        //      - Less than 10 will return the number itself
        function getValInNumber(num) {
            if (getObjType(num) == number) {
                return num.toString()
                    .split('')
                    .map(function(char, index) {
                        return (index == 0) ? char : '0';
                    })
                    .join('') - 0; // -0 Will convert the entire string to a number
            } else {
                throw new Error(num + ' must be a number!');
            }
        }

        function isEpochTimeInMs(epochDateTime) {
            var totalNoOfCharForCurrentTimeInSeconds = Number(Math.floor(Date.now() / 1000)).toString().length;
            var totalNoOfCharForCurrentTimeInMilliseconds = Number(Date.now()).toString().length;
            if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInMilliseconds) {
                return true;
            } else if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInSeconds) {
                return false;
            } else {
                throw new TypeError('Parameter passed in is not in seconds or milliseconds');
            }
        }

        /**
         * Fast UUID generator, RFC4122 version 4 compliant.
         *
         * Don't understand how it works? Please visit the link as shown below. Its not meant to be readable as much as its meant to be fast
         *
         * @author Jeff Ward (jcward.com).
         * @license MIT license
         * @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
         **/
        function getUUID() {
            var lut = [];
            for (var i = 0; i < 256; i++) {
                lut[i] = (i < 16 ? '0' : '') + (i).toString(16);
            }
            var d0 = Math.random() * 0xffffffff | 0;
            var d1 = Math.random() * 0xffffffff | 0;
            var d2 = Math.random() * 0xffffffff | 0;
            var d3 = Math.random() * 0xffffffff | 0;
            return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
                lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
                lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
                lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
        }

        function getObjType(object) { // Would really appreciate a unit test to test all for this as manual testing didn't cover everything
            var prop = {
                '[object Object]': 'object',
                '[object Array]': 'array',
                '[object String]': 'string',
                '[object Boolean]': 'boolean',
                '[object Number]': 'number',
                '[object Null]': 'null',
                '[object Undefined]': 'undefined',
                '[object Function]': 'function',
                '[object Date]': 'date',
                '[object HTMLDivElement]': 'htmlDivElement',
                '[object Blob]': 'blob',
                '[object File]': 'file'
            }

            return prop[Object.prototype.toString.call(object)];
        }

        /**
         * Thie method is inspired by rails .blank? method. This method check for is present (opposite of is blank)
         *     Rails .blank? method:
         *         - null.blank? => true
         *         - false.blank? => true
         *         - [].blank? => true
         *         - {}.blank? => true
         *         - ''.blank? => true
         *         - 5.blank? => false
         *         - 0.blank? => false
         *     Added another check is to check for function.
         *     An empty function is:
         *         - function () { }
         *         - function(param1, param2, param3) { }
         *     A non empty function is:
         *         - function() { console.log(); }
         *     An invalid date will return false for this function
         *     A valid date will return true for this function
         *     This will just check if its empty or not and not check if its syntatically correct or not
         * @param  {object}  obj [Since everything in javascript is considered an object, just pass in anything]
         * @return {Boolean}     [If its not blank, then will return true. Else, it will return false]
         */
        function isObjPresent(obj) {
            var type = getObjType(obj);
            if (type === 'object') {
                // The code below uses the Object.keys() function from ECMA Script 5+ specification. However, to ensure it can run for < ECMA Script 5, this is commented out
                // var objLength = Object.keys(obj).length;
                // if(objLength > 0) {
                //     return true;
                // } else if (objLength == 0) {
                //     return false;
                // } else {
                //     throw new Error(obj + ' comes to object if-else but the length is neither 0 or more than 0');
                // }

                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else if (type === 'array') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to array if-else but the length is neither 0 or more than 0');
                }
            } else if (type === 'string') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false
                } else {
                    throw new Error(obj + ' comes to string if-else but the length its not 0 or more than 0');
                }
            } else if (type === 'boolean') {
                if (obj === true) {
                    return true
                } else if (obj === false) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to boolean if-else but is neither true or false');
                }
            } else if (type === 'number') {
                return true; // We assume if the obj passed in is a number, that means it has a value and thus present (either negative or positive value)
            } else if (type === 'null') {
                return false;
            } else if (type === 'undefined') {
                return false;
            } else if (type === 'function') {
                var tmpStr = obj.toString();
                var tmpStr2 = tmpStr.substring(tmpStr.indexOf('{') + 1, tmpStr.indexOf('}')).trim().replace(/\r?\n|\r/g, ""); // The RegEx here is to check for: arriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS)
                if (isObjPresent(tmpStr2)) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'date') {
                if (isNaN(obj.getTime())) {
                    return false; // Date is invalid
                } else {
                    return true; // Date is valid
                }
            } else if (type === 'htmlDivElement') {
                if(type.toString().length > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'blob') {
                console.log('blob: ',obj);
                if(obj.size > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'file') {
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else {
                throw new Error(obj + ' is not an array, string, boolean or number. This fn only work with those for now');
            }
        }

        function getDateInDDMMMMYYYY(dateTimeInEpoch) { // Will return dd MMMM YYYY : 01 Jan 2012
            try {
                var dateTimeInNumber = Number(dateTimeInEpoch);
                var month = new Date(Number(dateTimeInEpoch)).getMonth();
                var monthInString = '';

                if (month == 0) {
                    monthInString = 'Jan';
                } else if (month == 1) {
                    monthInString = 'Feb';
                } else if (month == 2) {
                    monthInString = 'Mac';
                } else if (month == 3) {
                    monthInString = 'Apr';
                } else if (month == 4) {
                    monthInString = 'May';
                } else if (month == 5) {
                    monthInString = 'Jun';
                } else if (month == 6) {
                    monthInString = 'Jul';
                } else if (month == 7) {
                    monthInString = 'Aug';
                } else if (month == 8) {
                    monthInString = 'Sept';
                } else if (month == 9) {
                    monthInString = 'Oct';
                } else if (month == 10) {
                    monthInString = 'Nov';
                } else if (month == 11) {
                    monthInString = 'Dec';
                }

                return new Date(Number(dateTimeInEpoch)).getDay() + ' ' + monthInString + ' ' + new Date(Number(dateTimeInEpoch)).getFullYear();
            } catch (e) {
                throw new Error('date time is not in number');
            }
        }

        function resetForm(formName, formObj) {
            formName.$setPristine();
            angular.copy({}, formObj);
        }

        /* ======================================== Private Methods ======================================== */
        function init() {

        }

        init();
    }
})();<commit_msg>Add  as DI<commit_after>(function() {

    'use strict';

    angular.module('Core')
        .service('commonService', commonService);

    commonService.$inject = ['$document', '$stateParams', '$q', '$timeout', '$window'];

    function commonService($document, $stateParams, $q, $timeout, $window) {
        var service = this;
        service.resetForm = resetForm;
        service.getDateInDDMMMMYYYY = getDateInDDMMMMYYYY;
        service.isObjPresent = isObjPresent;
        service.getObjType = getObjType;
        service.getUUID = getUUID;
        service.isEpochTimeInMs = isEpochTimeInMs;
        service.getValInNumber = getValInNumber;
        service.loadingMode = loadingMode;
        service.goToPage = goToPage;
        service.getCurrentState = getCurrentState;
        service.getStateParam = getStateParam;

        /* ======================================== Var ==================================================== */
        service.$q = $q;
        service.$timeout = $timeout;
        service.$window = $window;

        /* ======================================== Services =============================================== */
        var stateParam = $stateParams;

        /* ======================================== Public Methods ========================================= */
        function getStateParam() {
            return stateParam.data;
        }

        function getCurrentState() {
            return $state.current;
        }

        function goToPage(stateName, hasRoot, toReload, stateParam) {
            var stateObj = {};

            if (isObjPresent(stateName)) {
                if (isObjPresent(hasRoot)) {
                    stateName = 'root.' + stateName;
                }

                if (isObjPresent(stateParam)) {
                    stateObj = $state.go(stateName, { data: stateParam });
                } else {
                    stateObj = $state.go(stateName);
                }
            } else {
                if (toReload) {
                    $state.reload();
                }
            }

            return stateObj.$$state;
        }

        function loadingMode(isLoading) {
            if(isLoading === true || isLoading === false) {
                if(isLoading == true) {
                    if(!isObjPresent(document.getElementById('loadingContainer'))) {
                        var loadingHtml = '

';
                        var body = $document.find('body').eq(0);
                        body.append(loadingHtml);

                        var opts = {
                            lines: 13, // The number of lines to draw
                            length: 28, // The length of each line
                            width: 14, // The line thickness
                            radius: 50, // The radius of the inner circle
                            scale: 1, // Scales overall size of the spinner
                            corners: 1, // Corner roundness (0..1)
                            color: '#FFF', // #rgb or #rrggbb or array of colors
                            opacity: 0, // Opacity of the lines
                            rotate: 0, // The rotation offset
                            direction: 1, // 1: clockwise, -1: counterclockwise
                            speed: 1, // Rounds per second
                            trail: 100, // Afterglow percentage
                            fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
                            zIndex: 2e9, // The z-index (defaults to 2000000000)
                            className: 'spinner', // The CSS class to assign to the spinner
                            top: '50%', // Top position relative to parent
                            left: '50%', // Left position relative to parent
                            shadow: false, // Whether to render a shadow
                            hwaccel: false, // Whether to use hardware acceleration
                            position: 'absolute' // Element positioning
                        }
                        var target = document.getElementById('spinner')
                        spinner = new Spinner(opts).spin(target);
                    }
                } else {
                    if(isObjPresent(spinner)) {
                        spinner.stop();
                        angular.element(document.getElementById('loadingContainer')).remove();
                    }
                }
            } else {
                throw new Error ('Parameter can only be TRUE or FALSE');
            }
        }

        // This function will return the following:
        //      - 111 => return 100
        //      - 1111 => return 1000
        //      - 53 => 50
        //      - 9987 => 9000
        //      - Less than 10 will return the number itself
        function getValInNumber(num) {
            if (getObjType(num) == number) {
                return num.toString()
                    .split('')
                    .map(function(char, index) {
                        return (index == 0) ? char : '0';
                    })
                    .join('') - 0; // -0 Will convert the entire string to a number
            } else {
                throw new Error(num + ' must be a number!');
            }
        }

        function isEpochTimeInMs(epochDateTime) {
            var totalNoOfCharForCurrentTimeInSeconds = Number(Math.floor(Date.now() / 1000)).toString().length;
            var totalNoOfCharForCurrentTimeInMilliseconds = Number(Date.now()).toString().length;
            if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInMilliseconds) {
                return true;
            } else if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInSeconds) {
                return false;
            } else {
                throw new TypeError('Parameter passed in is not in seconds or milliseconds');
            }
        }

        /**
         * Fast UUID generator, RFC4122 version 4 compliant.
         *
         * Don't understand how it works? Please visit the link as shown below. Its not meant to be readable as much as its meant to be fast
         *
         * @author Jeff Ward (jcward.com).
         * @license MIT license
         * @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
         **/
        function getUUID() {
            var lut = [];
            for (var i = 0; i < 256; i++) {
                lut[i] = (i < 16 ? '0' : '') + (i).toString(16);
            }
            var d0 = Math.random() * 0xffffffff | 0;
            var d1 = Math.random() * 0xffffffff | 0;
            var d2 = Math.random() * 0xffffffff | 0;
            var d3 = Math.random() * 0xffffffff | 0;
            return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
                lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
                lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
                lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
        }

        function getObjType(object) { // Would really appreciate a unit test to test all for this as manual testing didn't cover everything
            var prop = {
                '[object Object]': 'object',
                '[object Array]': 'array',
                '[object String]': 'string',
                '[object Boolean]': 'boolean',
                '[object Number]': 'number',
                '[object Null]': 'null',
                '[object Undefined]': 'undefined',
                '[object Function]': 'function',
                '[object Date]': 'date',
                '[object HTMLDivElement]': 'htmlDivElement',
                '[object Blob]': 'blob',
                '[object File]': 'file'
            }

            return prop[Object.prototype.toString.call(object)];
        }

        /**
         * Thie method is inspired by rails .blank? method. This method check for is present (opposite of is blank)
         *     Rails .blank? method:
         *         - null.blank? => true
         *         - false.blank? => true
         *         - [].blank? => true
         *         - {}.blank? => true
         *         - ''.blank? => true
         *         - 5.blank? => false
         *         - 0.blank? => false
         *     Added another check is to check for function.
         *     An empty function is:
         *         - function () { }
         *         - function(param1, param2, param3) { }
         *     A non empty function is:
         *         - function() { console.log(); }
         *     An invalid date will return false for this function
         *     A valid date will return true for this function
         *     This will just check if its empty or not and not check if its syntatically correct or not
         * @param  {object}  obj [Since everything in javascript is considered an object, just pass in anything]
         * @return {Boolean}     [If its not blank, then will return true. Else, it will return false]
         */
        function isObjPresent(obj) {
            var type = getObjType(obj);
            if (type === 'object') {
                // The code below uses the Object.keys() function from ECMA Script 5+ specification. However, to ensure it can run for < ECMA Script 5, this is commented out
                // var objLength = Object.keys(obj).length;
                // if(objLength > 0) {
                //     return true;
                // } else if (objLength == 0) {
                //     return false;
                // } else {
                //     throw new Error(obj + ' comes to object if-else but the length is neither 0 or more than 0');
                // }

                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else if (type === 'array') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to array if-else but the length is neither 0 or more than 0');
                }
            } else if (type === 'string') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false
                } else {
                    throw new Error(obj + ' comes to string if-else but the length its not 0 or more than 0');
                }
            } else if (type === 'boolean') {
                if (obj === true) {
                    return true
                } else if (obj === false) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to boolean if-else but is neither true or false');
                }
            } else if (type === 'number') {
                return true; // We assume if the obj passed in is a number, that means it has a value and thus present (either negative or positive value)
            } else if (type === 'null') {
                return false;
            } else if (type === 'undefined') {
                return false;
            } else if (type === 'function') {
                var tmpStr = obj.toString();
                var tmpStr2 = tmpStr.substring(tmpStr.indexOf('{') + 1, tmpStr.indexOf('}')).trim().replace(/\r?\n|\r/g, ""); // The RegEx here is to check for: arriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS)
                if (isObjPresent(tmpStr2)) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'date') {
                if (isNaN(obj.getTime())) {
                    return false; // Date is invalid
                } else {
                    return true; // Date is valid
                }
            } else if (type === 'htmlDivElement') {
                if(type.toString().length > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'blob') {
                console.log('blob: ',obj);
                if(obj.size > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'file') {
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else {
                throw new Error(obj + ' is not an array, string, boolean or number. This fn only work with those for now');
            }
        }

        function getDateInDDMMMMYYYY(dateTimeInEpoch) { // Will return dd MMMM YYYY : 01 Jan 2012
            try {
                var dateTimeInNumber = Number(dateTimeInEpoch);
                var month = new Date(Number(dateTimeInEpoch)).getMonth();
                var monthInString = '';

                if (month == 0) {
                    monthInString = 'Jan';
                } else if (month == 1) {
                    monthInString = 'Feb';
                } else if (month == 2) {
                    monthInString = 'Mac';
                } else if (month == 3) {
                    monthInString = 'Apr';
                } else if (month == 4) {
                    monthInString = 'May';
                } else if (month == 5) {
                    monthInString = 'Jun';
                } else if (month == 6) {
                    monthInString = 'Jul';
                } else if (month == 7) {
                    monthInString = 'Aug';
                } else if (month == 8) {
                    monthInString = 'Sept';
                } else if (month == 9) {
                    monthInString = 'Oct';
                } else if (month == 10) {
                    monthInString = 'Nov';
                } else if (month == 11) {
                    monthInString = 'Dec';
                }

                return new Date(Number(dateTimeInEpoch)).getDay() + ' ' + monthInString + ' ' + new Date(Number(dateTimeInEpoch)).getFullYear();
            } catch (e) {
                throw new Error('date time is not in number');
            }
        }

        function resetForm(formName, formObj) {
            formName.$setPristine();
            angular.copy({}, formObj);
        }

        /* ======================================== Private Methods ======================================== */
        function init() {

        }

        init();
    }
})();<|endoftext|>


<commit_before>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (

Welcome to React + ESRI

          To get started, edit src/App.js and save to reload.

    );
  }
}

export default App;
<commit_msg>Show a map<commit_after>import React, { Component } from 'react';
import EsriMap from 'esri/Map';
import MapView from './MapView';
import './App.css';

var map = new EsriMap({
  basemap: 'streets',
});

class App extends Component {
  render() {
    return <MapView map={map} />;
  }
}

export default App;
<|endoftext|>