<commit_before>/**
 * rc.js - Row/Column Conversions
 * v0.03 - Fixed rc.rotate, added Opt for minification
 */

(function(root){
	"use strict";

	/**
	 * Create an object and add a .commit() prototype to place the values back into the original.
	 * Useful for moving simple data types around. Objects and arrays will be automatically referenced.
	 * @constructor
	 * @param obj - A columnar object
	 * @param {number} index - The index to convert into a row-based object
	 * @param {Boolean} [clearUndef] - Clear undefined attributes when copying the object.
	 */
	function Proxy(obj, index, clearUndef) {
		var att;

		for ( att in obj ) {
			if ( obj.hasOwnProperty(att) && ( !clearUndef || obj[att][index] !== undefined ) ) {
				this[att] = obj[att][index];
			}
		}

		// Defined inside the constructor to give it access to the originating object and parameters
		Proxy.prototype.commit = function(){
			var att;
			for ( att in this ) {
				if ( this.hasOwnProperty(att) && ( !clearUndef || this[att] !== undefined ) ) {
					obj[att][index] = this[att];
				}
			}
		};
	}

	var Opt = Object.prototype.toString,
		self = {
		array: {
			getIndexes: function(array, filter) {
				var indexes = [],
					len = array.length,
					isFn = (typeof filter === 'function'),
					i;

				for (i = 0; i < len; i++) {
					if ( ( isFn && filter.call(null, i, array[i]) ) || ( !isFn && array[i] === filter ) ) {
						indexes.push(i);
					}
				}
				return indexes;
			},
			getByIndexes: function(array, indexes) {
				var len = indexes.length,
					data = [];

				for (;len;) {
					len--;
					data[len] = array[indexes[len]];
				}
				return data;
			},
			rotate: function(arr, result, limited, softFail) {
				var obj, len, i, att, has;

				// Not an array? Send it back.
				if ( Opt.call(arr) !== '[object Array]' ) {
					throw new TypeError("RC: Argument is not an array");
				}

				// Clean truthy/falsy values & undefined
				limited = !!limited;
				softFail = !!softFail;

				if ( !!result || typeof result !== 'object' ) {
					if ( limited ) {
						throw new TypeError("RC: Must pass a result object when 'limited' is true");
					} else {
						result = {};
					}
				}

				len = arr.length;

				for ( i = 0; i < len; i++ ) {
					obj = arr[i];

					if (typeof obj !== "object") {
						if ( !softFail ) {
							throw new TypeError("RC: Nested element is not an object");
						}
						// Otherwise skip this loop
					} else {
						for (att in obj) {
							if ( obj.hasOwnProperty(att) ) {
								has = result.hasOwnProperty(att);

								if ( !has ) {
									if ( limited ) {
										continue;
									} else {
										result[att] = [];
									}
								}
								result[att][i] = obj[att];
							}
						}
					}
				}
				return result;
			}
		},
		object: {
			filter: function(obj, field, filter) {
				return self.object.filterMerge(obj, self.object.filterIndexes(obj, field, filter));
			},
			filterIndexes: function(obj, field, filter) {
				var indexes = false;

				if ( obj.hasOwnProperty(field) ) {
					indexes = self.array.getIndexes(obj[field], filter);
				}
				return indexes;
			},
			filterMerge: function(obj, indexes) {
				var result = {},
					att;

				if ( indexes ) {
					for (att in obj) {
						if ( obj.hasOwnProperty(att) ) {
							result[att] = self.array.getByIndexes(obj[att], indexes);
						}
					}
				}
				return result;
			},
			rotate: function(obj, result, clearUndef) {
				var att, i, len = 0;

				// Not an array? Send it back.
				if ( typeof obj !== 'object' ) {
					throw new TypeError("RC: Argument is not an object");
				}

				if ( result === undefined ) {
					result = [];
				} else if ( Object.prototype.toString.call(result) !== '[object Array]' ) {
					throw new TypeError("RC: Result argument is an array");
				}

				// Get the longest length of all properties
				for (att in obj) {
					if ( obj.hasOwnProperty(att) ) {
						len = Math.max(len, att.length);
					}
				}

				for (i = 0; i < len; i++) {
					if ( result[i] === undefined ) {
						result[i] = {};
					} else if ( typeof result[i] !== 'object' ) {
						throw new TypeError("RC: Result contains incorrect type at index " + i);
					}

					for (att in obj) {
						if ( obj.hasOwnProperty(att) && ( !clearUndef || obj[att][i] !== undefined ) ) {
							result[i][att] = obj[att][i];
						}
					}
				}

				return result;
			},
			objFromIndex: function(obj, index, clearUndef) {
				return new Proxy(obj, index, clearUndef);
			},
			proxy: function(obj, index, clearUndef) {
				return new Proxy(obj, index, clearUndef);
			}
		},
		rotate: function(obj) {
			// Generic, which directs to the appropriate array/object rotate
			if (typeof obj !== 'object') throw new TypeError("RC: rotate requires an object or an array");
			if ( Opt.call(obj) === '[object Array]' ) {
				return self.array.rotate.apply(this, arguments);
			} else {
				return self.object.rotate.apply(this, arguments);
			}
		},
		version: 'v0.03'
	};

	root.rc = self;

	// Can we build a chaining mode?
	/**
	 * @constructor
	 * @param obj - A (hopefully) columnar object
	 * @param {Boolean} [clearUndef] - Clear undefined attributes when copying the object.
	 */
	root.RC = function(obj, clearUndef) {
		var att;

		for ( att in obj ) {
			if ( obj.hasOwnProperty(att) && ( !clearUndef || obj[att] !== undefined ) ) {
				this[att] = obj[att];
			}
		}
	};

	root.RC.prototype.filter = function(field, filter) {
		return new root.RC(self.object.filter(this, field, filter));
	};
	root.RC.prototype.proxy = function(index, clearUndef) {
		return self.object.proxy(this, index, clearUndef);
	};
	root.RC.prototype.rotate = function(mergeObj, clearUndef) {
		return self.object.rotate(this, mergeObj, clearUndef);
	};
}(this));
<commit_msg>v0.04<commit_after>/**
 * rc.js - Row/Column Conversions
 * v0.04 - getIndexes performance improvement */

(function(root){
	"use strict";

	/**
	 * Create an object and add a .commit() prototype to place the values back into the original.
	 * Useful for moving simple data types around. Objects and arrays will be automatically referenced.
	 * @constructor
	 * @param obj - A columnar object
	 * @param {number} index - The index to convert into a row-based object
	 * @param {Boolean} [clearUndef] - Clear undefined attributes when copying the object.
	 */
	function Proxy(obj, index, clearUndef) {
		var att;

		for ( att in obj ) {
			if ( obj.hasOwnProperty(att) && ( !clearUndef || obj[att][index] !== undefined ) ) {
				this[att] = obj[att][index];
			}
		}

		// Defined inside the constructor to give it access to the originating object and parameters
		Proxy.prototype.commit = function(){
			var att;
			for ( att in this ) {
				if ( this.hasOwnProperty(att) && ( !clearUndef || this[att] !== undefined ) ) {
					obj[att][index] = this[att];
				}
			}
		};
	}

	var Opt = Object.prototype.toString,
		self = {
		array: {
			getIndexes: function(array, filter) {
				var indexes = [],
					len = array.length,
					isFn = (typeof filter === 'function'),
					i;

				if (isFn) {
					for (i = 0; i < len; i++) {
						if ( filter(i, array[i]) ) {
							indexes.push(i);
						}
					}
				} else {
					for (i = 0; i < len; i++) {
						if ( array[i] === filter ) {
							indexes.push(i);
						}
					}
				}
			},
			getByIndexes: function(array, indexes) {
				var len = indexes.length,
					data = [];

				for (;len;) {
					len--;
					data[len] = array[indexes[len]];
				}
				return data;
			},
			rotate: function(arr, result, limited, softFail) {
				var obj, len, i, att, has;

				// Not an array? Send it back.
				if ( Opt.call(arr) !== '[object Array]' ) {
					throw new TypeError("RC: Argument is not an array");
				}

				// Clean truthy/falsy values & undefined
				limited = !!limited;
				softFail = !!softFail;

				if ( !!result || typeof result !== 'object' ) {
					if ( limited ) {
						throw new TypeError("RC: Must pass a result object when 'limited' is true");
					} else {
						result = {};
					}
				}

				len = arr.length;

				for ( i = 0; i < len; i++ ) {
					obj = arr[i];

					if (typeof obj !== "object") {
						if ( !softFail ) {
							throw new TypeError("RC: Nested element is not an object");
						}
						// Otherwise skip this loop
					} else {
						for (att in obj) {
							if ( obj.hasOwnProperty(att) ) {
								has = result.hasOwnProperty(att);

								if ( !has ) {
									if ( limited ) {
										continue;
									} else {
										result[att] = [];
									}
								}
								result[att][i] = obj[att];
							}
						}
					}
				}
				return result;
			}
		},
		object: {
			filter: function(obj, field, filter) {
				return self.object.filterMerge(obj, self.object.filterIndexes(obj, field, filter));
			},
			filterIndexes: function(obj, field, filter) {
				var indexes = false;

				if ( obj.hasOwnProperty(field) ) {
					indexes = self.array.getIndexes(obj[field], filter);
				}
				return indexes;
			},
			filterMerge: function(obj, indexes) {
				var result = {},
					att;

				if ( indexes ) {
					for (att in obj) {
						if ( obj.hasOwnProperty(att) ) {
							result[att] = self.array.getByIndexes(obj[att], indexes);
						}
					}
				}
				return result;
			},
			rotate: function(obj, result, clearUndef) {
				var att, i, len = 0;

				// Not an array? Send it back.
				if ( typeof obj !== 'object' ) {
					throw new TypeError("RC: Argument is not an object");
				}

				if ( result === undefined ) {
					result = [];
				} else if ( Object.prototype.toString.call(result) !== '[object Array]' ) {
					throw new TypeError("RC: Result argument is an array");
				}

				// Get the longest length of all properties
				for (att in obj) {
					if ( obj.hasOwnProperty(att) ) {
						len = Math.max(len, att.length);
					}
				}

				for (i = 0; i < len; i++) {
					if ( result[i] === undefined ) {
						result[i] = {};
					} else if ( typeof result[i] !== 'object' ) {
						throw new TypeError("RC: Result contains incorrect type at index " + i);
					}

					for (att in obj) {
						if ( obj.hasOwnProperty(att) && ( !clearUndef || obj[att][i] !== undefined ) ) {
							result[i][att] = obj[att][i];
						}
					}
				}

				return result;
			},
			objFromIndex: function(obj, index, clearUndef) {
				return new Proxy(obj, index, clearUndef);
			},
			proxy: function(obj, index, clearUndef) {
				return new Proxy(obj, index, clearUndef);
			}
		},
		rotate: function(obj) {
			// Generic, which directs to the appropriate array/object rotate
			if (typeof obj !== 'object') throw new TypeError("RC: rotate requires an object or an array");
			if ( Opt.call(obj) === '[object Array]' ) {
				return self.array.rotate.apply(this, arguments);
			} else {
				return self.object.rotate.apply(this, arguments);
			}
		},
		version: 'v0.04'
	};

	root.rc = self;

	// Can we build a chaining mode?
	/**
	 * @constructor
	 * @param obj - A (hopefully) columnar object
	 * @param {Boolean} [clearUndef] - Clear undefined attributes when copying the object.
	 */
	root.RC = function(obj, clearUndef) {
		var att;

		for ( att in obj ) {
			if ( obj.hasOwnProperty(att) && ( !clearUndef || obj[att] !== undefined ) ) {
				this[att] = obj[att];
			}
		}
	};

	root.RC.prototype.filter = function(field, filter) {
		return new root.RC(self.object.filter(this, field, filter));
	};
	root.RC.prototype.proxy = function(index, clearUndef) {
		return self.object.proxy(this, index, clearUndef);
	};
	root.RC.prototype.rotate = function(mergeObj, clearUndef) {
		return self.object.rotate(this, mergeObj, clearUndef);
	};
}(this));<|endoftext|>


<commit_before>// ==UserScript==
// @name                OLog
// @namespace           http://www.olog.com/
// @description         OLog Userscript
// @include             http://s*-*.ogame.gameforge.com/game/*
// @grant               GM_xmlhttpRequest
// ==/UserScript==

"use strict";

var menuTable = document.getElementById("menuTable");

var oLogLi = document.createElement("li");
oLogLi.onfocus = function(c) {
    if (b(c.target).closest(".dropdown").length == 0) {
        b(".currentlySelected a").removeClass("hover");
        b(".currentlySelected").removeClass("focus");
    }
}

var oLogAnchor = document.createElement("a");
oLogAnchor.className = "menubutton"
oLogAnchor.href = "#"
oLogAnchor.onclick = function() {
    var menuTableLiList = menuTable.querySelectorAll("li");
    for (var i = 0; i < menuTableLiList.length; i++) {
        console.log(menuTableLiList[i]);
        console.log(menuTableLiList[i].querySelector(".menubutton"));
        console.log(menuTableLiList[i].querySelector(".menubutton").classList);
        menuTableLiList[i].querySelector(".menubutton").classList.remove("selected");
    }

    oLogAnchor.classList.add("selected");

    var inhaltDiv = document.getElementById("inhalt");
    while (inhaltDiv.firstChild) {
        inhaltDiv.removeChild(inhaltDiv.firstChild);
    }
}

var oLogSpan = document.createElement("span");
oLogSpan.className = "textlabel"

var oLogText = document.createTextNode("OLog Settings");

oLogSpan.appendChild(oLogText);
oLogAnchor.appendChild(oLogSpan);
oLogLi.appendChild(oLogAnchor);
menuTable.appendChild(oLogLi);

var page = getWindowVariable("currentPage");

if (page === "messages") {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.localName === "ul" && node.classList.contains("tab_inner")) {
                    //send all messages at once such that all SR keys can be sent at once to the server
                    processMessageNodes(node.querySelectorAll(".msg"));
                }
            }
        });
    });

    observer.observe(document, { childList: true, subtree: true });
}

function processMessageNodes(nodes) {
    var reportKeys = {
        sr: [],     //spy report
        cr: [],     //combat report
        rr: [],     //recycle report
        mr: []      //missile report
    };

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var apiElement = node.querySelector(".icon_apikey");
        if (apiElement !== null) {
            var key = node.querySelector(".icon_apikey").title;
            var type = key.substring(0, 2);
            if (reportKeys.hasOwnProperty(type)) {
                reportKeys[type].push(key);
            }
        }
    }

    console.log(reportKeys);

    postData({
        endpoint: "keys",
        data: {
            reportKeys: reportKeys
        }
    });
}

function postData(object) {
    addPlayerData(object.data);
    console.log(JSON.stringify(object.data));
    GM_xmlhttpRequest({
        method: "POST",
        url: "http://localhost:8080/api/userscript/" + object.endpoint,
        data: JSON.stringify(object.data),
        headers: {
            "Content-Type": "application/json"
        },
        onload: function(response) {
            console.log("load");
        },
        onerror: function(response) {
            console.log("error");
        }
    });
}

function addPlayerData(data) {
    data.server = getWindowVariable("constants.language");
    data.universe = getWindowVariable("constants.name");
    data.playerId = getWindowVariable("playerId");
    data.playerName = getWindowVariable("playerName");
}

/**
 * Returns a global variable.
 *
 * Needed because a @grant other than none puts the script
 * in a separate scope.
 *
 * @param {string} name The name of the global variable.
 */
function getWindowVariable(name) {
    return window.eval(name);
}<commit_msg>Added settings form markup.<commit_after>// ==UserScript==
// @name                OLog
// @namespace           http://www.olog.com/
// @description         OLog Userscript
// @include             http://s*-*.ogame.gameforge.com/game/*
// @grant               GM_xmlhttpRequest
// ==/UserScript==

"use strict";

var menuTable = document.getElementById("menuTable");

var oLogLi = document.createElement("li");
oLogLi.onfocus = function(c) {
    if (b(c.target).closest(".dropdown").length == 0) {
        b(".currentlySelected a").removeClass("hover");
        b(".currentlySelected").removeClass("focus");
    }
}

var oLogAnchor = document.createElement("a");
oLogAnchor.className = "menubutton"
oLogAnchor.href = "#"
oLogAnchor.onclick = function() {
    var menuTableLiList = menuTable.querySelectorAll("li");
    for (var i = 0; i < menuTableLiList.length; i++) {
        menuTableLiList[i].querySelector(".menubutton").classList.remove("selected");
    }

    oLogAnchor.classList.add("selected");

    var inhaltDiv = document.getElementById("inhalt");
    while (inhaltDiv.firstChild) {
        inhaltDiv.removeChild(inhaltDiv.firstChild);
    }

    var buttonzDiv = document.createElement("div");
    buttonzDiv.id = "buttonz";

    var headerDiv = document.createElement("div");
    headerDiv.className = "header";

    var headerH2 = document.createElement("h2");

    var headerText = document.createTextNode("OLog Settings");

    var contentDiv = document.createElement("div");
    contentDiv.className = "content";

    var fieldwrapperDiv = document.createElement("div");
    fieldwrapperDiv.className = "fieldwrapper";

    var oLogInstanceUrlLabel = document.createElement("label");
    oLogInstanceUrlLabel.className = "styled textBeefy";

    var oLogInstanceUrlText = document.createTextNode("OLog Instance URL:");

    var oLogInstanceUrlTheFieldDiv = document.createElement("div");
    oLogInstanceUrlTheFieldDiv.className = "thefield";

    var oLogInstanceUrlInput = document.createElement("input");
    oLogInstanceUrlInput.className = "textinput w200";
    oLogInstanceUrlInput.type = "text";
    oLogInstanceUrlInput.size = "30";
    oLogInstanceUrlInput.value = "";
    oLogInstanceUrlInput.maxlength = "20";

    var settingsSaveDiv = document.createElement("div");
    settingsSaveDiv.className = "textCenter";

    var settingsSaveInput = document.createElement("input");
    settingsSaveInput.className = "btn_blue";
    settingsSaveInput.type = "submit";
    settingsSaveInput.value = "Save settings";

    oLogInstanceUrlLabel.appendChild(oLogInstanceUrlText);
    oLogInstanceUrlTheFieldDiv.appendChild(oLogInstanceUrlInput);
    fieldwrapperDiv.appendChild(oLogInstanceUrlLabel);
    fieldwrapperDiv.appendChild(oLogInstanceUrlTheFieldDiv);

    settingsSaveDiv.appendChild(settingsSaveInput);

    contentDiv.appendChild(fieldwrapperDiv);
    contentDiv.appendChild(settingsSaveDiv);

    headerH2.appendChild(headerText);
    headerDiv.appendChild(headerH2);
    buttonzDiv.appendChild(headerDiv);
    buttonzDiv.appendChild(contentDiv);
    inhaltDiv.appendChild(buttonzDiv);
}

var oLogSpan = document.createElement("span");
oLogSpan.className = "textlabel"

var oLogText = document.createTextNode("OLog Settings");

oLogSpan.appendChild(oLogText);
oLogAnchor.appendChild(oLogSpan);
oLogLi.appendChild(oLogAnchor);
menuTable.appendChild(oLogLi);

var page = getWindowVariable("currentPage");

if (page === "messages") {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.localName === "ul" && node.classList.contains("tab_inner")) {
                    //send all messages at once such that all SR keys can be sent at once to the server
                    processMessageNodes(node.querySelectorAll(".msg"));
                }
            }
        });
    });

    observer.observe(document, { childList: true, subtree: true });
}

function processMessageNodes(nodes) {
    var reportKeys = {
        sr: [],     //spy report
        cr: [],     //combat report
        rr: [],     //recycle report
        mr: []      //missile report
    };

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var apiElement = node.querySelector(".icon_apikey");
        if (apiElement !== null) {
            var key = node.querySelector(".icon_apikey").title;
            var type = key.substring(0, 2);
            if (reportKeys.hasOwnProperty(type)) {
                reportKeys[type].push(key);
            }
        }
    }

    console.log(reportKeys);

    postData({
        endpoint: "keys",
        data: {
            reportKeys: reportKeys
        }
    });
}

function postData(object) {
    addPlayerData(object.data);
    console.log(JSON.stringify(object.data));
    GM_xmlhttpRequest({
        method: "POST",
        url: "http://localhost:8080/api/userscript/" + object.endpoint,
        data: JSON.stringify(object.data),
        headers: {
            "Content-Type": "application/json"
        },
        onload: function(response) {
            console.log("load");
        },
        onerror: function(response) {
            console.log("error");
        }
    });
}

function addPlayerData(data) {
    data.server = getWindowVariable("constants.language");
    data.universe = getWindowVariable("constants.name");
    data.playerId = getWindowVariable("playerId");
    data.playerName = getWindowVariable("playerName");
}

/**
 * Returns a global variable.
 *
 * Needed because a @grant other than none puts the script
 * in a separate scope.
 *
 * @param {string} name The name of the global variable.
 */
function getWindowVariable(name) {
    return window.eval(name);
}<|endoftext|>


<commit_before>// Copyright (c) 2015 bivio Software, Inc.  All rights reserved.
'use strict';
var app = angular.module('EVC2015App', ['ngRoute', 'ngAnimate']);

app.config(function($routeProvider) {
    $routeProvider
        .when('/home', {
            controller: 'HomeController as home',
            templateUrl: '/static/html/home.html?' + PUBLIC_PRIZE_APP_VERSION,
        })
        .when('/about', {
            templateUrl: '/static/html/about.html?' + PUBLIC_PRIZE_APP_VERSION,
        })
        .when('/:nominee_biv_id/nominate-thank-you', {
            controller: 'NomineeController as nominee',
            templateUrl: '/static/html/nominate-thank-you.html?' + PUBLIC_PRIZE_APP_VERSION,
        })
        .otherwise({
            redirectTo: '/home',
        });
});

app.factory('serverRequest', function($http, $location) {
    var self = this;
    self.sendRequest = function(url, callback, postData) {
        var biv = $location.absUrl().match(/\/\/.*?\/(.*?)(#|$)/)[1];
        return $http.post('/' + biv + url, postData).success(function(data) {
            callback(data);
        }).error(function(data, status) {
            console.log(url, ' failed: ', status);
        });
    };
    return self;
});

app.factory('userState', function(serverRequest, $rootScope) {
    var self = this;
    self.state = {};

    function updateUserState(data) {
        self.state = {
            isLoggedIn: data.user_state.is_logged_in,
            isAdmin: data.user_state.is_admin,
            isJudge: data.user_state.is_judge,
        };
    }

    self.isLoggedIn = function() {
        return self.state.isLoggedIn ? true : false;
    };
    self.isAdmin = function() {
        return self.state.isAdmin ? true : false;
    };
    self.isJudge = function() {
        return self.state.isJudge ? true : false;
    };
    self.logout = function() {
        serverRequest.sendRequest('/logout', function(data) {
            updateUserState(data);
            $rootScope.$broadcast('pp.alert', 'You have successfully logged out.');
        });
    };
    self.updateState = function() {
        serverRequest.sendRequest('/user-state', updateUserState);
    }
    self.updateState()
    return self;
});

app.controller('NomineeController', function(serverRequest, $route) {
    var self = this;
    var nominee_biv_id = $route.current.params.nominee_biv_id;
    self.info = {};
    loadNominee();

    function loadNominee() {
        serverRequest.sendRequest(
            '/nominee-info',
            function(data) {
                self.info = data.nominee;
            },
            {
                nominee_biv_id: nominee_biv_id,
            });
    }
});

app.controller('HomeController', function(serverRequest, userState, $location) {
    var MAX_FOUNDERS = 3;
    var self = this;
    self.userState = userState;
    self.formData = {};
    self.formFields = [];
    self.formErrors = {};
    self.founderCount = 1;
    self.sponsors = [];
    loadFormMetadata();
    loadSponsors();

    function hideFounders() {
    }

    function loadFormMetadata() {
        var hidden = {
            founder2_name: true,
            founder2_desc: true,
            founder3_name: true,
            founder3_desc: true,
        };
        serverRequest.sendRequest('/nominee-form-metadata', function(data) {
            self.formFields = data.form_metadata;
            for (var i = 0; i < self.formFields.length; i++)
                self.formFields[i].visible = hidden[self.formFields[i].name] ? false : true;
            //TODO(pjm): timeout is a hack
            setTimeout(
                function() {
                    $('.pp-tooltip').tooltip({
                        'container': 'body'
                    })
                }, 100);
        });
    }

    function loadSponsors() {
        serverRequest.sendRequest('/sponsors', function(data) {
            self.sponsors = data.sponsors;
        });
    }

    self.addFounder = function() {
        self.founderCount++;
        for (var i = 0; i < self.formFields.length; i++) {
            var search = 'founder' + self.founderCount;
            if (self.formFields[i].name.indexOf(search) >= 0) {
                self.formFields[i].visible = true;
            }
        }
        if (self.founderCount >= MAX_FOUNDERS)
            $('#addFounderButton').fadeOut();
    };

    self.getError = function(name) {
        return self.formErrors[name];
    }

    self.hasError = function(name) {
        return self.getError(name) ? true : false;
    }

    self.saveForm = function() {
        var ladda = Ladda.create(document.querySelector('button.ladda-button'));
        ladda.start();

        serverRequest.sendRequest(
            '/nominee-form-submit',
            function(data) {
                ladda.stop();
                if (data.errors) {
                    self.formErrors = data.errors;
                    return;
                }
                $location.path('/' + data.nominee_biv_id  + '/nominate-thank-you');
            },
            self.formData)
            .error(function(data, status) {
                ladda.stop();
                if (status == 403)
                    self.formErrors.display_name = 'Log in to nominate a company';
            });
    };
});

app.controller('NavController', function () {
    var self = this;
    self.pageTitle = function() {
        return 'Esprit Venture Challenge - Public Prize';
    };
});

app.directive('loginModal', function() {
    return {
        scope: {
            loginModal: '@',
            loginText: '@',
        },
        template: [
            '
',
              '
',
                '
',
                  '
',
                    '<button type="button" class="close" data-dismiss="modal">×</button>',
                    '
{{ loginText }}
',
                  '
',
                  '
',
                    ' using LinkedIn',
                  '
',
                '
',
              '
',
            '
',
        ].join(''),
    };
});

app.directive('navLinks', function(userState) {
    return {
        scope: {},
        template: [
            '
Sign up
',
            '
Log in
',
            '
Log out
',
        ].join(''),
        controller: function($scope) {
            $scope.userState = userState;
        },
    };
});

app.directive('alertBox', function($rootScope) {
    return {
        scope: {},
        controller: function($scope) {
            $rootScope.$on('pp.alert', function(alert, message) {
                $scope.message = message;
            });
        },
        template: [
            '
',
              '
',
                '
',
                  '<button type="button" class="close" data-dismiss="alert">×</button>',
	          '{{ message }}',
	        '
',
              '
',
            '
',
        ].join(''),
    };
});

function formFieldTemplate(includeHelp) {
    return [
        '
',
          '{{ home.getError(f.name) }}',
          '

',
            (includeHelp ? '
' : ''),
              '

',
              '<textarea data-ng-switch-when="TextAreaField" class="form-control" data-ng-class="{slideDown: f.visible}" rows="5" placeholder="{{ f.label }}" data-ng-model="home.formData[f.name]"></textarea>',
              '<input data-ng-switch-default class="form-control" type="text" value="" data-ng-class="{slideDown: f.visible}" placeholder="{{ f.label }}" data-ng-model="home.formData[f.name]">',
              (includeHelp ? '' : ''),
            (includeHelp ? '
' : ''),
          '
',
        '
',
    ].join('');
}

//TODO(pjm): really ugly, combine formField with formFieldWithHelp
app.directive('formField', function() {
    return {
        scope: {
            f: '=formField',
            home: '=controller',
        },
        template: formFieldTemplate(false),
    };
});

app.directive('formFieldWithHelp', function() {
    return {
        scope: {
            f: '=formFieldWithHelp',
            home: '=controller',
        },
        template: formFieldTemplate(true),
    };
});

app.animation('.slideDown', function() {
    return {
        addClass: function(element, className, done) {
            if (className == 'slideDown') {
                $(element).hide();
                $(element).slideDown(done);
            }
        },
    }
});
<commit_msg>load contest-info from server, disable nominations at expiry<commit_after>// Copyright (c) 2015 bivio Software, Inc.  All rights reserved.
'use strict';
var app = angular.module('EVC2015App', ['ngRoute', 'ngAnimate']);

app.config(function($routeProvider) {
    $routeProvider
        .when('/home', {
            controller: 'HomeController as home',
            templateUrl: '/static/html/home.html?' + PUBLIC_PRIZE_APP_VERSION,
        })
        .when('/about', {
            templateUrl: '/static/html/about.html?' + PUBLIC_PRIZE_APP_VERSION,
        })
        .when('/:nominee_biv_id/nominate-thank-you', {
            controller: 'NomineeController as nominee',
            templateUrl: '/static/html/nominate-thank-you.html?' + PUBLIC_PRIZE_APP_VERSION,
        })
        .otherwise({
            redirectTo: '/home',
        });
});

app.factory('serverRequest', function($http, $location) {
    var self = this;
    self.sendRequest = function(url, callback, postData) {
        var biv = $location.absUrl().match(/\/\/.*?\/(.*?)(#|$)/)[1];
        return $http.post('/' + biv + url, postData).success(function(data) {
            callback(data);
        }).error(function(data, status) {
            console.log(url, ' failed: ', status);
        });
    };
    return self;
});

app.factory('userState', function(serverRequest, $rootScope) {
    var self = this;
    self.state = {};

    function updateUserState(data) {
        self.state = {
            isLoggedIn: data.user_state.is_logged_in,
            isAdmin: data.user_state.is_admin,
            isJudge: data.user_state.is_judge,
        };
    }

    self.isLoggedIn = function() {
        return self.state.isLoggedIn ? true : false;
    };
    self.isAdmin = function() {
        return self.state.isAdmin ? true : false;
    };
    self.isJudge = function() {
        return self.state.isJudge ? true : false;
    };
    self.logout = function() {
        serverRequest.sendRequest('/logout', function(data) {
            updateUserState(data);
            $rootScope.$broadcast('pp.alert', 'You have successfully logged out.');
        });
    };
    self.updateState = function() {
        serverRequest.sendRequest('/user-state', updateUserState);
    }
    self.updateState()
    return self;
});

app.controller('NomineeController', function(serverRequest, $route) {
    var self = this;
    var nominee_biv_id = $route.current.params.nominee_biv_id;
    self.info = {};
    loadNominee();

    function loadNominee() {
        serverRequest.sendRequest(
            '/nominee-info',
            function(data) {
                self.info = data.nominee;
            },
            {
                nominee_biv_id: nominee_biv_id,
            });
    }
});

app.controller('HomeController', function(serverRequest, userState, $location) {
    var MAX_FOUNDERS = 3;
    var self = this;
    self.userState = userState;
    self.formData = {};
    self.formFields = [];
    self.formErrors = {};
    self.founderCount = 1;
    self.sponsors = [];
    self.contestInfo = {};

    loadContestInfo();
    loadFormMetadata();
    loadSponsors();

    function loadContestInfo() {
        serverRequest.sendRequest('/contest-info', function(data) {
            self.contestInfo = data;
        });
    }

    function loadFormMetadata() {
        var hidden = {
            founder2_name: true,
            founder2_desc: true,
            founder3_name: true,
            founder3_desc: true,
        };
        serverRequest.sendRequest('/nominee-form-metadata', function(data) {
            self.formFields = data.form_metadata;
            for (var i = 0; i < self.formFields.length; i++)
                self.formFields[i].visible = hidden[self.formFields[i].name] ? false : true;
            //TODO(pjm): timeout is a hack
            setTimeout(
                function() {
                    $('.pp-tooltip').tooltip({
                        'container': 'body'
                    })
                }, 100);
        });
    }

    function loadSponsors() {
        serverRequest.sendRequest('/sponsors', function(data) {
            self.sponsors = data.sponsors;
        });
    }

    self.addFounder = function() {
        self.founderCount++;
        for (var i = 0; i < self.formFields.length; i++) {
            var search = 'founder' + self.founderCount;
            if (self.formFields[i].name.indexOf(search) >= 0) {
                self.formFields[i].visible = true;
            }
        }
        if (self.founderCount >= MAX_FOUNDERS)
            $('#addFounderButton').fadeOut();
    };

    self.allowNominations = function() {
        return self.contestInfo['allowNominations'] ? true : false;
    };

    self.getError = function(name) {
        return self.formErrors[name];
    }

    self.hasError = function(name) {
        return self.getError(name) ? true : false;
    }

    self.saveForm = function() {
        var ladda = Ladda.create(document.querySelector('button.ladda-button'));
        ladda.start();

        serverRequest.sendRequest(
            '/nominee-form-submit',
            function(data) {
                ladda.stop();
                if (data.errors) {
                    self.formErrors = data.errors;
                    return;
                }
                $location.path('/' + data.nominee_biv_id  + '/nominate-thank-you');
            },
            self.formData)
            .error(function(data, status) {
                ladda.stop();
                if (status == 403)
                    self.formErrors.display_name = 'Log in to nominate a company';
            });
    };
});

app.controller('NavController', function () {
    var self = this;
    self.pageTitle = function() {
        return 'Esprit Venture Challenge - Public Prize';
    };
});

app.directive('loginModal', function() {
    return {
        scope: {
            loginModal: '@',
            loginText: '@',
        },
        template: [
            '
',
              '
',
                '
',
                  '
',
                    '<button type="button" class="close" data-dismiss="modal">×</button>',
                    '
{{ loginText }}
',
                  '
',
                  '
',
                    ' using LinkedIn',
                  '
',
                '
',
              '
',
            '
',
        ].join(''),
    };
});

app.directive('navLinks', function(userState) {
    return {
        scope: {},
        template: [
            '
Sign up
',
            '
Log in
',
            '
Log out
',
        ].join(''),
        controller: function($scope) {
            $scope.userState = userState;
        },
    };
});

app.directive('alertBox', function($rootScope) {
    return {
        scope: {},
        controller: function($scope) {
            $rootScope.$on('pp.alert', function(alert, message) {
                $scope.message = message;
            });
        },
        template: [
            '
',
              '
',
                '
',
                  '<button type="button" class="close" data-dismiss="alert">×</button>',
	          '{{ message }}',
	        '
',
              '
',
            '
',
        ].join(''),
    };
});

function formFieldTemplate(includeHelp) {
    return [
        '
',
          '{{ home.getError(f.name) }}',
          '

',
            (includeHelp ? '
' : ''),
              '

',
              '<textarea data-ng-switch-when="TextAreaField" class="form-control" data-ng-class="{slideDown: f.visible}" rows="5" placeholder="{{ f.label }}" data-ng-model="home.formData[f.name]"></textarea>',
              '<input data-ng-switch-default class="form-control" type="text" value="" data-ng-class="{slideDown: f.visible}" placeholder="{{ f.label }}" data-ng-model="home.formData[f.name]">',
              (includeHelp ? '' : ''),
            (includeHelp ? '
' : ''),
          '
',
        '
',
    ].join('');
}

//TODO(pjm): really ugly, combine formField with formFieldWithHelp
app.directive('formField', function() {
    return {
        scope: {
            f: '=formField',
            home: '=controller',
        },
        template: formFieldTemplate(false),
    };
});

app.directive('formFieldWithHelp', function() {
    return {
        scope: {
            f: '=formFieldWithHelp',
            home: '=controller',
        },
        template: formFieldTemplate(true),
    };
});

app.animation('.slideDown', function() {
    return {
        addClass: function(element, className, done) {
            if (className == 'slideDown') {
                $(element).hide();
                $(element).slideDown(done);
            }
        },
    }
});
<|endoftext|>


<commit_before>'use strict'
var ButtonNavigator = require('./ButtonNavigator')
var Slider = require('./Slider')
var EventManager = require('../lib/eventManager')
var yo = require('yo-yo')
var utils = require('../helpers/util.js')

function StepManager (_parent, _traceManager) {
  this.event = new EventManager()
  this.parent = _parent
  this.traceManager = _traceManager
  this.sourceMapByAddress = {}
  this.solidityMode = false

  var self = this
  this.parent.event.register('newTraceLoaded', this, function () {
    self.traceManager.getLength(function (error, length) {
      if (error) {
        console.log(error)
      } else {
        self.slider.init(length)
        self.init()
      }
    })
  })

  this.slider = new Slider(this.traceManager, (step) => {
    return this.solidityMode ? this.resolveToReducedTrace(step, 0) : step
  })
  this.slider.event.register('moved', this, function (step) {
    self.sliderMoved(step)
  })

  this.parent.callTree.event.register('callTreeReady', () => {
    this.solidityMode = true
    this.parent.vmDebugger.asmCode.event.register('hide', () => {
      this.solidityMode = this.parent.callTree.reducedTrace.length !== 0
    })
    this.parent.vmDebugger.asmCode.event.register('show', () => {
      this.solidityMode = false
    })
  })

  this.buttonNavigator = new ButtonNavigator(_parent, this.traceManager)
  this.buttonNavigator.event.register('stepIntoBack', this, function () {
    self.stepIntoBack()
  })
  this.buttonNavigator.event.register('stepIntoForward', this, function () {
    self.stepIntoForward()
  })
  this.buttonNavigator.event.register('stepOverBack', this, function () {
    self.stepOverBack()
  })
  this.buttonNavigator.event.register('stepOverForward', this, function () {
    self.stepOverForward()
  })
  this.buttonNavigator.event.register('jumpOut', this, function () {
    self.jumpOut()
  })
  this.buttonNavigator.event.register('jumpToException', this, function (exceptionIndex) {
    self.jumpTo(exceptionIndex)
  })
  this.buttonNavigator.event.register('play', (exceptionIndex) => {
    if (self.parent.breakpointManager) {
      self.parent.breakpointManager.play()
    }
  })
}

StepManager.prototype.resolveToReducedTrace = function (value, incr) {
  if (this.parent.callTree.reducedTrace.length) {
    var nextSource = utils.findClosestIndex(value, this.parent.callTree.reducedTrace)
    nextSource = nextSource + incr
    if (nextSource <= 0) {
      nextSource = 0
    } else if (nextSource > this.parent.callTree.reducedTrace.length) {
      nextSource = this.parent.callTree.reducedTrace.length - 1
    }
    return this.parent.callTree.reducedTrace[nextSource]
  }
  return value
}

StepManager.prototype.render = function () {
  return (
  yo`

        ${this.slider.render()}
        ${this.buttonNavigator.render()}

`
  )
}

StepManager.prototype.reset = function () {
  this.slider.setValue(0)
  this.currentStepIndex = 0
  this.buttonNavigator.reset()
}

StepManager.prototype.init = function () {
  this.slider.setValue(0)
  this.changeState(0)
}

StepManager.prototype.newTraceAvailable = function () {
  this.init()
}

StepManager.prototype.jumpTo = function (step) {
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.sliderMoved = function (step) {
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.changeState(step)
}

StepManager.prototype.stepIntoForward = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.currentStepIndex
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, 1)
  } else {
    step += 1
  }
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.stepIntoBack = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.currentStepIndex
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, -1)
  } else {
    step -= 1
  }
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.stepOverForward = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.traceManager.findStepOverForward(this.currentStepIndex)
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, 1)
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.stepOverBack = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.traceManager.findStepOverBack(this.currentStepIndex)
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, -1)
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.jumpOut = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.traceManager.findStepOut(this.currentStepIndex)
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, 0)
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.changeState = function (step) {
  this.currentStepIndex = step
  this.buttonNavigator.stepChanged(step)
  this.event.trigger('stepChanged', [step])
}

module.exports = StepManager
<commit_msg>play until the end even if no breakpoint<commit_after>'use strict'
var ButtonNavigator = require('./ButtonNavigator')
var Slider = require('./Slider')
var EventManager = require('../lib/eventManager')
var yo = require('yo-yo')
var utils = require('../helpers/util.js')

function StepManager (_parent, _traceManager) {
  this.event = new EventManager()
  this.parent = _parent
  this.traceManager = _traceManager
  this.sourceMapByAddress = {}
  this.solidityMode = false

  var self = this
  this.parent.event.register('newTraceLoaded', this, function () {
    self.traceManager.getLength(function (error, length) {
      if (error) {
        console.log(error)
      } else {
        self.slider.init(length)
        self.init()
      }
    })
  })

  this.slider = new Slider(this.traceManager, (step) => {
    return this.solidityMode ? this.resolveToReducedTrace(step, 0) : step
  })
  this.slider.event.register('moved', this, function (step) {
    self.sliderMoved(step)
  })

  this.parent.callTree.event.register('callTreeReady', () => {
    this.solidityMode = true
    this.parent.vmDebugger.asmCode.event.register('hide', () => {
      this.solidityMode = this.parent.callTree.reducedTrace.length !== 0
    })
    this.parent.vmDebugger.asmCode.event.register('show', () => {
      this.solidityMode = false
    })
  })

  this.buttonNavigator = new ButtonNavigator(_parent, this.traceManager)
  this.buttonNavigator.event.register('stepIntoBack', this, function () {
    self.stepIntoBack()
  })
  this.buttonNavigator.event.register('stepIntoForward', this, function () {
    self.stepIntoForward()
  })
  this.buttonNavigator.event.register('stepOverBack', this, function () {
    self.stepOverBack()
  })
  this.buttonNavigator.event.register('stepOverForward', this, function () {
    self.stepOverForward()
  })
  this.buttonNavigator.event.register('jumpOut', this, function () {
    self.jumpOut()
  })
  this.buttonNavigator.event.register('jumpToException', this, function (exceptionIndex) {
    self.jumpTo(exceptionIndex)
  })
  this.buttonNavigator.event.register('play', (exceptionIndex) => {
    self.parent.breakpointManager.play()
  })
}

StepManager.prototype.resolveToReducedTrace = function (value, incr) {
  if (this.parent.callTree.reducedTrace.length) {
    var nextSource = utils.findClosestIndex(value, this.parent.callTree.reducedTrace)
    nextSource = nextSource + incr
    if (nextSource <= 0) {
      nextSource = 0
    } else if (nextSource > this.parent.callTree.reducedTrace.length) {
      nextSource = this.parent.callTree.reducedTrace.length - 1
    }
    return this.parent.callTree.reducedTrace[nextSource]
  }
  return value
}

StepManager.prototype.render = function () {
  return (
  yo`

        ${this.slider.render()}
        ${this.buttonNavigator.render()}

`
  )
}

StepManager.prototype.reset = function () {
  this.slider.setValue(0)
  this.currentStepIndex = 0
  this.buttonNavigator.reset()
}

StepManager.prototype.init = function () {
  this.slider.setValue(0)
  this.changeState(0)
}

StepManager.prototype.newTraceAvailable = function () {
  this.init()
}

StepManager.prototype.jumpTo = function (step) {
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.sliderMoved = function (step) {
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.changeState(step)
}

StepManager.prototype.stepIntoForward = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.currentStepIndex
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, 1)
  } else {
    step += 1
  }
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.stepIntoBack = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.currentStepIndex
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, -1)
  } else {
    step -= 1
  }
  if (!this.traceManager.inRange(step)) {
    return
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.stepOverForward = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.traceManager.findStepOverForward(this.currentStepIndex)
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, 1)
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.stepOverBack = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.traceManager.findStepOverBack(this.currentStepIndex)
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, -1)
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.jumpOut = function () {
  if (!this.traceManager.isLoaded()) {
    return
  }
  var step = this.traceManager.findStepOut(this.currentStepIndex)
  if (this.solidityMode) {
    step = this.resolveToReducedTrace(step, 0)
  }
  this.slider.setValue(step)
  this.changeState(step)
}

StepManager.prototype.changeState = function (step) {
  this.currentStepIndex = step
  this.buttonNavigator.stepChanged(step)
  this.event.trigger('stepChanged', [step])
}

module.exports = StepManager
<|endoftext|>


<commit_before>import React from 'react'

// import { ICON_CMD } from '@config'
import { Wrapper, Copyrights, Thanks, ThxTitle } from './styles/bottom_info'
import { toggleBusBanner } from './logic'

const BottomInfo = () => (
  <Wrapper>
    <Copyrights>©2018 All Rights Reserved</Copyrights>
    <Thanks onClick={toggleBusBanner}>
      <ThxTitle>特别鸣谢： (求赞助)</ThxTitle>
    </Thanks>
  </Wrapper>
)

export default BottomInfo
<commit_msg>chore(footer): update copyright year, closes #459<commit_after>import React from 'react'

// import { ICON_CMD } from '@config'
import { Wrapper, Copyrights, Thanks, ThxTitle } from './styles/bottom_info'
import { toggleBusBanner } from './logic'

const BottomInfo = () => (
  <Wrapper>
    <Copyrights>©2019 All Rights Reserved</Copyrights>
    <Thanks onClick={toggleBusBanner}>
      <ThxTitle>特别鸣谢： (求赞助)</ThxTitle>
    </Thanks>
  </Wrapper>
)

export default BottomInfo
<|endoftext|>


<commit_before>$(function() {

    var events = {
        FEATURE_RECEIVED: 'FEATURE_RECEIVED',
        PLAY: 'PLAY',
        NEXT: 'NEXT',
        PREVIOUS: 'PREVIOUS'
    };

    function MessageBus() {

        this.publish = function(event, data) {
            $(document).trigger(event, data);
        }

        this.subscribe = function(event, func) {
            $(document).on(event, func);
        }

        this.unsubscribe = function(events) {
            $(document).off(events.join(' '));
        }

    }

    function PngImage(url, root) {
        $('<img>').attr('src', url).appendTo(root);
    }

    function BasicAudio(url, root, bus) {
        var
            self = this,
            audio = $('<audio>').attr('controls', true);
        $('<source>').attr('src', url).appendTo(audio);
        audio.appendTo(root);

        this.isPlaying = function() {
            var el = audio[0];
            return el.duration > 0 && !el.paused;
        }

        bus.subscribe(events.PLAY, function(event, data) {
            if(self.isPlaying()) {
                audio[0].pause();
            }else {
                audio[0].play();
            }
        });

        this.destroy = function() {
            bus.unsubscribe([events.PLAY]);
        }
    }

    function AudioSlice(data, root, context, client) {
        var self = this;

        var
            slice = {
                start: data.slice.start,
                stop: data.slice.start + data.slice.duration
            },
            audio = client.fetchAudio(data.audio, slice, context),
            vis = client.fetchBinary(data.visualization, slice),
            aggregate = Promise.all([audio, vis]);

        this.play = function() {
            var source = context.createBufferSource();
            source.buffer = self.audio;
            source.connect(context.destination);
            source.start(0);
        }

        function arrayBufferToBase64(buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            var len = bytes.byteLength;
            for (var i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }

        aggregate.then(function(results) {
            var
                audio = results[0],
                image = results[1];

            self.audio = audio;
            $('<img>')
                .attr('src', 'data:image/png;base64,' + arrayBufferToBase64(image))
                .appendTo(root)
                .click(function() {
                    self.play();
                });
        });
    }

    function SearchResults(data, root, context, client, bus) {
        var
            position = 0,
            container = $('<div>'),
            el = $('<div>'),
            self = this;

        this.render = function() {
            container.empty();
            self.slice = new AudioSlice(data[position], container, context, client, bus);
        }

        this.next = function() {
            position += 1;
            if(position >= data.length){
                position = 0;
            }
            self.render();
        }

        this.previous = function() {
            position -= 1;
            if(position < 0) {
                position = data.length - 1;
            }
            self.render();
        }

        el.append(container);
        root.append(el);
        self.render();

        bus.subscribe(events.PLAY, function(event, data) {
            self.slice.play();
        });

        bus.subscribe(events.PREVIOUS, function(event, data) {
            self.previous();
        });

        bus.subscribe(events.NEXT, function(event, data) {
            self.next();
        });

        this.destroy = function() {
            bus.unsubscribe([events.PLAY, events.PREVIOUS, events.NEXT]);
        }
    }

    function Visualization(selector, bus, context, client) {
        var
            self = this,
            el = $(selector);

        bus.subscribe(events.FEATURE_RECEIVED, function(event, data) {

            el.empty();
            if(self.view && self.view.destroy) {
                self.view.destroy();
            }

            if(data.contentType === 'image/png') {
                self.view = new PngImage(data.url, el);
                return;
            }

            if(data.contentType === 'audio/ogg') {
                self.view = new BasicAudio(data.url, el, bus);
                return;
            }

            if(data.contentType == 'application/vnd.zounds.searchresults+json'
                || data.contentType == 'application/vnd.zounds.onsets+json') {
                $.ajax({
                    method: 'GET',
                    url: data.url,
                    dataType: 'json'
                }).done(function(resp) {
                    console.log(resp);
                    self.view = new SearchResults(resp.results, el, context, client, bus);
                });
            }
        });

        el.keydown(function(e) {
            if(e.which === 32) {
                bus.publish(events.PLAY);
            } else if(e.which === 37) {
                bus.publish(events.PREVIOUS);
            } else if(e.which === 39) {
                bus.publish(events.NEXT);
            }
        });

    }

    function ZoundsClient() {

        var etags = {};

        this.interpret = function(command) {
            return $.ajax({
                method: 'POST',
                url: '/zounds/repl',
                data: command,
                dataType: 'json',
                contentType: 'text/plain'
            });
        };

        this.fetchBinary = function(url, range) {
            return new Promise(function(resolve, reject) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                if(range) {
                    xhr.setRequestHeader('Range', 'seconds=' + range.start.toString() + '-' + range.stop.toString());
                }
                xhr.responseType = 'arraybuffer';
                xhr.onload = function() {
                    if(this.status >= 200 && this.status < 300) {
                        resolve(xhr.response);
                    } else {
                        reject(this.status, xhr.statusText);
                    }
                };
                xhr.onerror = function() {
                    reject(this.status, xhr.statusText);
                };
                xhr.send();
            });
        };

        this.fetchAudio = function(url, range, context) {
            return this
                .fetchBinary(url, range)
                .then(function(data) {
                    return new Promise(function(resolve, reject) {
                        context.decodeAudioData(data, function(buffer) {
                            resolve(buffer);
                        });
                    });
                });
        }
    }

    function History() {

        var
            history = [],
            hash = {};

        this.push = function(item) {
            if(!item || item === '') { return; }
            if(item in hash) { return; }
            history.push(item);
            hash[item] = true;
        }

        this.fetch = function(index) {
            var value = history[history.length - index];
            return value;
        }

        this.count = function() {
            return history.length;
        }
    }

    function Console(inputSelector, outputSelector, messageBus, client) {
        var
            input = $(inputSelector),
            output = $(outputSelector),
            history = new History(),
            history_pos = 0;

        function fetch() {
            value = history.fetch(history_pos);
            input.val(value);
            if(!value) { return; }
            setTimeout(function() {
                input.get(0).setSelectionRange(value.length, value.length);
            }, 0);
        }

        $(document).keydown(function(e) {
            if(e.which === 38 && history_pos < history.count()) {
                history_pos += 1;
                fetch();
                return;
            }

            if(e.which === 40 && history_pos > 0) {
                history_pos -= 1;
                fetch();
                return;
            }
        });

        input.keypress(function(e) {
            var command = $(this).val();

            if(e.which === 13) {
                client
                    .interpret(command)
                    .always(function(data) {
                        history.push(command);
                        history_pos = 0;
                        output.append($('<div>').addClass('statement').text(command));
                    })
                    .done(function(data) {
                        if(data.url && data.contentType) {
                            messageBus.publish(events.FEATURE_RECEIVED, data);
                        }
                        output.append($('<div>').addClass('result').text(data.result));
                        window.scrollTo(0,document.body.scrollHeight);
                    })
                    .fail(function(data) {
                        output.append($('<div>').addClass('error').text(data.responseJSON.error));
                        window.scrollTo(0 ,document.body.scrollHeight);
                    });
                $(this).val('');
            }
        });
    }

    var client = new ZoundsClient();
    var audioContext = new AudioContext();
    var bus = new MessageBus();
    var input = new Console('#input', '#output', bus, client);
    var vis = new Visualization('#visualization', bus, audioContext, client);
});<commit_msg>Simplify event handler setup<commit_after>$(function() {

    var events = {
        FEATURE_RECEIVED: 'FEATURE_RECEIVED',
        PLAY: 'PLAY',
        NEXT: 'NEXT',
        PREVIOUS: 'PREVIOUS'
    };

    function MessageBus() {

        this.publish = function(event, data) {
            $(document).trigger(event, data);
        }

        this.subscribe = function(event, func) {
            $(document).on(event, func);
        }

        this.unsubscribe = function(events) {
            $(document).off(events.join(' '));
        }

    }

    function PngImage(url, root) {
        $('<img>').attr('src', url).appendTo(root);
    }

    function BasicAudio(url, root, bus) {
        var
            self = this,
            audio = $('<audio>').attr('controls', true);
        $('<source>').attr('src', url).appendTo(audio);
        audio.appendTo(root);

        this.isPlaying = function() {
            var el = audio[0];
            return el.duration > 0 && !el.paused;
        }

        bus.subscribe(events.PLAY, function(event, data) {
            if(self.isPlaying()) {
                audio[0].pause();
            } else {
                audio[0].play();
            }
        });

        this.destroy = function() {
            bus.unsubscribe([events.PLAY]);
        }
    }

    function AudioSlice(data, root, context, client) {
        var self = this;

        var
            slice = {
                start: data.slice.start,
                stop: data.slice.start + data.slice.duration
            },
            audio = client.fetchAudio(data.audio, slice, context),
            vis = client.fetchBinary(data.visualization, slice),
            aggregate = Promise.all([audio, vis]);

        this.play = function() {
            var source = context.createBufferSource();
            source.buffer = self.audio;
            source.connect(context.destination);
            source.start(0);
        }

        function arrayBufferToBase64(buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            var len = bytes.byteLength;
            for (var i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }

        aggregate.then(function(results) {
            var
                audio = results[0],
                image = results[1];

            self.audio = audio;
            $('<img>')
                .attr('src', 'data:image/png;base64,' + arrayBufferToBase64(image))
                .appendTo(root)
                .click(function() {
                    self.play();
                });
        });
    }

    function SearchResults(data, root, context, client, bus) {
        var
            position = 0,
            container = $('<div>'),
            el = $('<div>'),
            self = this;

        this.render = function() {
            container.empty();
            self.slice = new AudioSlice(data[position], container, context, client, bus);
        }

        this.next = function() {
            position += 1;
            if(position >= data.length){
                position = 0;
            }
            self.render();
        }

        this.previous = function() {
            position -= 1;
            if(position < 0) {
                position = data.length - 1;
            }
            self.render();
        }

        this.play = function() {
            self.slice.play();
        }

        el.append(container);
        root.append(el);
        self.render();

        bus.subscribe(events.PLAY, self.play);

        bus.subscribe(events.PREVIOUS, self.previous);

        bus.subscribe(events.NEXT, self.next);

        this.destroy = function() {
            bus.unsubscribe([events.PLAY, events.PREVIOUS, events.NEXT]);
        }
    }

    function Visualization(selector, bus, context, client) {
        var
            self = this,
            el = $(selector);

        bus.subscribe(events.FEATURE_RECEIVED, function(event, data) {

            el.empty();
            if(self.view && self.view.destroy) {
                self.view.destroy();
            }

            if(data.contentType === 'image/png') {
                self.view = new PngImage(data.url, el);
                return;
            }

            if(data.contentType === 'audio/ogg') {
                self.view = new BasicAudio(data.url, el, bus);
                return;
            }

            if(data.contentType == 'application/vnd.zounds.searchresults+json'
                || data.contentType == 'application/vnd.zounds.onsets+json') {
                $.ajax({
                    method: 'GET',
                    url: data.url,
                    dataType: 'json'
                }).done(function(resp) {
                    console.log(resp);
                    self.view = new SearchResults(resp.results, el, context, client, bus);
                });
            }
        });

        el.keydown(function(e) {
            if(e.which === 32) {
                bus.publish(events.PLAY);
            } else if(e.which === 37) {
                bus.publish(events.PREVIOUS);
            } else if(e.which === 39) {
                bus.publish(events.NEXT);
            }
        });

    }

    function ZoundsClient() {

        var etags = {};

        this.interpret = function(command) {
            return $.ajax({
                method: 'POST',
                url: '/zounds/repl',
                data: command,
                dataType: 'json',
                contentType: 'text/plain'
            });
        };

        this.fetchBinary = function(url, range) {
            return new Promise(function(resolve, reject) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url);
                if(range) {
                    xhr.setRequestHeader('Range', 'seconds=' + range.start.toString() + '-' + range.stop.toString());
                }
                xhr.responseType = 'arraybuffer';
                xhr.onload = function() {
                    if(this.status >= 200 && this.status < 300) {
                        resolve(xhr.response);
                    } else {
                        reject(this.status, xhr.statusText);
                    }
                };
                xhr.onerror = function() {
                    reject(this.status, xhr.statusText);
                };
                xhr.send();
            });
        };

        this.fetchAudio = function(url, range, context) {
            return this
                .fetchBinary(url, range)
                .then(function(data) {
                    return new Promise(function(resolve, reject) {
                        context.decodeAudioData(data, function(buffer) {
                            resolve(buffer);
                        });
                    });
                });
        }
    }

    function History() {

        var
            history = [],
            hash = {};

        this.push = function(item) {
            if(!item || item === '') { return; }
            if(item in hash) { return; }
            history.push(item);
            hash[item] = true;
        }

        this.fetch = function(index) {
            var value = history[history.length - index];
            return value;
        }

        this.count = function() {
            return history.length;
        }
    }

    function Console(inputSelector, outputSelector, messageBus, client) {
        var
            input = $(inputSelector),
            output = $(outputSelector),
            history = new History(),
            history_pos = 0;

        function fetch() {
            value = history.fetch(history_pos);
            input.val(value);
            if(!value) { return; }
            setTimeout(function() {
                input.get(0).setSelectionRange(value.length, value.length);
            }, 0);
        }

        $(document).keydown(function(e) {
            if(e.which === 38 && history_pos < history.count()) {
                history_pos += 1;
                fetch();
                return;
            }

            if(e.which === 40 && history_pos > 0) {
                history_pos -= 1;
                fetch();
                return;
            }
        });

        input.keypress(function(e) {
            var command = $(this).val();

            if(e.which === 13) {
                client
                    .interpret(command)
                    .always(function(data) {
                        history.push(command);
                        history_pos = 0;
                        output.append($('<div>').addClass('statement').text(command));
                    })
                    .done(function(data) {
                        if(data.url && data.contentType) {
                            messageBus.publish(events.FEATURE_RECEIVED, data);
                        }
                        output.append($('<div>').addClass('result').text(data.result));
                        window.scrollTo(0,document.body.scrollHeight);
                    })
                    .fail(function(data) {
                        output.append($('<div>').addClass('error').text(data.responseJSON.error));
                        window.scrollTo(0 ,document.body.scrollHeight);
                    });
                $(this).val('');
            }
        });
    }

    var client = new ZoundsClient();
    var audioContext = new AudioContext();
    var bus = new MessageBus();
    var input = new Console('#input', '#output', bus, client);
    var vis = new Visualization('#visualization', bus, audioContext, client);
});<|endoftext|>


<commit_before>
function threejsPlot( id, data, config ) {

  if ( !( 'ambientLight' in config ) ) config.ambientLight = 'rgb(127,127,127)';
  if ( !( 'aspectRatio' in config ) ) config.aspectRatio = [1,1,1];
  if ( !( 'axes' in config ) ) config.axes = false;
  if ( !( 'axesLabels' in config ) ) config.axesLabels = ['x','y','z'];
  if ( !( 'clearColor' in config ) ) config.clearColor = 'white';
  if ( !( 'decimals' in config ) ) config.decimals = 2;
  if ( !( 'frame' in config ) ) config.frame = true;
  if ( !( 'viewpoint' in config ) ) config.viewpoint = 'auto';

  var output = document.getElementById( id + 'output' );

  if ( !config.frame ) config.axesLabels = false;

  if ( output.children.length > 0 && output.children[0].contentWindow ) {

    var cw = output.children[0].contentWindow;
    var v = cw.camera.position;

    // only direction of viewpoint meaningful, not normalization
    config.viewpoint = [ v.x - cw.xMid, v.y - cw.yMid, v.z - cw.zMid ];

  }

  var texts = [], points = [], lines = [], surfaces = [];

  for ( var i = 0 ; i < data.length ; i++ )
    for ( var j = 0 ; j < data[i].length ; j++ ) {
      var d = data[i][j];
      if ( d.type === 'text' ) texts.push( d );
      if ( d.type === 'point' ) points.push( d );
      if ( d.type === 'line' ) lines.push( d );
      if ( d.type === 'surface' ) {
        d.vertices = roundTo( d.vertices, 3, false ); // reduce raw data size
        if ( 'colors' in d.options ) d.options.colors = roundTo( d.options.colors, 3 );
        surfaces.push( d );
      }
    }

  var all = [];
  for ( var i = 0 ; i < texts.length ; i++ ) all.push( texts[i].point );
  for ( var i = 0 ; i < points.length ; i++ ) all.push( points[i].point );
  for ( var i = 0 ; i < lines.length ; i++ ) lines[i].points.forEach( p => all.push( p ) );
  for ( var i = 0 ; i < surfaces.length ; i++ ) surfaces[i].vertices.forEach( p => all.push( p ) );

  var xMinMax = minMax( all, 0 );
  var yMinMax = minMax( all, 1 );
  var zMinMax = minMax( all, 2 );

  if ( !( 'xMin' in config ) ) config.xMin = xMinMax.min;
  if ( !( 'yMin' in config ) ) config.yMin = yMinMax.min;
  if ( !( 'zMin' in config ) ) config.zMin = zMinMax.min;

  if ( !( 'xMax' in config ) ) config.xMax = xMinMax.max;
  if ( !( 'yMax' in config ) ) config.yMax = yMinMax.max;
  if ( !( 'zMax' in config ) ) config.zMax = zMinMax.max;

  config = JSON.stringify( config );

  var lights = JSON.stringify( [ { position: [-5,3,0], color: 'rgb(127,127,127)', parent: 'camera' } ] );

  texts = JSON.stringify( texts );
  points = JSON.stringify( points );
  lines = JSON.stringify( lines );
  surfaces = JSON.stringify( surfaces );

  var html = template( config, lights, texts, points, lines, surfaces );

  return ``;

}

<commit_msg>Code cleanup<commit_after>
function threejsPlot( id, data, config ) {

  if ( !( 'ambientLight' in config ) ) config.ambientLight = 'rgb(127,127,127)';
  if ( !( 'aspectRatio' in config ) ) config.aspectRatio = [1,1,1];
  if ( !( 'axes' in config ) ) config.axes = false;
  if ( !( 'axesLabels' in config ) ) config.axesLabels = ['x','y','z'];
  if ( !( 'clearColor' in config ) ) config.clearColor = 'white';
  if ( !( 'decimals' in config ) ) config.decimals = 2;
  if ( !( 'frame' in config ) ) config.frame = true;
  if ( !( 'viewpoint' in config ) ) config.viewpoint = 'auto';

  if ( !config.frame ) config.axesLabels = false;

  var output = document.getElementById( id + 'output' );

  if ( output.children.length > 0 && output.children[0].contentWindow ) {

    var cw = output.children[0].contentWindow;
    var v = cw.camera.position;

    // only direction of viewpoint meaningful, not normalization
    config.viewpoint = [ v.x - cw.xMid, v.y - cw.yMid, v.z - cw.zMid ];

  }

  var texts = [], points = [], lines = [], surfaces = [];

  for ( var i = 0 ; i < data.length ; i++ )
    for ( var j = 0 ; j < data[i].length ; j++ ) {
      var d = data[i][j];
      if ( d.type === 'text' ) texts.push( d );
      if ( d.type === 'point' ) points.push( d );
      if ( d.type === 'line' ) lines.push( d );
      if ( d.type === 'surface' ) {
        d.vertices = roundTo( d.vertices, 3, false ); // reduce raw data size
        if ( 'colors' in d.options ) d.options.colors = roundTo( d.options.colors, 3 );
        surfaces.push( d );
      }
    }

  var all = [];
  for ( var i = 0 ; i < texts.length ; i++ ) all.push( texts[i].point );
  for ( var i = 0 ; i < points.length ; i++ ) all.push( points[i].point );
  for ( var i = 0 ; i < lines.length ; i++ ) lines[i].points.forEach( p => all.push( p ) );
  for ( var i = 0 ; i < surfaces.length ; i++ ) surfaces[i].vertices.forEach( p => all.push( p ) );

  var xMinMax = minMax( all, 0 );
  var yMinMax = minMax( all, 1 );
  var zMinMax = minMax( all, 2 );

  if ( !( 'xMin' in config ) ) config.xMin = xMinMax.min;
  if ( !( 'yMin' in config ) ) config.yMin = yMinMax.min;
  if ( !( 'zMin' in config ) ) config.zMin = zMinMax.min;

  if ( !( 'xMax' in config ) ) config.xMax = xMinMax.max;
  if ( !( 'yMax' in config ) ) config.yMax = yMinMax.max;
  if ( !( 'zMax' in config ) ) config.zMax = zMinMax.max;

  config = JSON.stringify( config );

  var lights = JSON.stringify( [ { position: [-5,3,0], color: 'rgb(127,127,127)', parent: 'camera' } ] );

  texts = JSON.stringify( texts );
  points = JSON.stringify( points );
  lines = JSON.stringify( lines );
  surfaces = JSON.stringify( surfaces );

  var html = template( config, lights, texts, points, lines, surfaces );

  return ``;

}

<|endoftext|>


<commit_before>
t = 1 + b

t ? '1' : 'b';

if (getValue)
   execute;
else {
   execute;
}

for (i = 0; i <= 5; i++)
{
	x += i;
}

for (var i = 0; i < n; i++) {
  this[i] = 1 + v;
}

var sumOfDivisors = new ExprArray(n+1,1);

for (var i = 0; i < j; i++) {
    if (i > 0)
        consts += ", ";
    var t = tokens[i];
}

for (var i = 0, j = tokens.length; i < j; i++) {
    if (i > 0)
        consts += ", ";
    var t = tokens[i];
}

for (i = 0; ; i++)
{
	x += i;
}

for( x in bob)
{

}

if (typeof s != "string")
            return;

 while (--n >= 0)
            s += t;

var a, f, i, j, r, s, t, u, v;

(x.stmtStack.length > 1)
? STATEMENT_FORM
: DECLARED_FORM;

 n2 = new Node(t);
                if (tt == DEFAULT)
                    n.defaultIndex = n.cases.length;
                else
                    n2.caseLabel = Expression(t, x, COLON);
                break;

 n = new Node(t);
        t.mustMatch(LEFT_PAREN);
        n.discriminant = Expression(t, x);
        t.mustMatch(RIGHT_PAREN);
        n.cases = [];
        n.defaultIndex = -1;
        x.stmtStack.push(n);
        t.mustMatch(LEFT_CURLY);
        while ((tt = t.get()) != RIGHT_CURLY) {
            switch (tt) {
              case DEFAULT:
                if (n.defaultIndex >= 0)
                    throw t.newSyntaxError("More than one switch default");
                // FALL THROUGH
              case CASE:
                n2 = new Node(t);
                if (tt == DEFAULT)
                    n.defaultIndex = n.cases.length;
                else
                    n2.caseLabel = Expression(t, x, COLON);
                break;
              default:
                throw t.newSyntaxError("Invalid switch case");
            }
            t.mustMatch(COLON);
            n2.statements = new Node(t, BLOCK);
            while ((tt=t.peek()) != CASE && tt != DEFAULT && tt != RIGHT_CURLY)
                n2.statements.push(Statement(t, x));
            n.cases.push(n2);
        }
        x.stmtStack.pop();
        return n;

 do {
            try {
                execute(n.body, x);
            } catch (e if e == BREAK && x.target == n) {
                break;
            } catch (e if e == CONTINUE && x.target == n) {
                continue;
            }
        } while (getValue(execute(n.condition, x)));
        break;<commit_msg>Made this file parse with a stricter parser<commit_after>
t = 1 + b

t ? '1' : 'b';

if (getValue)
   execute;
else {
   execute;
}

for (i = 0; i <= 5; i++)
{
	x += i;
}

for (var i = 0; i < n; i++) {
  this[i] = 1 + v;
}

var sumOfDivisors = new ExprArray(n+1,1);

for (var i = 0; i < j; i++) {
    if (i > 0)
        consts += ", ";
    var t = tokens[i];
}

for (var i = 0, j = tokens.length; i < j; i++) {
    if (i > 0)
        consts += ", ";
    var t = tokens[i];
}

for (i = 0; ; i++)
{
	x += i;
}

for( x in bob)
{

}

function f() {
  if (typeof s != "string")
          return;

 while (--n >= 0)
            s += t;

var a, f, i, j, r, s, t, u, v;

(x.stmtStack.length > 1)
? STATEMENT_FORM
: DECLARED_FORM;

 n2 = new Node(t);
   while (1) {
                if (tt == DEFAULT)
                    n.defaultIndex = n.cases.length;
                else
                    n2.caseLabel = Expression(t, x, COLON);
                break;

 n = new Node(t);
        t.mustMatch(LEFT_PAREN);
        n.discriminant = Expression(t, x);
        t.mustMatch(RIGHT_PAREN);
        n.cases = [];
        n.defaultIndex = -1;
        x.stmtStack.push(n);
        t.mustMatch(LEFT_CURLY);
        while ((tt = t.get()) != RIGHT_CURLY) {
            switch (tt) {
              case DEFAULT:
                if (n.defaultIndex >= 0)
                    throw t.newSyntaxError("More than one switch default");
                // FALL THROUGH
              case CASE:
                n2 = new Node(t);
                if (tt == DEFAULT)
                    n.defaultIndex = n.cases.length;
                else
                    n2.caseLabel = Expression(t, x, COLON);
                break;
              default:
                throw t.newSyntaxError("Invalid switch case");
            }
            t.mustMatch(COLON);
            n2.statements = new Node(t, BLOCK);
            while ((tt=t.peek()) != CASE && tt != DEFAULT && tt != RIGHT_CURLY)
                n2.statements.push(Statement(t, x));
            n.cases.push(n2);
        }
        x.stmtStack.pop();
        return n;

 do {
            try {
                execute(n.body, x);
            } catch (e if e == BREAK && x.target == n) {
                break;
            } catch (e if e == CONTINUE && x.target == n) {
                continue;
            }
        } while (getValue(execute(n.condition, x)));
        break;
}
}
<|endoftext|>


<commit_before>import layout from '../../templates/components/nypr-account-forms/signup';
import Component from 'ember-component';
import get from 'ember-metal/get';
import set from 'ember-metal/set';
import { next } from 'ember-runloop';
import Changeset from 'ember-changeset';
import SignupValidations from 'nypr-account-settings/validations/nypr-accounts/signup';
import messages from 'nypr-account-settings/validations/nypr-accounts/custom-messages';
import lookupValidator from 'ember-changeset-validations';
import service from 'ember-service/inject';
import fetch from 'fetch';
import { rejectUnsuccessfulResponses } from 'nypr-account-settings/utils/fetch-utils';

export default Component.extend({
  layout,
  store: service(),
  flashMessages: service(),
  showSocialSignup: false,
  authApi: null,
  session: null,
  allowedKeys: ['email','emailConfirmation','givenName','familyName','typedPassword'],

  init() {
    this._super(...arguments);
    set(this, 'newUser', this.get('store').createRecord('user'));
    set(this, 'changeset', new Changeset(get(this, 'newUser'), lookupValidator(SignupValidations), SignupValidations));
    get(this, 'changeset').validate();
  },
  click() {
    get(this, 'flashMessages').clearMessages();
  },
  actions: {
    onSubmit() {
      return this.signUp();
    },
    onFailure(e) {
      if (e) {
        this.applyErrorToChangeset(e.errors, get(this, 'changeset'));
      }
    },
    signupWithFacebook() {
      get(this, 'session').authenticate('authenticator:torii', 'facebook-connect')
      .catch(() => this.onFacebookLoginFailure());
    }
  },
  onFacebookLoginFailure() {
    // because we clear flash messages when clicking this form,
    // wait a tick when we add one in an action that can
    // be triggered with a click
    next(() => {
      this.get('flashMessages').add({
        message: messages.socialAuthCancelled,
        type: 'warning',
        sticky: true,
      });
    });
  },
  signUp() {
    return get(this, 'newUser').save();
  },
  onEmailInput() {
    if (get(this, 'changeset.emailConfirmation')) {
      get(this, 'changeset').validate('emailConfirmation');
    }
  },
  applyErrorToChangeset(error, changeset) {
    if (error) {
      changeset.rollback(); // so errors don't stack up
      if (error.code === "AccountExists") {
        changeset.validate('email');
        changeset.pushErrors('email', `An account already exists for the email ${changeset.get('email')}.<br/> <a href="/login">Log in?</a> <a href="/forgot">Forgot password?</a>`);
      } else if (error.message === 'User is disabled') {
        changeset.pushErrors('email', messages.userDisabled);
      }
    }
  },
  resendConfirmationEmail(email) {
    let url = `${get(this, 'authAPI')}/v1/confirm/resend?email=${email}`;
    let method = 'GET';
    let mode = 'cors';
    return fetch(url, {method, mode})
    .then(rejectUnsuccessfulResponses);
  }
});
<commit_msg>Handle no email permission case on signup page too<commit_after>import layout from '../../templates/components/nypr-account-forms/signup';
import Component from 'ember-component';
import get from 'ember-metal/get';
import set from 'ember-metal/set';
import { next } from 'ember-runloop';
import Changeset from 'ember-changeset';
import SignupValidations from 'nypr-account-settings/validations/nypr-accounts/signup';
import messages from 'nypr-account-settings/validations/nypr-accounts/custom-messages';
import lookupValidator from 'ember-changeset-validations';
import service from 'ember-service/inject';
import fetch from 'fetch';
import { rejectUnsuccessfulResponses } from 'nypr-account-settings/utils/fetch-utils';

export default Component.extend({
  layout,
  store: service(),
  flashMessages: service(),
  showSocialSignup: false,
  authApi: null,
  session: null,
  allowedKeys: ['email','emailConfirmation','givenName','familyName','typedPassword'],

  init() {
    this._super(...arguments);
    set(this, 'newUser', this.get('store').createRecord('user'));
    set(this, 'changeset', new Changeset(get(this, 'newUser'), lookupValidator(SignupValidations), SignupValidations));
    get(this, 'changeset').validate();
  },
  click() {
    get(this, 'flashMessages').clearMessages();
  },
  actions: {
    onSubmit() {
      return this.signUp();
    },
    onFailure(e) {
      if (e) {
        this.applyErrorToChangeset(e.errors, get(this, 'changeset'));
      }
    },
    signupWithFacebook() {
      let authOptions = {};
      if (get(this, 'emailWasDeclined')) {
        authOptions = {authType: 'rerequest'};
        //reset emailWasDeclined on a new attempt
        set(this, 'emailWasDeclined', false);
      }
      get(this, 'session').authenticate('authenticator:torii', 'facebook-connect', authOptions)
      .catch((e) => {
        if (e && get(e, 'errors.code') === 'MissingAttributeException') {
          set(this, 'emailWasDeclined', true);
          return this.onFacebookLoginFailure(messages.socialAuthNoEmail);
        } else {
          return this.onFacebookLoginFailure(messages.socialAuthCancelled);
        }
      });
    }
  },
  onFacebookLoginFailure(message) {
    // because we clear flash messages when clicking this form,
    // wait a tick when we add one in an action that can
    // be triggered with a click
    next(() => {
      if (message) {
        this.get('flashMessages').add({
          message: message,
          type: 'warning',
          sticky: true,
        });
      }
    });
  },
  signUp() {
    return get(this, 'newUser').save();
  },
  onEmailInput() {
    if (get(this, 'changeset.emailConfirmation')) {
      get(this, 'changeset').validate('emailConfirmation');
    }
  },
  applyErrorToChangeset(error, changeset) {
    if (error) {
      changeset.rollback(); // so errors don't stack up
      if (error.code === "AccountExists") {
        changeset.validate('email');
        changeset.pushErrors('email', `An account already exists for the email ${changeset.get('email')}.<br/> <a href="/login">Log in?</a> <a href="/forgot">Forgot password?</a>`);
      } else if (error.message === 'User is disabled') {
        changeset.pushErrors('email', messages.userDisabled);
      }
    }
  },
  resendConfirmationEmail(email) {
    let url = `${get(this, 'authAPI')}/v1/confirm/resend?email=${email}`;
    let method = 'GET';
    let mode = 'cors';
    return fetch(url, {method, mode})
    .then(rejectUnsuccessfulResponses);
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import {shallow, mount} from 'enzyme';
import renderer from 'react-test-renderer';
import ReactComponent from '../../src/components/react-comp.js';
import HelloWorld from '../../src/components/react-element.js';

describe('the App module', () => {
  let element;
  let RC;
  beforeEach(() => {
    //document.body.innerHTML = '

';
    //element = document.getElementsByClassName('home')[0];
    //console.log(element);
    //console.log(new ReactComponent());
  });
  it('RC text should be "Hello World" ', () => {
    RC = shallow(<HelloWorld />);
    expect(RC.text()).toEqual("Hello World");
  });
  it('RC text should be "Hello World" ', () => {
    // document.body.innerHTML = '

';
    // element = document.getElementsByClassName('home')[0];
    RC = mount(<react-component divElement='

'/>);
    //let component = renderer.create(<ReactComponent />);
    //console.log(component.toJSON());

    console.log(RC.html());
    expect(RC.html()).toEqual("Hello World");
  });
});
<commit_msg>jest react and linter<commit_after>import React from 'react';
//import {shallow, mount} from 'enzyme';
import {shallow} from 'enzyme';
//import renderer from 'react-test-renderer';
//import ReactComponent from '../../src/components/react-comp.js';
import HelloWorld from '../../src/components/react-element.js';

describe('the App module', () => {
  //let element;
  let RC;
  beforeEach(() => {
    //document.body.innerHTML = '

';
    //element = document.getElementsByClassName('home')[0];
    //console.log(element);
    //console.log(new ReactComponent());
  });
  it('RC text should be "Hello World" ', () => {
    RC = shallow(<HelloWorld />);
    expect(RC.text()).toEqual('Hello World');
  });
  // it('RC text should be "Hello World" ', () => {
  //   // document.body.innerHTML = '

';
  //   // element = document.getElementsByClassName('home')[0];
  //   RC = mount(<react-component divElement='

'/>);
  //   //let component = renderer.create(<ReactComponent />);
  //   //console.log(component.toJSON());
  //
  //   console.log(RC.html());
  //   expect(RC.html()).toEqual('Hello World');
  // });
});
<|endoftext|>


<commit_before>function vaildMessage(receiver,message,botname,password,testMode){

  if(message === undefined){

    return {error:369};
  }

}

module.exports = {
  'vaildMessage':vaildMessage
};
<commit_msg>Will get config from nconf<commit_after>var nconf = require('nconf');
nconf.file('bots', __dirname + '/../config/bots.json')
     .file('receviers', __dirname + '/../config/receivers.json')
     .file('senders', __dirname + '/../config/senders.json');

function vaildMessage(receiver,message,botname,password,testMode){

  if(message === undefined){

    return {error:369};
  }
}

module.exports = {
  'vaildMessage':vaildMessage
};
<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import { getOwner } from '@ember/application';
import BaseMenu from './menu-base';
import Menu from '../menu';

export default BaseMenu.extend({
  time: service(),

  /**
   * Creates and opens the Connect Menu.
   */
  open(lastMenu) {
    this._super(lastMenu);

    this.set('menu', Menu.create(getOwner(this).ownerInjection(), { name: 'changeCameraHeightMenu' }));

    this.get('menu').addTitle('Change Camera');
    this.get('menu').addArrowButton('height_down', {x: 100, y: 182}, {x: 150, y: 242}, 'arrow_down', '#ffc338');
    this.get('menu').addArrowButton('height_up', {x: 366, y: 182}, {x: 416, y: 242}, 'arrow_up', '#ffc338');
    this.get('menu').addText(this.get('user').getPosition().y.toFixed(2), 'camera_height', 28, { x: 256, y: 202}, '#ffffff', 'center', false);
    this.get('menu').addTextButton('Back', 'back', {x: 100, y: 402}, 316, 50, 28, '#555555', '#ffffff', '#929292', true);

    let triggerController = this.get('user.primaryController');

    this.get('menu').interact = (action, position) => {
      let item = this.get('menu').getItem(position);
      if(item) {
        if(action === 'rightIntersect') {
          this.get('menu').setHover(item);
        }
        if(action === 'rightTriggerDown'){
          if(item.name === 'back') {
            this.back();
          } else {
            item.isActivated = true;
          }
        }
        if(action === 'rightTriggerUp'){
          item.isActivated = false;
        }
        if(action === 'rightTriggerPressed' && item.isActivated) {
          const triggerValue = triggerController.getTriggerValue();

          const moveDistance = triggerValue * this.get('time').getDeltaTime();

          if(item.name === 'height_down') {
            this.get('user').getPosition().y -= moveDistance;
            this.get('menu').updateText('camera_height', this.get('user').getPosition().y.toFixed(2));
          } else if(item.name === 'height_up') {
            this.get('user').getPosition().y += moveDistance;
            this.get('menu').updateText('camera_height', this.get('user').getPosition().y.toFixed(2));
          }
        }
      } else {
        this.get('menu').setHover(null);
        this.get('menu').deactivateItems();
      }
    };

    this.get('menu').createMesh();
    this.addToSecondaryController();
  }
});<commit_msg>Add reset option to camera height menu<commit_after>import { inject as service } from '@ember/service';
import { getOwner } from '@ember/application';
import BaseMenu from './menu-base';
import Menu from '../menu';

export default BaseMenu.extend({
  time: service(),

  /**
   * Creates and opens the Connect Menu.
   */
  open(lastMenu) {
    this._super(lastMenu);

    this.set('menu', Menu.create(getOwner(this).ownerInjection(), { name: 'changeCameraHeightMenu' }));

    this.get('menu').addTitle('Change Camera');
    this.get('menu').addArrowButton('height_down', {x: 100, y: 182}, {x: 150, y: 242}, 'arrow_down', '#ffc338');
    this.get('menu').addArrowButton('height_up', {x: 366, y: 182}, {x: 416, y: 242}, 'arrow_up', '#ffc338');
    this.get('menu').addText(this.get('user').getPosition().y.toFixed(2), 'camera_height', 28, { x: 256, y: 202}, '#ffffff', 'center', false);
    this.get('menu').addTextButton('Back', 'back', { x: 100, y: 402 }, 316, 50, 28, '#555555', '#ffffff', '#929292', true);

    this.get('menu').addTextButton('Reset', 'reset_camera', { x: 420, y: 13 }, 65, 40, 22, '#aaaaaa', '#ffffff', '#dc3b00', true);

    let triggerController = this.get('user.primaryController');

    this.get('menu').interact = (action, position) => {
      let item = this.get('menu').getItem(position);
      if(item) {
        if(action === 'rightIntersect') {
          this.get('menu').setHover(item);
        }
        if(action === 'rightTriggerDown'){
          if(item.name === 'back') {
            this.back();
          } else if (item.name === 'reset_camera') {
            this.get('user').getPosition().y = 0;
            this.get('menu').updateText('camera_height', this.get('user').getPosition().y.toFixed(2));
          } else {
            item.isActivated = true;
          }
        }
        if(action === 'rightTriggerUp'){
          item.isActivated = false;
        }
        if(action === 'rightTriggerPressed' && item.isActivated) {
          const triggerValue = triggerController.getTriggerValue();

          const moveDistance = triggerValue * this.get('time').getDeltaTime();

          if(item.name === 'height_down') {
            this.get('user').getPosition().y -= moveDistance;
            this.get('menu').updateText('camera_height', this.get('user').getPosition().y.toFixed(2));
          } else if(item.name === 'height_up') {
            this.get('user').getPosition().y += moveDistance;
            this.get('menu').updateText('camera_height', this.get('user').getPosition().y.toFixed(2));
          }
        }
      } else {
        this.get('menu').setHover(null);
        this.get('menu').deactivateItems();
      }
    };

    this.get('menu').createMesh();
    this.addToSecondaryController();
  }
});
<|endoftext|>