<commit_before>define('app/controllers/backends', [
    'app/models/backend',
    'app/models/rule',
    'ember'
    ],
    /**
     * Backends controller
     *
     * @returns Class
     */
    function(Backend, Rule) {
        return Ember.ArrayController.extend({
            content: [],
            machineCount: 0,
            imageCount: 0,
            // TODO make this property dynamic according to all backends states
            state: "waiting",
            ok: false,

            isOK: function() {
                if(this.state == 'state-ok'){
                    this.set('ok', true);
                } else {
                    this.set('ok', false);
                }
            }.observes('state'),

            getBackendById: function(backendId){
                for (var i = 0; i < this.content.length; i++){
                    if (this.content[i].id == backendId) {
                        return this.content[i];
                    }
                }
            },

            getMachineById: function(backendId, machineId){
                for (var i = 0; i < this.content.length; i++){
                    if (this.content[i].id == backendId) {
                        for (var j=0; j < this.content[i].machines.content.length; j++){
                            if (this.content[i].machines.content[j].id == machineId){
                                return this.content[i].machines.content[j];
                            }
                        }
                    }
                }
            },

            getMachineCount: function(){
                var count = 0;
                this.content.forEach(function(item){
                    count = count + item.machines.content.length;
                });
                this.set('machineCount', count);
            },

            getSelectedMachineCount: function() {
                var count = 0;
                this.content.forEach(function(item){
                    count = count + item.machines.filterProperty('selected', true).get('length');
                });
                this.set('selectedMachineCount', count);
            },

            getImageCount: function() {
                var count = 0;
                this.content.forEach(function(item){
                    count = count + item.images.get('length');
                });
                this.set('imageCount', count);
            },

            getSelectedMachine: function() {
            	if(this.selectedMachineCount == 1){
                        var machine = null;
                        this.content.forEach(function(item){
                            var machines = item.machines.filterProperty('selected', true);
                            if(machines.get('length') == 1){
                    	    machine = machines[0];
                            }
                        });
                        this.set('selectedMachine', machine);
            	} else {
            	    this.set('selectedMachine', null);
            	}
            },

            checkMonitoring: function(){
                if (!Mist.authenticated){
                    return
                }

                var that = this;

                $.ajax({
                    url: '/monitoring',
                    type: 'GET',
                    dataType: 'json',
                    headers: { "cache-control": "no-cache" },
                    success: function(data){
                        warn(data);
                        machines = data.machines;
                        Mist.set('auth_key', data.auth_key);
                        Mist.set('monitored_machines', data.machines);
                        Mist.set('plan', 'Basic');
                        Mist.set('expired', True);
                        Mist.set('machine_limit', 5);
                        //now loop on backend_id, machine_id  list of lists and check if pair found
                        machines.forEach(function(machine_tuple){
                            var b,m;
                            backend_id = machine_tuple[0];
                            machine_id = machine_tuple[1];

                            for (b=0; b < Mist.backendsController.content.length; b++) {
                                if (Mist.backendsController.content[b]['id'] == backend_id)
                                    break;
                            }

                            if (b != Mist.backendsController.content.length) {
                                for (m=0; m < Mist.backendsController.content[b].machines.content.length; m++){
                                    if (Mist.backendsController.content[b]['machines'].content[m]['id'] == machine_id){
                                        Mist.backendsController.content[b].machines.content[m].set('hasMonitoring', true);
                                        break;
                                    }
                                }
                            }
                        });

                        rules = data.rules;

                        for (ruleId in rules){
                            var isInController = false;
                            for (r=0; r < Mist.rulesController.content.length; r++) {
                                if (Mist.rulesController.content[r]['id'] == ruleId) {
                                    isInController = true;
                                    break;
                                }
                            }
                            if (!(isInController)) {
                                var rule = {};
                                rule['id'] = ruleId;
                                rule['machine'] = that.getMachineById(rules[ruleId]['backend'], rules[ruleId]['machine']);
                                rule['metric'] = rules[ruleId]['metric'];
                                rule['operator'] = Mist.rulesController.getOperatorByTitle(rules[ruleId]['operator']);
                                rule['value'] = rules[ruleId]['value'];
                                rule['actionToTake'] = rules[ruleId]['action'];
                                rule['command'] = rules[ruleId]['command'];
                                rule['maxValue'] = rules[ruleId]['max_value'];
                                if (rule['maxValue'] > 100) {
                                    rule['unit'] = 'KB/s';
                                } else if (rule['metric'] == 'cpu' || rule['metric'] == 'ram') {
                                        rule['unit'] = '%';
                                } else {
                                        rule['unit'] = '';
                                }

                                Mist.rulesController.pushObject(Rule.create(rule));
                            }
                        }
                        Mist.rulesController.redrawRules();
                    },
                    error: function(){
                        Mist.notificationController.notify('Error checking monitoring');
                    }
                });

            },

            init: function() {
                this._super();

                var that = this;

                that.addObserver('length', function() {
                    that.getMachineCount();
                    that.getSelectedMachineCount();
                    that.getImageCount();
                });

                $(document).bind('ready', function(){
                    Ember.run.next(function(){
                        $.getJSON('/backends', function(data) {
                            data.forEach(function(item){
                                that.pushObject(Backend.create(item));
                            });
                            that.content.forEach(function(item){
                                item.machines.addObserver('length', function() {
                                    that.getMachineCount();
                                });

                                item.machines.addObserver('@each.selected', function() {
                                    that.getSelectedMachineCount();
                                    that.getSelectedMachine();
                                });

                                item.images.addObserver('length', function() {
                                    that.getImageCount();
                                });

                                item.addObserver('state', function(){
                                    var waiting = false;
                                    var state = "ok";

                                    that.content.forEach(function(backend){
                                        if (backend.error) {
                                            state = 'error';
                                        } else if(backend.state == 'waiting'){
                                            waiting = true;
                                        } else if(backend.state == 'offline'){
                                            state = 'down';
                                        }
                                    });

                                    if(waiting){
                                        state = 'state-wait-' + state;
                                    } else {
                                        state = 'state-' + state;
                                    }
                                    that.set('state', state);
                                });
                            });
                        }).error(function() {
                            Mist.notificationController.notify("Error loading backends");
                        });

                        setTimeout(function(){

                            Mist.backendsController.checkMonitoring();
                        }, 5000);
                    });
                });
            }
        });
    }
);
<commit_msg>fix typo<commit_after>define('app/controllers/backends', [
    'app/models/backend',
    'app/models/rule',
    'ember'
    ],
    /**
     * Backends controller
     *
     * @returns Class
     */
    function(Backend, Rule) {
        return Ember.ArrayController.extend({
            content: [],
            machineCount: 0,
            imageCount: 0,
            // TODO make this property dynamic according to all backends states
            state: "waiting",
            ok: false,

            isOK: function() {
                if(this.state == 'state-ok'){
                    this.set('ok', true);
                } else {
                    this.set('ok', false);
                }
            }.observes('state'),

            getBackendById: function(backendId){
                for (var i = 0; i < this.content.length; i++){
                    if (this.content[i].id == backendId) {
                        return this.content[i];
                    }
                }
            },

            getMachineById: function(backendId, machineId){
                for (var i = 0; i < this.content.length; i++){
                    if (this.content[i].id == backendId) {
                        for (var j=0; j < this.content[i].machines.content.length; j++){
                            if (this.content[i].machines.content[j].id == machineId){
                                return this.content[i].machines.content[j];
                            }
                        }
                    }
                }
            },

            getMachineCount: function(){
                var count = 0;
                this.content.forEach(function(item){
                    count = count + item.machines.content.length;
                });
                this.set('machineCount', count);
            },

            getSelectedMachineCount: function() {
                var count = 0;
                this.content.forEach(function(item){
                    count = count + item.machines.filterProperty('selected', true).get('length');
                });
                this.set('selectedMachineCount', count);
            },

            getImageCount: function() {
                var count = 0;
                this.content.forEach(function(item){
                    count = count + item.images.get('length');
                });
                this.set('imageCount', count);
            },

            getSelectedMachine: function() {
            	if(this.selectedMachineCount == 1){
                        var machine = null;
                        this.content.forEach(function(item){
                            var machines = item.machines.filterProperty('selected', true);
                            if(machines.get('length') == 1){
                    	    machine = machines[0];
                            }
                        });
                        this.set('selectedMachine', machine);
            	} else {
            	    this.set('selectedMachine', null);
            	}
            },

            checkMonitoring: function(){
                if (!Mist.authenticated){
                    return
                }

                var that = this;

                $.ajax({
                    url: '/monitoring',
                    type: 'GET',
                    dataType: 'json',
                    headers: { "cache-control": "no-cache" },
                    success: function(data){
                        warn(data);
                        machines = data.machines;
                        Mist.set('auth_key', data.auth_key);
                        Mist.set('monitored_machines', data.machines);
                        Mist.set('plan', 'Basic');
                        Mist.set('expired', false);
                        Mist.set('machine_limit', 5);
                        //now loop on backend_id, machine_id  list of lists and check if pair found
                        machines.forEach(function(machine_tuple){
                            var b,m;
                            backend_id = machine_tuple[0];
                            machine_id = machine_tuple[1];

                            for (b=0; b < Mist.backendsController.content.length; b++) {
                                if (Mist.backendsController.content[b]['id'] == backend_id)
                                    break;
                            }

                            if (b != Mist.backendsController.content.length) {
                                for (m=0; m < Mist.backendsController.content[b].machines.content.length; m++){
                                    if (Mist.backendsController.content[b]['machines'].content[m]['id'] == machine_id){
                                        Mist.backendsController.content[b].machines.content[m].set('hasMonitoring', true);
                                        break;
                                    }
                                }
                            }
                        });

                        rules = data.rules;

                        for (ruleId in rules){
                            var isInController = false;
                            for (r=0; r < Mist.rulesController.content.length; r++) {
                                if (Mist.rulesController.content[r]['id'] == ruleId) {
                                    isInController = true;
                                    break;
                                }
                            }
                            if (!(isInController)) {
                                var rule = {};
                                rule['id'] = ruleId;
                                rule['machine'] = that.getMachineById(rules[ruleId]['backend'], rules[ruleId]['machine']);
                                rule['metric'] = rules[ruleId]['metric'];
                                rule['operator'] = Mist.rulesController.getOperatorByTitle(rules[ruleId]['operator']);
                                rule['value'] = rules[ruleId]['value'];
                                rule['actionToTake'] = rules[ruleId]['action'];
                                rule['command'] = rules[ruleId]['command'];
                                rule['maxValue'] = rules[ruleId]['max_value'];
                                if (rule['maxValue'] > 100) {
                                    rule['unit'] = 'KB/s';
                                } else if (rule['metric'] == 'cpu' || rule['metric'] == 'ram') {
                                        rule['unit'] = '%';
                                } else {
                                        rule['unit'] = '';
                                }

                                Mist.rulesController.pushObject(Rule.create(rule));
                            }
                        }
                        Mist.rulesController.redrawRules();
                    },
                    error: function(){
                        Mist.notificationController.notify('Error checking monitoring');
                    }
                });

            },

            init: function() {
                this._super();

                var that = this;

                that.addObserver('length', function() {
                    that.getMachineCount();
                    that.getSelectedMachineCount();
                    that.getImageCount();
                });

                $(document).bind('ready', function(){
                    Ember.run.next(function(){
                        $.getJSON('/backends', function(data) {
                            data.forEach(function(item){
                                that.pushObject(Backend.create(item));
                            });
                            that.content.forEach(function(item){
                                item.machines.addObserver('length', function() {
                                    that.getMachineCount();
                                });

                                item.machines.addObserver('@each.selected', function() {
                                    that.getSelectedMachineCount();
                                    that.getSelectedMachine();
                                });

                                item.images.addObserver('length', function() {
                                    that.getImageCount();
                                });

                                item.addObserver('state', function(){
                                    var waiting = false;
                                    var state = "ok";

                                    that.content.forEach(function(backend){
                                        if (backend.error) {
                                            state = 'error';
                                        } else if(backend.state == 'waiting'){
                                            waiting = true;
                                        } else if(backend.state == 'offline'){
                                            state = 'down';
                                        }
                                    });

                                    if(waiting){
                                        state = 'state-wait-' + state;
                                    } else {
                                        state = 'state-' + state;
                                    }
                                    that.set('state', state);
                                });
                            });
                        }).error(function() {
                            Mist.notificationController.notify("Error loading backends");
                        });

                        setTimeout(function(){

                            Mist.backendsController.checkMonitoring();
                        }, 5000);
                    });
                });
            }
        });
    }
);
<|endoftext|>


<commit_before>var servers = ['chkno.net', 'localhost'];

var session = Math.random();
var seen = {};

function rcserverbase(server) {
	// Add the default port if server doesn't contain a port number already
	if (server.indexOf(":") == -1) {
		return "http://" + server + ":21059";
	} else {
		return "http://" + server;
	}
}

function rcchangeserverstatus(server, new_status) {
	var statusbar = document.getElementById("status");
	var spans = statusbar.getElementsByTagName("span");
	for (i in spans) {
		if (spans[i].firstChild && 'data' in spans[i].firstChild && spans[i].firstChild.data == server) {
			spans[i].setAttribute("class", new_status);
		}
	}
}

function rcaddmessagetohistory(message) {
	var d = document.createElement("div");
	d.appendChild(document.createTextNode(message));
	var h = document.getElementById("history");
	h.appendChild(d);
	window.scrollTo(0, document.body.scrollHeight);
	return d;
}

function make_seen_key(id, text) {
	return id.replace(/@/g, "@@") + "_@_" + text.replace(/@/g, "@@");
}

function receiveMessage(server, time, id, text) {
	var seen_key = make_seen_key(id, text);
	if (!(seen_key in seen)) {
		seen[seen_key] = true;
		rcaddmessagetohistory(text);
		for (i in servers) {
			rcchangeserverstatus(servers[i], "sad");
		}
	}
	rcchangeserverstatus(server, "happy");
}

function receiveMessageEvent(event)
{
	for (i in servers) {
		if (event.origin === rcserverbase(servers[i])) {
			messages = JSON.parse(event.data);
			for (j in messages) {
				if ('Time' in messages[j] &&
				    'ID'   in messages[j] &&
				    'Text' in messages[j]) {
					receiveMessage(servers[i], messages[j]['Time'], messages[j]['ID'], messages[j]['Text']);
				}
			}
		}
	}
}

function rcconnect() {
	window.addEventListener("message", receiveMessageEvent, false);
	for (i in servers) {
		// Create a hidden iframe for same-origin workaround
		var iframe = document.createElement("iframe");
		iframe.setAttribute("src", rcserverbase(servers[i]) + "/frame");
		document.body.insertBefore(iframe, document.body.firstChild);
		// Status bar entry
		var status_indicator = document.createElement("span");
		status_indicator.appendChild(document.createTextNode(servers[i]));
		status_indicator.setAttribute("class", "sad");
		document.getElementById("status").appendChild(status_indicator);
	}
}

function rcsend(d, message) {
	var id = new Date().getTime() + "-" + session + "-" + Math.random();
	seen[make_seen_key(id, message)] = true;
	var path = "/speak" +
		"?id=" + encodeURIComponent(id) +
		"&text=" + encodeURIComponent(message);
	for (i in servers) {
		var uri = rcserverbase(servers[i]) + path;
		var img = document.createElement("img");
		img.setAttribute("src", uri);
		d.appendChild(img);
	}
}

function rckeydown(event) {
	if (event.keyCode == 13) {
		var d = rcaddmessagetohistory(document.input.say.value);
		rcsend(d, document.input.say.value);
		document.input.say.value = "";
		return false;
	}
}
<commit_msg>Actual server list<commit_after>var servers = ['chkno.net', 'rc2.chkno.net', 'echto.net', 'the-wes.com', 'vibrantlogic.com'];

var session = Math.random();
var seen = {};

function rcserverbase(server) {
	// Add the default port if server doesn't contain a port number already
	if (server.indexOf(":") == -1) {
		return "http://" + server + ":21059";
	} else {
		return "http://" + server;
	}
}

function rcchangeserverstatus(server, new_status) {
	var statusbar = document.getElementById("status");
	var spans = statusbar.getElementsByTagName("span");
	for (i in spans) {
		if (spans[i].firstChild && 'data' in spans[i].firstChild && spans[i].firstChild.data == server) {
			spans[i].setAttribute("class", new_status);
		}
	}
}

function rcaddmessagetohistory(message) {
	var d = document.createElement("div");
	d.appendChild(document.createTextNode(message));
	var h = document.getElementById("history");
	h.appendChild(d);
	window.scrollTo(0, document.body.scrollHeight);
	return d;
}

function make_seen_key(id, text) {
	return id.replace(/@/g, "@@") + "_@_" + text.replace(/@/g, "@@");
}

function receiveMessage(server, time, id, text) {
	var seen_key = make_seen_key(id, text);
	if (!(seen_key in seen)) {
		seen[seen_key] = true;
		rcaddmessagetohistory(text);
		for (i in servers) {
			rcchangeserverstatus(servers[i], "sad");
		}
	}
	rcchangeserverstatus(server, "happy");
}

function receiveMessageEvent(event)
{
	for (i in servers) {
		if (event.origin === rcserverbase(servers[i])) {
			messages = JSON.parse(event.data);
			for (j in messages) {
				if ('Time' in messages[j] &&
				    'ID'   in messages[j] &&
				    'Text' in messages[j]) {
					receiveMessage(servers[i], messages[j]['Time'], messages[j]['ID'], messages[j]['Text']);
				}
			}
		}
	}
}

function rcconnect() {
	window.addEventListener("message", receiveMessageEvent, false);
	for (i in servers) {
		// Create a hidden iframe for same-origin workaround
		var iframe = document.createElement("iframe");
		iframe.setAttribute("src", rcserverbase(servers[i]) + "/frame");
		document.body.insertBefore(iframe, document.body.firstChild);
		// Status bar entry
		var status_indicator = document.createElement("span");
		status_indicator.appendChild(document.createTextNode(servers[i]));
		status_indicator.setAttribute("class", "sad");
		document.getElementById("status").appendChild(status_indicator);
	}
}

function rcsend(d, message) {
	var id = new Date().getTime() + "-" + session + "-" + Math.random();
	seen[make_seen_key(id, message)] = true;
	var path = "/speak" +
		"?id=" + encodeURIComponent(id) +
		"&text=" + encodeURIComponent(message);
	for (i in servers) {
		var uri = rcserverbase(servers[i]) + path;
		var img = document.createElement("img");
		img.setAttribute("src", uri);
		d.appendChild(img);
	}
}

function rckeydown(event) {
	if (event.keyCode == 13) {
		var d = rcaddmessagetohistory(document.input.say.value);
		rcsend(d, document.input.say.value);
		document.input.say.value = "";
		return false;
	}
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
blnLocRunning = false;
blnInBackground = false;
strHost = "";
intCompNo = 0;
intSeqNo = 0;
strTechID = "";

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        //alert("In receivedEvent");
        console.log("In receivedEvent 01");
        fillvars();
        checkvalues(false);
        console.log('Received Event: ' + id);
    }
};

function onResume() {
    console.log("app resumed");
    blnInBackground = false;
    fillvars();
    checkvalues(false);
    return;
}

function onPause() {
    blnInBackground = true;
    return;
}

function alertDismissed() {
    return;
}

function fillvars() {
    if (localStorage.LocHost)
    {
        strHost = localStorage.LocHost;
        document.getElementById('txtHost').value = strHost;
    }
    if (localStorage.LocCompNo)
    {
        intval = parseInt(localStorage.LocCompNo, 10);
        intCompNo = 0;
        if (intval > 0 && intval < 1000)
        {
            intCompNo = intval;
        }
        if (intCompNo > 0)
        {
            document.getElementById('txtCompNo').value = intCompNo;
        }

    }
    if (localStorage.LocTechID)
    {
        strTechID = localStorage.LocTechID;
        document.getElementById('txtTechID').value = strTechID;
    }
}

function checkvalues(ShowError) {
    blnError = false;
    strError = "";
    lenHost = document.getElementById('txtHost').value.length;
    if (lenHost < 1)
    {
        strError += "Invalid Host or IP address\r\n";
        blnErrro = true;
    }
    intVal = parseInt(document.getElementById('txtCompNo').value, 10);
    if (isNaN(intVal))
    {
        intVal = 0;
    }
    if (intVal < 1 || intVal > 999)
    {
        strError += "Invalid Company number\r\n";
        blnError = true;
    }
    lenTechID = document.getElementById('txtTechID').value.length;
    if (lenTechID < 1)
    {
        strError += "Invalid TechID\r\n";
        blnError = true;
    }
    if (ShowError && blnError)
    {
        navigator.notification.alert(
            strError,
            alertDismissed,
            'Error in input fields',
            'OK'
        );
    }
    if (blnLocRunning)
    {
        document.getElementById('btnStart').disabled = true;
        document.getElementById('btnStop').disabled = false;
        document.getElementById('backstatus').innerHTML = "Broadcasting locations";
    } else {
        document.getElementById('btnStart').disabled = false;
        document.getElementById('btnStop').disabled = true;
        document.getElementById('backstatus').innerHTML = "Not broadcasting location";
    }
    return blnError;
}

function start() {
//    if (blnLocRunning)
//    {
//        return;
//    }
    /* If checkvalues returns true then errors were found */
    if (checkvalues(true))
    {
        return;
    }
    strHost = document.getElementById('txtHost').value;
    strCompNo = document.getElementById('txtCompNo').value;
    intCompNo = parseInt(strCompNo, 10);
    strTechID = document.getElementById('txtTechID').value;
    localStorage.setItem("LocHost", strHost);
    localStorage.setItem("LocCompNo", intCompNo);
    localStorage.setItem("LocTechID", strTechID);
    intSeqNo = 0;

    // Your app must execute AT LEAST ONE call for the current position via standard Cordova geolocation,
    //  in order to prompt the user for Location permission.
    window.navigator.geolocation.getCurrentPosition(function(location) {
        console.log('Location from Phonegap');
    });

    backgroundGeolocation = window.backgroundGeolocation || window.backgroundGeoLocation || window.universalGeolocation;

    /**
    * This callback will be executed every time a geolocation is recorded in the background.
    */
    var callbackFn = function(location,blnBackground) {
        var d = new Date();
        if (!blnBackground)
        {
            document.getElementById('backstatus').innerHTML = "Sending broadcasts" + " " + d.toLocaleString();
        }

        console.log('[js] backgroundGeolocation callback:  ' + location.latitude + ',' + location.longitude + " " + d.toLocaleString());
        sendupdate(location);
        // Do your HTTP request here to POST location to your server.
        // jQuery.post(url, JSON.stringify(location));

        /*
        IMPORTANT:  You must execute the finish method here to inform the native plugin that you're finished,
        and the background-task may be completed.  You must do this regardless if your HTTP request is successful or not.
        IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
        */
        backgroundGeolocation.finish();
    };

    function sendupdate(location) {
        xmlhttp = new XMLHttpRequest();
        if (!xmlhttp)
        {
            console.log("Could not transmit - no xmlhttp");
            return;
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                var xmlDoc = xmlhttp.responseText;
                console.log("Got post response: " + xmlDoc);
            }
        };

        var d = new Date();
        var strUpdTime = formatdate(d);
        var mph = Math.round(location.speed * 3600 / 1610.3*1000)/1000
        var locupdate = "request-cd=XLOC&comp-no=" + localStorage.LocCompNo +
                       "&tech-id=" + localStorage.LocTechID + "&longitude=" +
                       location.longitude + "&latitude=" + location.latitude +
                       "&accuracy=" + location.accuracy + "&speed=" +
                       mph + "&timestamp=" + strUpdTime +
                       "&resp-page=locupdresult.htm&error-page=" +
                       "locupderr.html";
        var url="https://" + localStorage.LocHost + "/cgi-bin/facshtml.cgi";
        console.log(url);
        console.log(locupdate);
        xmlhttp.open("POST",url,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.responseType = "text";
        xmlhttp.send(locupdate);
    }

    var failureFn = function(error) {
        console.log('BackgroundGeolocation error');
    };

    // BackgroundGeolocation is highly configurable. See platform specific configuration options
    backgroundGeolocation.configure(callbackFn, failureFn, {
        desiredAccuracy: 10,
        stationaryRadius: 20,
        distanceFilter: 5,
        pauseLocationUpdates: false,
        locationProvider: 0,
        interval: 1000
    });

    console.log("Start Tracking");
    // Turn ON the background-geolocation system.  The user will be tracked whenever they suspend the app.
    backgroundGeolocation.start();
    console.log("Tracking Started");

    blnLocRunning = true;

    checkvalues(false);
    // If you wish to turn OFF background-tracking, call the #stop method.
    // backgroundGeolocation.stop();

//    alert("Start Tracking");
}

function formatdate(dt) {
	strYear = dt.getFullYear().toString();
	var mth = dt.getMonth() + 1;
	var str = mth.toString();
	strMonth = pad(str, 2, '0', STR_PAD_LEFT);
	str = dt.getDate().toString();
	strDay = pad(str, 2, '0', STR_PAD_LEFT);
	var hrs = dt.getHours().toString();
	var mins = dt.getMinutes().toString();
	var strTime = pad(hrs, 2, '0', STR_PAD_LEFT) + ":" +
	              pad(mins,2, '0', STR_PAD_LEFT);
	return strYear + "-" + strMonth + "-" + strDay + " " + strTime;
}

/**
 *
 * Javascript string pad http://www.webtoolkit.info/
 *
 */

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {
	if (str == undefined) {
		return;
	}
	if (typeof (len) == "undefined") {
		var len = 0;
	}
	if (typeof (pad) == "undefined") {
		var pad = ' ';
	}
	if (typeof (dir) == "undefined") {
		var dir = STR_PAD_RIGHT;
	}

	if (len + 1 >= str.length) {

		switch (dir) {

		case STR_PAD_LEFT:
			str = Array(len + 1 - str.length).join(pad) + str;
			break;

		case STR_PAD_BOTH:
			var right = Math.ceil((padlen = len - str.length) / 2);
			var left = padlen - right;
			str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
			break;

		default:
			str = str + Array(len + 1 - str.length).join(pad);
			break;

		} // switch

	}

	return str;

}

function stop() {
    if (!blnLocRunning)
    {
        return;
    }
    backgroundGeolocation.stop();
    blnLocRunning = false;
    checkvalues(false);
}
<commit_msg>Turned on debug. Increased stationaryRadius from 20 to 100.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
blnLocRunning = false;
blnInBackground = false;
strHost = "";
intCompNo = 0;
intSeqNo = 0;
strTechID = "";

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        //alert("In receivedEvent");
        console.log("In receivedEvent 01");
        fillvars();
        checkvalues(false);
        console.log('Received Event: ' + id);
    }
};

function onResume() {
    console.log("app resumed");
    blnInBackground = false;
    fillvars();
    checkvalues(false);
    return;
}

function onPause() {
    blnInBackground = true;
    return;
}

function alertDismissed() {
    return;
}

function fillvars() {
    if (localStorage.LocHost)
    {
        strHost = localStorage.LocHost;
        document.getElementById('txtHost').value = strHost;
    }
    if (localStorage.LocCompNo)
    {
        intval = parseInt(localStorage.LocCompNo, 10);
        intCompNo = 0;
        if (intval > 0 && intval < 1000)
        {
            intCompNo = intval;
        }
        if (intCompNo > 0)
        {
            document.getElementById('txtCompNo').value = intCompNo;
        }

    }
    if (localStorage.LocTechID)
    {
        strTechID = localStorage.LocTechID;
        document.getElementById('txtTechID').value = strTechID;
    }
}

function checkvalues(ShowError) {
    blnError = false;
    strError = "";
    lenHost = document.getElementById('txtHost').value.length;
    if (lenHost < 1)
    {
        strError += "Invalid Host or IP address\r\n";
        blnErrro = true;
    }
    intVal = parseInt(document.getElementById('txtCompNo').value, 10);
    if (isNaN(intVal))
    {
        intVal = 0;
    }
    if (intVal < 1 || intVal > 999)
    {
        strError += "Invalid Company number\r\n";
        blnError = true;
    }
    lenTechID = document.getElementById('txtTechID').value.length;
    if (lenTechID < 1)
    {
        strError += "Invalid TechID\r\n";
        blnError = true;
    }
    if (ShowError && blnError)
    {
        navigator.notification.alert(
            strError,
            alertDismissed,
            'Error in input fields',
            'OK'
        );
    }
    if (blnLocRunning)
    {
        document.getElementById('btnStart').disabled = true;
        document.getElementById('btnStop').disabled = false;
        document.getElementById('backstatus').innerHTML = "Broadcasting locations";
    } else {
        document.getElementById('btnStart').disabled = false;
        document.getElementById('btnStop').disabled = true;
        document.getElementById('backstatus').innerHTML = "Not broadcasting location";
    }
    return blnError;
}

function start() {
//    if (blnLocRunning)
//    {
//        return;
//    }
    /* If checkvalues returns true then errors were found */
    if (checkvalues(true))
    {
        return;
    }
    strHost = document.getElementById('txtHost').value;
    strCompNo = document.getElementById('txtCompNo').value;
    intCompNo = parseInt(strCompNo, 10);
    strTechID = document.getElementById('txtTechID').value;
    localStorage.setItem("LocHost", strHost);
    localStorage.setItem("LocCompNo", intCompNo);
    localStorage.setItem("LocTechID", strTechID);
    intSeqNo = 0;

    // Your app must execute AT LEAST ONE call for the current position via standard Cordova geolocation,
    //  in order to prompt the user for Location permission.
    window.navigator.geolocation.getCurrentPosition(function(location) {
        console.log('Location from Phonegap');
    });

    backgroundGeolocation = window.backgroundGeolocation || window.backgroundGeoLocation || window.universalGeolocation;

    /**
    * This callback will be executed every time a geolocation is recorded in the background.
    */
    var callbackFn = function(location,blnBackground) {
        var d = new Date();
        if (!blnBackground)
        {
            document.getElementById('backstatus').innerHTML = "Sending broadcasts" + " " + d.toLocaleString();
        }

        console.log('[js] backgroundGeolocation callback:  ' + location.latitude + ',' + location.longitude + " " + d.toLocaleString());
        sendupdate(location);
        // Do your HTTP request here to POST location to your server.
        // jQuery.post(url, JSON.stringify(location));

        /*
        IMPORTANT:  You must execute the finish method here to inform the native plugin that you're finished,
        and the background-task may be completed.  You must do this regardless if your HTTP request is successful or not.
        IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
        */
        backgroundGeolocation.finish();
    };

    function sendupdate(location) {
        xmlhttp = new XMLHttpRequest();
        if (!xmlhttp)
        {
            console.log("Could not transmit - no xmlhttp");
            return;
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                var xmlDoc = xmlhttp.responseText;
                console.log("Got post response: " + xmlDoc);
            }
        };

        var d = new Date();
        var strUpdTime = formatdate(d);
        var mph = Math.round(location.speed * 3600 / 1610.3*1000)/1000
        var locupdate = "request-cd=XLOC&comp-no=" + localStorage.LocCompNo +
                       "&tech-id=" + localStorage.LocTechID + "&longitude=" +
                       location.longitude + "&latitude=" + location.latitude +
                       "&accuracy=" + location.accuracy + "&speed=" +
                       mph + "&timestamp=" + strUpdTime +
                       "&resp-page=locupdresult.htm&error-page=" +
                       "locupderr.html";
        var url="https://" + localStorage.LocHost + "/cgi-bin/facshtml.cgi";
        console.log(url);
        console.log(locupdate);
        xmlhttp.open("POST",url,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.responseType = "text";
        xmlhttp.send(locupdate);
    }

    var failureFn = function(error) {
        console.log('BackgroundGeolocation error');
    };

    // BackgroundGeolocation is highly configurable. See platform specific configuration options
    backgroundGeolocation.configure(callbackFn, failureFn, {
        desiredAccuracy: 10,
        stationaryRadius: 100,
        distanceFilter: 30,
        debug: true,
        pauseLocationUpdates: false,
        startOnBoot: true,
        startForeground: true,
        locationProvider: 0,
        interval: 1000
    });

    console.log("Start Tracking");
    // Turn ON the background-geolocation system.  The user will be tracked whenever they suspend the app.
    backgroundGeolocation.start();
    console.log("Tracking Started");

    blnLocRunning = true;

    checkvalues(false);
    // If you wish to turn OFF background-tracking, call the #stop method.
    // backgroundGeolocation.stop();

//    alert("Start Tracking");
}

function formatdate(dt) {
	strYear = dt.getFullYear().toString();
	var mth = dt.getMonth() + 1;
	var str = mth.toString();
	strMonth = pad(str, 2, '0', STR_PAD_LEFT);
	str = dt.getDate().toString();
	strDay = pad(str, 2, '0', STR_PAD_LEFT);
	var hrs = dt.getHours().toString();
	var mins = dt.getMinutes().toString();
	var strTime = pad(hrs, 2, '0', STR_PAD_LEFT) + ":" +
	              pad(mins,2, '0', STR_PAD_LEFT);
	return strYear + "-" + strMonth + "-" + strDay + " " + strTime;
}

/**
 *
 * Javascript string pad http://www.webtoolkit.info/
 *
 */

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {
	if (str == undefined) {
		return;
	}
	if (typeof (len) == "undefined") {
		var len = 0;
	}
	if (typeof (pad) == "undefined") {
		var pad = ' ';
	}
	if (typeof (dir) == "undefined") {
		var dir = STR_PAD_RIGHT;
	}

	if (len + 1 >= str.length) {

		switch (dir) {

		case STR_PAD_LEFT:
			str = Array(len + 1 - str.length).join(pad) + str;
			break;

		case STR_PAD_BOTH:
			var right = Math.ceil((padlen = len - str.length) / 2);
			var left = padlen - right;
			str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
			break;

		default:
			str = str + Array(len + 1 - str.length).join(pad);
			break;

		} // switch

	}

	return str;

}

function stop() {
    if (!blnLocRunning)
    {
        return;
    }
    backgroundGeolocation.stop();
    blnLocRunning = false;
    checkvalues(false);
}
<|endoftext|>


<commit_before>'use strict'

const db = require('APP/db')
const Product = db.model('products')

module.exports = require('express').Router()
    .get('/', function(req, res, next){
        Product.findAll()
        .then(products => res.json(products))
        .catch(next)
        })
    .get('/:id', function(req, res, next){
        Product.findById(req.params.id)
        .then(product => res.json(product))
        .catch(next)
        })<commit_msg>fixing branching error<commit_after><|endoftext|>


<commit_before>(function( window, document ) {
  var PI2 = 2 * Math.PI;

  var canvas = document.getElementById( 'canvas' );
  var context = canvas.getContext( '2d' );

  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  context.fillRect( 0, 0, canvas.width, canvas.height );

  var config = {
    player: {
      color: 'rgba(0, 255, 0, 1.0)',
      health: 100,
      speed: 15,
      frequency: 1000 / 10, // Number of ms to fire n bullets/second.
      hitFrequency: 1000 / 40 // Number of ms between player injuries.
    },
    zombie: {
      color: 'rgba(255, 0, 0, 1.0)',
      speed: 20,
      radiusSquared: 75 * 75,
      health: 10
    },
    civilian: {
      color: 'rgba(255, 255, 255, 1.0)',
      radiusSquared: 100 * 100,
      speed: 25
    },
    entity: {
      color: 'rgba(255, 0, 255, 1.0)'
    },
    bullet: {
      color: 'rgba(255, 255, 0, 1.0)'
    }
  };

  var keys = {};

  var zombies     = [],
      civilians   = [],
      projectiles = [],
      player;

  var prevTime = Date.now(),
      currTime,
      running = true;

  function tick() {
    if ( !running ) {
      return;
    }

    update();
    draw( context );
    window.requestAnimationFrame( tick );
  }

  function draw( ctx ) {
    ctx.fillStyle = 'black';
    ctx.fillRect( 0, 0, canvas.width, canvas.height );

    projectiles.forEach(function( projectile ) {
      projectile.draw( ctx );
    });

    ctx.beginPath();
    zombies.forEach(function( zombie ) {
      zombie.draw( ctx );
    });
    ctx.fillStyle = config.zombie.color;
    ctx.fill();

    ctx.beginPath();
    civilians.forEach(function( civilian ) {
      if ( !( civilian instanceof Player ) ) {
        civilian.draw( ctx );
      }
    });
    ctx.fillStyle = config.civilian.color;
    ctx.fill();

    player.draw( ctx );

    ctx.font = '14px Helvetica, Arial';
    ctx.fillStyle = 'white';
    ctx.fillText( player.health, 20, 20 );
  }

  function update() {
    currTime = Date.now();
    var dt = currTime - prevTime;
    prevTime = currTime;

    if ( dt > 1e2 ) {
      dt = 1e2;
    }

    dt *= 1e-3;

    projectiles.forEach(function( projectile ) {
      projectile.update( dt );
    });

    zombies.forEach(function( zombie ) {
      zombie.update( dt );
    });

    civilians.forEach(function( civilian ) {
      civilian.update( dt );
    });

    player.update( dt );
  }

  function distanceSquared( x0, y0, x1, y1 ) {
    var dx = x1 - x0,
        dy = y1 - y0;

    return dx * dx + dy * dy;
  }

  function distance( x0, y0, x1, y1 ) {
    return Math.sqrt( distanceSquared( x0, y0, x1, y1 ) );
  }

  /**
   * Returns the angle that a character at (x0, y0) would need to travel along
   * to reach (x1, y1);
   */
  function angleTo( x0, y0, x1, y1 ) {
    return Math.atan2( y1 - y0, x1 - x0 );
  }

  /**
   * Entity.
   */
  function Entity( x, y, width, height  ) {
    this.x = x || 0.0;
    this.y = y || 0.0;
    this.width = width || 0.0;
    this.height = height || 0.0;

    this.vx = 0.0;
    this.vy = 0.0;
  }

  Entity.prototype.update = function( dt ) {
    this.x += this.vx * dt;
    this.y += this.vy * dt;

    if ( 0 > this.x ) {
      this.x = 0;
      this.vx = -this.vx;
    }

    if ( this.x > canvas.width ) {
      this.x = canvas.width;
      this.vx = -this.vx;
    }

    if ( 0 > this.y ) {
      this.y = 0;
      this.vy = -this.vy;
    }

    if ( this.y > canvas.height ) {
      this.y = canvas.height;
      this.vy = -this.vy;
    }
  };

  Entity.prototype.draw = function( ctx ) {
    ctx.fillStyle = config.entity.color;
    ctx.fillRect( this.x - 0.5 * this.width, this.y - 0.5 * this.height, this.width, this.height );
  };

  /**
   * Bullet.
   */
  function Bullet( x, y, vx, vy ) {
    Entity.call( this, x, y, 1, 1 );
    this.vx = vx || 0.0;
    this.vy = vy || 0.0;
  }

  Bullet.prototype.draw = function( ctx ) {
    ctx.fillStyle = config.bullet.color;
    ctx.fillRect( this.x, this.y, this.width, this.height );
  };

  Bullet.prototype.update = function( dt ) {
    Entity.prototype.update.call( this, dt );

    var x = this.x,
        y = this.y;

    if ( x === 0 || x === canvas.width ||
         y === 0 || y === canvas.height ) {
      var index = projectiles.indexOf( this );
      if ( index !== -1 ) {
        projectiles.splice( index, 1 );
      }
    }

    var minDistanceSquared = Number.POSITIVE_INFINITY,
        currDistanceSquared,
        min;

    zombies.forEach(function( zombie ) {
      var currDistanceSquared = distanceSquared( x, y, zombie.x, zombie.y );
      if ( currDistanceSquared < minDistanceSquared ) {
        minDistanceSquared = currDistanceSquared;
        min = zombie;
      }
    });

    if ( min && minDistanceSquared < 4 ) {
      var index = zombies.indexOf( min );
      if ( index !== -1 ) {
        zombies.splice( index, 1 );

        index = projectiles.indexOf( this );
        if ( index !== -1 ) {
          projectiles.splice( index, 1 );
        }
      }
    }
  };

  /**
   * Character.
   */
  function Character( x, y ) {
    Entity.call( this, x, y, 2, 2 );
    this.speed = 0;
  }

  Character.prototype = new Entity();
  Character.prototype.constructor = Character;

  /**
   * Zombie.
   */
  function Zombie( x, y ) {
    Character.call( this, x, y );
    this.speed = ( Math.random() + 0.5 ) * config.zombie.speed;
  }

  Zombie.prototype = new Character();
  Zombie.prototype.constructor = Zombie;

  Zombie.prototype.draw = function( ctx ) {
    ctx.rect( this.x, this.y, this.width, this.height );
  };

  Zombie.prototype.update = function( dt ) {
    Character.prototype.update.call( this, dt );

    var x = this.x,
        y = this.y;

    var minDistanceSquared = Number.POSITIVE_INFINITY,
        currDistanceSquared,
        min;

    civilians.forEach(function( civilian ) {
      currDistanceSquared = distanceSquared( x, y, civilian.x, civilian.y );
      if ( currDistanceSquared < config.zombie.radiusSquared &&
           currDistanceSquared < minDistanceSquared ) {
        minDistanceSquared = currDistanceSquared;
        min = civilian;
      }
    });

    if ( minDistanceSquared < 1 ) {
      min.infect();
    } else {
      var angle;
      if ( min ) {
        angle = angleTo( x, y, min.x, min.y );
      } else {
        angle = Math.random() * PI2;
      }

      this.vx = Math.cos( angle ) * this.speed;
      this.vy = Math.sin( angle ) * this.speed;
    }
  };

  /**
   * Civilian.
   */
  function Civilian( x, y ) {
    Character.call( this, x, y );
    this.speed = ( Math.random() + 0.5 ) * config.civilian.speed;
  }

  Civilian.prototype = new Character();
  Civilian.prototype.constructor = Civilian;

  Civilian.prototype.draw = function( ctx ) {
    ctx.rect( this.x, this.y, this.width, this.height );
  };

  Civilian.prototype.update = function( dt ) {
    Character.prototype.update.call( this, dt );

    var x = this.x,
        y = this.y;

    var minDistanceSquared = Number.POSITIVE_INFINITY,
        currDistanceSquared,
        min;

    zombies.forEach(function( zombie ) {
      currDistanceSquared = distanceSquared( x, y, zombie.x, zombie.y );
      if ( currDistanceSquared < config.civilian.radiusSquared &&
           currDistanceSquared < minDistanceSquared ) {
        minDistanceSquared = currDistanceSquared;
        min = zombie;
      }
    });

    var angle;
    if ( min ) {
      angle = angleTo( x, y, min.x, min.y ) + Math.PI;
    } else {
      angle = Math.random() * PI2;
    }

    this.vx = Math.cos( angle ) * this.speed;
    this.vy = Math.sin( angle ) * this.speed;
  };

  Civilian.prototype.infect = function() {
    var index = civilians.indexOf( this );
    if ( index !== -1 ) {
      civilians.splice( index, 1 );
      zombies.push( new Zombie( this.x, this.y ) );
    }
  };

  /**
   * Player.
   */
  function Player( x, y ) {
    Character.call( this, x, y );
    this.canFire = true;

    this.health = config.player.health;
    this.living = true;
    this.injured = false;
  }

  Player.prototype = new Character();
  Player.prototype.constructor = Player;

  Player.prototype.draw = function( ctx ) {
    ctx.fillStyle = config.player.color;
    ctx.fillRect( this.x - 2, this.y - 2, this.width + 5, this.height + 5 );
  };

  Player.prototype.update = function( dt ) {
    var dx = 0,
        dy = 0;

    dx += keys[ 65 ] ? -1 : 0; // A.
    dx += keys[ 68 ] ?  1 : 0; // D.

    dy += keys[ 87 ] ? -1 : 0; // W.
    dy += keys[ 83 ] ?  1 : 0; // S.

    this.vx = dx * 30;
    this.vy = dy * 30;

    Character.prototype.update.call( this, dt );

    // Start shooting.
    var bx = 0,
        by = 0;

    bx += keys[ 37 ] ? -1 : 0; // Left.
    bx += keys[ 39 ] ?  1 : 0; // Right.

    by += keys[ 38 ] ? -1 : 0; // Top.
    by += keys[ 40 ] ?  1 : 0;  // Bottom.

    if ( !bx && !by || !this.canFire ) {
      return;
    }

    this.canFire = false;
    setTimeout(function() {
      this.canFire = true;
    }.bind( this ), config.player.frequency );

    bx *= 200;
    by *= 200;

    projectiles.push( new Bullet( this.x, this.y, bx, by ) );
  };

  Player.prototype.infect = function() {
    if ( !this.living ) {
      return;
    }

    if ( !this.injured ) {
      this.health--;
      this.injured = true;

      setTimeout(function() {
        this.injured = false;
      }.bind( this ), config.player.hitFrequency );
    }

    if ( !this.health ) {
      console.log( 'You\'re dead!' );
      this.living = false;
    }
  };

  function randomInt( min, max ) {
    return Math.round( min + Math.random() * ( max - min ) );
  }

  function init() {
    var width  = canvas.width,
        height = canvas.height;

    civilians.push( player = new Player( randomInt( 0, width ), randomInt( 0, height ) ) );
    var civilianCount = 500;
    var i;
    for ( i = 0; i < civilianCount; i++ ) {
      civilians.push( new Civilian( randomInt( 0, width ), randomInt( 0, height ) ) );
    }

    var zombieCount = 20;
    for ( i = 0; i < zombieCount; i++ ) {
      zombies.push( new Zombie( randomInt( 0, width ), randomInt( 0, height ) ) );
    }

    tick();
  }

  function onKeyDown( event ) {
    // console.log( event.which );
    keys[ event.which ] = true;
    // ESC.
    if ( event.which === 27 ) {
      running = false;
    }
  }

  function onKeyUp( event ) {
    // console.log( event.which );
    keys[ event.which ] = false;
  }

  document.addEventListener( 'keydown', onKeyDown );
  document.addEventListener( 'keyup', onKeyUp );

  init();
}) ( window, document );
<commit_msg>Add untested Quadtree implementation.<commit_after>(function( window, document ) {
  'use strict';

  var PI2 = 2 * Math.PI;

  var canvas = document.getElementById( 'canvas' );
  var context = canvas.getContext( '2d' );

  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  context.fillRect( 0, 0, canvas.width, canvas.height );

  var config = {
    player: {
      color: 'rgba(0, 255, 0, 1.0)',
      health: 100,
      speed: 15,
      frequency: 1000 / 10, // Number of ms to fire n bullets/second.
      hitFrequency: 1000 / 40 // Number of ms between player injuries.
    },
    zombie: {
      color: 'rgba(255, 0, 0, 1.0)',
      speed: 20,
      radiusSquared: 150 * 150,
      health: 10
    },
    civilian: {
      color: 'rgba(255, 255, 255, 1.0)',
      radiusSquared: 75 * 75,
      speed: 25
    },
    entity: {
      color: 'rgba(255, 0, 255, 1.0)'
    },
    bullet: {
      color: 'rgba(255, 255, 0, 1.0)'
    }
  };

  var keys = {};

  var zombies     = [],
      civilians   = [],
      projectiles = [],
      player;

  var prevTime = Date.now(),
      currTime,
      running = true;

  function tick() {
    if ( !running ) {
      return;
    }

    update();
    draw( context );
    window.requestAnimationFrame( tick );
  }

  function draw( ctx ) {
    ctx.fillStyle = 'black';
    ctx.fillRect( 0, 0, canvas.width, canvas.height );

    projectiles.forEach(function( projectile ) {
      projectile.draw( ctx );
    });

    ctx.beginPath();
    zombies.forEach(function( zombie ) {
      zombie.draw( ctx );
    });
    ctx.fillStyle = config.zombie.color;
    ctx.fill();

    ctx.beginPath();
    civilians.forEach(function( civilian ) {
      if ( !( civilian instanceof Player ) ) {
        civilian.draw( ctx );
      }
    });
    ctx.fillStyle = config.civilian.color;
    ctx.fill();

    player.draw( ctx );

    ctx.font = '14px Helvetica, Arial';
    ctx.fillStyle = 'white';
    ctx.fillText( player.health, 20, 20 );
  }

  function update() {
    currTime = Date.now();
    var dt = currTime - prevTime;
    prevTime = currTime;

    if ( dt > 1e2 ) {
      dt = 1e2;
    }

    dt *= 1e-3;

    projectiles.forEach(function( projectile ) {
      projectile.update( dt );
    });

    zombies.forEach(function( zombie ) {
      zombie.update( dt );
    });

    civilians.forEach(function( civilian ) {
      civilian.update( dt );
    });

    player.update( dt );
  }

  function distanceSquared( x0, y0, x1, y1 ) {
    var dx = x1 - x0,
        dy = y1 - y0;

    return dx * dx + dy * dy;
  }

  function distance( x0, y0, x1, y1 ) {
    return Math.sqrt( distanceSquared( x0, y0, x1, y1 ) );
  }

  /**
   * Returns the angle that a character at (x0, y0) would need to travel along
   * to reach (x1, y1);
   */
  function angleTo( x0, y0, x1, y1 ) {
    return Math.atan2( y1 - y0, x1 - x0 );
  }

  /**
   * Entity.
   */
  function Entity( x, y, width, height  ) {
    this.x = x || 0.0;
    this.y = y || 0.0;
    this.width = width || 0.0;
    this.height = height || 0.0;

    this.vx = 0.0;
    this.vy = 0.0;
  }

  Entity.prototype.update = function( dt ) {
    this.x += this.vx * dt;
    this.y += this.vy * dt;

    if ( 0 > this.x ) {
      this.x = 0;
      this.vx = -this.vx;
    }

    if ( this.x > canvas.width ) {
      this.x = canvas.width;
      this.vx = -this.vx;
    }

    if ( 0 > this.y ) {
      this.y = 0;
      this.vy = -this.vy;
    }

    if ( this.y > canvas.height ) {
      this.y = canvas.height;
      this.vy = -this.vy;
    }
  };

  Entity.prototype.draw = function( ctx ) {
    ctx.fillStyle = config.entity.color;
    ctx.fillRect( this.x - 0.5 * this.width, this.y - 0.5 * this.height, this.width, this.height );
  };

  /**
   * Bullet.
   */
  function Bullet( x, y, vx, vy ) {
    Entity.call( this, x, y, 1, 1 );
    this.vx = vx || 0.0;
    this.vy = vy || 0.0;
  }

  Bullet.prototype.draw = function( ctx ) {
    ctx.fillStyle = config.bullet.color;
    ctx.fillRect( this.x, this.y, this.width, this.height );
  };

  Bullet.prototype.update = function( dt ) {
    Entity.prototype.update.call( this, dt );

    var x = this.x,
        y = this.y;

    var index;
    if ( x === 0 || x === canvas.width ||
         y === 0 || y === canvas.height ) {
      index = projectiles.indexOf( this );
      if ( index !== -1 ) {
        projectiles.splice( index, 1 );
      }
    }

    var minDistanceSquared = Number.POSITIVE_INFINITY,
        currDistanceSquared,
        min;

    zombies.forEach(function( zombie ) {
      currDistanceSquared = distanceSquared( x, y, zombie.x, zombie.y );
      if ( currDistanceSquared < minDistanceSquared ) {
        minDistanceSquared = currDistanceSquared;
        min = zombie;
      }
    });

    if ( min && minDistanceSquared < 4 ) {
      index = zombies.indexOf( min );
      if ( index !== -1 ) {
        zombies.splice( index, 1 );

        index = projectiles.indexOf( this );
        if ( index !== -1 ) {
          projectiles.splice( index, 1 );
        }
      }
    }
  };

  /**
   * Character.
   */
  function Character( x, y ) {
    Entity.call( this, x, y, 2, 2 );
    this.speed = 0;
  }

  Character.prototype = new Entity();
  Character.prototype.constructor = Character;

  /**
   * Zombie.
   */
  function Zombie( x, y ) {
    Character.call( this, x, y );
    this.speed = ( Math.random() + 0.5 ) * config.zombie.speed;
  }

  Zombie.prototype = new Character();
  Zombie.prototype.constructor = Zombie;

  Zombie.prototype.draw = function( ctx ) {
    ctx.rect( this.x, this.y, this.width, this.height );
  };

  Zombie.prototype.update = function( dt ) {
    Character.prototype.update.call( this, dt );

    var x = this.x,
        y = this.y;

    var minDistanceSquared = Number.POSITIVE_INFINITY,
        currDistanceSquared,
        min;

    civilians.forEach(function( civilian ) {
      currDistanceSquared = distanceSquared( x, y, civilian.x, civilian.y );
      if ( currDistanceSquared < config.zombie.radiusSquared &&
           currDistanceSquared < minDistanceSquared ) {
        minDistanceSquared = currDistanceSquared;
        min = civilian;
      }
    });

    if ( minDistanceSquared < 1 ) {
      min.infect();
    } else {
      var angle;
      if ( min ) {
        angle = angleTo( x, y, min.x, min.y );
      } else {
        angle = Math.random() * PI2;
      }

      this.vx = Math.cos( angle ) * this.speed;
      this.vy = Math.sin( angle ) * this.speed;
    }
  };

  /**
   * Civilian.
   */
  function Civilian( x, y ) {
    Character.call( this, x, y );
    this.speed = ( Math.random() + 0.5 ) * config.civilian.speed;
  }

  Civilian.prototype = new Character();
  Civilian.prototype.constructor = Civilian;

  Civilian.prototype.draw = function( ctx ) {
    ctx.rect( this.x, this.y, this.width, this.height );
  };

  Civilian.prototype.update = function( dt ) {
    Character.prototype.update.call( this, dt );

    var x = this.x,
        y = this.y;

    var minDistanceSquared = Number.POSITIVE_INFINITY,
        currDistanceSquared,
        min;

    zombies.forEach(function( zombie ) {
      currDistanceSquared = distanceSquared( x, y, zombie.x, zombie.y );
      if ( currDistanceSquared < config.civilian.radiusSquared &&
           currDistanceSquared < minDistanceSquared ) {
        minDistanceSquared = currDistanceSquared;
        min = zombie;
      }
    });

    var angle;
    if ( min ) {
      angle = angleTo( x, y, min.x, min.y ) + Math.PI;
    } else {
      angle = Math.random() * PI2;
    }

    this.vx = Math.cos( angle ) * this.speed;
    this.vy = Math.sin( angle ) * this.speed;
  };

  Civilian.prototype.infect = function() {
    var index = civilians.indexOf( this );
    if ( index !== -1 ) {
      civilians.splice( index, 1 );
      zombies.push( new Zombie( this.x, this.y ) );
    }
  };

  /**
   * Player.
   */
  function Player( x, y ) {
    Character.call( this, x, y );
    this.canFire = true;

    this.health = config.player.health;
    this.living = true;
    this.injured = false;
  }

  Player.prototype = new Character();
  Player.prototype.constructor = Player;

  Player.prototype.draw = function( ctx ) {
    ctx.fillStyle = config.player.color;
    ctx.fillRect( this.x - 2, this.y - 2, this.width + 5, this.height + 5 );
  };

  Player.prototype.update = function( dt ) {
    var dx = 0,
        dy = 0;

    dx += keys[ 65 ] ? -1 : 0; // A.
    dx += keys[ 68 ] ?  1 : 0; // D.

    dy += keys[ 87 ] ? -1 : 0; // W.
    dy += keys[ 83 ] ?  1 : 0; // S.

    this.vx = dx * 30;
    this.vy = dy * 30;

    Character.prototype.update.call( this, dt );

    // Start shooting.
    var bx = 0,
        by = 0;

    bx += keys[ 37 ] ? -1 : 0; // Left.
    bx += keys[ 39 ] ?  1 : 0; // Right.

    by += keys[ 38 ] ? -1 : 0; // Top.
    by += keys[ 40 ] ?  1 : 0;  // Bottom.

    if ( !bx && !by || !this.canFire ) {
      return;
    }

    this.canFire = false;
    setTimeout(function() {
      this.canFire = true;
    }.bind( this ), config.player.frequency );

    bx *= 200;
    by *= 200;

    projectiles.push( new Bullet( this.x, this.y, bx, by ) );
  };

  Player.prototype.infect = function() {
    if ( !this.living ) {
      return;
    }

    if ( !this.injured ) {
      this.health--;
      this.injured = true;

      setTimeout(function() {
        this.injured = false;
      }.bind( this ), config.player.hitFrequency );
    }

    if ( !this.health ) {
      console.log( 'You\'re dead!' );
      this.living = false;
    }
  };

  /**
   * Quadtree.
   *
   * Taken from:
   * http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/
   */
  function Quadtree( depth, aabb ) {
    this.depth = depth || 0;

    this.objects = [];
    this.nodes = [];

    this.aabb = aabb || {
      x0: 0.0,
      y0: 0.0,
      x1: 0.0,
      y1: 0.0
    };
  }

  Quadtree.MAX_OBJECTS = 10;
  Quadtree.MAX_DEPTH = 5;

  Quadtree.prototype.clear = function() {
    this.objects = [];
    this.nodes = [];
  };

  Quadtree.prototype.split = function() {
    var x0 = this.aabb.x0,
        y0 = this.aabb.y0,
        x1 = this.aabb.x1,
        y1 = this.aabb.y1;

    var mx = x0 + 0.5 * ( x1 - x0 ),
        my = y0 + 0.5 * ( y1 - y0 );

    this.nodes[0] = new Quadtree( this.depth + 1, { x0: mx, y0: y0, x1: x1, y1: my } );
    this.nodes[1] = new Quadtree( this.depth + 1, { x0: x0, y0: y0, x1: mx, y1: my } );
    this.nodes[2] = new Quadtree( this.depth + 1, { x0: x0, y0: my, x1: mx, y1: y1 } );
    this.nodes[3] = new Quadtree( this.depth + 1, { x0: mx, y0: my, x1: x1, y1: y1 } );
  };

  Quadtree.prototype.indexOf = function( object ) {
    var index = -1;

    var mx = 0.5 * ( this.x0 + this.x1 ),
        my = 0.5 * ( this.y0 + this.y1 );

    var top = object.y < my;

    if ( object.x < mx ) {
      index = top ? 1 : 2;
    } else {
      index = top ? 0 : 3;
    }

    return index;
  };

  Quadtree.prototype.insert = function( object ) {
    var index;
    if ( this.nodes[0] ) {
      index = this.indexOf( object );
      if ( index !== -1 ) {
        this.nodes[ index ].insert( object );
        return;
      }
    }

    this.objects.push( object );

    if ( this.objects.size() > Quadtree.MAX_OBJECTS && this.depth < Quadtree.MAX_DEPTH ) {
      if ( !this.nodes[0] ) {
        this.split();
      }

      var i = 0;
      while ( i < this.objects.length ) {
        index = this.indexOf( this.objects[i] );
        if ( index !== -1 ) {
          this.nodes[ index ].insert( this.objects.splice( i, 1 ) );
        } else {
          i++;
        }
      }
    }
  };

  Quadtree.prototype.retrieve = function( object, potentials ) {
    var index = this.indexOf( object );
    if ( index !== -1 && this.nodes[0] ) {
      this.nodes[ index ].retrieve( object, potentials );
    }

    potentials = potentials.concat( this.objects );
    return potentials;
  };

  function arrayAABB( array ) {
    var x0 = Number.POSITIVE_INFINITY,
        y0 = Number.POSITIVE_INFINITY,
        x1 = Number.NEGATIVE_INFINITY,
        y1 = Number.NEGATIVE_INFINITY;

    var x, y;
    array.forEach(function( element ) {
      x = element.x;
      y = element.y;

      if ( x < x0 ) {
        x0 = x;
      }

      if ( x > x1 ) {
        x1 = x;
      }

      if ( y < y0 ) {
        y0 = y;
      }

      if ( y > y1 ) {
        y1 = y;
      }
    });

    return {
      x0: x0,
      y0: y0,
      x1: x1,
      y1: y1
    };
  }

  function randomInt( min, max ) {
    return Math.round( min + Math.random() * ( max - min ) );
  }

  function init() {
    var width  = canvas.width,
        height = canvas.height;

    civilians.push( player = new Player( randomInt( 0, width ), randomInt( 0, height ) ) );
    var civilianCount = 500;
    var i;
    for ( i = 0; i < civilianCount; i++ ) {
      civilians.push( new Civilian( randomInt( 0, width ), randomInt( 0, height ) ) );
    }

    var zombieCount = 20;
    for ( i = 0; i < zombieCount; i++ ) {
      zombies.push( new Zombie( randomInt( 0, width ), randomInt( 0, height ) ) );
    }

    tick();
  }

  function onKeyDown( event ) {
    // console.log( event.which );
    keys[ event.which ] = true;
    // ESC.
    if ( event.which === 27 ) {
      running = false;
    }
  }

  function onKeyUp( event ) {
    // console.log( event.which );
    keys[ event.which ] = false;
  }

  document.addEventListener( 'keydown', onKeyDown );
  document.addEventListener( 'keyup', onKeyUp );

  init();
}) ( window, document );
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs')
  , path = require('path')
  , util = require('util')
  , file = path.join(process.cwd(), 'package.json')
  , readFile = function (cb) {
      fs.readFile(file, function (err, data) {
        var jsonData;
        if (err) return cb('Theres no package.json file in this directory.');
        try {
          jsonData = JSON.parse(data);
        } catch (ex) {
          return cb('Package.json in an illegal format.');
        }
        return cb(void 0, jsonData);
      });
    }
  , saveFile = function (data, cb) {
      fs.writeFile(file, JSON.stringify(data, null, 2), function (err) {
        cb(err, data);
      });
    }
  , scriptGenerator = function (styleFolder, browserFolder, targetFolder) {
    styleFolder = styleFolder || 'style';
    browserFolder = browserFolder || 'browser';
    targetFolder = targetFolder || 'static';

    return {
        "watch-css": "catw -c 'lessc -' '" + styleFolder + "/*.less' -o " + targetFolder + "/bundle.css -v"
      , "watch-js": "watchify " + browserFolder + "/*.js -o " + targetFolder + "/bundle.js -dv"
      , "watch": "npm run watch-css & npm run watch-js"
      , "build-css": "catw -c 'lessc -' '" + styleFolder + "/*.less' > " + targetFolder + "/bundle.css"
      , "build-js": "browserify " + browserFolder + "/*.js > " + targetFolder + "/bundle.js"
      , "build": "npm run build-css && npm run build-js"
    };
  }
  , setContent = function (input, newSetup) {
      input.scripts = input.scripts || {};
      newSetup = newSetup || {};
      var newScripts = scriptGenerator(newSetup.style, newSetup.browser, newSetup.target);
      Object.keys(newScripts).forEach(function (key) {
        input.scripts[key] = newScripts[key];
      });
      return input;
    }
  ;

module.exports = function (settings, cb) {
  if (typeof settings === 'function') {
    cb = settings;
    settings = void 0;
  }
  readFile(function (err, data) {
    if (err) return cb(err);
    var newInput = setContent(data, settings);
    saveFile(newInput, cb);
  });
};
<commit_msg>Adds setting of developer dependencies<commit_after>'use strict';

var fs = require('fs')
  , path = require('path')
  , util = require('util')
  , file = path.join(process.cwd(), 'package.json')
  , readFile = function (cb) {
      fs.readFile(file, function (err, data) {
        var jsonData;
        if (err) return cb('Theres no package.json file in this directory.');
        try {
          jsonData = JSON.parse(data);
        } catch (ex) {
          return cb('Package.json in an illegal format.');
        }
        return cb(void 0, jsonData);
      });
    }
  , saveFile = function (data, cb) {
      fs.writeFile(file, JSON.stringify(data, null, 2), function (err) {
        cb(err, data);
      });
    }
  , dependencies = {
      "catw": "*"
    , "watchify": "*"
    , "browserify": "*"
    , "less": "*"
  }
  , scriptGenerator = function (styleFolder, browserFolder, targetFolder) {
    styleFolder = styleFolder || 'style';
    browserFolder = browserFolder || 'browser';
    targetFolder = targetFolder || 'static';

    return {
        "watch-css": "catw -c 'lessc -' '" + styleFolder + "/*.less' -o " + targetFolder + "/bundle.css -v"
      , "watch-js": "watchify " + browserFolder + "/*.js -o " + targetFolder + "/bundle.js -dv"
      , "watch": "npm run watch-css & npm run watch-js"
      , "build-css": "catw -c 'lessc -' '" + styleFolder + "/*.less' > " + targetFolder + "/bundle.css"
      , "build-js": "browserify " + browserFolder + "/*.js > " + targetFolder + "/bundle.js"
      , "build": "npm run build-css && npm run build-js"
    };
  }
  , setContent = function (field, input, newSetup) {
      input[field] = input[field] || {};
      Object.keys(newSetup).forEach(function (key) {
        input[field][key] = newSetup[key];
      });
      return input;
    }
  ;

module.exports = function (settings, cb) {
  if (typeof settings === 'function') {
    cb = settings;
    settings = {};
  }
  readFile(function (err, data) {
    if (err) return cb(err);
    var newInput = setContent("scripts"
          , data
          , scriptGenerator(settings.style, settings.browser, settings.target)
        );
    newInput = setContent("devDependencies", newInput, dependencies);
    saveFile(newInput, cb);
  });
};
<|endoftext|>


<commit_before>!(function(window, document) {
  'use strict';

  /**
   * Default settings
   * @private
   * @const
   * @type {Object}
   */
  var DEFAULT_SETTINGS = {
    ppd: 2,
    insensitivity: 5,
    useControl: true
  };

  /**
   * Is ready to jump?
   * @private
   * @type {Boolean}
   */
  var isCharged = false;

  /**
   * Is preparing to be ready or no?
   * @private
   * @type {Boolean}
   */
  var isCharging = false;

  /**
   * Is the spatial scrolling on?
   * @private
   * @type {Boolean}
   */
  var isOn = false;

  /**
   * Last orientation of the device around the Z axis
   * @see https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
   * @private
   * @type {Number}
   */
  var lastAlpha;

  /**
   * Last orientation of the device around the X axis
   * @see https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
   * @private
   * @type {Number}
   */
  var lastBeta;

  /**
   * Last orientation of the device around the Y axis
   * @see https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
   * @private
   * @type {Number}
   */
  var lastGamma;

  /**
   * Current settings
   * @private
   * @type {Object}
   */
  var settings;

  /**
   * Interdimensional controller
   * @private
   * @type {HTMLElement}
   */
  var control;

  /**
   * Checks support of necessary features
   * @private
   * @param {Function} success
   * @param {Function} fail
   */
  function checkSupport(success, fail) {

    // Check the deviceorientation event and touch events
    if (
      !window.DeviceOrientationEvent ||
      !(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch)
    ) {
      fail();
    }

    // Check the deviceorientation event in the action
    window.addEventListener('deviceorientation', function checkDeviceOrientationEvent(e) {
      window.removeEventListener('deviceorientation', checkDeviceOrientationEvent, false);

      if (!isCharging) {
        return;
      }

      if ((e.alpha != null || e.beta != null || e.gamma != null)) {
        success();
      } else {
        fail();
      }
    }, false);
  }

  /**
   * Parses a string with options
   * @private
   * @param   {String} str
   * @returns {Object|String}
   */
  function parseOptions(str) {
    var obj = {};
    var delimiterIndex;
    var option;
    var prop;
    var val;
    var arr;
    var len;
    var i;

    // remove spaces around delimiters and split
    arr = str.replace(/\s*:\s*/g, ':').replace(/\s*,\s*/g, ',').split(',');

    // parse a string
    for (i = 0, len = arr.length; i < len; i++) {
      option = arr[i];

      // Ignore urls and a string without colon delimiters
      if (option.search(/^(http|https|ftp):\/\//) !== -1 ||
        option.search(':') === -1) {

        break;
      }

      delimiterIndex = option.indexOf(':');
      prop = option.substring(0, delimiterIndex);
      val = option.substring(delimiterIndex + 1);

      // if val is an empty string, make it undefined
      if (!val) {
        val = undefined;
      }

      // convert a string value if it is like a boolean
      if (typeof val === 'string') {
        val = val === 'true' || (val === 'false' ? false : val);
      }

      // convert a string value if it is like a number
      if (typeof val === 'string') {
        val = !isNaN(val) ? +val : val;
      }

      obj[prop] = val;
    }

    // if nothing is parsed
    if (prop == null && val == null) {
      return str;
    }

    return obj;
  }

  /**
   * Calculates a number of pixels to scroll
   * @private
   * @param  {Number} lastAngle Last orientation
   * @param  {Number} newAngle New orientation
   * @return {Number} Pixels to scroll
   */
  function calcShift(lastAngle, newAngle) {
    var diff = newAngle - lastAngle;
    var absDiff = Math.abs(diff);
    var sign = diff === 0 ? 0 : diff / absDiff;

    return absDiff > settings.insensitivity ?
      settings.ppd * (diff - sign * settings.insensitivity) : 0;
  }

  /**
   * Triggers events
   * @private
   * @param {String} Name of an event
   */
  function trigger(eventName) {
    var event;

    if (!eventName) {
      return;
    }

    // Add namespace
    eventName = 'interdimensional:' + eventName;

    if (!window.Event || typeof window.Event !== 'function') {

      // The old way
      event = document.createEvent('Event');
      event.initEvent(eventName, true, true);
    } else {

      // The new way
      event = new Event(eventName);
    }

    document.dispatchEvent(event);
  }

  /**
   * Enables/disables the spatial scrolling
   * @private
   * @listens touchstart
   */
  function handleTouchStartEvent() {
    Interdimensional.toggle();
  }

  /**
   * Scrolls the page
   * @private
   * @listens deviceorientation
   * @param {Event} e
   */
  function handleDeviceOrientationEvent(e) {
    if (!isOn || (lastAlpha == null || lastBeta == null || lastGamma == null)) {
      lastAlpha = e.alpha;
      lastBeta = e.beta;
      lastGamma = e.gamma;
    } else {
      if (window.innerHeight > window.innerWidth) {
        window.scrollBy(
          calcShift(lastAlpha, e.alpha),
          calcShift(lastBeta, e.beta)
        );
      } else {
        window.scrollBy(
          calcShift(lastBeta, e.beta),
          calcShift(lastGamma, e.gamma)
        );
      }
    }
  }

  /**
   * Disables the spacial scrolling
   * @private
   * @listens orientationchange
   */
  function handleOrientationChangeEvent() {
    Interdimensional.kick();
  }

  /**
   * Initializes declaratively
   * @private
   * @listens DOMContentLoaded
   */
  function handleDOMContentLoadedEvent() {
    var data = document.body.getAttribute('data-interdimensional');

    if (data != null) {
      Interdimensional.charge(parseOptions(data));
    }
  }

  /**
   * @public
   * @constructor
   */
  function Interdimensional() {}

  /**
   * Initializes
   * @public
   * @static
   * @param {Object} options
   */
  Interdimensional.charge = function(options) {
    if (!isCharged && !isCharging) {
      isCharging = true;

      checkSupport(function() {
        isCharged = true;
        isCharging = false;

        // Set settings
        settings = {};
        for (var key in DEFAULT_SETTINGS) {
          options && typeof options[key] !== 'undefined' ?
            settings[key] = options[key] :
            settings[key] = DEFAULT_SETTINGS[key];
        }

        // Create the control
        control = document.createElement('div');
        control.className = 'interdimensional-control';
        settings.useControl && document.body.appendChild(control);

        // Add event listeners
        control.addEventListener('touchstart', handleTouchStartEvent, false);
        window.addEventListener('deviceorientation', handleDeviceOrientationEvent, false);
        window.addEventListener('orientationchange', handleOrientationChangeEvent, false);

        trigger('charge');
      }, function() {
        isCharging = false;
        trigger('fail');
      });
    }
  };

  /**
   * Enables the spatial scrolling
   * @public
   * @static
   */
  Interdimensional.jump = function() {
    if (!isCharged) {
      return;
    }

    isOn = true;
    control.classList.add('interdimensional-control-is-active');

    trigger('jump');
  };

  /**
   * Disables the spatial scrolling
   * @public
   * @static
   */
  Interdimensional.kick = function() {
    if (!isCharged) {
      return;
    }

    isOn = false;
    control.classList.remove('interdimensional-control-is-active');

    trigger('kick');
  };

  /**
   * Toggles the spatial scrolling
   * @public
   * @static
   */
  Interdimensional.toggle = function() {
    isOn ? Interdimensional.kick() : Interdimensional.jump();
  };

  /**
   * Destroys
   * @public
   * @static
   */
  Interdimensional.discharge = function() {
    if (!isCharged) {
      return;
    }

    Interdimensional.kick();

    isCharged = false;
    settings.useControl && document.body.removeChild(control);

    // Remove event listeners
    control.removeEventListener('touchstart', handleTouchStartEvent, false);
    window.removeEventListener('deviceorientation', handleDeviceOrientationEvent, false);
    window.removeEventListener('orientationchange', handleOrientationChangeEvent, false);

    trigger('discharge');
  };

  document.addEventListener('DOMContentLoaded', handleDOMContentLoadedEvent, false);

  window.Interdimensional = Interdimensional;
})(window, document);
<commit_msg>Add #isOn, #isCharged methods<commit_after>!(function(window, document) {
  'use strict';

  /**
   * Default settings
   * @private
   * @const
   * @type {Object}
   */
  var DEFAULT_SETTINGS = {
    ppd: 2,
    insensitivity: 5,
    useControl: true
  };

  /**
   * Is ready to jump?
   * @private
   * @type {Boolean}
   */
  var isCharged = false;

  /**
   * Is preparing to be ready or no?
   * @private
   * @type {Boolean}
   */
  var isCharging = false;

  /**
   * Is the spatial scrolling on?
   * @private
   * @type {Boolean}
   */
  var isOn = false;

  /**
   * Last orientation of the device around the Z axis
   * @see https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
   * @private
   * @type {Number}
   */
  var lastAlpha;

  /**
   * Last orientation of the device around the X axis
   * @see https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
   * @private
   * @type {Number}
   */
  var lastBeta;

  /**
   * Last orientation of the device around the Y axis
   * @see https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
   * @private
   * @type {Number}
   */
  var lastGamma;

  /**
   * Current settings
   * @private
   * @type {Object}
   */
  var settings;

  /**
   * Interdimensional controller
   * @private
   * @type {HTMLElement}
   */
  var control;

  /**
   * Checks support of necessary features
   * @private
   * @param {Function} success
   * @param {Function} fail
   */
  function checkSupport(success, fail) {

    // Check the deviceorientation event and touch events
    if (
      !window.DeviceOrientationEvent ||
      !(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch)
    ) {
      fail();
    }

    // Check the deviceorientation event in the action
    window.addEventListener('deviceorientation', function checkDeviceOrientationEvent(e) {
      window.removeEventListener('deviceorientation', checkDeviceOrientationEvent, false);

      if (!isCharging) {
        return;
      }

      if ((e.alpha != null || e.beta != null || e.gamma != null)) {
        success();
      } else {
        fail();
      }
    }, false);
  }

  /**
   * Parses a string with options
   * @private
   * @param   {String} str
   * @returns {Object|String}
   */
  function parseOptions(str) {
    var obj = {};
    var delimiterIndex;
    var option;
    var prop;
    var val;
    var arr;
    var len;
    var i;

    // remove spaces around delimiters and split
    arr = str.replace(/\s*:\s*/g, ':').replace(/\s*,\s*/g, ',').split(',');

    // parse a string
    for (i = 0, len = arr.length; i < len; i++) {
      option = arr[i];

      // Ignore urls and a string without colon delimiters
      if (option.search(/^(http|https|ftp):\/\//) !== -1 ||
        option.search(':') === -1) {

        break;
      }

      delimiterIndex = option.indexOf(':');
      prop = option.substring(0, delimiterIndex);
      val = option.substring(delimiterIndex + 1);

      // if val is an empty string, make it undefined
      if (!val) {
        val = undefined;
      }

      // convert a string value if it is like a boolean
      if (typeof val === 'string') {
        val = val === 'true' || (val === 'false' ? false : val);
      }

      // convert a string value if it is like a number
      if (typeof val === 'string') {
        val = !isNaN(val) ? +val : val;
      }

      obj[prop] = val;
    }

    // if nothing is parsed
    if (prop == null && val == null) {
      return str;
    }

    return obj;
  }

  /**
   * Calculates a number of pixels to scroll
   * @private
   * @param  {Number} lastAngle Last orientation
   * @param  {Number} newAngle New orientation
   * @return {Number} Pixels to scroll
   */
  function calcShift(lastAngle, newAngle) {
    var diff = newAngle - lastAngle;
    var absDiff = Math.abs(diff);
    var sign = diff === 0 ? 0 : diff / absDiff;

    return absDiff > settings.insensitivity ?
      settings.ppd * (diff - sign * settings.insensitivity) : 0;
  }

  /**
   * Triggers events
   * @private
   * @param {String} Name of an event
   */
  function trigger(eventName) {
    var event;

    if (!eventName) {
      return;
    }

    // Add namespace
    eventName = 'interdimensional:' + eventName;

    if (!window.Event || typeof window.Event !== 'function') {

      // The old way
      event = document.createEvent('Event');
      event.initEvent(eventName, true, true);
    } else {

      // The new way
      event = new Event(eventName);
    }

    document.dispatchEvent(event);
  }

  /**
   * Enables/disables the spatial scrolling
   * @private
   * @listens touchstart
   */
  function handleTouchStartEvent() {
    Interdimensional.toggle();
  }

  /**
   * Scrolls the page
   * @private
   * @listens deviceorientation
   * @param {Event} e
   */
  function handleDeviceOrientationEvent(e) {
    if (!isOn || (lastAlpha == null || lastBeta == null || lastGamma == null)) {
      lastAlpha = e.alpha;
      lastBeta = e.beta;
      lastGamma = e.gamma;
    } else {
      if (window.innerHeight > window.innerWidth) {
        window.scrollBy(
          calcShift(lastAlpha, e.alpha),
          calcShift(lastBeta, e.beta)
        );
      } else {
        window.scrollBy(
          calcShift(lastBeta, e.beta),
          calcShift(lastGamma, e.gamma)
        );
      }
    }
  }

  /**
   * Disables the spacial scrolling
   * @private
   * @listens orientationchange
   */
  function handleOrientationChangeEvent() {
    Interdimensional.kick();
  }

  /**
   * Initializes declaratively
   * @private
   * @listens DOMContentLoaded
   */
  function handleDOMContentLoadedEvent() {
    var data = document.body.getAttribute('data-interdimensional');

    if (data != null) {
      Interdimensional.charge(parseOptions(data));
    }
  }

  /**
   * @public
   * @constructor
   */
  function Interdimensional() {}

  /**
   * @public
   * @returns {Boolean} `isCharged` variable
   */
  Interdimensional.isCharged = function() {
    return isCharged;
  };

  /**
   * @public
   * @returns {Boolean} `isOn` variable
   */
  Interdimensional.isOn = function() {
    return isOn;
  };

  /**
   * Initializes
   * @public
   * @static
   * @param {Object} options
   */
  Interdimensional.charge = function(options) {
    if (!isCharged && !isCharging) {
      isCharging = true;

      checkSupport(function() {
        isCharged = true;
        isCharging = false;

        // Set settings
        settings = {};
        for (var key in DEFAULT_SETTINGS) {
          options && typeof options[key] !== 'undefined' ?
            settings[key] = options[key] :
            settings[key] = DEFAULT_SETTINGS[key];
        }

        // Create the control
        control = document.createElement('div');
        control.className = 'interdimensional-control';
        settings.useControl && document.body.appendChild(control);

        // Add event listeners
        control.addEventListener('touchstart', handleTouchStartEvent, false);
        window.addEventListener('deviceorientation', handleDeviceOrientationEvent, false);
        window.addEventListener('orientationchange', handleOrientationChangeEvent, false);

        trigger('charge');
      }, function() {
        isCharging = false;
        trigger('fail');
      });
    }
  };

  /**
   * Enables the spatial scrolling
   * @public
   * @static
   */
  Interdimensional.jump = function() {
    if (!isCharged) {
      return;
    }

    isOn = true;
    control.classList.add('interdimensional-control-is-active');

    trigger('jump');
  };

  /**
   * Disables the spatial scrolling
   * @public
   * @static
   */
  Interdimensional.kick = function() {
    if (!isCharged) {
      return;
    }

    isOn = false;
    control.classList.remove('interdimensional-control-is-active');

    trigger('kick');
  };

  /**
   * Toggles the spatial scrolling
   * @public
   * @static
   */
  Interdimensional.toggle = function() {
    isOn ? Interdimensional.kick() : Interdimensional.jump();
  };

  /**
   * Destroys
   * @public
   * @static
   */
  Interdimensional.discharge = function() {
    if (!isCharged) {
      return;
    }

    Interdimensional.kick();

    isCharged = false;
    settings.useControl && document.body.removeChild(control);

    // Remove event listeners
    control.removeEventListener('touchstart', handleTouchStartEvent, false);
    window.removeEventListener('deviceorientation', handleDeviceOrientationEvent, false);
    window.removeEventListener('orientationchange', handleOrientationChangeEvent, false);

    trigger('discharge');
  };

  document.addEventListener('DOMContentLoaded', handleDOMContentLoadedEvent, false);

  window.Interdimensional = Interdimensional;
})(window, document);
<|endoftext|>


<commit_before>//Version: 1.0,
//Author: SCOTTJSON
//Created: MAY 2013

function mthA(number1, task, number2) {

    var result = undefined;

    switch(task){
        case "times":
            result = number1*number2;
            break;

        case "divideby":
            result = number1/number2;
            break;

        case "remainder":
            result = number1%number2;
            break;

        case "percentof":
            result = (number1/number2)*100;
            break;

        case "%off":  //20% off $50 = Answer: $40
            result = number2*(1-(number1/100));
            break;

        case "toradians":
            var pi = Math.PI;
            result = number1*(pi/180);
            break;
    }
    return result;
};

function mthACalculate(){
    var number1 = document.getElementById("mthAnumber1").value;
    var number2 = document.getElementById("mthAnumber2").value;
    var task = document.getElementById("mthATask").value;
    var result = document.getElementById("mthAresult");
    result.value = mthA(number1, task, number2);
}<commit_msg>Refactored to be fluent<commit_after>//Version: 1.0,
//Author: SCOTTJSON
//Created: MAY 2013

(function(){

    function multiplyBy(number){
        (this.value *= number);
        return this;
    }
    function divideBy(number){
        this.value /= number;
        return this;
    }
    function modulus(number){
        this.value %= number;
        return this;
    }
    function percentOf(number){
        this.value = this.value / number * 100;
        return this;
    }
    function percentOff(number){
        this.value = number*(1-(this.value/100));
        return this;
    }
    function toRadians(number){
        this.value = this.value*(Math.PI/180);
        return this;
    }

    function mthA(number){
        if(!(this instanceof mthA)){
            return new mthA(number);
        }
        this.value = number;
        return this;
    }
    mthA.prototype.value = 0;
    mthA.prototype.getValue = function(){
        return this.value;
    };
    mthA.prototype.toString = function(){
        return this.value.toString();
    };

    mthA.prototype.multiplyBy =
    mthA.prototype.timesBy =
    mthA.prototype.timesedBy =
    mthA.prototype.multipliedBy = multiplyBy;

    mthA.prototype.divideBy = divideBy;

    mthA.prototype.modulus = modulus;

    mthA.prototype.percentOf = percentOf;

    mthA.prototype.percentOff = percentOff;

    mthA.prototype.percentOff = percentOff;

    mthA.prototype.toRadians = toRadians;

    window.mthA = mthA;

    function mthACalculate(){
        var number1 = document.getElementById("mthAnumber1").value;
        var number2 = document.getElementById("mthAnumber2").value;
        var task = document.getElementById("mthATask").value;
        var result = document.getElementById("mthAresult");
        result.value = mthA(number1)[task](number2).value;
    }

    window.mthACalculate = mthACalculate;

})();<|endoftext|>


<commit_before><commit_msg>prettify code in app-test [PT #159876649]<commit_after><|endoftext|>


<commit_before>'use strict';

var getAllParts = require('./lib/getAllParts');
var buildMessage = require('./lib/buildMessage');

angular.module('ngHintInterpolation', [])
  .config(['$provide', function($provide) {
    $provide.decorator('$interpolate', ['$delegate', function($delegate) {
      var interpolateWrapper = function() {
        var interpolationFn = $delegate.apply(this, arguments);
        if(interpolationFn) {
          var temp;
          if(arguments[0].indexOf('?') === -1 && arguments[0].indexOf(':') === -1) {
            var parts = getAllParts(arguments[0], $delegate.startSymbol(), $delegate.endSymbol());
          }
          temp = interpolationFnWrap(interpolationFn, arguments, parts || []);
          return temp;
        }
      };
      var interpolationFnWrap = function(interpolationFn, interpolationArgs, allParts) {
        return function(){
          var result = interpolationFn.apply(this, arguments);
          buildMessage(allParts, interpolationArgs[0].trim(), arguments[0]);
          return result;
        };
      };
      angular.extend(interpolateWrapper,$delegate);
      return interpolateWrapper;
    }]);
  }]);
<commit_msg>chore(*): clean up code<commit_after>'use strict';

var getAllParts = require('./lib/getAllParts');
var buildMessage = require('./lib/buildMessage');

angular.module('ngHintInterpolation', [])
  .config(['$provide', function($provide) {
    $provide.decorator('$interpolate', ['$delegate', function($delegate) {
      var interpolateWrapper = function() {
        var interpolationFn = $delegate.apply(this, arguments);
        if(interpolationFn) {
          var temp;
          var interpolation = arguments[0];
          if(interpolation.indexOf('?') === -1 && interpolation.indexOf(':') === -1) {
            var parts = getAllParts(interpolation, $delegate.startSymbol(), $delegate.endSymbol());
          }
          temp = interpolationFnWrap(interpolationFn, arguments, parts || []);
          return temp;
        }
      };
      var interpolationFnWrap = function(interpolationFn, interpolationArgs, allParts) {
        return function(){
          var result = interpolationFn.apply(this, arguments);
          var originalInterpolation = interpolationArgs[0].trim();
          buildMessage(allParts, originalInterpolation, arguments[0]);
          return result;
        };
      };
      angular.extend(interpolateWrapper, $delegate);
      return interpolateWrapper;
    }]);
  }]);
<|endoftext|>