<commit_before>/*
 * Simulated browser environment for Rhino
 *   By John Resig <http://ejohn.org/>
 * Copyright 2007 John Resig, under the MIT License
 */

// The window Object
var window = this;

(function(){

	// Browser Navigator

	window.navigator = {
		get userAgent(){
			return "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
		}
	};

	window.__defineSetter__("location", function(url){
		window.document = new DOMDocument(
			new Packages.org.xml.sax.InputSource(
			new java.io.InputStreamReader(
				new java.io.FileInputStream(url))));
	});

	window.__defineGetter__("location", function(url){
		return {
			get protocol(){
				return "file:";
			}
		};
	});

	// Timers

	var timers = [];

	window.setTimeout = function(fn, time){
		var num;
		return num = setInterval(function(){
			fn();
			clearInterval(num);
		}, time);
	};

	window.setInterval = function(fn, time){
		var num = timers.length;

		timers[num] = new java.lang.Thread(new java.lang.Runnable({
			run: function(){
				while (true){
					java.lang.Thread.currentThread().sleep(time);
					fn();
				}
			}
		}));

		timers[num].start();

		return num;
	};

	window.clearInterval = function(num){
		if ( timers[num] ) {
			timers[num].stop();
			delete timers[num];
		}
	};

	// Window Events

	window.addEventListener = function(){};
	window.removeEventListener = function(){};

	// DOM Document

	window.DOMDocument = function(file){
		this._file = file;
		this._dom = Packages.javax.xml.parsers.
			DocumentBuilderFactory.newInstance()
				.newDocumentBuilder().parse(file);

		if ( !obj_nodes.containsKey( this._dom ) )
			obj_nodes.put( this._dom, this );
	};

	DOMDocument.prototype = {
		createTextNode: function(text){
			return makeNode( this._dom.createTextNode(
				text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")) );
		},
		createElement: function(name){
			return makeNode( this._dom.createElement(name.toLowerCase()) );
		},
		getElementsByTagName: function(name){
			return new DOMNodeList( this._dom.getElementsByTagName(
				name.toLowerCase()) );
		},
		getElementById: function(id){
			var elems = this._dom.getElementsByTagName("*");

			for ( var i = 0; i < elems.length; i++ ) {
				var elem = elems.item(i);
				if ( elem.getAttribute("id") == id )
					return makeNode(elem);
			}

			return null;
		},
		get body(){
			return this.getElementsByTagName("body")[0];
		},
		get documentElement(){
			return makeNode( this._dom.getDocumentElement() );
		},
		get ownerDocument(){
			return null;
		},
		addEventListener: function(){},
		removeEventListener: function(){},
		get nodeName() {
			return "#document";
		},
		importNode: function(node, deep){
			return makeNode( this._dom.importNode(node._dom, deep) );
		},
		toString: function(){
			return "Document" + (typeof this._file == "string" ?
				": " + this._file : "");
		},

		get defaultView(){
			return {
				getComputedStyle: function(elem){
					return {
						getPropertyValue: function(prop){
							prop = prop.replace(/\-(\w)/g,function(m,c){
								return c.toUpperCase();
							});
							var val = elem.style[prop];

							if ( prop == "opacity" && val == "" )
								val = "1";

							return val;
						}
					};
				}
			};
		}
	};

	function getDocument(node){
		return obj_nodes.get(node);
	}

	// DOM NodeList

	window.DOMNodeList = function(list){
		this._dom = list;
		this.length = list.getLength();

		for ( var i = 0; i < this.length; i++ ) {
			var node = list.item(i);
			this[i] = makeNode( node );
		}
	};

	DOMNodeList.prototype = {
		toString: function(){
			return "[ " +
				Array.prototype.join.call( this, ", " ) + " ]";
		},
		valueOf: function(){
			return Array.prototype.map.call(
				this, function(node){return node.valueOf();}).join('');
		}
	};

	// DOM Node

	window.DOMNode = function(node){
		this._dom = node;
	};

	DOMNode.prototype = {
		get nodeType(){
			return this._dom.getNodeType();
		},
		get nodeValue(){
			return this._dom.getNodeValue();
		},
		get nodeName() {
			return this._dom.getNodeName();
		},
		cloneNode: function(deep){
			return makeNode( this._dom.cloneNode(deep) );
		},
		get ownerDocument(){
			return getDocument( this._dom.ownerDocument );
		},
		get documentElement(){
			return makeNode( this._dom.documentElement );
		},
		get parentNode() {
			return makeNode( this._dom.getParentNode() );
		},
		get nextSibling() {
			return makeNode( this._dom.getNextSibling() );
		},
		get previousSibling() {
			return makeNode( this._dom.getPreviousSibling() );
		},
		toString: function(){
			return '"' + this.nodeValue + '"';
		},
		valueOf: function(){
			return this.nodeValue;
		}
	};

	// DOM Element

	window.DOMElement = function(elem){
		this._dom = elem;
		this.style = {
			get opacity(){ return this._opacity; },
			set opacity(val){ this._opacity = val + ""; }
		};

		// Load CSS info
		var styles = (this.getAttribute("style") || "").split(/\s*;\s*/);

		for ( var i = 0; i < styles.length; i++ ) {
			var style = styles[i].split(/\s*:\s*/);
			if ( style.length == 2 )
				this.style[ style[0] ] = style[1];
		}
	};

	DOMElement.prototype = extend( new DOMNode(), {
		get nodeName(){
			return this.tagName.toUpperCase();
		},
		get tagName(){
			return this._dom.getTagName();
		},
		toString: function(){
			return "<" + this.tagName + (this.id ? "#" + this.id : "" ) + ">";
		},
		valueOf: function(){
			var ret = "<" + this.tagName, attr = this.attributes;

			for ( var i in attr )
				ret += " " + i + "='" + attr[i] + "'";

			if ( this.childNodes.length || this.nodeName == "SCRIPT" )
				ret += ">" + this.childNodes.valueOf() +
					"</" + this.tagName + ">";
			else
				ret += "/>";

			return ret;
		},

		get attributes(){
			var attr = {}, attrs = this._dom.getAttributes();

			for ( var i = 0; i < attrs.getLength(); i++ )
				attr[ attrs.item(i).nodeName ] = attrs.item(i).nodeValue;

			return attr;
		},

		get innerHTML(){
			return this.childNodes.valueOf();
		},
		set innerHTML(html){
			html = html.replace(/<\/?([A-Z]+)/g, function(m){
				return m.toLowerCase();
			});

			var nodes = this.ownerDocument.importNode(
				new DOMDocument( new java.io.ByteArrayInputStream(
					(new java.lang.String("<wrap>" + html + "</wrap>"))
						.getBytes("UTF8"))).documentElement, true).childNodes;

			while (this.firstChild)
				this.removeChild( this.firstChild );

			for ( var i = 0; i < nodes.length; i++ )
				this.appendChild( nodes[i] );
		},

		get textContent(){
			return nav(this.childNodes);

			function nav(nodes){
				var str = "";
				for ( var i = 0; i < nodes.length; i++ )
					if ( nodes[i].nodeType == 3 )
						str += nodes[i].nodeValue;
					else if ( nodes[i].nodeType == 1 )
						str += nav(nodes[i].childNodes);
				return str;
			}
		},
		set textContent(text){
			while (this.firstChild)
				this.removeChild( this.firstChild );
			this.appendChild( this.ownerDocument.createTextNode(text));
		},

		style: {},
		clientHeight: 0,
		clientWidth: 0,
		offsetHeight: 0,
		offsetWidth: 0,

		get disabled() {
			var val = this.getAttribute("disabled");
			return val != "false" && !!val;
		},
		set disabled(val) { return this.setAttribute("disabled",val); },

		get checked() {
			var val = this.getAttribute("checked");
			return val != "false" && !!val;
		},
		set checked(val) { return this.setAttribute("checked",val); },

		get selected() {
			if ( !this._selectDone ) {
				this._selectDone = true;

				if ( this.nodeName == "OPTION" && !this.parentNode.getAttribute("multiple") ) {
					var opt = this.parentNode.getElementsByTagName("option");

					if ( this == opt[0] ) {
						var select = true;

						for ( var i = 1; i < opt.length; i++ )
							if ( opt[i].selected ) {
								select = false;
								break;
							}

						if ( select )
							this.selected = true;
					}
				}
			}

			var val = this.getAttribute("selected");
			return val != "false" && !!val;
		},
		set selected(val) { return this.setAttribute("selected",val); },

		get className() { return this.getAttribute("class") || ""; },
		set className(val) {
			return this.setAttribute("class",
				val.replace(/(^\s*|\s*$)/g,""));
		},

		get type() { return this.getAttribute("type") || ""; },
		set type(val) { return this.setAttribute("type",val); },

		get value() { return this.getAttribute("value") || ""; },
		set value(val) { return this.setAttribute("value",val); },

		get src() { return this.getAttribute("src") || ""; },
		set src(val) { return this.setAttribute("src",val); },

		get id() { return this.getAttribute("id") || ""; },
		set id(val) { return this.setAttribute("id",val); },

		getAttribute: function(name){
			return this._dom.hasAttribute(name) ?
				new String( this._dom.getAttribute(name) ) :
				null;
		},
		setAttribute: function(name,value){
			this._dom.setAttribute(name,value);
		},
		removeAttribute: function(name){
			this._dom.removeAttribute(name);
		},

		get childNodes(){
			return new DOMNodeList( this._dom.getChildNodes() );
		},
		get firstChild(){
			return makeNode( this._dom.getFirstChild() );
		},
		get lastChild(){
			return makeNode( this._dom.getLastChild() );
		},
		appendChild: function(node){
			this._dom.appendChild( node._dom );
		},
		insertBefore: function(node,before){
			this._dom.insertBefore( node._dom, before ? before._dom : before );
		},
		removeChild: function(node){
			this._dom.removeChild( node._dom );
		},

		getElementsByTagName: DOMDocument.prototype.getElementsByTagName,
		addEventListener: function(){},
		removeEventListener: function(){},
		click: function(){},
		submit: function(){},
		focus: function(){},
		blur: function(){},
		get elements(){
			return this.getElementsByTagName("*");
		},
		get contentWindow(){
			return this.nodeName == "IFRAME" ? {
				document: this.contentDocument
			} : null;
		},
		get contentDocument(){
			if ( this.nodeName == "IFRAME" ) {
				if ( !this._doc )
					this._doc = new DOMDocument(
						new java.io.ByteArrayInputStream((new java.lang.String(
						"<title></title>"))
						.getBytes("UTF8")));
				return this._doc;
			} else
				return null;
		}
	});

	// Helper method for extending one object with another

	function extend(a,b) {
		for ( var i in b ) {
			var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);

			if ( g || s ) {
				if ( g )
					a.__defineGetter__(i, g);
				if ( s )
					a.__defineSetter__(i, s);
			} else
				a[i] = b[i];
		}
		return a;
	}

	// Helper method for generating the right
	// DOM objects based upon the type

	var obj_nodes = new java.util.HashMap();

	function makeNode(node){
		if ( node ) {
			if ( !obj_nodes.containsKey( node ) )
				obj_nodes.put( node, node.getNodeType() ==
					Packages.org.w3c.dom.Node.ELEMENT_NODE ?
						new DOMElement( node ) : new DOMNode( node ) );

			return obj_nodes.get(node);
		} else
			return null;
	}

	// XMLHttpRequest

	window.XMLHttpRequest = function(){ };

	XMLHttpRequest.prototype = {
		open: function(){ },
		setRequestHeader: function(){ },
		getResponseHeader: function(){ },
		readyState: 0,
		responseText: "",
		responseXML: {},
		status: 0
	};
})();
<commit_msg>Adds XHR support to Rhino evn<commit_after>/*
 * Simulated browser environment for Rhino
 *   By John Resig <http://ejohn.org/>
 * Copyright 2007 John Resig, under the MIT License
 */

// The window Object
var window = this;

(function(){

	// Browser Navigator

	window.navigator = {
		get userAgent(){
			return "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
		}
	};

	window.__defineSetter__("location", function(url){
		window.document = new DOMDocument(
			new Packages.org.xml.sax.InputSource(
			new java.io.InputStreamReader(
				new java.io.FileInputStream(url))));
	});

	window.__defineGetter__("location", function(url){
		return {
			get protocol(){
				return "file:";
			}
		};
	});

	// Timers

	var timers = [];

	window.setTimeout = function(fn, time){
		var num;
		return num = setInterval(function(){
			fn();
			clearInterval(num);
		}, time);
	};

	window.setInterval = function(fn, time){
		var num = timers.length;

		timers[num] = new java.lang.Thread(new java.lang.Runnable({
			run: function(){
				while (true){
					java.lang.Thread.currentThread().sleep(time);
					fn();
				}
			}
		}));

		timers[num].start();

		return num;
	};

	window.clearInterval = function(num){
		if ( timers[num] ) {
			timers[num].stop();
			delete timers[num];
		}
	};

	// Window Events

	window.addEventListener = function(){};
	window.removeEventListener = function(){};

	// DOM Document

	window.DOMDocument = function(file){
		this._file = file;
		this._dom = Packages.javax.xml.parsers.
			DocumentBuilderFactory.newInstance()
				.newDocumentBuilder().parse(file);

		if ( !obj_nodes.containsKey( this._dom ) )
			obj_nodes.put( this._dom, this );
	};

	DOMDocument.prototype = {
		createTextNode: function(text){
			return makeNode( this._dom.createTextNode(
				text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")) );
		},
		createElement: function(name){
			return makeNode( this._dom.createElement(name.toLowerCase()) );
		},
		getElementsByTagName: function(name){
			return new DOMNodeList( this._dom.getElementsByTagName(
				name.toLowerCase()) );
		},
		getElementById: function(id){
			var elems = this._dom.getElementsByTagName("*");

			for ( var i = 0; i < elems.length; i++ ) {
				var elem = elems.item(i);
				if ( elem.getAttribute("id") == id )
					return makeNode(elem);
			}

			return null;
		},
		get body(){
			return this.getElementsByTagName("body")[0];
		},
		get documentElement(){
			return makeNode( this._dom.getDocumentElement() );
		},
		get ownerDocument(){
			return null;
		},
		addEventListener: function(){},
		removeEventListener: function(){},
		get nodeName() {
			return "#document";
		},
		importNode: function(node, deep){
			return makeNode( this._dom.importNode(node._dom, deep) );
		},
		toString: function(){
			return "Document" + (typeof this._file == "string" ?
				": " + this._file : "");
		},

		get defaultView(){
			return {
				getComputedStyle: function(elem){
					return {
						getPropertyValue: function(prop){
							prop = prop.replace(/\-(\w)/g,function(m,c){
								return c.toUpperCase();
							});
							var val = elem.style[prop];

							if ( prop == "opacity" && val == "" )
								val = "1";

							return val;
						}
					};
				}
			};
		}
	};

	function getDocument(node){
		return obj_nodes.get(node);
	}

	// DOM NodeList

	window.DOMNodeList = function(list){
		this._dom = list;
		this.length = list.getLength();

		for ( var i = 0; i < this.length; i++ ) {
			var node = list.item(i);
			this[i] = makeNode( node );
		}
	};

	DOMNodeList.prototype = {
		toString: function(){
			return "[ " +
				Array.prototype.join.call( this, ", " ) + " ]";
		},
		valueOf: function(){
			return Array.prototype.map.call(
				this, function(node){return node.valueOf();}).join('');
		}
	};

	// DOM Node

	window.DOMNode = function(node){
		this._dom = node;
	};

	DOMNode.prototype = {
		get nodeType(){
			return this._dom.getNodeType();
		},
		get nodeValue(){
			return this._dom.getNodeValue();
		},
		get nodeName() {
			return this._dom.getNodeName();
		},
		cloneNode: function(deep){
			return makeNode( this._dom.cloneNode(deep) );
		},
		get ownerDocument(){
			return getDocument( this._dom.ownerDocument );
		},
		get documentElement(){
			return makeNode( this._dom.documentElement );
		},
		get parentNode() {
			return makeNode( this._dom.getParentNode() );
		},
		get nextSibling() {
			return makeNode( this._dom.getNextSibling() );
		},
		get previousSibling() {
			return makeNode( this._dom.getPreviousSibling() );
		},
		toString: function(){
			return '"' + this.nodeValue + '"';
		},
		valueOf: function(){
			return this.nodeValue;
		}
	};

	// DOM Element

	window.DOMElement = function(elem){
		this._dom = elem;
		this.style = {
			get opacity(){ return this._opacity; },
			set opacity(val){ this._opacity = val + ""; }
		};

		// Load CSS info
		var styles = (this.getAttribute("style") || "").split(/\s*;\s*/);

		for ( var i = 0; i < styles.length; i++ ) {
			var style = styles[i].split(/\s*:\s*/);
			if ( style.length == 2 )
				this.style[ style[0] ] = style[1];
		}
	};

	DOMElement.prototype = extend( new DOMNode(), {
		get nodeName(){
			return this.tagName.toUpperCase();
		},
		get tagName(){
			return this._dom.getTagName();
		},
		toString: function(){
			return "<" + this.tagName + (this.id ? "#" + this.id : "" ) + ">";
		},
		valueOf: function(){
			var ret = "<" + this.tagName, attr = this.attributes;

			for ( var i in attr )
				ret += " " + i + "='" + attr[i] + "'";

			if ( this.childNodes.length || this.nodeName == "SCRIPT" )
				ret += ">" + this.childNodes.valueOf() +
					"</" + this.tagName + ">";
			else
				ret += "/>";

			return ret;
		},

		get attributes(){
			var attr = {}, attrs = this._dom.getAttributes();

			for ( var i = 0; i < attrs.getLength(); i++ )
				attr[ attrs.item(i).nodeName ] = attrs.item(i).nodeValue;

			return attr;
		},

		get innerHTML(){
			return this.childNodes.valueOf();
		},
		set innerHTML(html){
			html = html.replace(/<\/?([A-Z]+)/g, function(m){
				return m.toLowerCase();
			});

			var nodes = this.ownerDocument.importNode(
				new DOMDocument( new java.io.ByteArrayInputStream(
					(new java.lang.String("<wrap>" + html + "</wrap>"))
						.getBytes("UTF8"))).documentElement, true).childNodes;

			while (this.firstChild)
				this.removeChild( this.firstChild );

			for ( var i = 0; i < nodes.length; i++ )
				this.appendChild( nodes[i] );
		},

		get textContent(){
			return nav(this.childNodes);

			function nav(nodes){
				var str = "";
				for ( var i = 0; i < nodes.length; i++ )
					if ( nodes[i].nodeType == 3 )
						str += nodes[i].nodeValue;
					else if ( nodes[i].nodeType == 1 )
						str += nav(nodes[i].childNodes);
				return str;
			}
		},
		set textContent(text){
			while (this.firstChild)
				this.removeChild( this.firstChild );
			this.appendChild( this.ownerDocument.createTextNode(text));
		},

		style: {},
		clientHeight: 0,
		clientWidth: 0,
		offsetHeight: 0,
		offsetWidth: 0,

		get disabled() {
			var val = this.getAttribute("disabled");
			return val != "false" && !!val;
		},
		set disabled(val) { return this.setAttribute("disabled",val); },

		get checked() {
			var val = this.getAttribute("checked");
			return val != "false" && !!val;
		},
		set checked(val) { return this.setAttribute("checked",val); },

		get selected() {
			if ( !this._selectDone ) {
				this._selectDone = true;

				if ( this.nodeName == "OPTION" && !this.parentNode.getAttribute("multiple") ) {
					var opt = this.parentNode.getElementsByTagName("option");

					if ( this == opt[0] ) {
						var select = true;

						for ( var i = 1; i < opt.length; i++ )
							if ( opt[i].selected ) {
								select = false;
								break;
							}

						if ( select )
							this.selected = true;
					}
				}
			}

			var val = this.getAttribute("selected");
			return val != "false" && !!val;
		},
		set selected(val) { return this.setAttribute("selected",val); },

		get className() { return this.getAttribute("class") || ""; },
		set className(val) {
			return this.setAttribute("class",
				val.replace(/(^\s*|\s*$)/g,""));
		},

		get type() { return this.getAttribute("type") || ""; },
		set type(val) { return this.setAttribute("type",val); },

		get value() { return this.getAttribute("value") || ""; },
		set value(val) { return this.setAttribute("value",val); },

		get src() { return this.getAttribute("src") || ""; },
		set src(val) { return this.setAttribute("src",val); },

		get id() { return this.getAttribute("id") || ""; },
		set id(val) { return this.setAttribute("id",val); },

		getAttribute: function(name){
			return this._dom.hasAttribute(name) ?
				new String( this._dom.getAttribute(name) ) :
				null;
		},
		setAttribute: function(name,value){
			this._dom.setAttribute(name,value);
		},
		removeAttribute: function(name){
			this._dom.removeAttribute(name);
		},

		get childNodes(){
			return new DOMNodeList( this._dom.getChildNodes() );
		},
		get firstChild(){
			return makeNode( this._dom.getFirstChild() );
		},
		get lastChild(){
			return makeNode( this._dom.getLastChild() );
		},
		appendChild: function(node){
			this._dom.appendChild( node._dom );
		},
		insertBefore: function(node,before){
			this._dom.insertBefore( node._dom, before ? before._dom : before );
		},
		removeChild: function(node){
			this._dom.removeChild( node._dom );
		},

		getElementsByTagName: DOMDocument.prototype.getElementsByTagName,
		addEventListener: function(){},
		removeEventListener: function(){},
		click: function(){},
		submit: function(){},
		focus: function(){},
		blur: function(){},
		get elements(){
			return this.getElementsByTagName("*");
		},
		get contentWindow(){
			return this.nodeName == "IFRAME" ? {
				document: this.contentDocument
			} : null;
		},
		get contentDocument(){
			if ( this.nodeName == "IFRAME" ) {
				if ( !this._doc )
					this._doc = new DOMDocument(
						new java.io.ByteArrayInputStream((new java.lang.String(
						"<title></title>"))
						.getBytes("UTF8")));
				return this._doc;
			} else
				return null;
		}
	});

	// Helper method for extending one object with another

	function extend(a,b) {
		for ( var i in b ) {
			var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);

			if ( g || s ) {
				if ( g )
					a.__defineGetter__(i, g);
				if ( s )
					a.__defineSetter__(i, s);
			} else
				a[i] = b[i];
		}
		return a;
	}

	// Helper method for generating the right
	// DOM objects based upon the type

	var obj_nodes = new java.util.HashMap();

	function makeNode(node){
		if ( node ) {
			if ( !obj_nodes.containsKey( node ) )
				obj_nodes.put( node, node.getNodeType() ==
					Packages.org.w3c.dom.Node.ELEMENT_NODE ?
						new DOMElement( node ) : new DOMNode( node ) );

			return obj_nodes.get(node);
		} else
			return null;
	}

	// XMLHttpRequest

	window.XMLHttpRequest = function(){
	  this.headers = {};
	  this.responseHeaders = {};
	};

	XMLHttpRequest.prototype = {
		open: function(method, url, async, user, password){
		  this.readyState = 1;
		  if(async) this.async = true;
		  this.method = method || "GET";
		  this.url = url;
		  this.onreadystatechange();
		},
		setRequestHeader: function(header, value){
		  this.headers[header] = value;
		},
		getResponseHeader: function(header){ },
		send: function(data){
		  var makeRequest = function() {
		    var url = new java.net.URL(this.url);
		    var connection = url.openConnection();
		    // Add headers to Java connection
		    for(header in this.headers) connection.addRequestProperty(header, this.headers[header]);
		    connection.connect();
		    // Stick the response headers into responseHeaders
		    for(i=0;;i++) {
		      headerName = connection.getHeaderFieldKey(i);
		      headerValue = connection.getHeaderField(i);
		      if(!headerName && !headerValue) break;
		      if(headerName) this.responseHeaders[headerName] = headerValue;
		    }
	      this.readyState = 4;
        this.status = parseInt(connection.responseCode);
        this.statusText = connection.responseMessage;
        var stream = new java.io.InputStreamReader(connection.getInputStream());
        var buffer = new java.io.BufferedReader(stream);
        var line;
        while((line = buffer.readLine()) != null) this.responseText += line;
        try {
          this.responseXML = new DOMDocument(this.responseText);
        } catch(e) {
          this.responseXML = null;
        }
        this.onreadystatechange();
		  };
		  if(this.async) {
  		  var requestThread = (new java.lang.Thread(new java.lang.Runnable({
  		    run: makeRequest
  		  })));
  		  requestThread.start();
		  }
  		else makeRequest();
		},
		abort: function(){ },
		onreadystatechange: function(){ },
		getResponseHeader: function(header) {
		  if(this.readyState < 3) throw new Error("INVALID_STATE_ERR");
		  else {
		    var returnedHeaders = [];
		    for(rHeader in this.responseHeaders) {
		      if(rHeader.match(new Regexp(header, "i"))) returnedHeaders.push(this.responseHeaders[rHeader]);
		    }
		    if(returnedHeaders != []) return returnedHeaders.join(", ");
		  }
		  return null;
		},
		getAllResponseHeaders: function(header) {
		  if(this.readyState < 3) throw new Error("INVALID_STATE_ERR");
		  else {
		    returnedHeaders = [];
		    for(var header in this.responseHeaders) {
		      returnedHeaders += (header + ": " + this.responseHeaders[header]);
		    }
		    return returnedHeaders.join("\r\n");
		  }
		},
		async: true,
		readyState: 0,
		responseText: "",
		status: 0
	};
})();
<|endoftext|>


<commit_before>/**
 * @fileOverview
 *
 * Implements the EdgeGrid authorization method.
 * Specification document: https://developer.akamai.com/legacy/introduction/Client_Auth.html
 * Sample impletentation by Akamai: https://github.com/akamai/AkamaiOPEN-edgegrid-node
 */

var _ = require('lodash'),
    sdk = require('postman-collection'),
    crypto = require('crypto'),
    querystring = require('querystring'),
    urlEncoder = require('postman-url-encoder'),
    RequestBody = require('postman-collection').RequestBody,
    bodyBuilder = require('../requester/core-body-builder'),

    ASCII_SOURCE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
    ASCII_SOURCE_LENGTH = ASCII_SOURCE.length,
    EMPTY = '',
    COLON = ':',
    UTC_OFFSET = '+0000',
    ZERO = '0',
    DATE_TIME_SEPARATOR = 'T',
    TAB = '\t',
    SPACE = ' ',
    AUTHORIZATION = 'Authorization',

    /**
     * Generates a random string of given length
     *
     * @param {Number} [length=6] Length of the string to be generated
     * @returns {String} Randomly generated string
     */
    randomString = function (length) {
        length = length || 6;

        var result = [],
            i;

        for (i = 0; i < length; i++) {
            result[i] = ASCII_SOURCE[(Math.random() * ASCII_SOURCE_LENGTH) | 0];
        }

        return result.join(EMPTY);
    },

    /**
     * Returns current timestamp in the format described in EdgeGrid specification (yyyyMMddTHH:mm:ss+0000)
     *
     * @returns {String} UTC timestamp in format yyyyMMddTHH:mm:ss+0000
     */
    getTimestamp = function () {
        var timestamp,
            date = new Date();

        timestamp = date.getUTCFullYear() +
                    String(date.getUTCMonth() + 1).padStart(2, ZERO) +
                    String(date.getUTCDate()).padStart(2, ZERO) +
                    DATE_TIME_SEPARATOR +
                    String(date.getUTCHours()).padStart(2, ZERO) +
                    COLON +
                    String(date.getUTCMinutes()).padStart(2, ZERO) +
                    COLON +
                    String(date.getUTCSeconds()).padStart(2, ZERO) +
                    UTC_OFFSET;

        return timestamp;
    },

    /**
     * Creates a String containing a tab delimited set of headers.
     *
     * @param {String[]} headersToSign Headers to include in signature
     * @param {Object} headers Request headers
     * @returns {String} Canonicalized headers
     */
    canonicalizeHeaders = function (headersToSign, headers) {
        var formattedHeaders = [],
            headerValue;

        headersToSign.forEach(function (headerName) {
            headerName = headerName.trim().toLowerCase();
            headerValue = headers[headerName];

            if (!headerValue) { return; }

            formattedHeaders.push(`${headerName}:${headerValue.trim().replace(/\s+/g, SPACE)}`);
        });

        return formattedHeaders.join(TAB);
    },

    /**
     * Returns base64 encoding of the SHA–256 HMAC of given data signed with given key
     *
     * @param {String} data Data to sign
     * @param {String} key Key to use while signing the data
     * @returns {String} Base64 encoded signature
     */
    base64HmacSha256 = function (data, key) {
        var encrypt = crypto.createHmac('sha256', key);

        encrypt.update(data);

        return encrypt.digest('base64');
    },

    /**
     * Encodes characters not encoded by querystring.stringify() according to RFC3986.
     * REFER: https://github.com/postmanlabs/postman-request/blob/master/lib/querystring.js#L42
     *
     * @param {String} str Partially encoded string by querystring.stringify()
     * @returns {String} Fully encoded string
     */
    rfc3986 = function (str) {
        return str.replace(/[!'()*]/g, function (c) {
            return '%' + c.charCodeAt(0).toString(16).toUpperCase();
        });
    },

    /**
     * Calculates body hash with given algorithm and digestEncoding.
     *
     * @param {RequestBody} body
     * @param {String} algorithm
     * @param {String} digestEncoding
     * @param {Function} callback
     */
    computeBodyHash = function (body, algorithm, digestEncoding, callback) {
        if (!(body && algorithm && digestEncoding) || body.isEmpty()) { return callback(); }

        var hash = crypto.createHash(algorithm),
            originalReadStream,
            rawBody,
            urlencodedBody,
            graphqlBody;

        if (body.mode === RequestBody.MODES.raw) {
            rawBody = bodyBuilder.raw(body.raw).body;
            hash.update(rawBody);

            return callback(hash.digest(digestEncoding));
        }

        if (body.mode === RequestBody.MODES.urlencoded) {
            urlencodedBody = bodyBuilder.urlencoded(body.urlencoded).form;
            urlencodedBody = querystring.stringify(urlencodedBody);
            urlencodedBody = rfc3986(urlencodedBody);
            hash.update(urlencodedBody);

            return callback(hash.digest(digestEncoding));
        }

        if (body.mode === RequestBody.MODES.file) {
            originalReadStream = _.get(body, 'file.content');

            if (!originalReadStream) {
                return callback();
            }

            originalReadStream.cloneReadStream(function (err, clonedStream) {
                if (err) { return callback(); }

                clonedStream.on('data', function (chunk) {
                    hash.update(chunk);
                });

                clonedStream.on('end', function () {
                    callback(hash.digest(digestEncoding));
                });
            });
        }

        if (body.mode === RequestBody.MODES.graphql) {
            graphqlBody = bodyBuilder.graphql(body.graphql).body;
            hash.update(graphqlBody);

            return callback(hash.digest(digestEncoding));
        }

        // @todo: Figure out a way to calculate hash for formdata body type.

        // ensure that callback is called if body.mode doesn't match with any of the above modes
        return callback();
    };

/**
 * @implements {AuthHandlerInterface}
 */
module.exports = {
    /**
     * @property {AuthHandlerInterface~AuthManifest}
     */
    manifest: {
        info: {
            name: 'edgegrid',
            version: '1.0.0'
        },
        updates: [
            {
                property: 'Authorization',
                type: 'header'
            }
        ]
    },

    /**
     * Initializes a item (fetches all required parameters, etc) before the actual authorization step.
     *
     * @param {AuthInterface} auth
     * @param {Response} response
     * @param {AuthHandlerInterface~authInitHookCallback} done
     */
    init: function (auth, response, done) {
        done(null);
    },

    /**
     * Checks the item, and fetches any parameters that are not already provided.
     *
     * @param {AuthInterface} auth
     * @param {AuthHandlerInterface~authPreHookCallback} done
     */
    pre: function (auth, done) {
        // only check required auth params here
        done(null, Boolean(auth.get('accessToken') && auth.get('clientToken') && auth.get('clientSecret')));
    },

    /**
     * Verifies whether the request was successful after being sent.
     *
     * @param {AuthInterface} auth
     * @param {Requester} response
     * @param {AuthHandlerInterface~authPostHookCallback} done
     */
    post: function (auth, response, done) {
        done(null, true);
    },

    /**
     * Generates the signature, and returns the Authorization header.
     *
     * @param {Object} params
     * @param {String} params.accessToken Access token provided by service provider
     * @param {String} params.clientToken Client token provided by service provider
     * @param {String} params.clientSecret Client secret provided by service provider
     * @param {String} params.nonce Nonce to include in authorization header
     * @param {String} params.timestamp Timestamp as defined in protocol specification
     * @param {String} [params.bodyHash] Base64-encoded SHA–256 hash of request body for POST request
     * @param {Object[]} params.headers Request headers
     * @param {String[]} params.headersToSign Ordered list of headers to include in signature
     * @param {String} params.method Request method
     * @param {Url} params.url Node's URL object
     * @returns {String} Authorization header
     */
    computeHeader: function (params) {
        var authHeader = 'EG1-HMAC-SHA256 ',
            signingKey = base64HmacSha256(params.timestamp, params.clientSecret),
            dataToSign;

        authHeader += `client_token=${params.clientToken};`;
        authHeader += `access_token=${params.accessToken};`;
        authHeader += `timestamp=${params.timestamp};`;
        authHeader += `nonce=${params.nonce};`;

        dataToSign = [
            params.method,
            params.url.protocol.replace(COLON, EMPTY),
            params.baseURL || params.url.host,
            params.url.path,
            canonicalizeHeaders(params.headersToSign, params.headers),
            params.bodyHash || EMPTY,
            authHeader
        ].join(TAB);

        return authHeader + 'signature=' + base64HmacSha256(dataToSign, signingKey);
    },

    /**
     * Signs a request.
     *
     * @param {AuthInterface} auth
     * @param {Request} request
     * @param {AuthHandlerInterface~authSignHookCallback} done
     */
    sign: function (auth, request, done) {
        var params = auth.get([
                'accessToken',
                'clientToken',
                'clientSecret',
                'baseURL',
                'nonce',
                'timestamp',
                'headersToSign'
            ]),
            url = urlEncoder.toNodeUrl(request.url.toString(true)),
            self = this;

        // Extract host from provided baseURL.
        // @note: Here, instead of directly passing params.baseURL in urlEncoder.toNodeUrl() we first parse it using
        //        sdk.Url() and add protocol because urlEncoder.toNodeUrl() method doesn't work properly with URLs
        //        without protocol
        params.baseURL = params.baseURL && urlEncoder.toNodeUrl(new sdk.Url(params.baseURL).toString(true)).host;
        params.nonce = params.nonce || randomString(6);
        params.timestamp = params.timestamp || getTimestamp();
        params.url = url;
        params.method = request.method;

        // ensure that headers are case-insensitive as specified in the documentation
        params.headers = request.getHeaders({enabled: true, ignoreCase: true});

        if (typeof params.headersToSign === 'string') {
            params.headersToSign = params.headersToSign.split(',');
        }
        else if (!_.isArray(params.headersToSign)) {
            params.headersToSign = [];
        }

        if (request.method === 'POST') {
            return computeBodyHash(request.body, 'sha256', 'base64', function (bodyHash) {
                params.bodyHash = bodyHash;

                request.upsertHeader({
                    key: AUTHORIZATION,
                    value: self.computeHeader(params),
                    system: true
                });

                return done();
            });
        }

        request.upsertHeader({
            key: AUTHORIZATION,
            value: self.computeHeader(params),
            system: true
        });

        return done();
    }
};
<commit_msg>Minor code improvements<commit_after>/**
 * @fileOverview
 *
 * Implements the EdgeGrid authorization method.
 * Specification document: https://developer.akamai.com/legacy/introduction/Client_Auth.html
 * Sample impletentation by Akamai: https://github.com/akamai/AkamaiOPEN-edgegrid-node
 */

var _ = require('lodash'),
    sdk = require('postman-collection'),
    crypto = require('crypto'),
    querystring = require('querystring'),
    urlEncoder = require('postman-url-encoder'),
    RequestBody = require('postman-collection').RequestBody,
    bodyBuilder = require('../requester/core-body-builder'),

    ASCII_SOURCE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
    ASCII_SOURCE_LENGTH = ASCII_SOURCE.length,
    EMPTY = '',
    COLON = ':',
    UTC_OFFSET = '+0000',
    ZERO = '0',
    DATE_TIME_SEPARATOR = 'T',
    TAB = '\t',
    SPACE = ' ',
    SLASH = '/',
    SIGNING_ALGORITHM = 'EG1-HMAC-SHA256 ',
    AUTHORIZATION = 'Authorization',

    /**
     * Generates a random string of given length
     *
     * @param {Number} [length=6] Length of the string to be generated
     * @returns {String} Randomly generated string
     */
    randomString = function (length) {
        length = length || 6;

        var result = [],
            i;

        for (i = 0; i < length; i++) {
            result[i] = ASCII_SOURCE[(Math.random() * ASCII_SOURCE_LENGTH) | 0];
        }

        return result.join(EMPTY);
    },

    /**
     * Pads the given number with '0' and returns a string with given length (or greater if number is already longer
     * than given length)
     *
     * @param {Number} num Number to pad
     * @param {Number} length Minimum length of the string to return
     * @returns {String} Padded number
     */
    padNumber = function (num, length) {
        var paddedNum = `${num}`;

        while (paddedNum.length < length) {
            paddedNum = ZERO + paddedNum;
        }

        return paddedNum;
    },

    /**
     * Returns current timestamp in the format described in EdgeGrid specification (yyyyMMddTHH:mm:ss+0000)
     *
     * @returns {String} UTC timestamp in format yyyyMMddTHH:mm:ss+0000
     */
    getTimestamp = function () {
        var date = new Date();

        return date.getUTCFullYear() +
                padNumber(date.getUTCMonth() + 1, 2) +
                padNumber(date.getUTCDate(), 2) +
                DATE_TIME_SEPARATOR +
                padNumber(date.getUTCHours(), 2) +
                COLON +
                padNumber(date.getUTCMinutes(), 2) +
                COLON +
                padNumber(date.getUTCSeconds(), 2) +
                UTC_OFFSET;
    },

    /**
     * Creates a String containing a tab delimited set of headers.
     *
     * @param {String[]} headersToSign Headers to include in signature
     * @param {Object} headers Request headers
     * @returns {String} Canonicalized headers
     */
    canonicalizeHeaders = function (headersToSign, headers) {
        var formattedHeaders = [],
            headerValue;

        headersToSign.forEach(function (headerName) {
            if (typeof headerName !== 'string') { return; }

            headerName = headerName.trim().toLowerCase();
            headerValue = headers[headerName];

            // should not include empty headers as per the specification
            if (typeof headerValue !== 'string' || headerValue === EMPTY) { return; }

            formattedHeaders.push(`${headerName}:${headerValue.trim().replace(/\s+/g, SPACE)}`);
        });

        return formattedHeaders.join(TAB);
    },

    /**
     * Returns base64 encoding of the SHA–256 HMAC of given data signed with given key
     *
     * @param {String} data Data to sign
     * @param {String} key Key to use while signing the data
     * @returns {String} Base64 encoded signature
     */
    base64HmacSha256 = function (data, key) {
        var encrypt = crypto.createHmac('sha256', key);

        encrypt.update(data);

        return encrypt.digest('base64');
    },

    /**
     * Encodes characters not encoded by querystring.stringify() according to RFC3986.
     * REFER: https://github.com/postmanlabs/postman-request/blob/master/lib/querystring.js#L42
     *
     * @param {String} str Partially encoded string by querystring.stringify()
     * @returns {String} Fully encoded string
     */
    rfc3986 = function (str) {
        return str.replace(/[!'()*]/g, function (c) {
            return '%' + c.charCodeAt(0).toString(16).toUpperCase();
        });
    },

    /**
     * Calculates body hash with given algorithm and digestEncoding.
     *
     * @param {RequestBody} body
     * @param {String} algorithm
     * @param {String} digestEncoding
     * @param {Function} callback
     */
    computeBodyHash = function (body, algorithm, digestEncoding, callback) {
        if (!(body && algorithm && digestEncoding) || body.isEmpty()) { return callback(); }

        var hash = crypto.createHash(algorithm),
            originalReadStream,
            rawBody,
            urlencodedBody,
            graphqlBody;

        if (body.mode === RequestBody.MODES.raw) {
            rawBody = bodyBuilder.raw(body.raw).body;
            hash.update(rawBody);

            return callback(hash.digest(digestEncoding));
        }

        if (body.mode === RequestBody.MODES.urlencoded) {
            urlencodedBody = bodyBuilder.urlencoded(body.urlencoded).form;
            urlencodedBody = querystring.stringify(urlencodedBody);
            urlencodedBody = rfc3986(urlencodedBody);
            hash.update(urlencodedBody);

            return callback(hash.digest(digestEncoding));
        }

        if (body.mode === RequestBody.MODES.file) {
            originalReadStream = _.get(body, 'file.content');

            if (!originalReadStream) {
                return callback();
            }

            originalReadStream.cloneReadStream(function (err, clonedStream) {
                if (err) { return callback(); }

                clonedStream.on('data', function (chunk) {
                    hash.update(chunk);
                });

                clonedStream.on('end', function () {
                    callback(hash.digest(digestEncoding));
                });
            });
        }

        if (body.mode === RequestBody.MODES.graphql) {
            graphqlBody = bodyBuilder.graphql(body.graphql).body;
            hash.update(graphqlBody);

            return callback(hash.digest(digestEncoding));
        }

        // @todo: Figure out a way to calculate hash for formdata body type.

        // ensure that callback is called if body.mode doesn't match with any of the above modes
        return callback();
    };

/**
 * @implements {AuthHandlerInterface}
 */
module.exports = {
    /**
     * @property {AuthHandlerInterface~AuthManifest}
     */
    manifest: {
        info: {
            name: 'edgegrid',
            version: '1.0.0'
        },
        updates: [
            {
                property: 'Authorization',
                type: 'header'
            }
        ]
    },

    /**
     * Initializes a item (fetches all required parameters, etc) before the actual authorization step.
     *
     * @param {AuthInterface} auth
     * @param {Response} response
     * @param {AuthHandlerInterface~authInitHookCallback} done
     */
    init: function (auth, response, done) {
        done(null);
    },

    /**
     * Checks the item, and fetches any parameters that are not already provided.
     *
     * @param {AuthInterface} auth
     * @param {AuthHandlerInterface~authPreHookCallback} done
     */
    pre: function (auth, done) {
        // only check required auth params here
        done(null, Boolean(auth.get('accessToken') && auth.get('clientToken') && auth.get('clientSecret')));
    },

    /**
     * Verifies whether the request was successful after being sent.
     *
     * @param {AuthInterface} auth
     * @param {Requester} response
     * @param {AuthHandlerInterface~authPostHookCallback} done
     */
    post: function (auth, response, done) {
        done(null, true);
    },

    /**
     * Generates the signature, and returns the Authorization header.
     *
     * @param {Object} params
     * @param {String} params.accessToken Access token provided by service provider
     * @param {String} params.clientToken Client token provided by service provider
     * @param {String} params.clientSecret Client secret provided by service provider
     * @param {String} params.nonce Nonce to include in authorization header
     * @param {String} params.timestamp Timestamp as defined in protocol specification
     * @param {String} [params.bodyHash] Base64-encoded SHA–256 hash of request body for POST request
     * @param {Object[]} params.headers Request headers
     * @param {String[]} params.headersToSign Ordered list of headers to include in signature
     * @param {String} params.method Request method
     * @param {Url} params.url Node's URL object
     * @returns {String} Authorization header
     */
    computeHeader: function (params) {
        var authHeader = SIGNING_ALGORITHM,
            signingKey = base64HmacSha256(params.timestamp, params.clientSecret),
            dataToSign;

        authHeader += `client_token=${params.clientToken};`;
        authHeader += `access_token=${params.accessToken};`;
        authHeader += `timestamp=${params.timestamp};`;
        authHeader += `nonce=${params.nonce};`;

        dataToSign = [
            params.method,

            // trim to convert 'http:' from Node's URL object to 'http'
            _.trimEnd(params.url.protocol, COLON),
            params.baseURL || params.url.host,
            params.url.path || SLASH,
            canonicalizeHeaders(params.headersToSign, params.headers),
            params.bodyHash || EMPTY,
            authHeader
        ].join(TAB);

        return authHeader + 'signature=' + base64HmacSha256(dataToSign, signingKey);
    },

    /**
     * Signs a request.
     *
     * @param {AuthInterface} auth
     * @param {Request} request
     * @param {AuthHandlerInterface~authSignHookCallback} done
     */
    sign: function (auth, request, done) {
        var params = auth.get([
                'accessToken',
                'clientToken',
                'clientSecret',
                'baseURL',
                'nonce',
                'timestamp',
                'headersToSign'
            ]),
            url = urlEncoder.toNodeUrl(request.url.toString(true)),
            self = this;

        request.removeHeader(AUTHORIZATION, {ignoreCase: true});

        // Extract host from provided baseURL.
        // @note: Here, instead of directly passing params.baseURL in urlEncoder.toNodeUrl() we first parse it using
        //        sdk.Url() and add protocol because urlEncoder.toNodeUrl() method doesn't work properly with URLs
        //        without protocol
        params.baseURL = params.baseURL && urlEncoder.toNodeUrl(new sdk.Url(params.baseURL).toString(true)).host;
        params.nonce = params.nonce || randomString(6);
        params.timestamp = params.timestamp || getTimestamp();
        params.url = url;
        params.method = request.method;

        // ensure that headers are case-insensitive as specified in the documentation
        params.headers = request.getHeaders({enabled: true, ignoreCase: true});

        if (typeof params.headersToSign === 'string') {
            params.headersToSign = params.headersToSign.split(',');
        }
        else if (!_.isArray(params.headersToSign)) {
            params.headersToSign = [];
        }

        if (request.method === 'POST') {
            return computeBodyHash(request.body, 'sha256', 'base64', function (bodyHash) {
                params.bodyHash = bodyHash;

                request.addHeader({
                    key: AUTHORIZATION,
                    value: self.computeHeader(params),
                    system: true
                });

                return done();
            });
        }

        request.addHeader({
            key: AUTHORIZATION,
            value: self.computeHeader(params),
            system: true
        });

        return done();
    }
};
<|endoftext|>


<commit_before><commit_msg>Add comments for clarity<commit_after><|endoftext|>


<commit_before>import React from 'react'
import moment from 'moment';
import { Link } from 'react-router'

var getCPULimit = function(pod) {
  var cpuLimit = 'NA';
  if (pod.spec.containers[0].resources && pod.spec.containers[0].resources.limits) {
    cpuLimit = pod.spec.containers[0].resources.limits.cpu
  }
  return cpuLimit;
};

var getMemoryLimit = function(pod) {
  var memLimit = 'NA';
  if (pod.spec.containers[0].resources && pod.spec.containers[0].resources.limits) {
    memLimit = pod.spec.containers[0].resources.limits.memory
  }
  return memLimit;
};

var getStartTime = function(pod) {
  return moment(pod.status.startTime).format("MM/DD HH:mm:ss");
};

var getLastStartTime = function(pod) {
  var startTime = "";
  if (pod.status.containerStatuses && pod.status.containerStatuses[0] && pod.status.containerStatuses[0].state.running) {
    startTime = pod.status.containerStatuses[0].state.running.startedAt;
  }
  return moment(startTime).format("MM/DD HH:mm:ss");
};

var getRestartCount = function(pod) {
  var restartCount = "NA";
  if (pod.status.containerStatuses && pod.status.containerStatuses[0]) {
    restartCount = pod.status.containerStatuses[0].restartCount;
  }
  return restartCount;
};

var getStatus = function(pod) {
  var status = "";
  if (pod.status.containerStatuses && pod.status.containerStatuses[0].state.waiting) {
    status = pod.status.containerStatuses[0].state.waiting.reason;
  }
  return status;
};

var getRestartStyle = function (count) {
  // TODO: Count for uptime
  if (parseInt(count) > 20) {
    return "warning";
  } else {
    return "";
  }
};

var showLabels = function(labels) {
  var labelArray = [];
  for (var key in labels){
    labelArray.push(

        <Link to={"/pods/label/"+ key +"/" + labels[key]}>{key}: {labels[key]}</Link>

    );
  }
  return (

      Labels:
      { labelArray }

  );
};

export default React.createClass({

  render() {
    var pod = this.props.pod;
    var restartCount = getRestartCount(pod);

    return (

        POD: <Link to={"/namespaces/"+ pod.metadata.namespace +"/pods/" + pod.metadata.name}>{pod.metadata.name}</Link>

        {pod.spec.containers[0].image}

          Status: {pod.status.phase}
          ({restartCount} restarts)

        NS: <Link to={"/namespaces/"+ pod.metadata.namespace +"/pods"}>{pod.metadata.namespace}</Link>

        {showLabels(pod.metadata.labels)}
        CPU: {getCPULimit(pod)} Mem: {getMemoryLimit(pod)}

        Started: {getStartTime(pod)}

        Last Start: {getLastStartTime(pod)}

    )
  }

});
<commit_msg>List all container images in Pod<commit_after>import React from 'react'
import moment from 'moment';
import { Link } from 'react-router'

var getCPULimit = function(pod) {
  var cpuLimit = 'NA';
  if (pod.spec.containers[0].resources && pod.spec.containers[0].resources.limits) {
    cpuLimit = pod.spec.containers[0].resources.limits.cpu
  }
  return cpuLimit;
};

var getMemoryLimit = function(pod) {
  var memLimit = 'NA';
  if (pod.spec.containers[0].resources && pod.spec.containers[0].resources.limits) {
    memLimit = pod.spec.containers[0].resources.limits.memory
  }
  return memLimit;
};

var getStartTime = function(pod) {
  return moment(pod.status.startTime).format("MM/DD HH:mm:ss");
};

var getLastStartTime = function(pod) {
  var startTime = "";
  if (pod.status.containerStatuses && pod.status.containerStatuses[0] && pod.status.containerStatuses[0].state.running) {
    startTime = pod.status.containerStatuses[0].state.running.startedAt;
  }
  return moment(startTime).format("MM/DD HH:mm:ss");
};

var getRestartCount = function(pod) {
  var restartCount = "NA";
  if (pod.status.containerStatuses && pod.status.containerStatuses[0]) {
    restartCount = pod.status.containerStatuses[0].restartCount;
  }
  return restartCount;
};

var getStatus = function(pod) {
  var status = "";
  if (pod.status.containerStatuses && pod.status.containerStatuses[0].state.waiting) {
    status = pod.status.containerStatuses[0].state.waiting.reason;
  }
  return status;
};

var getRestartStyle = function (count) {
  // TODO: Count for uptime
  if (parseInt(count) > 20) {
    return "warning";
  } else {
    return "";
  }
};

var showLabels = function(labels) {
  var labelArray = [];
  for (var key in labels){
    labelArray.push(

        <Link to={"/pods/label/"+ key +"/" + labels[key]}>{key}: {labels[key]}</Link>

    );
  }
  return (

      Labels:
      { labelArray }

  );
};

export default React.createClass({

  render() {
    var pod = this.props.pod;
    var restartCount = getRestartCount(pod);

    return (

        POD: <Link to={"/namespaces/"+ pod.metadata.namespace +"/pods/" + pod.metadata.name}>{pod.metadata.name}</Link>

        {pod.spec.containers.map(container =>

{container.image}

        )}

          Status: {pod.status.phase}
          ({restartCount} restarts)

        NS: <Link to={"/namespaces/"+ pod.metadata.namespace +"/pods"}>{pod.metadata.namespace}</Link>

        {showLabels(pod.metadata.labels)}
        CPU: {getCPULimit(pod)} Mem: {getMemoryLimit(pod)}

        Started: {getStartTime(pod)}

        Last Start: {getLastStartTime(pod)}

    )
  }

});
<|endoftext|>


<commit_before>const display = document.getElementById("canvas");
const ctx = display.getContext("2d");

let timescale = 1;
let creatures = [];

function Creature(x, y, s, c) {
	this.x = x || Math.random() * 1920;
	this.y = y || Math.random() * 1080;

	this.size = s || Math.random() * (maxCreatureSize - minCreatureSize) + minCreatureSize;
	this.color = c || newColor();
}

function newColor() {
	let h = Math.floor(Math.random() * 360);
	let s = Math.floor(Math.random() * 100);
	let l = Math.floor(Math.random() * 100);

	return "hsl(" + h + ", " + s + "%, " + l + "%)";
}

let test = new Creature(1920 / 2, 1080 / 2, 20);
creatures.push(test);<commit_msg>Delete init.js<commit_after><|endoftext|>


<commit_before>
function RunQueue() {
	var q = []; // array of runFuncs

	this.clear = function() {
		q = []; // TODO: reject all promises?
	};

	this.push = function(taskFunc) {
		return new Promise(function(resolve) {

			// should run this function when it's taskFunc's turn to run.
			// responsible for popping itself off the queue.
			var runFunc = function() {
				Promise.resolve(taskFunc()) // result might be async, coerce to promise
					.then(resolve) // resolve RunQueue::push's promise, for the caller. will receive result of taskFunc.
					.then(function() {
						q.shift(); // pop itself off

						// run the next task, if any
						if (q.length) {
							q[0]();
						}
					});
			};

			// always put the task at the end of the queue, BEFORE running the task
			q.push(runFunc);

			// if it's the only task in the queue, run immediately
			if (q.length === 1) {
				runFunc();
			}
		});
	};
}

FC.RunQueue = RunQueue;

/*
q = new RunQueue();

function work(i) {
	return q.push(function() {
		trigger();
		console.log('work' + i);
	});
}

var cnt = 0;

function trigger() {
	if (cnt < 5) {
		cnt++;
		work(cnt);
	}
}

work(9);
*/
<commit_msg>change RunQueue api<commit_after>
// TODO: write tests and clean up code

function RunQueue() {
	var _this = this;
	var q = []; // array of runFuncs
	var completedCnt = 0;

	$.extend(this, EmitterMixin);

	this.add = function(taskFunc) {
		return new Promise(function(resolve) {

			// should run this function when it's taskFunc's turn to run.
			// responsible for popping itself off the queue.
			var runFunc = function() {
				Promise.resolve(taskFunc()) // result might be async, coerce to promise
					.then(resolve) // resolve RunQueue::push's promise, for the caller. will receive result of taskFunc.
					.then(function() {
						q.shift(); // pop itself off

						completedCnt++;
						_this.trigger('add');

						// run the next task, if any
						if (q.length) {
							q[0]();
						}
					});
			};

			// always put the task at the end of the queue, BEFORE running the task
			q.push(runFunc);

			// if it's the only task in the queue, run immediately
			if (q.length === 1) {
				runFunc();
			}
		});
	};

	this.completed = function() {
		return completedCnt;
	};

	this.forgetCompleted = function() {
		completedCnt = 0;
	};

	this.promise = function() {
		if (this.completedCnt) {
			return Promise.resolve();
		}
		return new Promise(function(resolve) {
			_this.one('add', resolve);
		});
	};
}

FC.RunQueue = RunQueue;

/*
q = new RunQueue();

function work(i) {
	return q.push(function() {
		trigger();
		console.log('work' + i);
	});
}

var cnt = 0;

function trigger() {
	if (cnt < 5) {
		cnt++;
		work(cnt);
	}
}

work(9);
*/
<|endoftext|>


<commit_before>
// Includes a JS file into the HTML document
// Selfmade import feature
//
// @param file {String} - The file to import
//
let importFile = function(file) {
	let imported = document.createElement('script');
	imported.src = file;
	document.head.appendChild(imported);
}

// JQuery
importFile('Data/Resources/js/jquery.3.2.1.min.js');

// Modules
importFile('Data/Resources/js/colors.js');
importFile('Data/Resources/js/correction.js');
importFile('Data/Resources/js/images.js');
importFile('Data/Resources/js/info.js');
importFile('Data/Resources/js/messages.js');

// #################
// # Configuration #
// #################

// grey Message Block for alternating colors to have a better visibility
let greyBlock = false;

// # ################# #
// # Textual Callbacks #
// # ################# #

Textual.newMessagePostedToView = function (lineNumber) {

	// get the message object
	let message = $('#line-' + lineNumber);
	let messageType = getMessageType(message);

	switch (messageType) {
		// # ############### #
		// # Private Message #
		// # ############### #
		case 'privmsg':
			// see if the message is a correction of the previous message
			if(messageIsCorrection(message)){
				handleCorrect(message);
			}
			// handle the normal message
			else{
				// colorize the sender
				colorizeSender(message);
				// colorize inline mentions
				colorizeInlineMentions(message);
				// add the bottom class, because at this point it is the last message
				// of this sender
				addBottomMessageStyle(message);
				// get some information
				let sender = getSender(message);
				let lastMessage = getPreviousMessage(message);

				// same Sender
				if(getMessageType(lastMessage) === 'privmsg' && sender === getSender(lastMessage)){
					hideSenderAndTime(message);
					// remove the bottom message style from the last message
					removeBottomMessageStyle(lastMessage);
				}
				// new Sender
				else{
					addTopMessageStyle(message);
					greyBlock = !greyBlock;
				}

				// style the images if present
				handleInlineImages(message);

				// color the message background
				if(greyBlock) {
					addBackground(message);
				}
			}
			break;
		// # ###### #
		// # Action #
		// # ###### #
		case 'action':
			// add Bottom Message Style by default
			addBottomMessageStyle(message);

			// get some information
			let sender = getSender(message);
			let lastMessage = getPreviousMessage(message);
			if(getMessageType(lastMessage) === 'privmsg' && sender === getSender(lastMessage)){
				// remove the bottom message style from the last message
				removeBottomMessageStyle(lastMessage);
			}
			else{
				addTopMessageStyle(message);
				greyBlock = !greyBlock;
			}
			break;
		// # ############ #
		// # Topic Change #
		// # ############ #
		case 'topic':
			handleTopicChange(message);
			break;
		// # ########### #
		// # Mode Change #
		// # ########### #
		case 'mode':
			handleModeChange(message);
			break;
		// # ################## #
		// # Join / Part / Quit #
		// # ################## #
		case 'join':
		case 'part':
		case 'quit':
			// hide the user's own status messages
			hideIfOwn(message);
			break;
		default:

	}

}

Textual.viewFinishedLoading =  () => {
	Textual.fadeOutLoadingScreen(1.00, 1.00);
	setTimeout( () => {
		Textual.scrollToBottomOfView();
	}, 300);
}

Textual.viewFinishedReload =  () => {
	Textual.viewFinishedLoading();
}

Textual.viewInitiated = (viewType, serverHash, channelHash, channelName) => {
	// inserts the spinner to the loading screen
	$('#loading_screen').html("

")
	//
	let topicBar = $('#topic_bar');
	if(topicBar){
		// make the content below the topic bar visible
		$('body').css({
			'margin-top': topicBar.innerHeight() + "px"
		});
	}
}
<commit_msg>Styled action messages properly.<commit_after>
// Includes a JS file into the HTML document
// Selfmade import feature
//
// @param file {String} - The file to import
//
let importFile = function(file) {
	let imported = document.createElement('script');
	imported.src = file;
	document.head.appendChild(imported);
}

// JQuery
importFile('Data/Resources/js/jquery.3.2.1.min.js');

// Modules
importFile('Data/Resources/js/colors.js');
importFile('Data/Resources/js/correction.js');
importFile('Data/Resources/js/images.js');
importFile('Data/Resources/js/info.js');
importFile('Data/Resources/js/messages.js');

// #################
// # Configuration #
// #################

// grey Message Block for alternating colors to have a better visibility
let greyBlock = false;

// # ################# #
// # Textual Callbacks #
// # ################# #

Textual.newMessagePostedToView = function (lineNumber) {

	// get the message object
	let message = $('#line-' + lineNumber);
	let messageType = getMessageType(message);

	switch (messageType) {
		// # ############### #
		// # Private Message #
		// # ############### #
		case 'privmsg':
			// see if the message is a correction of the previous message
			if(messageIsCorrection(message)){
				handleCorrect(message);
			}
			// handle the normal message
			else{
				// colorize the sender
				colorizeSender(message);
				// colorize inline mentions
				colorizeInlineMentions(message);
				// add the bottom class, because at this point it is the last message
				// of this sender
				addBottomMessageStyle(message);
				// get some information
				let sender = getSender(message);
				let lastMessage = getPreviousMessage(message);

				// same Sender
				if(sender === getSender(lastMessage)){
					if(getMessageType(lastMessage) === 'privmsg'){
						hideSenderAndTime(message);
					}
					// if it was the same sender but not a private message (an action
					// for example), add the top padding
					else{
						addTopMessageStyle(message);
					}
					// remove the bottom message style from the last message
					removeBottomMessageStyle(lastMessage);
				}
				// new Sender
				else{
					addTopMessageStyle(message);
					greyBlock = !greyBlock;
				}

				// style the images if present
				handleInlineImages(message);

				// color the message background
				if(greyBlock) {
					addBackground(message);
				}
			}
			break;
		// # ###### #
		// # Action #
		// # ###### #
		case 'action':
			// add Bottom Message Style by default
			addBottomMessageStyle(message);
			addTopMessageStyle(message);

			//get some information
			let sender = getSender(message);
			let lastMessage = getPreviousMessage(message);
			if(sender === getSender(lastMessage)){
				// remove the bottom message style from the last message
				removeBottomMessageStyle(lastMessage);
			}
			else{
				greyBlock = !greyBlock;
			}
			break;
		// # ############ #
		// # Topic Change #
		// # ############ #
		case 'topic':
			handleTopicChange(message);
			break;
		// # ########### #
		// # Mode Change #
		// # ########### #
		case 'mode':
			handleModeChange(message);
			break;
		// # ################## #
		// # Join / Part / Quit #
		// # ################## #
		case 'join':
		case 'part':
		case 'quit':
			// hide the user's own status messages
			hideIfOwn(message);
			break;
		default:

	}

}

Textual.viewFinishedLoading =  () => {
	Textual.fadeOutLoadingScreen(1.00, 1.00);
	setTimeout( () => {
		Textual.scrollToBottomOfView();
	}, 300);
}

Textual.viewFinishedReload =  () => {
	Textual.viewFinishedLoading();
}

Textual.viewInitiated = (viewType, serverHash, channelHash, channelName) => {
	// inserts the spinner to the loading screen
	$('#loading_screen').html("

")
	//
	let topicBar = $('#topic_bar');
	if(topicBar){
		// make the content below the topic bar visible
		$('body').css({
			'margin-top': topicBar.innerHeight() + "px"
		});
	}
}
<|endoftext|>


<commit_before>/**
 *  Grunt tasks to support running linter and unit tests.
 *
 *  @module Gruntfile
 *
 *  @copyright 2014, Digium, Inc.
 *  @license Apache License, Version 2.0
 *  @author Samuel Fortier-Galarneau <sgalarneau@digium.com>
 */

'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
    jshint: {
      options: {
        jshintrc: true
      },
      all: [
        'Gruntfile.js',
        'lib/*.js',
        'test/*.js'
      ]
    },
    mochaTest: {
      test: {
        options: {
          mocha: require('mocha'),
          reporter: 'spec',
          timeout: 2000
        },
        src: ['test/*.js']
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-mocha-test');

  // Default task.
  grunt.registerTask('default', ['jshint', 'mochaTest']);
};
<commit_msg>Added helpers dir to list to run jshint against.<commit_after>/**
 *  Grunt tasks to support running linter and unit tests.
 *
 *  @module Gruntfile
 *
 *  @copyright 2014, Digium, Inc.
 *  @license Apache License, Version 2.0
 *  @author Samuel Fortier-Galarneau <sgalarneau@digium.com>
 */

'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
    jshint: {
      options: {
        jshintrc: true
      },
      all: [
        'Gruntfile.js',
        'lib/*.js',
        'lib/helpers/*.js',
        'test/*.js'
      ]
    },
    mochaTest: {
      test: {
        options: {
          mocha: require('mocha'),
          reporter: 'spec',
          timeout: 2000
        },
        src: ['test/*.js']
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-mocha-test');

  // Default task.
  grunt.registerTask('default', ['jshint', 'mochaTest']);
};
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var noop = require( '@stdlib/utils/noop' );
var homedir = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof homedir, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function aliases `os.homedir` if available', function test( t ) {
	var homedir;
	var opts;

	opts = {
		'os': {
			'homedir': noop
		}
	};
	homedir = proxyquire( './../lib', opts );

	t.strictEqual( homedir, noop, 'equals `os.homedir`' );
	t.end();
});

tape( 'the function supports older Node versions', function test( t ) {
	var homedir;
	var opts;
	var env;

	opts = {
		'os': {
			'homedir': void 0
		},
		'./homedir.js': mock
	};
	homedir = proxyquire( './../lib', opts );

	t.strictEqual( homedir(), '/Users/beep', 'returns home directory' );

	t.end();

	function mock() {
		return '/Users/beep';
	}
});
<commit_msg>Remove unused variable declaration<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var noop = require( '@stdlib/utils/noop' );
var homedir = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof homedir, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function aliases `os.homedir` if available', function test( t ) {
	var homedir;
	var opts;

	opts = {
		'os': {
			'homedir': noop
		}
	};
	homedir = proxyquire( './../lib', opts );

	t.strictEqual( homedir, noop, 'equals `os.homedir`' );
	t.end();
});

tape( 'the function supports older Node versions', function test( t ) {
	var homedir;
	var opts;

	opts = {
		'os': {
			'homedir': void 0
		},
		'./homedir.js': mock
	};
	homedir = proxyquire( './../lib', opts );

	t.strictEqual( homedir(), '/Users/beep', 'returns home directory' );

	t.end();

	function mock() {
		return '/Users/beep';
	}
});
<|endoftext|>


<commit_before>import { MapProvider } from '../maps/create-map.js';
import { UsersManager } from '../kinvey/users.js';
import { WeatherProvider } from '../weather/get-weather.js';

import { ProfileScreen } from '../profile/profileScreen.js';
import { TemplatesProvider } from '../kinvey/templates.js';

const WeatherApp = (() => {
    let users,
        weather,
        maps,
        templates,
        profileScreen;

    class WeatherApp {
        constructor() {
            maps = new MapProvider();
            users = new UsersManager();
            weather = new WeatherProvider();
            templates = new TemplatesProvider();
            profileScreen = new ProfileScreen();

            this.__app__ = this.__initializeSammyApp__();
        }

        start() {
            this.__app__.run('#/');
        }

        __initializeSammyApp__() {
            var sammyApp = Sammy("#content", function () {
                var $content = $("#content"),
                    $weatherInfo = $("#weather");

                this.get("#/", function () {
                    $content.html("Route: #/ Content: TBD");
                });

                this.get("#/login", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        return;
                    }

                    templates.get("login")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-login").on("click", function () {
                                var logUser = {
                                    username: $('#username').val(),
                                    password: $('#password').val()
                                };

                                users.login(logUser)
                                    .then(function (response) {
                                        context.redirect('#/profile');
                                        document.location.reload(true);
                                    });
                            });
                        });
                });

                this.get("#/register", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        return;
                    }

                    templates.get("register")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-register").on("click", function () {
                                var newUser = {
                                    username: $('#new-username').val(),
                                    password: $('#new-username').val()
                                }

                                users.register(newUser)
                                    .then(function (response) {
                                        context.redirect('#/');
                                        document.location.reload(true);
                                    });
                            });
                        });
                });

                this.get('#/profile', function () {
                    startProfileScreen();
                });

                this.get('#/profile/:location/:duration', function (route) {
                    // Display weather location
                    // for params.location
                    // with params.duration
                    const profileScreen = $('#profile-screen');
                    if (profileScreen.length === 0) {
                        startProfileScreen();
                    }

                    let templateName;
                    let duration = Number(route.params.duration);
                    if (isNaN(duration)) {
                        duration = 14;
                    }

                    switch (duration) {
                        case 1:
                            templateName = 'current-weather';
                            break;
                        case 5:
                            templateName = 'five-day';
                            break;
                        case 14:
                            templateName = 'fourteen-day';
                            break;
                        default:
                            return;
                    }

                    Promise.all([
                        weather.getForecast(route.params.location, duration),
                        templates.get(templateName)
                    ])
                        .then(([data, template]) => {
                            const generatedHtml = template(data);
                            $("#weather").html(generatedHtml);
                            return data;
                        })
                        .then(data => {
                            maps.initializeMap(
                                data.city.coord.lat,
                                data.city.coord.lon,
                                document.getElementById('map-container')
                            );
                        })
                        .catch(console.log);
                });

                this.get('#/profile/add', function (route) {
                    const newLocation = $('#input-location').val();
                    if (!newLocation) {
                        return;
                    }

                    users.setUserLocations(newLocation);
                    startProfileScreen();
                    window.location = `#/profile/${newLocation}/1`;
                });

                function startProfileScreen() {
                    profileScreen.start('#content');
                    profileScreen.displayLocationsListForUser('#location-list');
                }
            });

            //logout
            $("#nav-btn-logout").on("click", function () {
                users.logout()
                    .then(function () {
                        location = "#/";
                        document.location.reload(true);
                    });
            });

            return sammyApp;
        }
    }

    return WeatherApp;
})();

export { WeatherApp };<commit_msg>changed #/ content again<commit_after>import { MapProvider } from '../maps/create-map.js';
import { UsersManager } from '../kinvey/users.js';
import { WeatherProvider } from '../weather/get-weather.js';

import { ProfileScreen } from '../profile/profileScreen.js';
import { TemplatesProvider } from '../kinvey/templates.js';

const WeatherApp = (() => {
    let users,
        weather,
        maps,
        templates,
        profileScreen;

    class WeatherApp {
        constructor() {
            maps = new MapProvider();
            users = new UsersManager();
            weather = new WeatherProvider();
            templates = new TemplatesProvider();
            profileScreen = new ProfileScreen();

            this.__app__ = this.__initializeSammyApp__();
        }

        start() {
            this.__app__.run('#/');
        }

        __initializeSammyApp__() {
            var sammyApp = Sammy("#content", function () {
                var $content = $("#content"),
                    $weatherInfo = $("#weather");

                this.get("#/", function () {
                    $content.html("
Route: #/

Content: TBD
");
                });

                this.get("#/login", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        return;
                    }

                    templates.get("login")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-login").on("click", function () {
                                var logUser = {
                                    username: $('#username').val(),
                                    password: $('#password').val()
                                };

                                users.login(logUser)
                                    .then(function (response) {
                                        context.redirect('#/profile');
                                        document.location.reload(true);
                                    });
                            });
                        });
                });

                this.get("#/register", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        return;
                    }

                    templates.get("register")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-register").on("click", function () {
                                var newUser = {
                                    username: $('#new-username').val(),
                                    password: $('#new-username').val()
                                }

                                users.register(newUser)
                                    .then(function (response) {
                                        context.redirect('#/');
                                        document.location.reload(true);
                                    });
                            });
                        });
                });

                this.get('#/profile', function () {
                    startProfileScreen();
                });

                this.get('#/profile/:location/:duration', function (route) {
                    // Display weather location
                    // for params.location
                    // with params.duration
                    const profileScreen = $('#profile-screen');
                    if (profileScreen.length === 0) {
                        startProfileScreen();
                    }

                    let templateName;
                    let duration = Number(route.params.duration);
                    if (isNaN(duration)) {
                        duration = 14;
                    }

                    switch (duration) {
                        case 1:
                            templateName = 'current-weather';
                            break;
                        case 5:
                            templateName = 'five-day';
                            break;
                        case 14:
                            templateName = 'fourteen-day';
                            break;
                        default:
                            return;
                    }

                    Promise.all([
                        weather.getForecast(route.params.location, duration),
                        templates.get(templateName)
                    ])
                        .then(([data, template]) => {
                            const generatedHtml = template(data);
                            $("#weather").html(generatedHtml);
                            return data;
                        })
                        .then(data => {
                            maps.initializeMap(
                                data.city.coord.lat,
                                data.city.coord.lon,
                                document.getElementById('map-container')
                            );
                        })
                        .catch(console.log);
                });

                this.get('#/profile/add', function (route) {
                    const newLocation = $('#input-location').val();
                    if (!newLocation) {
                        return;
                    }

                    users.setUserLocations(newLocation);
                    startProfileScreen();
                    window.location = `#/profile/${newLocation}/1`;
                });

                function startProfileScreen() {
                    profileScreen.start('#content');
                    profileScreen.displayLocationsListForUser('#location-list');
                }
            });

            //logout
            $("#nav-btn-logout").on("click", function () {
                users.logout()
                    .then(function () {
                        location = "#/";
                        document.location.reload(true);
                    });
            });

            return sammyApp;
        }
    }

    return WeatherApp;
})();

export { WeatherApp };<|endoftext|>


<commit_before>module.exports = function (grunt) {

    // load package.json values
    var pkg = grunt.file.readJSON('package.json');

    grunt.initConfig({
        //----------------------------------------------------------------------
        // CONFIG: VARIABLES
        //----------------------------------------------------------------------

        // general values
        keys: {
            name: 'chefling'
        },
        // file paths
        paths: {
            build: './build',
            dist: './dist'
        },
        // package
        pkg: pkg,
        //----------------------------------------------------------------------
        // CONFIG: TASKS
        //----------------------------------------------------------------------

        // clean directories
        clean: {
            before: ['<%=paths.build%>', '<%=paths.dist%>'],
            after: ['<%=paths.build%>']
        },
        // combine source files
        concat: {
            target: {
                src: ['./src/hashmap.js', './src/container.js'],
                dest: '<%=paths.build%>/<%=keys.name%>.js'
            }
        },
        // add UMD wrapper
        umd: {
            main: {
                src: '<%=concat.target.dest%>',
                dest: '<%=paths.build%>/<%=keys.name%>.umd.js',
                objectToExport: 'Container',
                globalAlias: 'Container',
                indent: 4
            }
        },
        // minify code
        uglify: {
            options: {
                mangle: {
                    except: ['Container', 'HashMap']
                }
            },
            build: {
                src: '<%=umd.main.dest%>',
                dest: '<%=paths.build%>/<%=keys.name%>.min.js'
            }
        },
        // copy files
        copy: {
            main: {
                files: [
                    {
                        src: '<%=umd.main.dest%>',
                        dest: '<%=paths.dist%>/<%=keys.name%>-' + pkg.version + '.js'
                    },
                    {
                        src: '<%=uglify.build.dest%>',
                        dest: '<%=paths.dist%>/<%=keys.name%>-' + pkg.version + '.min.js'
                    }
                ]
            }
        },
        // manage versioning
        version: {
            src: ['package.json', 'bower.json']
        }
    });

    //--------------------------------------------------------------------------
    // REGISTER TASKS
    //--------------------------------------------------------------------------

    // load tasks
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-umd');
    grunt.loadNpmTasks('grunt-version');

    // register tasks
    grunt.registerTask('default', [
        'clean:before',
        'concat',
        'umd',
        'uglify',
        'copy',
        'clean:after'
    ]);

};
<commit_msg>Adds readme file versioning task<commit_after>module.exports = function (grunt) {

    // load package.json values
    var pkg = grunt.file.readJSON('package.json');

    grunt.initConfig({
        //----------------------------------------------------------------------
        // CONFIG: VARIABLES
        //----------------------------------------------------------------------

        // general values
        keys: {
            name: 'chefling'
        },
        // file paths
        paths: {
            build: './build',
            dist: './dist'
        },
        // package
        pkg: pkg,
        //----------------------------------------------------------------------
        // CONFIG: TASKS
        //----------------------------------------------------------------------

        // clean directories
        clean: {
            before: ['<%=paths.build%>', '<%=paths.dist%>'],
            after: ['<%=paths.build%>']
        },
        // combine source files
        concat: {
            target: {
                src: ['./src/hashmap.js', './src/container.js'],
                dest: '<%=paths.build%>/<%=keys.name%>.js'
            }
        },
        // add UMD wrapper
        umd: {
            main: {
                src: '<%=concat.target.dest%>',
                dest: '<%=paths.build%>/<%=keys.name%>.umd.js',
                objectToExport: 'Container',
                globalAlias: 'Container',
                indent: 4
            }
        },
        // minify code
        uglify: {
            options: {
                mangle: {
                    except: ['Container', 'HashMap']
                }
            },
            build: {
                src: '<%=umd.main.dest%>',
                dest: '<%=paths.build%>/<%=keys.name%>.min.js'
            }
        },
        // copy files
        copy: {
            main: {
                files: [
                    {
                        src: '<%=umd.main.dest%>',
                        dest: '<%=paths.dist%>/<%=keys.name%>-' + pkg.version + '.js'
                    },
                    {
                        src: '<%=uglify.build.dest%>',
                        dest: '<%=paths.dist%>/<%=keys.name%>-' + pkg.version + '.min.js'
                    }
                ]
            }
        },
        // manage versioning
        version: {
            defaults: {
                src: ['package.json', 'bower.json']
            },
            readme: {
                options: {
                    prefix: '[a-z]+\\-v',
                    replace: '\\d+(\\.\\d+){2}'
                },
                src: ['README.md']
            }
        }
    });

    //--------------------------------------------------------------------------
    // REGISTER TASKS
    //--------------------------------------------------------------------------

    // load tasks
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-umd');
    grunt.loadNpmTasks('grunt-version');

    // register tasks
    grunt.registerTask('default', [
        'clean:before',
        'concat',
        'umd',
        'uglify',
        'copy',
        'clean:after'
    ]);

};
<|endoftext|>


<commit_before>/**
 * Flow Control tests.
 *
 * @author tlwr [toby@toby.codes]
 *
 * @copyright Crown Copyright 2017
 * @license Apache-2.0
 */
import TestRegister from "../../TestRegister.js";

TestRegister.addTests([
    {
        name: "Fork: nothing",
        input: "",
        expectedOutput: "",
        recipeConfig: [
            {
                op: "Fork",
                args: ["\n", "\n", false],
            },
        ],
    },
    {
        name: "Fork, Merge: nothing",
        input: "",
        expectedOutput: "",
        recipeConfig: [
            {
                op: "Fork",
                args: ["\n", "\n", false],
            },
            {
                op: "Merge",
                args: [],
            },
        ],
    },
    {
        name: "Fork, (expect) Error, Merge",
        input: "1\n2\na\n4",
        expectedError: true,
        recipeConfig: [
            {
                op: "Fork",
                args: ["\n", "\n", false],
            },
            {
                op: "To Base",
                args: [16],
            },
            {
                op: "Merge",
                args: [],
            },
        ],
    },
    {
        name: "Fork, Conditional Jump, Encodings",
        input: "Some data with a 1 in it\nSome data with a 2 in it",
        expectedOutput: "U29tZSBkYXRhIHdpdGggYSAxIGluIGl0\n53 6f 6d 65 20 64 61 74 61 20 77 69 74 68 20 61 20 32 20 69 6e 20 69 74\n",
        recipeConfig: [
            {"op":"Fork", "args":["\\n", "\\n", false]},
            {"op":"Conditional Jump", "args":["1", "2", "10"]},
            {"op":"To Hex", "args":["Space"]},
            {"op":"Return", "args":[]},
            {"op":"To Base64", "args":["A-Za-z0-9+/="]}
        ]
    },
    {
        name: "Conditional Jump: Skips 0",
        input: [
            "match",
            "should be changed 1",
            "should be changed 2",
        ].join("\n"),
        expectedOutput: [
            "match",
            "should be changed 1 was changed",
            "should be changed 2 was changed"
        ].join("\n"),
        recipeConfig: [
            {
                op: "Conditional Jump",
                args: ["match", 0, 0],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should be changed 1"
                    },
                    "should be changed 1 was changed",
                    true,
                    true,
                    true,
                ],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should be changed 2"
                    },
                    "should be changed 2 was changed",
                    true,
                    true,
                    true,
                ],
            },
        ],
    },
]);
<commit_msg>Add more tests for flow control ops<commit_after>/**
 * Flow Control tests.
 *
 * @author tlwr [toby@toby.codes]
 *
 * @copyright Crown Copyright 2017
 * @license Apache-2.0
 */
import TestRegister from "../../TestRegister.js";

TestRegister.addTests([
    {
        name: "Fork: nothing",
        input: "",
        expectedOutput: "",
        recipeConfig: [
            {
                op: "Fork",
                args: ["\n", "\n", false],
            },
        ],
    },
    {
        name: "Fork, Merge: nothing",
        input: "",
        expectedOutput: "",
        recipeConfig: [
            {
                op: "Fork",
                args: ["\n", "\n", false],
            },
            {
                op: "Merge",
                args: [],
            },
        ],
    },
    {
        name: "Fork, (expect) Error, Merge",
        input: "1\n2\na\n4",
        expectedError: true,
        recipeConfig: [
            {
                op: "Fork",
                args: ["\n", "\n", false],
            },
            {
                op: "To Base",
                args: [16],
            },
            {
                op: "Merge",
                args: [],
            },
        ],
    },
    {
        name: "Fork, Conditional Jump, Encodings",
        input: "Some data with a 1 in it\nSome data with a 2 in it",
        expectedOutput: "U29tZSBkYXRhIHdpdGggYSAxIGluIGl0\n53 6f 6d 65 20 64 61 74 61 20 77 69 74 68 20 61 20 32 20 69 6e 20 69 74\n",
        recipeConfig: [
            {"op":"Fork", "args":["\\n", "\\n", false]},
            {"op":"Conditional Jump", "args":["1", "2", "10"]},
            {"op":"To Hex", "args":["Space"]},
            {"op":"Return", "args":[]},
            {"op":"To Base64", "args":["A-Za-z0-9+/="]}
        ]
    },
    {
        name: "Jump: skips 0",
        input: [
            "should be changed",
        ].join("\n"),
        expectedOutput: [
            "should be changed was changed",
        ].join("\n"),
        recipeConfig: [
            {
                op: "Jump",
                args: [0, 10],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should be changed"
                    },
                    "should be changed was changed",
                    true,
                    true,
                    true,
                ],
            },
        ],
    },
    {
        name: "Jump: skips 1",
        input: [
            "shouldnt be changed",
        ].join("\n"),
        expectedOutput: [
            "shouldnt be changed",
        ].join("\n"),
        recipeConfig: [
            {
                op: "Jump",
                args: [1, 10],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "shouldnt be changed"
                    },
                    "shouldnt be changed was changed",
                    true,
                    true,
                    true,
                ],
            },
        ],
    },
    {
        name: "Conditional Jump: Skips 0",
        input: [
            "match",
            "should be changed 1",
            "should be changed 2",
        ].join("\n"),
        expectedOutput: [
            "match",
            "should be changed 1 was changed",
            "should be changed 2 was changed"
        ].join("\n"),
        recipeConfig: [
            {
                op: "Conditional Jump",
                args: ["match", 0, 0],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should be changed 1"
                    },
                    "should be changed 1 was changed",
                    true,
                    true,
                    true,
                ],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should be changed 2"
                    },
                    "should be changed 2 was changed",
                    true,
                    true,
                    true,
                ],
            },
        ],
    },
    {
        name: "Conditional Jump: Skips 1",
        input: [
            "match",
            "should not be changed",
            "should be changed",
        ].join("\n"),
        expectedOutput: [
            "match",
            "should not be changed",
            "should be changed was changed"
        ].join("\n"),
        recipeConfig: [
            {
                op: "Conditional Jump",
                args: ["match", 1, 10],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should not be changed"
                    },
                    "should not be changed was changed",
                    true,
                    true,
                    true,
                ],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "should be changed"
                    },
                    "should be changed was changed",
                    true,
                    true,
                    true,
                ],
            },
        ],
    },
    {
        name: "Conditional Jump: Skips negatively",
        input: [
            "match",
        ].join("\n"),
        expectedOutput: [
            "replaced",
        ].join("\n"),
        recipeConfig: [
            {
                op: "Jump",
                args: [1],
            },
            {
                op: "Find / Replace",
                args: [
                    {
                        "option": "Regex",
                        "string": "match"
                    },
                    "replaced",
                    true,
                    true,
                    true,
                ],
            },
            {
                op: "Conditional Jump",
                args: ["match", -2, 10],
            },
        ],
    },
]);
<|endoftext|>