<commit_before>var request = require('request').defaults({ json: true });
var HttpStatus = require('http-status-codes');
var auth = require('../helper/auth');
var api = require('../helper/api').skvsApiUrl;
var fingerprint = require('ssh-fingerprint');
var error_helper = require('../helper/error').errorHelper;
var request_handler = require('../helper/error').requestHandler;

module.exports = function(router) {

  router.post('/ssh/add', auth, function(req, res, next) {
    var key = req.body['key'];
    if (key != undefined && key != "") {
      var description = key.split(' ')[2];
      if (description == undefined) {
        description = '';
      }
      var key_name = new Buffer(fingerprint(key) + ' (' + description + ')').toString('hex');

      var options = {
        url: api('/ssh/' + key_name),
        method: 'PUT',
        form: {
          value: key
        }
      };
      request(options, request_handler(function(response, res_result) {
        if (response.statusCode == HttpStatus.OK) {
          res.json({
            success: true
          });
        } else {
          next(error_helper(HttpStatus.BAD_REQUEST));
        }
      }, next));
    }
  });

  router.post('/ssh/delete', auth, function(req, res, next) {
    var key_name = req.body['id'];
    var options = {
      url: api('/ssh/' + key_name),
      method: 'DELETE'
    };
    request(options, request_handler(function(response, res_result) {
      if (response.statusCode == HttpStatus.OK) {
        res.json({
          success: true
        });
      } else if(response.statusCode == HttpStatus.NOT_FOUND) {
        next(error_helper(HttpStatus.NOT_FOUND, 'Key with id ' + key_name + ' does not exists!'));
      } else {
        next(error_helper(HttpStatus.BAD_REQUEST));
      }
    }, next));
  });

  router.get('/ssh', auth, function(req, res, next) {
    request(api('/ssh'), request_handler(function(response, res_result) {
      var result = { keys: [] };
      if (response.statusCode == HttpStatus.OK && res_result.namespace) {
        for(var index in res_result.keys) {
          try {
            var key_name = res_result.keys[index];
            result.keys.push({
              id: key_name,
              description: new Buffer(key_name, 'hex').toString('utf8')
            });
          } catch(err) {
            // do nothing, looks like there are dirty entries in skvs
            console.log("Error", err);
          }
        }
      }
      res.json(result);
    }, next));
  });
};
<commit_msg>Reformat<commit_after>var request = require('request').defaults({json: true});
var HttpStatus = require('http-status-codes');
var auth = require('../helper/auth');
var api = require('../helper/api').skvsApiUrl;
var fingerprint = require('ssh-fingerprint');
var error_helper = require('../helper/error').errorHelper;
var request_handler = require('../helper/error').requestHandler;

module.exports = function (router) {

  router.post('/ssh/add', auth, function (req, res, next) {
    var key = req.body['key'];
    if (key != undefined && key != "") {
      var description = key.split(' ')[2];
      if (description == undefined) {
        description = '';
      }
      var key_name = new Buffer(fingerprint(key) + ' (' + description + ')').toString('hex');

      var options = {
        url: api('/ssh/' + key_name),
        method: 'PUT',
        form: {
          value: key
        }
      };
      request(options, request_handler(function (response, res_result) {
        if (response.statusCode == HttpStatus.OK) {
          res.json({
            success: true
          });
        } else {
          next(error_helper(HttpStatus.BAD_REQUEST));
        }
      }, next));
    }
  });

  router.post('/ssh/delete', auth, function (req, res, next) {
    var key_name = req.body['id'];
    var options = {
      url: api('/ssh/' + key_name),
      method: 'DELETE'
    };
    request(options, request_handler(function (response, res_result) {
      if (response.statusCode == HttpStatus.OK) {
        res.json({
          success: true
        });
      } else if (response.statusCode == HttpStatus.NOT_FOUND) {
        next(error_helper(HttpStatus.NOT_FOUND, 'Key with id ' + key_name + ' does not exists!'));
      } else {
        next(error_helper(HttpStatus.BAD_REQUEST));
      }
    }, next));
  });

  router.get('/ssh', auth, function (req, res, next) {
    request(api('/ssh'), request_handler(function (response, res_result) {
      var result = {keys: []};
      if (response.statusCode == HttpStatus.OK && res_result.namespace) {
        for(var index in res_result.keys) {
          try {
            var key_name = res_result.keys[index];
            result.keys.push({
              id: key_name,
              description: new Buffer(key_name, 'hex').toString('utf8')
            });
          } catch(err) {
            // do nothing, looks like there are dirty entries in skvs
            console.log("Error", err);
          }
        }
      }
      res.json(result);
    }, next));
  });
};
<|endoftext|>


<commit_before>var SECTION = document.getElementsByClassName("js-section");
var lang = "it";
var form_stop;
var to_stop;
var matching_busstops = new Array(5);
var busstops = $.getJSON( "js/busstops.json", function(data) {
		autocom(0);
	});
if (navigator.language === "de") {
		lang = de;
}
clearPage();

function clearPage() {
	var i = 1;
	while (i < SECTION.length) {
		SECTION[i].style.display = "none";
		i++;
	}
}

function autocom(current_section) {
	var i;
	var children = SECTION[current_section].children;
	var input_string = children[1].value;

	i = 2
	while (i < children.length) {
			console.log(i);
			children[i].children[0].innerHTML = "";
			children[i].children[1].innerHTML = "";
			i++;
	}
	if (input_string != "") {
	input_string = input_string.split(" ");
	data = busstops.responseJSON;
	i = 2;
	data[lang].every( function (element, index, array) {
			var res = input_string.every( function (item, index, array) {
					var pattern = new RegExp(item, "i");
					var found_match = element.label.match(pattern);

					if (found_match != null) {
							return true;
					}
					else{
							return false;
					}

			});

			if (res && i < children.length) {

					matching_busstops[i-2] = element;
					children[i].children[0].innerHTML = element.name+", ";
					children[i].children[1].innerHTML = element.city;
					i++;
			}
			if (i >= children.length) {
					return false;
			}
			else{
					return true;
			}

});
}
}
function selectBusstop(current_section, div_number) {
	SECTION[current_section].children[0].children[1].innerHTML = matching_busstops[div_number].name + ", ";
	SECTION[current_section].children[0].children[2].innerHTML = matching_busstops[div_number].city;
	SECTION[current_section].children[1].value = "";
	makeBlank(current_section);
	unBlank(current_section + 1);
	autocom(current_section);
	if (current_section === 0) {
			from_stop = matching_busstops[div_number].id;
	}
	if (current_section === 1) {
			to_stop = matching_busstops[div_number].id;
	}
}
function makeBlank(current_section) {
	var i = 1;
	while (i < SECTION[current_section].children.length) {
			SECTION[current_section].children[i].style.display = "none";
			i++;
	}
	SECTION[current_section].className = "js-section";
}
function unBlank(current_section) {
	var i = 0;
	while (i < SECTION.length) {
			makeBlank(i);
			i++;
	}
	SECTION[current_section].style.display = "block";
	i = 0;
	while (i < SECTION[current_section].children.length) {
			SECTION[current_section].children[i].style.display = "block";
			i++;
	}
	addClass(current_section);
}
function selectTime(current_section) {
		var data = SECTION[current_section].children[1].value;
		var time = SECTION[current_section].children[2].value;
		SECTION[current_section].children[0].children[1].innerHTML = data + ", ";
		SECTION[current_section].children[0].children[2].innerHTML = time;
		getRoute(data,time);
}
function addClass(current_section) {
	SECTION[current_section].className += " active-section";
}
function removeClass(current_section) {
	SECTION[current_section].className = "js-section";
}
function getRoute(data, time) {
	data = data.replace(/\//g, ":");
	data = data.replace(/\./g, ":");
	data = data.split(":");
	console.log(data);
	time = time.replace(":", "");
	var url = "http://html5.sasabus.org/backend/sasabusdb/calcRoute?";
	url = url + "startBusStationId=" + from_stop;
	url = url + "&endBusStationId=" + to_stop;
	url = url + "&yyyymmddhhmm=" + data[2] + data[1] + data[0] + time;
$.ajax({
		dataType: "jsonp",
		jsonpCallback: "Callback",
		url: url,
	 	success: function(data) {
				console.log(data);
		}
});
}
<commit_msg>removed some console.logs<commit_after>var SECTION = document.getElementsByClassName("js-section");
var lang = "it";
var form_stop;
var to_stop;
var matching_busstops = new Array(5);
var busstops = $.getJSON( "js/busstops.json", function(data) {
		autocom(0);
	});
if (navigator.language === "de") {
		lang = de;
}
clearPage();

function clearPage() {
	var i = 1;
	while (i < SECTION.length) {
		SECTION[i].style.display = "none";
		i++;
	}
}

function autocom(current_section) {
	var i;
	var children = SECTION[current_section].children;
	var input_string = children[1].value;

	i = 2
	while (i < children.length) {
			children[i].children[0].innerHTML = "";
			children[i].children[1].innerHTML = "";
			i++;
	}
	if (input_string != "") {
	input_string = input_string.split(" ");
	data = busstops.responseJSON;
	i = 2;
	data[lang].every( function (element, index, array) {
			var res = input_string.every( function (item, index, array) {
					var pattern = new RegExp(item, "i");
					var found_match = element.label.match(pattern);

					if (found_match != null) {
							return true;
					}
					else{
							return false;
					}

			});

			if (res && i < children.length) {

					matching_busstops[i-2] = element;
					children[i].children[0].innerHTML = element.name+", ";
					children[i].children[1].innerHTML = element.city;
					i++;
			}
			if (i >= children.length) {
					return false;
			}
			else{
					return true;
			}

});
}
}
function selectBusstop(current_section, div_number) {
	SECTION[current_section].children[0].children[1].innerHTML = matching_busstops[div_number].name + ", ";
	SECTION[current_section].children[0].children[2].innerHTML = matching_busstops[div_number].city;
	SECTION[current_section].children[1].value = "";
	makeBlank(current_section);
	unBlank(current_section + 1);
	autocom(current_section);
	if (current_section === 0) {
			from_stop = matching_busstops[div_number].id;
	}
	if (current_section === 1) {
			to_stop = matching_busstops[div_number].id;
	}
}
function makeBlank(current_section) {
	var i = 1;
	while (i < SECTION[current_section].children.length) {
			SECTION[current_section].children[i].style.display = "none";
			i++;
	}
	SECTION[current_section].className = "js-section";
}
function unBlank(current_section) {
	var i = 0;
	while (i < SECTION.length) {
			makeBlank(i);
			i++;
	}
	SECTION[current_section].style.display = "block";
	i = 0;
	while (i < SECTION[current_section].children.length) {
			SECTION[current_section].children[i].style.display = "block";
			i++;
	}
	addClass(current_section);
}
function selectTime(current_section) {
		var data = SECTION[current_section].children[1].value;
		var time = SECTION[current_section].children[2].value;
		SECTION[current_section].children[0].children[1].innerHTML = data + ", ";
		SECTION[current_section].children[0].children[2].innerHTML = time;
		getRoute(data,time);
}
function addClass(current_section) {
	SECTION[current_section].className += " active-section";
}
function removeClass(current_section) {
	SECTION[current_section].className = "js-section";
}
function getRoute(data, time) {
	data = data.replace(/\//g, ":");
	data = data.replace(/\./g, ":");
	data = data.split(":");
	time = time.replace(":", "");
	var url = "http://html5.sasabus.org/backend/sasabusdb/calcRoute?";
	url = url + "startBusStationId=" + from_stop;
	url = url + "&endBusStationId=" + to_stop;
	url = url + "&yyyymmddhhmm=" + data[2] + data[1] + data[0] + time;
$.ajax({
		dataType: "jsonp",
		jsonpCallback: "Callback",
		url: url,
	 	success: function(data) {
				console.log(data);
		}
});
}
<|endoftext|>


<commit_before>
class CommLink {

    constructor(view, gui, graph, server, port=8891) {
        this.socket = new WebSocket("ws://"+server+":"+port+"/ws");

        this.view = view;
        this.gui = gui;
        this.graph = graph;

        this.configure_callbacks(this.socket)
    }

    socket_onopen(e) {
        console.log('Socket opened');
    }

    socket_onclose(e) {
        console.log('Socket closed');
    }

    socket_onerror(e) {
        console.log('Socket error');
    }

    socket_onmessage(e) {
        let json = JSON.parse(e.data);
        if (json.command == 'definitions') {
            this.graph.defs.definitions = json['data'];
            this.gui.init();
            _.demo_graph(this.view, this.graph);
        }
        if (json.command == 'image_update') {
            let node = this.graph.find_node(json['data']['name']);
            if (!node) {console.log('Warning: node not found'); return }
            let boxtype = this.graph.defs.boxtype(node.type);
            if (node.image_opts) {
                node.image_opts.imdata = json['data']['b64'];
                boxtype.update_image(node, this.view, true);
            }
        }
    }

    configure_callbacks(socket) {
        socket.onopen =    (e) => this.socket_onopen;
        socket.onerror =   (e) => this.socket_onerror;
        socket.onmessage = (e) => this.socket_onmessage(e);
        socket.onclose =   (e) => this.socket_onclose;
    }

    send_message(command, data) {
        if (this.socket.readyState === this.socket.OPEN ) {
            this.socket.send(JSON.stringify({'command': command, 'data':data}));
        }
        else {
            console.log('Socket not ready');
        }
    }

    add_node(node) {
        this.send_message('add_node',
                          {'type':node.type, 'name':node.name, 'params':node.params});
        // Use watch.js to follow the new nodes parameters
        watch(node.params, () => {
            this.update_params(node);
        });
    }

    remove_node(node) {
        this.send_message('remove_node',
                          {'name':node.name})
    }

    add_edge(edge) {
        this.send_message('add_edge',
                          {'src':edge.src.name,
                           'output': edge.output,
                           'dest' : edge.dest.name,
                           'input': edge.input});
        this.update_params(edge.dest);
    }

    remove_edge(edge) {
        this.send_message('remove_edge',
                          {'src':edge.src.name,
                           'output': edge.output,
                           'dest' : edge.dest.name,
                           'input': edge.input});
        this.update_params(edge.dest);
    }

    update_params(node) {
        // Send updated param values to Python
        this.send_message('update_params',
                          {'name':node.name, 'params':node.params})
    }

    unwatch_params(node) {

    }
}
<commit_msg>Renamed CommLink.configure_callbacks to setup<commit_after>
class CommLink {

    constructor(view, gui, graph, server, port=8891) {
        this.socket = new WebSocket("ws://"+server+":"+port+"/ws");

        this.view = view;
        this.gui = gui;
        this.graph = graph;

        this.setup(this.socket)
    }

    setup(socket) {
        socket.onopen =    (e) => this.socket_onopen;
        socket.onerror =   (e) => this.socket_onerror;
        socket.onmessage = (e) => this.socket_onmessage(e);
        socket.onclose =   (e) => this.socket_onclose;
    }

    socket_onopen(e) {
        console.log('Socket opened');
    }

    socket_onclose(e) {
        console.log('Socket closed');
    }

    socket_onerror(e) {
        console.log('Socket error');
    }

    socket_onmessage(e) {
        let json = JSON.parse(e.data);
        if (json.command == 'definitions') {
            this.graph.defs.definitions = json['data'];
            this.gui.init();
            _.demo_graph(this.view, this.graph);
        }
        if (json.command == 'image_update') {
            let node = this.graph.find_node(json['data']['name']);
            if (!node) {console.log('Warning: node not found'); return }
            let boxtype = this.graph.defs.boxtype(node.type);
            if (node.image_opts) {
                node.image_opts.imdata = json['data']['b64'];
                boxtype.update_image(node, this.view, true);
            }
        }
    }

    send_message(command, data) {
        if (this.socket.readyState === this.socket.OPEN ) {
            this.socket.send(JSON.stringify({'command': command, 'data':data}));
        }
        else {
            console.log('Socket not ready');
        }
    }

    add_node(node) {
        this.send_message('add_node',
                          {'type':node.type, 'name':node.name, 'params':node.params});
        // Use watch.js to follow the new nodes parameters
        watch(node.params, () => {
            this.update_params(node);
        });
    }

    remove_node(node) {
        this.send_message('remove_node',
                          {'name':node.name})
    }

    add_edge(edge) {
        this.send_message('add_edge',
                          {'src':edge.src.name,
                           'output': edge.output,
                           'dest' : edge.dest.name,
                           'input': edge.input});
        this.update_params(edge.dest);
    }

    remove_edge(edge) {
        this.send_message('remove_edge',
                          {'src':edge.src.name,
                           'output': edge.output,
                           'dest' : edge.dest.name,
                           'input': edge.input});
        this.update_params(edge.dest);
    }

    update_params(node) {
        // Send updated param values to Python
        this.send_message('update_params',
                          {'name':node.name, 'params':node.params})
    }

    unwatch_params(node) {

    }
}
<|endoftext|>


<commit_before>var CSS_COLOR_NAMES = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "ForestGreen", "Fuchsia", "Gainsboro", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "Yellow", "YellowGreen"];
var color;
var reset_counter = 0;
var lamp_awsome = '';
var spinner = '';
var first_init = 0;
var player_name = null;
var score = 0;
var first_move = true;
var init_flag = false;
var total_move = 0;
var restart_flag = 0;
var no_move_counter=0;
var hr = (new Date()).getHours();
if (hr>=19||hr<6){
    lamp_awsome='';
}
function redirect(flag){
    switch(flag){
        case 1:
            window.open("https://saythanks.io/to/lightsout");
            break;
        case 2:
            swal("Bitocin Wallet","1XGr9qbZjBpUQJJSB6WtgBQbDTgrhPLPA");
            break;
        case 3:
            window.open("https://beerpay.io/sepandhaghighi/lightsout");
            break;
        case 4:
            window.open("https://www.payping.ir/sepandhaghighi");
            break;
        default:
            window.open("https://saythanks.io/to/lightsout");

    }

}
function getname(){
    swal({
  title: "Enter Your Name",
  text: "1-10 Character",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  animation: "slide-from-top",
  inputPlaceholder: "Player Name"
},
function(inputValue){
  if (inputValue === false){
      player_name="Guest-"+Math.floor(Math.random()*400+1).toString();
      return false;
  }

  if (inputValue === "") {
    swal.showInputError("Enter Your Name!");
    return false
  }
    player_name=inputValue;
  if (inputValue.length>10){
      player_name=player_name.substring(0,10);
  }
  swal("Welcome!","Lights Out, Linear Algebra Game");
});
}

function reply_click(e) {
    var input_id, ele, move;
    move = document.getElementById("move");
    if ((first_move==true)&&(init_flag==false)){
                display = document.querySelector('#time');
                startTimer(60*7, display);
        first_move=false;
    }
    input_id = parseInt(e);
    if (first_init == 1) {
        if ((input_id + 5) <= 25) {
            toggle(input_id + 5);
        }
        if ((input_id - 5) >= 1) {
            toggle(input_id - 5);
        }
        if (((input_id - 1) % 5) == 0) {
            toggle(input_id + 1);
        }
        else if ((input_id % 5) == 0) {
            toggle(input_id - 1);

        }
        else {
            toggle(input_id - 1);
            toggle(input_id + 1);
        }
        toggle(input_id);
        if (init_flag==false){
        move.innerHTML = parseInt(move.innerHTML) + 1;
        total_move=total_move+1;
        }
        end_game();

    }
    no_move_counter=0;

}

function init(flag) {
    first_init = 1;
    color = CSS_COLOR_NAMES[Math.floor((Math.random() * CSS_COLOR_NAMES.length) + 1)].toLowerCase();
    var i, random_number, random_counter, move, game_name, random_init, reset;
    var random_list = [];
    random_counter = 0;
    game_name = document.getElementById("game_name");
    game_name.style.color = color;
    game_name.innerHTML = "Lights Out Game";
    move = document.getElementById("move");
    reset = document.getElementById("reset");
    random_init = 0;
    init_flag=true;
    if (flag == 2) {
        reset_counter = reset_counter + 1;
        reset.innerHTML = "Reset" + " (" + reset_counter + ")";
    }
    while (random_init < 10) {
        random_init = Math.floor((Math.random() * 15) + 1);
    }
    while (random_counter < random_init) {
        random_number = Math.floor((Math.random() * 25) + 1);
        if (random_list.indexOf(random_number) < 0) {
            random_list.push(random_number);
            random_counter = random_counter + 1;
        }
    }
    for (i = 1; i < 26; i++) {
        document.getElementById(i.toString()).style.backgroundColor = color;
        document.getElementById(i.toString()).innerHTML = "";
    }
    for (i = 0; i < random_list.length; i++) {
        reply_click(random_list[i].toString());
    }
    move.innerHTML = 0;
    init_flag=false;
}

function toggle(input_id) {
    var press_button;
    press_button = document.getElementById(input_id.toString());
    if (press_button.style.backgroundColor == color) {
        press_button.style.backgroundColor = "white";
        press_button.innerHTML = lamp_awsome;
    }
    else {
        press_button.style.backgroundColor = color;
        press_button.innerHTML = "";
    }

}

function end_game() {
    var i, on_lamp, win;
    on_lamp = 0;
    for (i = 1; i < 26; i++) {
        if (document.getElementById(i.toString()).style.backgroundColor == "white") {
            on_lamp = on_lamp + 1;
            break;
        }
    }
    if (on_lamp == 0) {
        score=score+1
        win = document.getElementById("win");
        win.innerHTML = parseInt(win.innerHTML) + 1;
        init(1);
    }
}

function savescore(){
    getname();
    saveToFirebase(player_name,score);

}

function get_data(){
    var leadsRef = firebase.database().ref('subscription-entries').orderByChild("score").limitToLast(10);
    var counter = 0;
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var name = childSnapshot.val().name;
      var score= childSnapshot.val().score;
      document.getElementById("N"+(10-counter).toString()).innerHTML=name;
      document.getElementById("S"+(10-counter).toString()).innerHTML=score;
     counter=counter+1;
    });
});
}

function saveToFirebase(name,score,total_move,player_reset) {
    var scoreObject = {
        name: name,
        score: score,
        reset: player_reset,
        move:total_move
    };
    try{
    firebase.database().ref('subscription-entries').push().set(scoreObject)
        .then(function(snapshot) {
        }, function(error) {
            console.log('error' + error);
        });
    }
    catch(e){
    }
}
function restart_game(){
    swal({
  title: "Are you sure?",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes",
  cancelButtonText: "No",
  closeOnConfirm: true,
  closeOnCancel: true
},
function(isConfirm){
  if (isConfirm) {
    if (first_move==false){
    restart_flag=1;
    }
    else{
            reset = document.getElementById("reset");
            reset.innerHTML = "Reset!";
            reset_counter=0;
    }
  } else {
  }
});

}
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var interval_id = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        no_move_counter+=1;
        if (timer==(duration/2)){
            display.style.color="orange";
        }
        else if (timer==60){
            display.style.color="red";
        }
        if (no_move_counter>=60&&timer>100){
            swal({
            title: "Hurry Up!!!",
            imageUrl: "images/hurry.png"
            });
            no_move_counter=0;
        }
        if (--timer < 0||restart_flag==1) {
            if (restart_flag==0){
                saveToFirebase(player_name,score.toString(),total_move.toString(),reset_counter.toString());
                swal({
                    title:"Time's Up",
                    text: "Player Name : "+player_name+"\nScore : "+score.toString()+"\nReset : "+reset_counter.toString()+"\nTotal Move : "+total_move.toString(),
                    imageUrl: "images/timeup.png"
                    });}
            timer = duration;
            restart_config(display);
            clearInterval(interval_id);
        }
    }, 1000);
}

function restart_config(display){
     display.textContent = "TI" + ":" + "ME";
    total_move=0;
    display.style.color="black";
    win = document.getElementById("win");
            win.innerHTML = 0;
    score=0;
    reset = document.getElementById("reset");
            reset.innerHTML = "Reset!";
            reset_counter=0;
     first_move=true;
            restart_flag=0;
    init(1);

}

<commit_msg>fix: minor edit in js for some browser<commit_after>var CSS_COLOR_NAMES = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "ForestGreen", "Fuchsia", "Gainsboro", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "Yellow", "YellowGreen"];
var color;
var reset_counter = 0;
var lamp_awsome = '';
var spinner = '';
var first_init = 0;
var player_name = null;
var score = 0;
var first_move = true;
var init_flag = false;
var total_move = 0;
var restart_flag = 0;
var no_move_counter=0;
var hr = (new Date()).getHours();
if (hr>=19||hr<6){
    lamp_awsome='';
}
function redirect(flag){
    switch(flag){
        case 1:
            window.open("https://saythanks.io/to/lightsout");
            break;
        case 2:
            swal("Bitocin Wallet","1XGr9qbZjBpUQJJSB6WtgBQbDTgrhPLPA");
            break;
        case 3:
            window.open("https://beerpay.io/sepandhaghighi/lightsout");
            break;
        case 4:
            window.open("https://www.payping.ir/sepandhaghighi");
            break;
        default:
            window.open("https://saythanks.io/to/lightsout");

    }

}
function getname(){
    swal({
  title: "Enter Your Name",
  text: "1-10 Character",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  animation: "slide-from-top",
  inputPlaceholder: "Player Name"
},
function(inputValue){
  if (inputValue === false){
      player_name="Guest-"+Math.floor(Math.random()*400+1).toString();
      return false;
  }

  if (inputValue === "") {
    swal.showInputError("Enter Your Name!");
    return false
  }
    player_name=inputValue;
  if (inputValue.length>10){
      player_name=player_name.substring(0,10);
  }
  swal("Welcome!","Lights Out, Linear Algebra Game");
});
}

function reply_click(e) {
    var input_id, ele, move;
    move = document.getElementById("move");
    if ((first_move==true)&&(init_flag==false)){
                document.getElementById("win")=0;
                display = document.querySelector('#time');
                startTimer(60*7, display);
        first_move=false;
    }
    input_id = parseInt(e);
    if (first_init == 1) {
        if ((input_id + 5) <= 25) {
            toggle(input_id + 5);
        }
        if ((input_id - 5) >= 1) {
            toggle(input_id - 5);
        }
        if (((input_id - 1) % 5) == 0) {
            toggle(input_id + 1);
        }
        else if ((input_id % 5) == 0) {
            toggle(input_id - 1);

        }
        else {
            toggle(input_id - 1);
            toggle(input_id + 1);
        }

        if (init_flag==false){
        move.innerHTML = parseInt(move.innerHTML) + 1;
        total_move=total_move+1;
        }
        toggle(input_id);
        end_game();

    }
    no_move_counter=0;

}

function init(flag) {
    first_init = 1;
    color = CSS_COLOR_NAMES[Math.floor((Math.random() * CSS_COLOR_NAMES.length) + 1)].toLowerCase();
    var i, random_number, random_counter, move, game_name, random_init, reset;
    var random_list = [];
    random_counter = 0;
    game_name = document.getElementById("game_name");
    game_name.style.color = color;
    game_name.innerHTML = "Lights Out Game";
    move = document.getElementById("move");
    reset = document.getElementById("reset");
    random_init = 0;
    init_flag=true;
    if (flag == 2) {
        reset_counter = reset_counter + 1;
        reset.innerHTML = "Reset" + " (" + reset_counter + ")";
    }
    while (random_init < 10) {
        random_init = Math.floor((Math.random() * 15) + 1);
    }
    while (random_counter < random_init) {
        random_number = Math.floor((Math.random() * 25) + 1);
        if (random_list.indexOf(random_number) < 0) {
            random_list.push(random_number);
            random_counter = random_counter + 1;
        }
    }
    for (i = 1; i < 26; i++) {
        document.getElementById(i.toString()).style.backgroundColor = color;
        document.getElementById(i.toString()).innerHTML = "";
    }
    for (i = 0; i < random_list.length; i++) {
        reply_click(random_list[i].toString());
    }
    move.innerHTML = 0;
    init_flag=false;
}

function toggle(input_id) {
    var press_button;
    press_button = document.getElementById(input_id.toString());
    if (press_button.style.backgroundColor == color) {
        press_button.style.backgroundColor = "white";
        press_button.innerHTML = lamp_awsome;
    }
    else {
        press_button.style.backgroundColor = color;
        press_button.innerHTML = "";
    }

}

function end_game() {
    var i, on_lamp, win;
    on_lamp = 0;
    for (i = 1; i < 26; i++) {
        if (document.getElementById(i.toString()).style.backgroundColor == "white") {
            on_lamp = on_lamp + 1;
            break;
        }
    }
    if (on_lamp == 0) {
        score=score+1
        win = document.getElementById("win");
        win.innerHTML = parseInt(win.innerHTML) + 1;
        init(1);
    }
}

function savescore(){
    getname();
    saveToFirebase(player_name,score);

}

function get_data(){
    var leadsRef = firebase.database().ref('subscription-entries').orderByChild("score").limitToLast(10);
    var counter = 0;
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var name = childSnapshot.val().name;
      var score= childSnapshot.val().score;
      document.getElementById("N"+(10-counter).toString()).innerHTML=name;
      document.getElementById("S"+(10-counter).toString()).innerHTML=score;
     counter=counter+1;
    });
});
}

function saveToFirebase(name,score,total_move,player_reset) {
    var scoreObject = {
        name: name,
        score: score,
        reset: player_reset,
        move:total_move
    };
    try{
    firebase.database().ref('subscription-entries').push().set(scoreObject)
        .then(function(snapshot) {
        }, function(error) {
            console.log('error' + error);
        });
    }
    catch(e){
    }
}
function restart_game(){
    swal({
  title: "Are you sure?",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes",
  cancelButtonText: "No",
  closeOnConfirm: true,
  closeOnCancel: true
},
function(isConfirm){
  if (isConfirm) {
    if (first_move==false){
    restart_flag=1;
    }
    else{
            reset = document.getElementById("reset");
            reset.innerHTML = "Reset!";
            reset_counter=0;
    }
  } else {
  }
});

}
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var interval_id = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        no_move_counter+=1;
        if (timer==(duration/2)){
            display.style.color="orange";
        }
        else if (timer==60){
            display.style.color="red";
        }
        if (no_move_counter>=60&&timer>100){
            swal({
            title: "Hurry Up!!!",
            imageUrl: "images/hurry.png"
            });
            no_move_counter=0;
        }
        if (--timer < 0||restart_flag==1) {
            if (restart_flag==0){
                saveToFirebase(player_name,score.toString(),total_move.toString(),reset_counter.toString());
                swal({
                    title:"Time's Up",
                    text: "Player Name : "+player_name+"\nScore : "+score.toString()+"\nReset : "+reset_counter.toString()+"\nTotal Move : "+total_move.toString(),
                    imageUrl: "images/timeup.png"
                    });}
            timer = duration;
            restart_config(display);
            clearInterval(interval_id);
        }
    }, 1000);
}

function restart_config(display){
     display.textContent = "TI" + ":" + "ME";
    total_move=0;
    display.style.color="black";
    win = document.getElementById("win");
            win.innerHTML = 0;
    score=0;
    reset = document.getElementById("reset");
            reset.innerHTML = "Reset!";
            reset_counter=0;
     first_move=true;
            restart_flag=0;
    init(1);

}

<|endoftext|>


<commit_before>'use strict';

var emitter = require('contra.emitter');
var once = require('./once');
var router = require('./router');
var interceptors = emitter({ count: 0 });

function getInterceptorEvent (url, route) {
  var e = {
    url: url,
    route: route,
    parts: route.parts,
    model: null,
    defaultPrevented: false,
    preventDefault: once(preventDefault)
  };

  function preventDefault (model) {
    e.defaultPrevented = true;
    e.model = model;
  }

  return e;
}

function add (action, fn) {
  if (arguments.length === 1) {
    fn = action;
    action = '*';
  }
  interceptors.count++;
  interceptors.on(action, fn);
}

function executeSync (route) {
  var e = getInterceptorEvent(route.url, route);

  interceptors.emit('*', e);
  interceptors.emit(route.action, e);

  return e;
}

function execute (route, done) {
  var e = getInterceptorEvent(route.url, route);
  if (interceptors.count === 0) { // fail fast
    end(); return;
  }
  var fn = once(end);
  var preventDefaultBase = e.preventDefault;

  e.preventDefault = once(preventDefaultEnds);

  interceptors.emit('*', e);
  interceptors.emit(route.action, e);

  setTimeout(fn, 500); // at worst, spend 500ms waiting on interceptors

  function preventDefaultEnds () {
    preventDefaultBase.apply(null, arguments);
    fn();
  }

  function end () {
    done(null, e);
  }
}

module.exports = {
  add: add,
  execute: execute
};
<commit_msg>run interceptors async.<commit_after>'use strict';

var emitter = require('contra.emitter');
var once = require('./once');
var router = require('./router');
var interceptors = emitter({ count: 0 }, { async: true });

function getInterceptorEvent (url, route) {
  var e = {
    url: url,
    route: route,
    parts: route.parts,
    model: null,
    defaultPrevented: false,
    preventDefault: once(preventDefault)
  };

  function preventDefault (model) {
    e.defaultPrevented = true;
    e.model = model;
  }

  return e;
}

function add (action, fn) {
  if (arguments.length === 1) {
    fn = action;
    action = '*';
  }
  interceptors.count++;
  interceptors.on(action, fn);
}

function executeSync (route) {
  var e = getInterceptorEvent(route.url, route);

  interceptors.emit('*', e);
  interceptors.emit(route.action, e);

  return e;
}

function execute (route, done) {
  var e = getInterceptorEvent(route.url, route);
  if (interceptors.count === 0) { // fail fast
    end(); return;
  }
  var fn = once(end);
  var preventDefaultBase = e.preventDefault;

  e.preventDefault = once(preventDefaultEnds);

  interceptors.emit('*', e);
  interceptors.emit(route.action, e);

  setTimeout(fn, 500); // at worst, spend 500ms waiting on interceptors

  function preventDefaultEnds () {
    preventDefaultBase.apply(null, arguments);
    fn();
  }

  function end () {
    done(null, e);
  }
}

module.exports = {
  add: add,
  execute: execute
};
<|endoftext|>


<commit_before>(function($, MathJax) {
    $(function() {
        var bayesapp = {
            templates: {
                hypothesis: _.template($('#hypothesis').html())
            },
            template_options: {
                a_fortiori: false,
                hide_remove: false,
                labels: {
                    hypothesis: 'Hypothesis',
                    evidence: 'Evidence'
                },
                fields: [{
                    name: 'hb',
                    label: '\\(\\mathrm{\\Pr( H<% if (!single) { %><%= \'_\' + num %><% } %> \\mid b )}\\)',
                    className: 'hb',
                    val: 0,
                    title: 'Probability that \'<%= labels.hypothesis %>\' is true given the background evidence',
                    disabled: false
                }, {
                    name: 'nhb',
                    label: '\\(\\mathrm{\\Pr( \\neg{H}<% if (!single) { %><%= \'_\' + num %><% } %> \\mid b )}\\)',
                    className: 'nhb',
                    val: 1,
                    title: 'Probability that \'<%= labels.hypothesis %>\' is false given the background evidence',
                    disabled: false
                }, {
                    name: 'ehb',
                    label: '\\(\\mathrm{\\Pr( E \\mid H<% if (!single) { %><%= \'_\' + num %><% } %>.b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.evidence %>\' is true given that \'<%= labels.hypothesis %>\' is true and the background evidence',
                    disabled: false
                }, {
                    name: 'enhb',
                    label: '\\(\\mathrm{\\Pr( E \\mid \\neg{H}<% if (!single) { %><%= \'_\' + num %><% } %>.b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.evidence %>\' is true given that \'<%= labels.hypothesis %>\' is false and the background evidence',
                    disabled: false
                }, {
                    name: 'eb',
                    label: '\\(\\mathrm{\\Pr( E \\mid b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.evidence %>\' is true given the background evidence',
                    hint: 'Must be greater than 0',
                    disabled: false
                }, {
                    name: 'heb',
                    label: '\\(\\mathrm{\\Pr( H<% if (!single) { %><%= \'_\' + num %><% } %> \\mid E.b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.hypothesis %>\' is true given that \'<%= labels.evidence %>\' is true and the background evidence',
                    disabled: true
                }]
            },
            round: function(num, dec) {
                return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
            },
            add_hypothesis: function(e, $el) {
                if (e) e.preventDefault();
                var $hypotheses_container = ($el || $(this)).closest('form').find('.hypotheses');
                $hypotheses_container.find('.remove').hide();
                $hypotheses_container.append(bayesapp.templates.hypothesis($.extend(bayesapp.template_options, {
                    num: $hypotheses_container.find('.hypothesis').length + 1,
                    single: $hypotheses_container.hasClass('basic')
                })));
                if (MathJax) MathJax.Hub.Queue(["Typeset", MathJax.Hub, $hypotheses_container.get(0)]);
            },
            validate: function($form) {
                var data = $form.serializeObject(),
                    errors = [],
                    i, k, $input;
                $form.find('.error').removeClass('error');
                if (_.isArray(data['eb'])) {
                    for (i = 0; i < data['eb'].length; i++) {
                        errors = [];
                        if (data['enhb'][i] == 0 && (data['hb'][i] * data['ehb'][i]) / data['eb'][i] > 1) {
                            errors.push('hb');
                            errors.push('nhb');
                            errors.push('ehb');
                            errors.push('enhb');
                            errors.push('eb');
                        }
                        if (data['enhb'][i] == 0 && data['eb'][i] <= 0) errors.push('eb');
                        if (errors.length > 0) {
                            for (k in errors) {
                                $form.find('.field-' + errors[k] + ' .inputs:eq(' + i + ') input[name=' + errors[k] + ']').addClass('error');
                            }
                        }
                    }
                }
                else {
                    var $inputs = $form.find('input');
                    if (data['enhb'] == 0 && (data['hb'] * data['ehb']) / data['eb'] > 1) {
                        errors.push('hb');
                        errors.push('nhb');
                        errors.push('ehb');
                        errors.push('enhb');
                        errors.push('eb');
                    }
                    if (data['enhb'] == 0 && data['eb'] <= 0) errors.push('eb');
                    if (errors.length > 0) {
                        for (i in errors) {
                            $inputs.filter('[name=' + errors[i] + ']').addClass('error');
                        }
                    }
                }
            },
            calculate: function(calc) {
                if (calc.length == 1) {
                    if (calc[0].enhb > 0) {
                        return (parseFloat(calc[0].hb) * parseFloat(calc[0].ehb)) / (parseFloat(calc[0].hb) * parseFloat(calc[0].ehb) + parseFloat(calc[0].nhb) * parseFloat(calc[0].enhb));
                    }
                    else {
                        return parseFloat(calc[0].eb) != 0 ? (parseFloat(calc[0].hb) * parseFloat(calc[0].ehb)) / parseFloat(calc[0].eb) : 0;
                    }
                }
                else {
                    return false;
                }
            },
            update_calculation: function(e, $this) {
                if (e) e.preventDefault();
                $this = !$this ? $(this) : $this;
                bayesapp.validate($this);
                var data = $this.serializeObject();
                if (_.isArray(data['eb'])) {
                    for (var i = 0; i < data['eb'].length; i++) {
                        $this.find('.field-heb .inputs:eq(' + i + ') span').text(bayesapp.round(bayesapp.calculate([{
                            eb: data['eb'][i],
                            ehb: data['ehb'][i],
                            hb: data['hb'][i],
                            heb: data['heb'][i],
                            nhb: data['nhb'][i]
                        }]), 2));
                    }
                }
                else {
                    $this.find('.field-heb .inputs span').text(bayesapp.round(bayesapp.calculate([data]), 2));
                }
            },
            update_joined_fields: function($this, type) {
                var $field = $this.closest('.field'),
                    $fields = $field.siblings('.field'),
                    $inputs = $field.find('.inputs'),
                    $input = $this.closest('.inputs'),
                    i = $inputs.index($input);
                $this.siblings('input[type=' + type + ']').val($this.val());
                if ($field.hasClass('field-hb')) {
                    $fields.filter('.field-nhb').find('.inputs:eq(' + i + ') input').val(1 - parseFloat($this.val()));
                }
                if ($field.hasClass('field-nhb')) {
                    $fields.filter('.field-hb').find('.inputs:eq(' + i + ') input').val(1 - parseFloat($this.val()));
                }
                bayesapp.update_calculation(false, $this.closest('form'));
            },
            init: function() {
                $('#tabs').find('a').click(function(e) {
                    e.preventDefault();
                    var $this = $(this);
                    $('#tabs .active').removeClass('active');
                    $this.addClass('active');
                    $('#panels').find('.panel').removeClass('active').eq($('#tabs').find('a').index($this)).addClass('active');
                });
                bayesapp.add_hypothesis(false, $('.basic'));
                //$('.add_hypothesis').click(bayesapp.add_hypothesis).click();
                $('.a_fortiori').click(function(e) {
                    e.preventDefault();
                    bayesapp.template_options.a_fortiori = !bayesapp.template_options.a_fortiori;
                    var $hypotheses_container = $(this).closest('form').find('.hypotheses'),
                        $hypotheses = $hypotheses_container.find('.hypothesis')
                        $hypotheses.each(function(index) {
                            $(this).replaceWith(bayesapp.templates.hypothesis($.extend(bayesapp.template_options, {
                                num: index + 1,
                                hide_remove: (index + 1) !== $hypotheses.length,
                                single: $hypotheses_container.hasClass('basic')
                            })));
                        });
                    if (MathJax) MathJax.Hub.Queue(["Typeset", MathJax.Hub, $hypotheses_container.get(0)]);
                });
                var $form = $('form');
                $form.delegate('input[type=range]', 'change', function() {
                    bayesapp.update_joined_fields($(this), 'number');
                });
                $form.delegate('input[type=number]', 'change', function() {
                    bayesapp.update_joined_fields($(this), 'range');
                });
                $form.delegate('.remove', 'click', function(event) {
                    event.preventDefault();
                    var $this = $(this),
                        $form = $this.closest('form'),
                        $hypothesis = $this.closest('.hypothesis'),
                        $hypotheses = $hypothesis.siblings('.hypothesis');
                    if ($hypotheses.length > 0) {
                        $hypothesis.remove();
                        $form.find('.remove:last').show();
                    }
                });
                $form.delegate('label[title],input[title],button[title]', 'mouseover', function() {
                    var $this = $(this);
                    if (!$this.data("tooltip")) {
                        $this.tooltip({
                            position: "center right"
                        }).trigger('mouseover');
                    }
                });
                $form.delegate('.set', 'click', function(e) {
                    e.preventDefault();
                    var $this = $(this),
                    $inputs = $this.closest('fieldset').find('input');
                    $inputs.each(function () {
                        var $input = $(this);
                        bayesapp.template_options.labels[$input.attr('name')] = $input.val();
                    });
                    var $hypotheses_container = $this.closest('form').find('.hypotheses');
                    $hypotheses_container.find('.hypothesis').remove();
                    bayesapp.add_hypothesis(false, $hypotheses_container);
                });
            }
        }; //End bayesapp
        bayesapp.init();
    });
}(jQuery, MathJax));<commit_msg>A fortiori complete calculation now working<commit_after>(function($, MathJax) {
    $(function() {
        var bayesapp = {
            templates: {
                hypothesis: _.template($('#hypothesis').html())
            },
            template_options: {
                a_fortiori: false,
                hide_remove: false,
                labels: {
                    hypothesis: 'Hypothesis',
                    evidence: 'Evidence'
                },
                fields: [{
                    name: 'hb',
                    label: '\\(\\mathrm{\\Pr( H<% if (!single) { %><%= \'_\' + num %><% } %> \\mid b )}\\)',
                    className: 'hb',
                    val: 0,
                    title: 'Probability that \'<%= labels.hypothesis %>\' is true given the background evidence',
                    disabled: false
                }, {
                    name: 'nhb',
                    label: '\\(\\mathrm{\\Pr( \\neg{H}<% if (!single) { %><%= \'_\' + num %><% } %> \\mid b )}\\)',
                    className: 'nhb',
                    val: 1,
                    title: 'Probability that \'<%= labels.hypothesis %>\' is false given the background evidence',
                    disabled: false
                }, {
                    name: 'ehb',
                    label: '\\(\\mathrm{\\Pr( E \\mid H<% if (!single) { %><%= \'_\' + num %><% } %>.b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.evidence %>\' is true given that \'<%= labels.hypothesis %>\' is true and the background evidence',
                    disabled: false
                }, {
                    name: 'enhb',
                    label: '\\(\\mathrm{\\Pr( E \\mid \\neg{H}<% if (!single) { %><%= \'_\' + num %><% } %>.b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.evidence %>\' is true given that \'<%= labels.hypothesis %>\' is false and the background evidence',
                    disabled: false
                }, {
                    name: 'eb',
                    label: '\\(\\mathrm{\\Pr( E \\mid b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.evidence %>\' is true given the background evidence',
                    hint: 'Must be greater than 0',
                    disabled: false
                }, {
                    name: 'heb',
                    label: '\\(\\mathrm{\\Pr( H<% if (!single) { %><%= \'_\' + num %><% } %> \\mid E.b )}\\)',
                    className: '',
                    val: 0,
                    title: 'Probability that \'<%= labels.hypothesis %>\' is true given that \'<%= labels.evidence %>\' is true and the background evidence',
                    disabled: true
                }]
            },
            round: function(num, dec) {
                return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
            },
            add_hypothesis: function(e, $el) {
                if (e) e.preventDefault();
                var $hypotheses_container = ($el || $(this)).closest('form').find('.hypotheses');
                $hypotheses_container.find('.remove').hide();
                $hypotheses_container.append(bayesapp.templates.hypothesis($.extend(bayesapp.template_options, {
                    num: $hypotheses_container.find('.hypothesis').length + 1,
                    single: $hypotheses_container.hasClass('basic')
                })));
                if (MathJax) MathJax.Hub.Queue(["Typeset", MathJax.Hub, $hypotheses_container.get(0)]);
            },
            validate: function($form) {
                var data = $form.serializeObject(),
                    errors = [],
                    i, k, $input;
                $form.find('.error').removeClass('error');
                if (_.isArray(data['eb'])) {
                    for (i = 0; i < data['eb'].length; i++) {
                        errors = [];
                        if (data['enhb'][i] == 0 && (data['hb'][i] * data['ehb'][i]) / data['eb'][i] > 1) {
                            errors.push('hb');
                            errors.push('nhb');
                            errors.push('ehb');
                            errors.push('enhb');
                            errors.push('eb');
                        }
                        if (data['enhb'][i] == 0 && data['eb'][i] <= 0) errors.push('eb');
                        if (errors.length > 0) {
                            for (k in errors) {
                                $form.find('.field-' + errors[k] + ' .inputs:eq(' + i + ') input[name=' + errors[k] + ']').addClass('error');
                            }
                        }
                    }
                }
                else {
                    var $inputs = $form.find('input');
                    if (data['enhb'] == 0 && (data['hb'] * data['ehb']) / data['eb'] > 1) {
                        errors.push('hb');
                        errors.push('nhb');
                        errors.push('ehb');
                        errors.push('enhb');
                        errors.push('eb');
                    }
                    if (data['enhb'] == 0 && data['eb'] <= 0) errors.push('eb');
                    if (errors.length > 0) {
                        for (i in errors) {
                            $inputs.filter('[name=' + errors[i] + ']').addClass('error');
                        }
                    }
                }
            },
            calculate: function(calc) {
                if (calc.enhb > 0) {
                    return (parseFloat(calc.hb) * parseFloat(calc.ehb)) / (parseFloat(calc.hb) * parseFloat(calc.ehb) + parseFloat(calc.nhb) * parseFloat(calc.enhb));
                }
                else {
                    return parseFloat(calc.eb) != 0 ? (parseFloat(calc.hb) * parseFloat(calc.ehb)) / parseFloat(calc.eb) : 0;
                }
            },
            update_calculation: function(e, $this) {
                if (e) e.preventDefault();
                $this = !$this ? $(this) : $this;
                bayesapp.validate($this);
                var data = $this.serializeObject();
                if (_.isArray(data['hb'])) {
                    for (var i = 0; i < data['hb'].length; i++) {
                        $this.find('.field-heb .inputs:eq(' + i + ') span').text(bayesapp.round(bayesapp.calculate({
                            eb: data['eb'][i],
                            ehb: data['ehb'][i],
                            hb: data['hb'][i],
                            heb: data['heb'][i],
                            nhb: data['nhb'][i],
                            enhb: data['enhb'][i],
                        }), 2));
                    }
                }
                else {
                    $this.find('.field-heb .inputs span').text(bayesapp.round(bayesapp.calculate(data), 2));
                }
            },
            update_joined_fields: function($this, type) {
                var $field = $this.closest('.field'),
                    $fields = $field.siblings('.field'),
                    $inputs = $field.find('.inputs'),
                    $input = $this.closest('.inputs'),
                    i = $inputs.index($input);
                $this.siblings('input[type=' + type + ']').val($this.val());
                if ($field.hasClass('field-hb')) {
                    $fields.filter('.field-nhb').find('.inputs:eq(' + i + ') input').val(1 - parseFloat($this.val()));
                }
                if ($field.hasClass('field-nhb')) {
                    $fields.filter('.field-hb').find('.inputs:eq(' + i + ') input').val(1 - parseFloat($this.val()));
                }
                bayesapp.update_calculation(false, $this.closest('form'));
            },
            init: function() {
                $('#tabs').find('a').click(function(e) {
                    e.preventDefault();
                    var $this = $(this);
                    $('#tabs .active').removeClass('active');
                    $this.addClass('active');
                    $('#panels').find('.panel').removeClass('active').eq($('#tabs').find('a').index($this)).addClass('active');
                });
                bayesapp.add_hypothesis(false, $('.basic'));
                //$('.add_hypothesis').click(bayesapp.add_hypothesis).click();
                $('.a_fortiori').click(function(e) {
                    e.preventDefault();
                    bayesapp.template_options.a_fortiori = !bayesapp.template_options.a_fortiori;
                    var $hypotheses_container = $(this).closest('form').find('.hypotheses'),
                        $hypotheses = $hypotheses_container.find('.hypothesis')
                        $hypotheses.each(function(index) {
                            $(this).replaceWith(bayesapp.templates.hypothesis($.extend(bayesapp.template_options, {
                                num: index + 1,
                                hide_remove: (index + 1) !== $hypotheses.length,
                                single: $hypotheses_container.hasClass('basic')
                            })));
                        });
                    if (MathJax) MathJax.Hub.Queue(["Typeset", MathJax.Hub, $hypotheses_container.get(0)]);
                });
                var $form = $('form');
                $form.delegate('input[type=range]', 'change', function() {
                    bayesapp.update_joined_fields($(this), 'number');
                });
                $form.delegate('input[type=number]', 'change', function() {
                    bayesapp.update_joined_fields($(this), 'range');
                });
                $form.delegate('.remove', 'click', function(event) {
                    event.preventDefault();
                    var $this = $(this),
                        $form = $this.closest('form'),
                        $hypothesis = $this.closest('.hypothesis'),
                        $hypotheses = $hypothesis.siblings('.hypothesis');
                    if ($hypotheses.length > 0) {
                        $hypothesis.remove();
                        $form.find('.remove:last').show();
                    }
                });
                $form.delegate('label[title],input[title],button[title]', 'mouseover', function() {
                    var $this = $(this);
                    if (!$this.data("tooltip")) {
                        $this.tooltip({
                            position: "center right"
                        }).trigger('mouseover');
                    }
                });
                $form.delegate('.set', 'click', function(e) {
                    e.preventDefault();
                    var $this = $(this),
                    $inputs = $this.closest('fieldset').find('input');
                    $inputs.each(function () {
                        var $input = $(this);
                        bayesapp.template_options.labels[$input.attr('name')] = $input.val();
                    });
                    var $hypotheses_container = $this.closest('form').find('.hypotheses');
                    $hypotheses_container.find('.hypothesis').remove();
                    bayesapp.add_hypothesis(false, $hypotheses_container);
                });
            }
        }; //End bayesapp
        bayesapp.init();
    });
}(jQuery, MathJax));<|endoftext|>


<commit_before>
/**
 * --------------------------------------------------
 *
 *  A simple base for JavaScript creative coding
 *  experiments or sketches...
 *
 * --------------------------------------------------
 */

var Sketch;

Sketch = (function() {

    /**
     * requestAnimationFrame polyfill by Erik Möller
     * Fixes from Paul Irish and Tino Zijdel
     *
     * @see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
     * @see http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
     */

    (function(){for(var d=0,a=["ms","moz","webkit","o"],b=0;b<a.length&&!window.requestAnimationFrame;++b)window.requestAnimationFrame=window[a[b]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[a[b]+"CancelAnimationFrame"]||window[a[b]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(b){var a=(new Date).getTime(),c=Math.max(0,16-(a-d)),e=window.setTimeout(function(){b(a+c)},c);d=a+c;return e});window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)})})();

    /**
     * Function.prototype.bind polyfill
     *
     * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
     */

    Function.prototype.bind||(Function.prototype.bind=function(c){if("function"!==typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var a=[].slice,d=a.call(arguments,1),e=this,f=function(){},b=function(){return e.apply(this instanceof f?this:c||{},d.concat(a.call(arguments)))};b.prototype=this.prototype;return b});

    /**
     * --------------------------------------------------
     *
     *  Sketch
     *
     * --------------------------------------------------
     */

    function Sketch( options ) {

        // Provide some useful global properties & methods.
        this._extend( window, this._globals );

        // Merge options with defaults.
        options = this._extend( options || {}, this._defaults );
        this._extend( this, options );

        if ( this.autostart ) {
            this.start();
        }
    }

    Sketch.CANVAS = 'canvas';

    Sketch.prototype = {

        /**
         * --------------------------------------------------
         *
         *  Config
         *
         * --------------------------------------------------
         */

        _globals: {

            PI         : Math.PI,
            TWO_PI     : Math.PI * 2,
            HALF_PI    : Math.PI / 2,
            QUATER_PI  : Math.PI / 4,

            sin        : Math.sin,
            cos        : Math.cos,
            tan        : Math.tan,
            pow        : Math.pow,
            exp        : Math.exp,
            min        : Math.min,
            max        : Math.max,
            sqrt       : Math.sqrt,
            atan       : Math.atan,
            atan2      : Math.atan2,
            ceil       : Math.ceil,
            round      : Math.round,
            floor      : Math.floor,

            random     : function( min, max ) {

                // Allow for random string / array access.
                if ( min && typeof min.length === 'number' && !!min.length ) {
                    return min[ Math.floor( Math.random() * min.length ) ];
                }

                if ( typeof max !== 'number' ) {
                    max = min || 1.0, min = 0;
                }

                return min + Math.random() * (max - min);
            }
        },

        _defaults: {

            type        : Sketch.CANVAS,
            fullscreen  : true,
            autoclear   : true,
            autostart   : true,
            container   : document.body,

            setup       : function() {},
            draw        : function( ctx, dt ) {},
            resize      : function( width, height ) {},
            touchstart  : function( event ) {},
            touchmove   : function( event ) {},
            mousemove   : function( event ) {},
            click       : function( event ) {},
            keydown     : function( event ) {},
            keyup       : function( event ) {}
        },

        /**
         * --------------------------------------------------
         *
         *  Public API
         *
         * --------------------------------------------------
         */

        start: function() {

            // Bind all methods to this scope.
            this._bindAll();

            // Initialise properties.
            this.currentTime = +new Date();
            this.previousTime = this.currentTime;

            this.mouseX = 0.0;
            this.mouseY = 0.0;
            this.oMouseX = 0.0;
            this.oMouseY = 0.0;
            this.touches = [];

            this.ALT = false;
            this.CTRL = false;
            this.SHIFT = false;

            // Create container.
            this.domElement = document.createElement( 'div' );
            this.container.appendChild( this.domElement );

            // Create rendering context.
            switch( this.type ) {

                case Sketch.CANVAS:

                    if ( !!window.CanvasRenderingContext2D ) {

                        this.canvas = document.createElement( 'canvas' );
                        this.ctx = this.canvas.getContext( '2d' );
                        this.domElement.appendChild( this.canvas );

                    } else {

                        throw new Error( 'CanvasRenderingContext2D not supported' );
                    }

                    break;
            }

            // Bind event handlers.
            this._addEvent( this.domElement, 'click', this._onClick );
            this._addEvent( this.domElement, 'mousemove', this._onMouseMove );
            this._addEvent( this.domElement, 'touchstart', this._onTouchStart );
            this._addEvent( this.domElement, 'touchmove', this._onTouchMove );
            this._addEvent( window, 'keydown', this._onKeyDown );
            this._addEvent( window, 'keyup', this._onKeyUp );
            this._addEvent( window, 'resize', this._onResize );

            // Add stats.
            if ( this.stats ) {

                if ( typeof Stats === 'function' ) {

                    this._initStats();

                } else {

                    var script = document.createElement( 'script' );
                    script.setAttribute( 'type', 'text/javascript' );
                    script.setAttribute( 'src', 'https://raw.github.com/mrdoob/stats.js/d5f5aa40a24a6d5667ecbcef20c13c75cf236bcd/build/Stats.js' );
                    script.onload = this.onreadystatechange = this._initStats;

                    document.body.appendChild( script );
                }
            }

            // Initialise.
            this._onResize();
            this.setup();
            this._update( this.currentTime );
        },

        clear: function() {

            switch ( this.type ) {

                case Sketch.CANVAS:

                    this.canvas.width = this.canvas.width;

                    break;
            }
        },

        destroy: function() {

            // Unbind event handlers.
            this._removeEvent( this.domElement, 'click', this._onClick );
            this._removeEvent( this.domElement, 'mousemove', this._onMouseMove );
            this._removeEvent( this.domElement, 'touchstart', this._onTouchStart );
            this._removeEvent( this.domElement, 'touchmove', this._onTouchMove );
            this._removeEvent( window, 'keydown', this._onKeyDown );
            this._removeEvent( window, 'keyup', this._onKeyUp );
            this._removeEvent( window, 'resize', this._onResize );
        },

        /**
         * --------------------------------------------------
         *
         *  Methods
         *
         * --------------------------------------------------
         */

        _extend: function( child, parent ) {

            for ( var prop in parent ) {
                if ( !child.hasOwnProperty( prop ) && parent.hasOwnProperty( prop ) ) {
                    child[ prop ] = parent[ prop ];
                }
            }

            return child;
        },

        _bindAll: function( target, scope ) {

            target = target || this;
            scope = scope || this;

            for ( var prop in target ) {
                if ( typeof target[ prop ] === 'function' ) {
                    target[ prop ] = target[ prop ].bind( scope );
                }
            }
        },

        _addEvent: function( el, ev, fn ) {

            if ( window.addEventListener ) {

                el.addEventListener( ev, fn, false );

            } else if ( window.attachEvent ) {

                el.attachEvent( 'on' + ev, fn );

            } else {

                el[ 'on' + ev ] =  fn;
            }
        },

        _removeEvent: function() {

            if ( window.removeEventListener ) {

                el.removeEventListener( ev, fn, false );

            } else if ( window.detachEvent ) {

                el.detachEvent( 'on' + ev, fn );

            } else {

                el[ 'on' + ev ] =  null;
            }
        },

        _initStats: function() {

            if ( typeof Stats === 'function' ) {

                this._stats = new Stats();
                this._stats.setMode(0);

                this._stats.domElement.style.position = 'absolute';
                this._stats.domElement.style.right = '10px';
                this._stats.domElement.style.top = '10px';

                document.body.appendChild( this._stats.domElement );
            }
        },

        _setMouse: function( x, y ) {

            this.oMouseX = this.mouseX;
            this.oMouseY = this.mouseY;

            this.mouseX = x;
            this.mouseY = y;
        },

        _update: function( time ) {

            if ( this._stats ) {
                this._stats.begin();
            }

            this.previousTime = this.currentTime;
            this.currentTime = time;

            if ( this.autoclear ) {
                this.clear();
            }

            this.draw( this.ctx, this.currentTime - this.previousTime );

            requestAnimationFrame( this._update );

            if ( this._stats ) {
                this._stats.end();
            }
        },

        /**
         * --------------------------------------------------
         *
         *  Event Handlers
         *
         * --------------------------------------------------
         */

        _onResize: function( event ) {

            if ( this.fullscreen ) {

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

            } else {

                this.width = this.width;
                this.height = this.height;
            }

            switch ( this.type ) {

                case Sketch.CANVAS:

                    this.canvas.width = this.width;
                    this.canvas.height = this.height;

                    break;
            }

            this.domElement.style.width = this.width;
            this.domElement.style.height = this.height;

            this.resize( this.width, this.height );
        },

        _onTouchStart: function( event ) {
        },

        _onClick: function( event ) {

            this.click( event );
        },

        _onMouseMove: function( event ) {

            this._setMouse( event.clientX, event.clientY );
            this.mousemove( event );
        },

        _onTouchMove: function( event ) {

            event.preventDefault();

            this.touches = event.touches;
            var touch = this.touches[0];

            this._setMouse( touch.pageX, touch.pageY );
            this.touchmove( event );
            this.mousemove( event );
        },

        _onKeyDown: function( event ) {

            this.key = event.keyCode;
            this.ALT = event.altKey;
            this.CTRL = event.ctrlKey || event.metaKey;
            this.SHIFT = event.shiftKey;

            this.keydown( event );
        },

        _onKeyUp: function( event ) {

            this.key = null;
            this.ALT = this.CTRL = this.SHIFT = false;

            this.keyup( event );
        }
    };

    return Sketch;

})();<commit_msg>Added sketch class and GUID hooks to domElement. #3<commit_after>
/**
 * --------------------------------------------------
 *
 *  A simple base for JavaScript creative coding
 *  experiments or sketches...
 *
 * --------------------------------------------------
 */

var Sketch;

Sketch = (function() {

    /**
     * requestAnimationFrame polyfill by Erik Möller
     * Fixes from Paul Irish and Tino Zijdel
     *
     * @see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
     * @see http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
     */

    (function(){for(var d=0,a=["ms","moz","webkit","o"],b=0;b<a.length&&!window.requestAnimationFrame;++b)window.requestAnimationFrame=window[a[b]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[a[b]+"CancelAnimationFrame"]||window[a[b]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(b){var a=(new Date).getTime(),c=Math.max(0,16-(a-d)),e=window.setTimeout(function(){b(a+c)},c);d=a+c;return e});window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)})})();

    /**
     * Function.prototype.bind polyfill
     *
     * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
     */

    Function.prototype.bind||(Function.prototype.bind=function(c){if("function"!==typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var a=[].slice,d=a.call(arguments,1),e=this,f=function(){},b=function(){return e.apply(this instanceof f?this:c||{},d.concat(a.call(arguments)))};b.prototype=this.prototype;return b});

    /**
     * --------------------------------------------------
     *
     *  Sketch
     *
     * --------------------------------------------------
     */

    function Sketch( options ) {

        // Provide some useful global properties & methods.
        this._extend( window, this._globals );

        // Generate a GUID for thi sketch.
        this.id = 'sketch-' + floor( random( 0xffffff ) );

        // Merge options with defaults.
        options = this._extend( options || {}, this._defaults );
        this._extend( this, options );

        if ( this.autostart ) {
            this.start();
        }
    }

    Sketch.CANVAS = 'canvas';

    Sketch.prototype = {

        /**
         * --------------------------------------------------
         *
         *  Config
         *
         * --------------------------------------------------
         */

        _globals: {

            PI         : Math.PI,
            TWO_PI     : Math.PI * 2,
            HALF_PI    : Math.PI / 2,
            QUATER_PI  : Math.PI / 4,

            sin        : Math.sin,
            cos        : Math.cos,
            tan        : Math.tan,
            pow        : Math.pow,
            exp        : Math.exp,
            min        : Math.min,
            max        : Math.max,
            sqrt       : Math.sqrt,
            atan       : Math.atan,
            atan2      : Math.atan2,
            ceil       : Math.ceil,
            round      : Math.round,
            floor      : Math.floor,

            random     : function( min, max ) {

                // Allow for random string / array access.
                if ( min && typeof min.length === 'number' && !!min.length ) {
                    return min[ Math.floor( Math.random() * min.length ) ];
                }

                if ( typeof max !== 'number' ) {
                    max = min || 1.0, min = 0;
                }

                return min + Math.random() * (max - min);
            }
        },

        _defaults: {

            type        : Sketch.CANVAS,
            fullscreen  : true,
            autoclear   : true,
            autostart   : true,
            container   : document.body,

            setup       : function() {},
            draw        : function( ctx, dt ) {},
            resize      : function( width, height ) {},
            touchstart  : function( event ) {},
            touchmove   : function( event ) {},
            mousemove   : function( event ) {},
            click       : function( event ) {},
            keydown     : function( event ) {},
            keyup       : function( event ) {}
        },

        /**
         * --------------------------------------------------
         *
         *  Public API
         *
         * --------------------------------------------------
         */

        start: function() {

            // Bind all methods to this scope.
            this._bindAll();

            // Initialise properties.
            this.currentTime = +new Date();
            this.previousTime = this.currentTime;

            this.mouseX = 0.0;
            this.mouseY = 0.0;
            this.oMouseX = 0.0;
            this.oMouseY = 0.0;
            this.touches = [];

            this.ALT = false;
            this.CTRL = false;
            this.SHIFT = false;

            // Create container.
            this.domElement = document.createElement( 'div' );
            this.domElement.id = this.id;
            this.domElement.className = 'sketch';
            this.container.appendChild( this.domElement );

            // Create rendering context.
            switch( this.type ) {

                case Sketch.CANVAS:

                    if ( !!window.CanvasRenderingContext2D ) {

                        this.canvas = document.createElement( 'canvas' );
                        this.ctx = this.canvas.getContext( '2d' );
                        this.domElement.appendChild( this.canvas );

                    } else {

                        throw new Error( 'CanvasRenderingContext2D not supported' );
                    }

                    break;
            }

            // Bind event handlers.
            this._addEvent( this.domElement, 'click', this._onClick );
            this._addEvent( this.domElement, 'mousemove', this._onMouseMove );
            this._addEvent( this.domElement, 'touchstart', this._onTouchStart );
            this._addEvent( this.domElement, 'touchmove', this._onTouchMove );
            this._addEvent( window, 'keydown', this._onKeyDown );
            this._addEvent( window, 'keyup', this._onKeyUp );
            this._addEvent( window, 'resize', this._onResize );

            // Add stats.
            if ( this.stats ) {

                if ( typeof Stats === 'function' ) {

                    this._initStats();

                } else {

                    var script = document.createElement( 'script' );
                    script.setAttribute( 'type', 'text/javascript' );
                    script.setAttribute( 'src', 'https://raw.github.com/mrdoob/stats.js/d5f5aa40a24a6d5667ecbcef20c13c75cf236bcd/build/Stats.js' );
                    script.onload = this.onreadystatechange = this._initStats;

                    document.body.appendChild( script );
                }
            }

            // Initialise.
            this._onResize();
            this.setup();
            this._update( this.currentTime );
        },

        clear: function() {

            switch ( this.type ) {

                case Sketch.CANVAS:

                    this.canvas.width = this.canvas.width;

                    break;
            }
        },

        destroy: function() {

            // Unbind event handlers.
            this._removeEvent( this.domElement, 'click', this._onClick );
            this._removeEvent( this.domElement, 'mousemove', this._onMouseMove );
            this._removeEvent( this.domElement, 'touchstart', this._onTouchStart );
            this._removeEvent( this.domElement, 'touchmove', this._onTouchMove );
            this._removeEvent( window, 'keydown', this._onKeyDown );
            this._removeEvent( window, 'keyup', this._onKeyUp );
            this._removeEvent( window, 'resize', this._onResize );
        },

        /**
         * --------------------------------------------------
         *
         *  Methods
         *
         * --------------------------------------------------
         */

        _extend: function( child, parent ) {

            for ( var prop in parent ) {
                if ( !child.hasOwnProperty( prop ) && parent.hasOwnProperty( prop ) ) {
                    child[ prop ] = parent[ prop ];
                }
            }

            return child;
        },

        _bindAll: function( target, scope ) {

            target = target || this;
            scope = scope || this;

            for ( var prop in target ) {
                if ( typeof target[ prop ] === 'function' ) {
                    target[ prop ] = target[ prop ].bind( scope );
                }
            }
        },

        _addEvent: function( el, ev, fn ) {

            if ( window.addEventListener ) {

                el.addEventListener( ev, fn, false );

            } else if ( window.attachEvent ) {

                el.attachEvent( 'on' + ev, fn );

            } else {

                el[ 'on' + ev ] =  fn;
            }
        },

        _removeEvent: function() {

            if ( window.removeEventListener ) {

                el.removeEventListener( ev, fn, false );

            } else if ( window.detachEvent ) {

                el.detachEvent( 'on' + ev, fn );

            } else {

                el[ 'on' + ev ] =  null;
            }
        },

        _initStats: function() {

            if ( typeof Stats === 'function' ) {

                this._stats = new Stats();
                this._stats.setMode(0);

                this._stats.domElement.style.position = 'absolute';
                this._stats.domElement.style.right = '10px';
                this._stats.domElement.style.top = '10px';

                document.body.appendChild( this._stats.domElement );
            }
        },

        _setMouse: function( x, y ) {

            this.oMouseX = this.mouseX;
            this.oMouseY = this.mouseY;

            this.mouseX = x;
            this.mouseY = y;
        },

        _update: function( time ) {

            if ( this._stats ) {
                this._stats.begin();
            }

            this.previousTime = this.currentTime;
            this.currentTime = time;

            if ( this.autoclear ) {
                this.clear();
            }

            this.draw( this.ctx, this.currentTime - this.previousTime );

            requestAnimationFrame( this._update );

            if ( this._stats ) {
                this._stats.end();
            }
        },

        /**
         * --------------------------------------------------
         *
         *  Event Handlers
         *
         * --------------------------------------------------
         */

        _onResize: function( event ) {

            if ( this.fullscreen ) {

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

            } else {

                this.width = this.width;
                this.height = this.height;
            }

            switch ( this.type ) {

                case Sketch.CANVAS:

                    this.canvas.width = this.width;
                    this.canvas.height = this.height;

                    break;
            }

            this.domElement.style.width = this.width;
            this.domElement.style.height = this.height;

            this.resize( this.width, this.height );
        },

        _onTouchStart: function( event ) {
        },

        _onClick: function( event ) {

            this.click( event );
        },

        _onMouseMove: function( event ) {

            this._setMouse( event.clientX, event.clientY );
            this.mousemove( event );
        },

        _onTouchMove: function( event ) {

            event.preventDefault();

            this.touches = event.touches;
            var touch = this.touches[0];

            this._setMouse( touch.pageX, touch.pageY );
            this.touchmove( event );
            this.mousemove( event );
        },

        _onKeyDown: function( event ) {

            this.key = event.keyCode;
            this.ALT = event.altKey;
            this.CTRL = event.ctrlKey || event.metaKey;
            this.SHIFT = event.shiftKey;

            this.keydown( event );
        },

        _onKeyUp: function( event ) {

            this.key = null;
            this.ALT = this.CTRL = this.SHIFT = false;

            this.keyup( event );
        }
    };

    return Sketch;

})();<|endoftext|>


<commit_before>
var access_token = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken();
        getProfileInfo();
        updateView();
      }
    });
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

function getProfileInfo() {
  FB.api('/me?field=name,id', function(response) {
    alert('Successful login for: ' + response.name);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "e perche' fuori nevica ",
    "e perche' PEJO e' un bel paesino ",
    "e perche' sono stanco di scrivere ");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  // $.ajax({
  //   crossDomain: true,
  //   type:'POST',
  //   dataType: 'jsonp',
  //   url: "http://127.0.0.1:8000/project-director/facebook",
  //   data: JSON.stringify(myObject),
  //   success: function(data)
  //   {
  //     var obj = jQuery.parseJSON(data);
  //     alert(obj.id);
  //     alert(obj.fist_name);
  //     alert(obj.image_url);
  //     // $('body').append(data);
  //     // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
  //     //   $('#form-send-message').addClass('form-send-errors')
  //     // }
  //     // else {
  //     //   $('#form-send-message').addClass('form-send-success');
  //     // }
  //   }//,
  //   // error: function(error) {
  //   //   alert(error);
  //   // }
  // });

  $.getJSON("http://127.0.0.1:8000/project-director/facebook?callback=?&token=" + access_token, function(result){
    //response data are now in the result variable
    var obj = jQuery.parseJSON(result);
    alert(obj.info.id);
    alert(obj.info.first_name);
    alert(obj.image.image_url);
  });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('#title').text("Hi Roberto. Insert your health profile!");
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<commit_msg>commit for heroku<commit_after>
var access_token = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken();
        getProfileInfo();
        updateView();
      }
    });
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

function getProfileInfo() {
  FB.api('/me?field=name,id', function(response) {
    alert('Successful login for: ' + response.name);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "e perche' fuori nevica ",
    "e perche' PEJO e' un bel paesino ",
    "e perche' sono stanco di scrivere ");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  // $.ajax({
  //   crossDomain: true,
  //   type:'POST',
  //   dataType: 'jsonp',
  //   url: "http://127.0.0.1:8000/project-director/facebook",
  //   data: JSON.stringify(myObject),
  //   success: function(data)
  //   {
  //     var obj = jQuery.parseJSON(data);
  //     alert(obj.id);
  //     alert(obj.fist_name);
  //     alert(obj.image_url);
  //     // $('body').append(data);
  //     // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
  //     //   $('#form-send-message').addClass('form-send-errors')
  //     // }
  //     // else {
  //     //   $('#form-send-message').addClass('form-send-success');
  //     // }
  //   }//,
  //   // error: function(error) {
  //   //   alert(error);
  //   // }
  // });

  $.getJSON("http://127.0.0.1:8000/project-director/facebook?callback=?&token=" + access_token, function(result){
    //response data are now in the result variable
    console.log(result);
    var obj = jQuery.parseJSON(result);
    console.log("parsed");
    console.log(obj.info);
    console.log(obj.info.first_name);
    console.log(obj.image.image_url);
  });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('#title').text("Hi Roberto. Insert your health profile!");
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<|endoftext|>