<commit_before>(function (ns) {
    'use strict';

    ns.BedTime = function (time) {
        this.time = time || '00:00';

        this.inMinutes = (function (that) {
            var time = that.time;
            var index = time.indexOf(':');

            var total = 0;
            total += parseInt(time.slice(-index), 10);          // minutes
            total += parseInt(time.slice(0, index), 10) * 60;   // hrs in mins

            return total;
        }(this));

        this.angle = (function (that) {
            return (2 * Math.PI * that.inMinutes) / (24 * 60);
        }(this));
    };
})(TrueColours);
<commit_msg>example code of what a Jasmine based unit test would look like<commit_after>(function (ns) {
    'use strict';

    ns.BedTime = function (time) {
        this.time = time || '00:00';

        this.inMinutes = (function (that) {
            var time = that.time;
            var index = time.indexOf(':');

            var total = 0;
            total += parseInt(time.slice(-index), 10);          // minutes
            total += parseInt(time.slice(0, index), 10) * 60;   // hrs in mins

            return total;
        }(this));

        this.angle = (function (that) {
            return (2 * Math.PI * that.inMinutes) / (24 * 60);
        }(this));
    };
})(TrueColours);

//
//describe("unit tests for getCircularMean() function", function () {
//    beforeEach(function () {
//        ga = function () {};  // mock-out any Google Analytics dependencies
//    });
//
//    it("should return the average time for a set of sleep-times", function () {
//        // build input data
//        var sleepTimes = [ '23:00', '22:30', '23:15', '01:30', '22:00' ];
//
//        var expected = '23:14';
//        var returned = TrueColours.Helpers.getCircularMean(sleepTimes);
//
//        // test the result
//        expect(returned).toBe.(expected);
//    });
//});
<|endoftext|>


<commit_before>/**
 * @license RequireJS order 1.0.0 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/requirejs for details
 */
/*jslint nomen: false, plusplus: false, strict: false */
/*global require: false, define: false, window: false, document: false,
  setTimeout: false */

//Specify that requirejs optimizer should wrap this code in a closure that
//maps the namespaced requirejs API to non-namespaced local variables.
/*requirejs namespace: true */

(function () {

    //Sadly necessary browser inference due to differences in the way
    //that browsers load and execute dynamically inserted javascript
    //and whether the script/cache method works when ordered execution is
    //desired. Currently, Gecko and Opera do not load/fire onload for scripts with
    //type="script/cache" but they execute injected scripts in order
    //unless the 'async' flag is present.
    //However, this is all changing in latest browsers implementing HTML5
    //spec. With compliant browsers .async true by default, and
    //if false, then it will execute in order. Favor that test first for forward
    //compatibility.
    var testScript = typeof document !== "undefined" &&
                 typeof window !== "undefined" &&
                 document.createElement("script"),

        supportsInOrderExecution = testScript && (testScript.async ||
                               ((window.opera &&
                                 Object.prototype.toString.call(window.opera) === "[object Opera]") ||
                               //If Firefox 2 does not have to be supported, then
                               //a better check may be:
                               //('mozIsLocallyAvailable' in window.navigator)
                               ("MozAppearance" in document.documentElement.style))),

        //This test is true for IE browsers, which will load scripts but only
        //execute them once the script is added to the DOM.
        supportsLoadSeparateFromExecute = testScript &&
                                          testScript.readyState === 'uninitialized',

        readyRegExp = /^(complete|loaded)$/,
        cacheWaiting = [],
        cached = {},
        scriptNodes = {},
        scriptWaiting = [];

    //Done with the test script.
    testScript = null;

    //Callback used by the type="script/cache" callback that indicates a script
    //has finished downloading.
    function scriptCacheCallback(evt) {
        var node = evt.currentTarget || evt.srcElement, i,
            moduleName, resource;

        if (evt.type === "load" || readyRegExp.test(node.readyState)) {
            //Pull out the name of the module and the context.
            moduleName = node.getAttribute("data-requiremodule");

            //Mark this cache request as loaded
            cached[moduleName] = true;

            //Find out how many ordered modules have loaded
            for (i = 0; (resource = cacheWaiting[i]); i++) {
                if (cached[resource.name]) {
                    resource.req([resource.name], resource.onLoad);
                } else {
                    //Something in the ordered list is not loaded,
                    //so wait.
                    break;
                }
            }

            //If just loaded some items, remove them from cacheWaiting.
            if (i > 0) {
                cacheWaiting.splice(0, i);
            }

            //Remove this script tag from the DOM
            //Use a setTimeout for cleanup because some older IE versions vomit
            //if removing a script node while it is being evaluated.
            setTimeout(function () {
                node.parentNode.removeChild(node);
            }, 15);
        }
    }

    /**
     * Used for the IE case, where fetching is done by creating script element
     * but not attaching it to the DOM. This function will be called when that
     * happens so it can be determined when the node can be attached to the
     * DOM to trigger its execution.
     */
    function onFetchOnly(node) {
        var i, loadedNode, resourceName;

        //Mark this script as loaded.
        node.setAttribute('data-orderloaded', 'loaded');

        //Cycle through waiting scripts. If the matching node for them
        //is loaded, and is in the right order, add it to the DOM
        //to execute the script.
        for (i = 0; (resourceName = scriptWaiting[i]); i++) {
            loadedNode = scriptNodes[resourceName];
            if (loadedNode &&
                loadedNode.getAttribute('data-orderloaded') === 'loaded') {
                delete scriptNodes[resourceName];
                require.addScriptToDom(loadedNode);
            } else {
                break;
            }
        }

        //If just loaded some items, remove them from waiting.
        if (i > 0) {
            scriptWaiting.splice(0, i);
        }
    }

    define({
        version: '1.0.0',

        load: function (name, req, onLoad, config) {
            var url = req.nameToUrl(name, null),
                node, context;

            //Make sure the async attribute is not set for any pathway involving
            //this script.
            require.s.skipAsync[url] = true;
            if (supportsInOrderExecution || config.isBuild) {
                //Just a normal script tag append, but without async attribute
                //on the script.
                req([name], onLoad);
            } else if (supportsLoadSeparateFromExecute) {
                //Just fetch the URL, but do not execute it yet. The
                //non-standards IE case. Really not so nice because it is
                //assuming and touching requrejs internals. OK though since
                //ordered execution should go away after a long while.
                context = require.s.contexts._;

                if (!context.urlFetched[url] && !context.loaded[name]) {
                    //Indicate the script is being fetched.
                    context.urlFetched[url] = true;

                    //Stuff from require.load
                    require.resourcesReady(false);
                    context.scriptCount += 1;

                    //Fetch the script now, remember it.
                    node = require.attach(url, context, name, null, null, onFetchOnly);
                    scriptNodes[name] = node;
                    scriptWaiting.push(name);
                }

                //Do a normal require for it, once it loads, use it as return
                //value.
                req([name], onLoad);
            } else {
                //Credit to LABjs author Kyle Simpson for finding that scripts
                //with type="script/cache" allow scripts to be downloaded into
                //browser cache but not executed. Use that
                //so that subsequent addition of a real type="text/javascript"
                //tag will cause the scripts to be executed immediately in the
                //correct order.
                if (req.specified(name)) {
                    req([name], onLoad);
                } else {
                    cacheWaiting.push({
                        name: name,
                        req: req,
                        onLoad: onLoad
                    });
                    require.attach(url, null, name, scriptCacheCallback, "script/cache");
                }
            }
        }
    });
}());
<commit_msg>Not using order after all<commit_after><|endoftext|>


<commit_before>/**
 * Author: wxwdesign@gmail.com
 * Source: https://github.com/wahaha2012/ads-cleaner-extension
 */
(function () {
    var tabURL = window.location.href,
        cleanKey = '',
        autoCleanRules = ['jisilu.cn','xueqiu.com','eastmoney.com'],
        clearRules = {
            'blog.sina.com.cn/s': function(){
                // cleanDomBySelector(".sinaad-toolkit-box,.popBox,.godreply,.sinaads,.blogreco,#column_1");
                document.body.innerHTML = document.querySelector('#module_920_SG_connBody').innerHTML;
                document.body.style.cssText = 'background:#4d4d4d;color:#c1c1c1';
                document.querySelector('.articalContent,.BNE_cont').style.cssText = 'margin:0 auto;';
            },
            'eastmoney.com': function(request){
                if(request && request.cleanAds){
                    cleanDomBySelector(".lbadbox,.rbadbox,iframe");
                }

                if(request && request.cleanStartup){
                    var table = document.querySelectorAll("#dt_1 tr");
                    Array.prototype.forEach.call(table, function(item){
                        var tds = item.querySelectorAll("td");
                        if(tds.length < 1){return;}
                        if(tds[0] && tds[0].innerText && tds[0].innerText.replace(/\s+/g,'').indexOf("3")==0){
                            item.style.cssText="display:none";
                        }
                    });
                }

                if (~window.location.href.indexOf('PC_HSF10')) {
                    var F10Table = document.querySelector('#F10MainTargetDiv');
                    if (F10Table) { F10Table.style.cssText = 'height: auto'; }
                    document.querySelector('#RightMenu').style.display = 'none';
                    document.querySelector('.header').style.position = 'static';
                    document.querySelector('.subnav').style.position = 'static';
                }
            },
            'iteye.com': function(){
                cleanDomBySelector("iframe");
            },
            'stock.hexun.com': function(){
                cleanDomBySelector(".box15_ad,#topFullWidthBanner,#list4_ad,#BannerMiddle_01,#BannerMiddle_02");

                Array.prototype.forEach.call(document.querySelectorAll('.adcLoadingTip'),function(item){
                    item.style.cssText="display:none";
                    nextNode = item.nextSlbling||item.nextElementSibling;
                    nextNode.style.cssText="display:none";
                });
            },
            'chinaz.com':function(){
                cleanDomBySelector("iframe,.mt10,.mb10,.mtb20,.otherContent_01,.ml10,.sideAdList");
            },
            'jisilu.cn':function(){
                cleanDomBySelector("div.foot_ad");
                var adsBanner = document.querySelector('a.jsl_ad_banner').parentNode;
                if (adsBanner) {
                    adsBanner.style.cssText="display:none"
                }
            },
            'xueqiu.com':function(){
                cleanDomBySelector('.nav__logo');
                setStyles('.nav', {position: 'absolute'});

                var symbol = window.location.href.toLowerCase().match(/s[hz]\d{6}/);
                if (symbol && Object.prototype.toString.call(symbol).slice(8, -1) === 'Array') {
                    var stockTabs = document.querySelector('.stock-timeline-tabs');
                    var financeLink = document.createElement('a');

                    financeLink.innerHTML = '财务';
                    financeLink.setAttribute('href', 'http://emweb.securities.eastmoney.com/PC_HSF10/NewFinanceAnalysis/Index?code=' + symbol);
                    financeLink.setAttribute('target', '_blank');
                    stockTabs.appendChild(financeLink);
                }
            }
        };

    function cleanDomBySelector(selector){
        Array.prototype.forEach.call(document.querySelectorAll(selector),function(item){
            item.style.cssText="display:none";
        });
    }

    function setStyles(selector, options) {
        const cssText = [];
        for(var key in options) {
            cssText.push(key + ':' + options[key]);
        }
        Array.prototype.forEach.call(document.querySelectorAll(selector),function(item){
            item.style.cssText = cssText.join(';');
        });
    }

    function init(){
        for(var key in clearRules){
            if(clearRules.hasOwnProperty(key) && tabURL.indexOf(key)>-1){
                cleanKey = key;
                if (autoCleanRules.includes(key)) {
                    try{
                        clearRules[key]();
                    }catch(err){
                        console.log('err=>', err);
                    }
                }

                chrome.extension.sendMessage({
                    showContextMenu: true
                });
                break;
            }
        }
    }

    chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
        if(request){
            clearRules[cleanKey](request);
        }
    });

    init();
})();<commit_msg>update links<commit_after>/**
 * Author: wxwdesign@gmail.com
 * Source: https://github.com/wahaha2012/ads-cleaner-extension
 */
(function () {
    var tabURL = window.location.href,
        cleanKey = '',
        autoCleanRules = ['jisilu.cn','xueqiu.com','eastmoney.com'],
        clearRules = {
            'blog.sina.com.cn/s': function(){
                // cleanDomBySelector(".sinaad-toolkit-box,.popBox,.godreply,.sinaads,.blogreco,#column_1");
                document.body.innerHTML = document.querySelector('#module_920_SG_connBody').innerHTML;
                document.body.style.cssText = 'background:#4d4d4d;color:#c1c1c1';
                document.querySelector('.articalContent,.BNE_cont').style.cssText = 'margin:0 auto;';
            },
            'eastmoney.com': function(request){
                if(request && request.cleanAds){
                    cleanDomBySelector(".lbadbox,.rbadbox,iframe");
                }

                if(request && request.cleanStartup){
                    var table = document.querySelectorAll("#dt_1 tr");
                    Array.prototype.forEach.call(table, function(item){
                        var tds = item.querySelectorAll("td");
                        if(tds.length < 1){return;}
                        if(tds[0] && tds[0].innerText && tds[0].innerText.replace(/\s+/g,'').indexOf("3")==0){
                            item.style.cssText="display:none";
                        }
                    });
                }

                if (~window.location.href.indexOf('PC_HSF10')) {
                    var F10Table = document.querySelector('#F10MainTargetDiv');
                    if (F10Table) { F10Table.style.cssText = 'height: auto'; }
                    document.querySelector('#RightMenu').style.display = 'none';
                    document.querySelector('.header').style.position = 'static';
                    document.querySelector('.subnav').style.position = 'static';
                }
            },
            'iteye.com': function(){
                cleanDomBySelector("iframe");
            },
            'stock.hexun.com': function(){
                cleanDomBySelector(".box15_ad,#topFullWidthBanner,#list4_ad,#BannerMiddle_01,#BannerMiddle_02");

                Array.prototype.forEach.call(document.querySelectorAll('.adcLoadingTip'),function(item){
                    item.style.cssText="display:none";
                    nextNode = item.nextSlbling||item.nextElementSibling;
                    nextNode.style.cssText="display:none";
                });
            },
            'chinaz.com':function(){
                cleanDomBySelector("iframe,.mt10,.mb10,.mtb20,.otherContent_01,.ml10,.sideAdList");
            },
            'jisilu.cn':function(){
                cleanDomBySelector("div.foot_ad");
                var adsBanner = document.querySelector('a.jsl_ad_banner').parentNode;
                if (adsBanner) {
                    adsBanner.style.cssText="display:none"
                }
            },
            'xueqiu.com':function(){
                cleanDomBySelector('.nav__logo');
                setStyles('.nav', {position: 'absolute'});

                var symbol = window.location.href.toLowerCase().match(/s[hz]\d{6}/);
                if (symbol && Object.prototype.toString.call(symbol).slice(8, -1) === 'Array') {
                    var stockTabs = document.querySelector('.stock-timeline-tabs');
                    var financeLink = document.createElement('a');

                    financeLink.innerHTML = '财务';
                    financeLink.setAttribute('href', 'http://emweb.securities.eastmoney.com/PC_HSF10/NewFinanceAnalysis/Index?code=' + symbol);
                    financeLink.setAttribute('target', '_blank');
                    stockTabs.appendChild(financeLink);

                    var valueGoLink = document.createElement('a');
                    valueGoLink.innerHTML = '指标';
                    valueGoLink.setAttribute('href', 'https://wayougou.com/stock/' + String(symbol).replace(/[a-z]+/, '') + '/outline/outline');
                    valueGoLink.setAttribute('target', '_blank');
                    stockTabs.appendChild(valueGoLink);
                }
            }
        };

    function cleanDomBySelector(selector){
        Array.prototype.forEach.call(document.querySelectorAll(selector),function(item){
            item.style.cssText="display:none";
        });
    }

    function setStyles(selector, options) {
        const cssText = [];
        for(var key in options) {
            cssText.push(key + ':' + options[key]);
        }
        Array.prototype.forEach.call(document.querySelectorAll(selector),function(item){
            item.style.cssText = cssText.join(';');
        });
    }

    function init(){
        for(var key in clearRules){
            if(clearRules.hasOwnProperty(key) && tabURL.indexOf(key)>-1){
                cleanKey = key;
                if (autoCleanRules.includes(key)) {
                    try{
                        clearRules[key]();
                    }catch(err){
                        console.log('err=>', err);
                    }
                }

                chrome.extension.sendMessage({
                    showContextMenu: true
                });
                break;
            }
        }
    }

    chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
        if(request){
            clearRules[cleanKey](request);
        }
    });

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


<commit_before>// Get the element
var add = document.getElementById('addToCartButton');
var addplus = document.getElementsByClassName('plussign');
var a1 = document.getElementById('a1');
var sq1 = document.getElementById('square1');
var plus1 = document.getElementById('plus1');
var minus1 = document.getElementById('minus1');
var order = 0;

//Add element to cart from detailed view
add.onclick = function(event) {
	if(event.target == add) {
		order += 1;
		sq1.style.display = 'block';
		a1.innerHTML = order;
		menuModal.style.display = "none";
		//TODO send json details about the beer to cart
	}
}

//Add element to cart from card view
function addElementToCart(){
	for(var i = 0, length = addplus.length; i < length; i++) {
		addplus[i].onclick = function(event) {
				order += 1;
				sq1.style.display = 'block';
				a1.innerHTML = order;
				//TODO send json details about the beer to cart
		}
	}
}

addElementToCart();
/*Add another of this item to the cart.
/*Limit is 10. */
plus1.onclick = function(event) {
	if(event.target == plus1 && order < 10) {
		order += 1;
		a1.innerHTML = order;
	}
	else if(event.target == plus1 && order >= 10) {
		alert("Maximum drink limit had been reached");
	}
}

/*Remove one of this item from the cart.
/*If number goes below 0, the drink is removed from view*/
minus1.onclick = function(event) {
	if(event.target == minus1 && order > 0) {
		order -= 1;
		a1.innerHTML = order;
	}

	else if(event.target == minus1 && order == 0) {
		sq1.style.display = 'none';
	}
}

//TODO
//onclick add new square for different beers;
//If same beer ordered, add to above square1
//If new drink, display square 2 and add to that, etc.
<commit_msg>Fix adding to cart max no.<commit_after>// Get the element
var add = document.getElementById('addToCartButton');
var addplus = document.getElementsByClassName('plussign');
var a1 = document.getElementById('a1');
var sq1 = document.getElementById('square1');
var plus1 = document.getElementById('plus1');
var minus1 = document.getElementById('minus1');
var order = 0;

//Add element to cart from detailed view
add.onclick = function(event) {
	if(event.target == add) {
		if(order < 10) {
			order += 1;
			sq1.style.display = 'block';
			a1.innerHTML = order;
			menuModal.style.display = "none";
			//TODO send json details about the beer to cart
		}
		else {
			alert("Maximum drink limit had been reached");
			menuModal.style.display = "none";
		}
	}
}

//Add element to cart from card view
function addElementToCart(){
	for(var i = 0, length = addplus.length; i < length; i++) {
		addplus[i].onclick = function(event) {
			if(order < 10) {
				order += 1;
				sq1.style.display = 'block';
				a1.innerHTML = order;
				//TODO send json details about the beer to cart
			}
			else {
				alert("Maximum drink limit had been reached");
			}
		}
	}
}

addElementToCart();
/*Add another of this item to the cart.
/*Limit is 10. */
plus1.onclick = function(event) {
	if(event.target == plus1 && order < 10) {
		order += 1;
		a1.innerHTML = order;
	}
	else if(event.target == plus1 && order >= 10) {
		alert("Maximum drink limit had been reached");
	}
}

/*Remove one of this item from the cart.
/*If number goes below 0, the drink is removed from view*/
minus1.onclick = function(event) {
	if(event.target == minus1 && order > 0) {
		order -= 1;
		a1.innerHTML = order;
	}

	else if(event.target == minus1 && order == 0) {
		sq1.style.display = 'none';
	}
}

//TODO
//onclick add new square for different beers;
//If same beer ordered, add to above square1
//If new drink, display square 2 and add to that, etc.
<|endoftext|>


<commit_before>var PADDLE_LENGHT = 100;
var speedX = 0;
var speedY = 3;
var score = [0, 0, 0, 0];

var webrtc = new SimpleWebRTC({
	// we don't do video
	localVideoEl: '',
	remoteVideosEl: '',
	// dont ask for camera access
	autoRequestMedia: false,
	// dont negotiate media
	receiveMedia: {
		mandatory: {
			OfferToReceiveAudio: false,
			OfferToReceiveVideo: false
		}
	}
});

var positions = [];
var players = [];

// join without waiting for media
webrtc.joinRoom('marco');

// called when a peer is created
webrtc.on('createdPeer', function (peer) {
	console.log('createdPeer', peer);
	var div = document.getElementById("peers");
	var channel = peer.getDataChannel("message");
	var allPeers = webrtc.webrtc.peers;
	peer.on('channelClose', function (channel, error) {
		console.log("Losed data channel", channel, error);
		console.log("Should remove player");
		location.reload();
	});

	//handle incoming data
	peer.on('channelMessage', function (peer, channel, msg) {
		// check type, has to be json
		if(msg.type === "json"){
			doStuff(peer, msg.payload);
		}
	});

	//sendPeer(peer, {msg: "Hi, im Player " + webrtc.connection.getSessionid(), job: "init", positions: positions});
	//addPlayer(peer);
	//stage.update();
	if(allPeers.length === 3){
		console.log("Ready to play");
		initGame();
	}

	div.innerHTML = "";
	for (var i = 0; i < allPeers.length; i++)
		div.innerHTML += allPeers[i].id + "
";
});

webrtc.on('joinedRoom', function (room) {
	console.log("entered room " + room);
	//addPlayer(webrtc.connection.getSessionid());
	//stage.update();
});

//send a json to a peer
function sendPeer(peer, data){
	//create data channel
	var channel = peer.getDataChannel("message");

	var isOpen = peer.sendDirectly("message", "json", data);
	if(isOpen){}
	//console.log("Data send");
	else{
		//retry when channel is open
		var saveOldOnopen = channel.onopen;
		channel.onopen = function() {
			sendPeer(peer, data);
			channel.onopen = saveOldOnopen;
		}
		console.log("Problem sending data");
	}
}

//send a json to all peers
function sendAll(data){
	var peers = webrtc.webrtc.peers;
	for (var i = 0; i < peers.length; i++) {
		sendPeer(peers[i], data);
	}
}

function initGame(){
	players = [];
	choosePositon();
}

function choosePositon(){
	var rnd = Math.floor(Math.random() * 100) + 1;
	var myId = webrtc.connection.getSessionid();
	players.push({id: myId, rnd: rnd});
	sendAll({msg: "Hi, im Player " + rnd, job: "posInit", rnd: rnd});
	console.log(rnd);
}

function sortPlacePlayer(){
	//Sort Player list
	console.log(players);
	players.sort(function (a, b) {
		if (a.rnd  b.rnd) return 1;
		if (a.rnd === b.rnd) return 0;
	});
	//Place player
	for(var i = 0; i < players.length; i++){
		players[i].element = addPlayer(players[i].id);
		players[i].vertical = (i % 2 == 0)? true: false;
	}
	//stage.update();

}

function doStuff(peer, data){
	switch (data.job) {
		case "posInit":
			players.push({id: peer.id, rnd: data.rnd});
			if(players.length === 4 && !stage) {
				stage = new createjs.Stage("demoCanvas");
				sortPlacePlayer();
				startGame();
			}
			break;
		case "move":
			//console.log(data);
			repositionPaddle(peer.id, data.position);
			break;
		default:
			console.log(data);
	}
	//y = data.y;
	//console.log(y);
}

var y = 0;
var stage;

//createjs
function init() {

}

function startGame() {
	console.log("Start Game");
	//litle delay before game start
	window.setTimeout(function() {
		gameLoop();
	}, 100);
}

function gameLoop() {
	var ball = new createjs.Shape();
	ball.graphics.beginFill("Crimson").drawCircle(0, 0, 10);
	ball.x = stage.canvas.width / 2;
	ball.y = stage.canvas.height / 2;
	//ball.snapToPixel = false;
	stage.addChild(ball);
	//stage.update();
	 var scoreText = new createjs.Text("0,0,0,0", "30px Arial", "#fff");
	scoreText.x = stage.canvas.width / 2;
	scoreText.y = stage.canvas.height / 2;
	scoreText.textAlign = "center";
	scoreText.textBaseline = "middle";
	stage.addChild(scoreText);

	console.log(ball);
	ball.checkCollision = function(a) {
			var b = {x: this.x, y: this.y, width: 20, height: 20};
			//vertical check
			if (b.x - b.width/2 < a.x + a.width/2 && b.y + b.height/2  a.x - a.width/2 && b.y + b.height/2 > a.y - a.height/2) return true;
			//horizontal check
			if (b.x + b.width/2 > a.x - a.width/2 && b.x - b.width/2 < a.x + a.width/2 && b.y - b.height/2  a.y - a.height/2) return true;
			return false;
}
	createjs.Ticker.setFPS(30);

	createjs.Ticker.addEventListener("tick", handleTick);
	function handleTick(event) {
		// Actions carried out each tick (aka frame)
		if (!event.paused) {
			// Actions carried out when the Ticker is not paused.
			var maxWidth = stage.canvas.width;
			var maxHeight = stage.canvas.height;
			//console.log(ball.x, ball.y)
			//collision detection
			for (var i = 0; i < stage.children.length && !collision; i++) {
				if(stage.children[i].playerId)
				var collision = ball.checkCollision(stage.children[i]);
			}
			if (collision) {
				console.log("collision");
				speedX *= -1;
				speedY *= -1;
			}

			var hitWall = false;
			//All 4 walls
			var wall = 10;
			if (ball.x + speedX > maxWidth - wall) {
				score[2]++;
				speedX *= -1;
				hitWall = true;
			}
			if (ball.x + speedX < 0 + wall) {
				score[0]++;
				speedX *= -1;
				hitWall = true;
			}
 			if (ball.y + speedY > maxHeight - wall) {
				score[1]++;
				speedY *= -1;
				hitWall = true;
			}
			if (ball.y + speedY < 0 + wall) {
				score[3]++;
				speedY *= -1;
				hitWall = true;
			}

			if(hitWall) {
				scoreText.text = score;
			}
				ball.x += speedX;
				ball.y += speedY;
			stage.update();
		}

	}
}

function checkState() {
	console.log("Hello");
}

function addPlayer(id) {
	console.log("Add player " + id);
	player = new createjs.Shape();
	var pos = findNextPostion();
	if (pos) {
		if (pos.vertical === true) {
			player.graphics.beginFill("DeepSkyBlue").drawRect(-(PADDLE_LENGHT/2), -10/2, PADDLE_LENGHT, 10);
			player.width = PADDLE_LENGHT;
			player.height = 10;
		}
		else {
			player.graphics.beginFill("Crimson").drawRect(-10/2, -(PADDLE_LENGHT/2), 10, PADDLE_LENGHT);
			player.width = 10;
			player.height = PADDLE_LENGHT;
		}
		player.playerId = id;
		player.x = pos.x;
		player.y = pos.y;
		stage.addChild(player);
		console.log(player.width);
		return player;
	}
}

function findNextPostion() {
	var nextPos = stage.children.length;
	if (nextPos < 4) {
		var x, y;
		var width = stage.canvas.width;
		var height = stage.canvas.height;
		var vertical = false;

		switch (nextPos) {
			case 0: x = 5; y = height/2;	break;
			case 1: x = width/2; y = 5; vertical = true;	break;
			case 2: x = width - 5; y = height/2;	break;
			case 3: x = width/2; y = height - 5;	vertical = true; break;
		}
		return {x: x, y: y, vertical: vertical};
	}
	return undefined;
}
function repositionPaddle(peerId, position) {
	var peer = findPaddleToMove(peerId);
			peer.element.x = position.x;
			peer.element.y = position.y;
}

function movePaddle(peerId, direction){
	var step;
	var peer = findPaddleToMove(peerId);
	switch (direction){
		case "up":
			step = -2;
			break;
		case "down":
			step = 2;
			break;
	}

	if(peer.vertical) {
		if(peer.element.y + step - PADDLE_LENGHT/2 > 0 && peer.element.y + step + PADDLE_LENGHT/2 < stage.canvas.height)
			peer.element.y += step;
	}
	else {
		if(peer.element.x + step - PADDLE_LENGHT/2 > 0 && peer.element.x + step + PADDLE_LENGHT/2 < stage.canvas.width)
			peer.element.x += step;
	}
	//stage.update();
	return {x: peer.element.x, y: peer.element.y}
}

function findPaddleToMove(peerId){
	for (var i = 0; i < players.length; i++){
		if (players[i].id === peerId)
			return players[i];
	}
}

//add listener
document.onkeydown = function(e){
	var direction;
	var myId = webrtc.connection.getSessionid();
	switch (e.keyCode){
		//up arrow
		case 38:
				direction = "up"
				sendAll({msg: "Please move my paddle", job: "move", position: movePaddle(myId, direction)});
			break;
			//down arrow
		case 40:
				direction = "down"
				sendAll({msg: "Please move my paddle", job: "move", position: movePaddle(myId, direction)});
			break;
	}
}
<commit_msg>[fix] collison<commit_after>var PADDLE_LENGHT = 100;
var speedX = 5;
var speedY = -5;
var score = [0, 0, 0, 0];

var webrtc = new SimpleWebRTC({
	// we don't do video
	localVideoEl: '',
	remoteVideosEl: '',
	// dont ask for camera access
	autoRequestMedia: false,
	// dont negotiate media
	receiveMedia: {
		mandatory: {
			OfferToReceiveAudio: false,
			OfferToReceiveVideo: false
		}
	}
});

var positions = [];
var players = [];

// join without waiting for media
webrtc.joinRoom('marco');

// called when a peer is created
webrtc.on('createdPeer', function (peer) {
	console.log('createdPeer', peer);
	var div = document.getElementById("peers");
	var channel = peer.getDataChannel("message");
	var allPeers = webrtc.webrtc.peers;
	peer.on('channelClose', function (channel, error) {
		console.log("Losed data channel", channel, error);
		console.log("Should remove player");
		location.reload();
	});

	//handle incoming data
	peer.on('channelMessage', function (peer, channel, msg) {
		// check type, has to be json
		if(msg.type === "json"){
			doStuff(peer, msg.payload);
		}
	});

	//sendPeer(peer, {msg: "Hi, im Player " + webrtc.connection.getSessionid(), job: "init", positions: positions});
	//addPlayer(peer);
	//stage.update();
	if(allPeers.length === 3){
		console.log("Ready to play");
		initGame();
	}

	div.innerHTML = "";
	for (var i = 0; i < allPeers.length; i++)
		div.innerHTML += allPeers[i].id + "
";
});

webrtc.on('joinedRoom', function (room) {
	console.log("entered room " + room);
	//addPlayer(webrtc.connection.getSessionid());
	//stage.update();
});

//send a json to a peer
function sendPeer(peer, data){
	//create data channel
	var channel = peer.getDataChannel("message");

	var isOpen = peer.sendDirectly("message", "json", data);
	if(isOpen){}
	//console.log("Data send");
	else{
		//retry when channel is open
		var saveOldOnopen = channel.onopen;
		channel.onopen = function() {
			sendPeer(peer, data);
			channel.onopen = saveOldOnopen;
		}
		console.log("Problem sending data");
	}
}

//send a json to all peers
function sendAll(data){
	var peers = webrtc.webrtc.peers;
	for (var i = 0; i < peers.length; i++) {
		sendPeer(peers[i], data);
	}
}

function initGame(){
	players = [];
	choosePositon();
}

function choosePositon(){
	var rnd = Math.floor(Math.random() * 100) + 1;
	var myId = webrtc.connection.getSessionid();
	players.push({id: myId, rnd: rnd});
	sendAll({msg: "Hi, im Player " + rnd, job: "posInit", rnd: rnd});
	console.log(rnd);
}

function sortPlacePlayer(){
	//Sort Player list
	console.log(players);
	players.sort(function (a, b) {
		if (a.rnd  b.rnd) return 1;
		if (a.rnd === b.rnd) return 0;
	});
	//Place player
	for(var i = 0; i < players.length; i++){
		players[i].element = addPlayer(players[i].id);
		players[i].vertical = (i % 2 == 0)? true: false;
	}
	//stage.update();

}

function doStuff(peer, data){
	switch (data.job) {
		case "posInit":
			players.push({id: peer.id, rnd: data.rnd});
			if(players.length === 4 && !stage) {
				stage = new createjs.Stage("demoCanvas");
				sortPlacePlayer();
				startGame();
			}
			break;
		case "move":
			//console.log(data);
			repositionPaddle(peer.id, data.position);
			break;
		default:
			console.log(data);
	}
	//y = data.y;
	//console.log(y);
}

var y = 0;
var stage;

//createjs
function init() {

}

function startGame() {
	console.log("Start Game");
	//litle delay before game start
	window.setTimeout(function() {
		gameLoop();
	}, 100);
}

function gameLoop() {
	var ball = new createjs.Shape();
	ball.graphics.beginFill("Crimson").drawCircle(0, 0, 10);
	ball.x = stage.canvas.width / 2;
	ball.y = stage.canvas.height / 2;
	//ball.snapToPixel = false;
	stage.addChild(ball);
	//stage.update();
	 var scoreText = new createjs.Text("0,0,0,0", "30px Arial", "#fff");
	scoreText.x = stage.canvas.width / 2;
	scoreText.y = stage.canvas.height / 2;
	scoreText.textAlign = "center";
	scoreText.textBaseline = "middle";
	stage.addChild(scoreText);

	console.log(ball);
	ball.checkCollision = function(a) {
			var b = {x: this.x, y: this.y, width: 20, height: 20};
			//vertical check
			if (b.x - b.width/2 < a.x + a.width/2 && b.y - b.height/2  a.x - a.width/2 && b.y + b.height/2 > a.y - a.height/2) {
				//console.log("first");
			 	return true;
			}
			//horizontal check
			/*if (b.x + b.width/2 > a.x - a.width/2 && b.x - b.width/2 < a.x + a.width/2 && b.y - b.height/2  a.y - a.height/2){
				console.log("secound");
			 	return true;
			}
			*/
			return false;
}
	createjs.Ticker.setFPS(30);

	createjs.Ticker.addEventListener("tick", handleTick);
	function handleTick(event) {
		// Actions carried out each tick (aka frame)
		if (!event.paused) {
			// Actions carried out when the Ticker is not paused.
			var maxWidth = stage.canvas.width;
			var maxHeight = stage.canvas.height;
			//console.log(ball.x, ball.y)
			//collision detection
			for (var i = 0; i < stage.children.length && !collision; i++) {
				if(stage.children[i].playerId)
				var collision = ball.checkCollision(stage.children[i]);
			}
			if (collision) {
				console.log("collision");
				speedX *= -1;
				speedY *= -1;
			}

			var hitWall = false;
			//All 4 walls
			var wall = 10;
			if (ball.x + speedX > maxWidth - wall) {
				score[2]++;
				speedX *= -1;
				hitWall = true;
			}
			if (ball.x + speedX < 0 + wall) {
				score[0]++;
				speedX *= -1;
				hitWall = true;
			}
 			if (ball.y + speedY > maxHeight - wall) {
				score[1]++;
				speedY *= -1;
				hitWall = true;
			}
			if (ball.y + speedY < 0 + wall) {
				score[3]++;
				speedY *= -1;
				hitWall = true;
			}

			if(hitWall) {
				scoreText.text = score;
			}
				ball.x += speedX;
				ball.y += speedY;
			stage.update();
		}

	}
}

function checkState() {
	console.log("Hello");
}

function addPlayer(id) {
	console.log("Add player " + id);
	player = new createjs.Shape();
	var pos = findNextPostion();
	if (pos) {
		if (pos.vertical === true) {
			player.graphics.beginFill("DeepSkyBlue").drawRect(-(PADDLE_LENGHT/2), -10/2, PADDLE_LENGHT, 10);
			player.width = PADDLE_LENGHT;
			player.height = 10;
		}
		else {
			player.graphics.beginFill("Crimson").drawRect(-10/2, -(PADDLE_LENGHT/2), 10, PADDLE_LENGHT);
			player.width = 10;
			player.height = PADDLE_LENGHT;
		}
		player.playerId = id;
		player.x = pos.x;
		player.y = pos.y;
		stage.addChild(player);
		console.log(player.width);
		return player;
	}
}

function findNextPostion() {
	var nextPos = stage.children.length;
	if (nextPos < 4) {
		var x, y;
		var width = stage.canvas.width;
		var height = stage.canvas.height;
		var vertical = false;

		switch (nextPos) {
			case 0: x = 5; y = height/2;	break;
			case 1: x = width/2; y = 5; vertical = true;	break;
			case 2: x = width - 5; y = height/2;	break;
			case 3: x = width/2; y = height - 5;	vertical = true; break;
		}
		return {x: x, y: y, vertical: vertical};
	}
	return undefined;
}
function repositionPaddle(peerId, position) {
	var peer = findPaddleToMove(peerId);
			peer.element.x = position.x;
			peer.element.y = position.y;
}

function movePaddle(peerId, direction){
	var step;
	var peer = findPaddleToMove(peerId);
	switch (direction){
		case "up":
			step = -2;
			break;
		case "down":
			step = 2;
			break;
	}

	if(peer.vertical) {
		if(peer.element.y + step - PADDLE_LENGHT/2 > 0 && peer.element.y + step + PADDLE_LENGHT/2 < stage.canvas.height)
			peer.element.y += step;
	}
	else {
		if(peer.element.x + step - PADDLE_LENGHT/2 > 0 && peer.element.x + step + PADDLE_LENGHT/2 < stage.canvas.width)
			peer.element.x += step;
	}
	//stage.update();
	return {x: peer.element.x, y: peer.element.y}
}

function findPaddleToMove(peerId){
	for (var i = 0; i < players.length; i++){
		if (players[i].id === peerId)
			return players[i];
	}
}

//add listener
document.onkeydown = function(e){
	var direction;
	var myId = webrtc.connection.getSessionid();
	switch (e.keyCode){
		//up arrow
		case 38:
				direction = "up"
				sendAll({msg: "Please move my paddle", job: "move", position: movePaddle(myId, direction)});
			break;
			//down arrow
		case 40:
				direction = "down"
				sendAll({msg: "Please move my paddle", job: "move", position: movePaddle(myId, direction)});
			break;
	}
}
<|endoftext|>


<commit_before>(function($) {
	$(function() {
		$('.form-horizontal').on('submit', function() {
			if ($('#inputStudentNum').val() === "") {
				alert('Please enter username!!');
				return false;
			}

			$.post('/user/login',
			{
				'school_id' : $('#inputStudentNum').val()
			},
			function(response) {
				if (response.status === 0) {
					// Success!
					//console.log(response.data);
					//alert(JSON.stringify(response.data));
					location.href = "index.html";
					//var term = $('#inputStudentNum').val();
				}
				else {
					// Fail.
					alert(response.data);
				}
			}, 'json');

			return false;
		});
	});
})(jQuery);
<commit_msg>fix redirection after login<commit_after>(function($) {
	$(function() {
		$('.form-horizontal').on('submit', function() {
			if ($('#inputStudentNum').val() === "") {
				alert('Please enter username!!');
				return false;
			}

			$.post('/user/login',
			{
				'school_id' : $('#inputStudentNum').val()
			},
			function(response) {
				if (response.status === 0) {
					// Success!
					//console.log(response.data);
					//alert(JSON.stringify(response.data));
					location.href = '/';
					//var term = $('#inputStudentNum').val();
				}
				else {
					// Fail.
					alert(response.data);
				}
			}, 'json');

			return false;
		});
	});
})(jQuery);
<|endoftext|>


<commit_before>(function() {
	'use strict';

	var width = 1280,
		height = 720,
		video = document.querySelector('#video'),
		canvas = createCanvas(),
		capture = document.querySelector('#capture'),
		photo = document.querySelector('#photo'),
		vendorUrl = window.URL || window.webkitURL;

	// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia
	navigator.getUserMedia = navigator.getUserMedia
                           || navigator.webkitGetUserMedia
                           || navigator.mozGetUserMedia
                           || navigator.msGetUserMedia;

	if (navigator.getUserMedia) {
		navigator.getUserMedia({
			video: {
				width: width,
				height: height
			},
			audio: false
		}, function (stream) {
			video.src = vendorUrl.createObjectURL(stream);
			video.onloadedmetadata = function(e) {
	           video.play();
	        };
		}, function (error) {
			console.log(error.message);
		});
	} else {
	   console.log("getUserMedia not supported");
	}

	capture.addEventListener('click', function(e) {
		takepicture();
		e.preventDefault();
	}, false);

	function createCanvas() {
		var e = document.createElement('canvas');
		e.width = width;
		e.height = height;
		return e;
	}

	function takepicture() {
		var context = canvas.getContext('2d');
		if (width && height) {
			canvas.width = width;
			canvas.height = height;
			context.drawImage(video, 0, 0, width, height);
			photo.setAttribute('src', canvas.toDataURL('image/png'));
		} else {
			clearphoto();
		}
	}

	function clearphoto() {
	    var context = canvas.getContext('2d');
	    context.fillStyle = "#AAA";
	    context.fillRect(0, 0, canvas.width, canvas.height);

	    var data = canvas.toDataURL('image/png');
	    photo.setAttribute('src', data);
	}

})();<commit_msg>Add mirror for photo<commit_after>(function() {
	'use strict';

	var width = 1280,
		height = 720,
		video = document.querySelector('#video'),
		canvas = createCanvas(),
		capture = document.querySelector('#capture'),
		photo = document.querySelector('#photo'),
		vendorUrl = window.URL || window.webkitURL;

	// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia
	navigator.getUserMedia = navigator.getUserMedia
                           || navigator.webkitGetUserMedia
                           || navigator.mozGetUserMedia
                           || navigator.msGetUserMedia;

	if (navigator.getUserMedia) {
		navigator.getUserMedia({
			video: {
				width: width,
				height: height
			},
			audio: false
		}, function (stream) {
			video.src = vendorUrl.createObjectURL(stream);
			video.onloadedmetadata = function(e) {
	           video.play();
	        };
		}, function (error) {
			console.log(error.message);
		});
	} else {
	   console.log("getUserMedia not supported");
	}

	capture.addEventListener('click', function(e) {
		takepicture();
		e.preventDefault();
	}, false);

	function createCanvas() {
		var e = document.createElement('canvas');
		e.width = width;
		e.height = height;
		return e;
	}

	function takepicture() {
		var context = canvas.getContext('2d');
		if (width && height) {
			canvas.width = width;
			canvas.height = height;

			context.translate(canvas.width, 0);
			context.scale(-1, 1);

			context.drawImage(video, 0, 0, width, height);
			photo.setAttribute('src', canvas.toDataURL('image/png'));
		} else {
			clearphoto();
		}
	}

	function clearphoto() {
	    var context = canvas.getContext('2d');
	    context.fillStyle = "#AAA";
	    context.fillRect(0, 0, canvas.width, canvas.height);

	    var data = canvas.toDataURL('image/png');
	    photo.setAttribute('src', data);
	}

})();
<|endoftext|>


<commit_before>function closeOnSuccess() {
    setTimeout(function() {
            window.close();
            }, 100);
}

var addCard = function(num, title, bdesc, link) {
    var list = $('#lists_list :selected').val();
    var name = num + " - " + title;
    var desc = link + '\n\n' + bdesc;
    Trello.post("cards", {
        name: name,
        desc: desc,
        idList: list,
        success: closeOnSuccess
    });
}

var getBoards = function(){
    Trello.get("/members/me/boards?filter=open", function(boards) {
        $.each(boards, function(ix, boards) {
            $(new Option(boards.name, boards.id)).appendTo("#board_list");
        });
    });
}

function boardSelected(){
    var board = $('#board_list :selected').val();
    var boardLink = "https://trello.com/board/" + board
    $('#trello-link a').prop('href', boardLink)
    $('#lists_list').find('option').remove();
    if (board == "Select a board") {
        $('#lists_list').append('<option>Select a list</option>');
        $("#add-bug").removeClass("btn-primary");
        $("#add-bug").addClass("disabled");
        $("i").removeClass("icon-white");
    }
    else {
        Trello.get("boards/" + board + "/lists", function(lists) {
            $.each(lists, function(ix, lists) {
                $(new Option(lists.name, lists.id)).appendTo("#lists_list");
            });
        });
        $("#lists_list").val($("#lists_list option:first").val());
        $("#add-bug").addClass("btn-primary");
        $("#add-bug").removeClass("disabled");
        $("i").addClass("icon-white");
    }
}

function onAuthorize() {
    Trello.members.get("me", function(member) {
        $("#fullName").text(member.fullName);
    });
    $('#loggedout').hide();
    $('#loggedin').show();
    getBoards();
}

var logout = function() {
    Trello.deauthorize();
    $('#loggedin').hide();
    $('#loggedout').show();
    $('#lists_list').find('option').remove();
    $('#lists_list').append('<option>Select a list</option>');
    $('#board_list').find('option').remove();
    $('#board_list').append('<option>Select a board</option>');
    $("#add-bug").removeClass("btn-primary");
    $("#add-bug").addClass("disabled");
}

function addGithub(url) {
    var path = url.pathname.split('/');
    var bugNum = path[path.length - 1];
    var bugOwner = path[1];
    var bugRepo = path[2];
    var bugUrl = "https://api.github.com/repos/" + bugOwner + "/" + bugRepo + "/" + "issues/" + bugNum
    bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        dataType: "json",
        success: function (data) {
            var num = bugRepo + ": #" + data.number
            addCard(num, data.title ,data.body, data.html_url)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addBitbucket(url) {
    var path = url.pathname.split('/');
    var bugNum = path[4];
    var bugOwner = path[1];
    var bugRepo = path[2];
    var bugUrl = "https://bitbucket.org/api/1.0/repositories/" + bugOwner + "/" + bugRepo + "/" + "issues/" + bugNum
    bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        dataType: "json",
        success: function (data) {
            var num = bugRepo + ": #" + data.local_id
            addCard(num, data.title ,data.content, url)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addGoogle(url) {
    var path = url.pathname.split('/');
    var bugNum = url.search.split('id=').slice(-1)[0];
    var bugProj = path[2];
    var bugUrl = "https://code.google.com/feeds/issues/p/" + bugProj + "/issues/full?id=" + bugNum
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "xml",
        success: function (data) {
            desc = $(data).find('content').text()
            title = $(data).find("entry").find('title').text();
            var num = bugProj + ": #" + bugNum;
            addCard(num, title, desc, url);
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addLaunchpad(url) {
    var path = url.pathname.split('+bug/').slice(-1)[0];
    var bugNum = path.split('/')[0];
    var bugUrl = "https://api.launchpad.net/1.0/bugs/" + bugNum
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "json",
        success: function (data) {
            var num = "LP: #" + data.id
            addCard(num, data.title ,data.description, data.web_link)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addSourceforge(url) {
    var path = url.pathname.split('/');
    var bugNum = path[4];
    var bugType = path[3];
    var bugProject = path[2];
    var bugUrl = "https://sourceforge.net/rest/p/" + bugProject + "/" + bugType + "/"+ bugNum
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "json",
        success: function (data) {
            var num = "SF: #" + data.ticket.ticket_num
            var url = "https://sourceforge.net/p/" + bugProject + "/" + bugType + "/"+ bugNum
            addCard(num, data.ticket.summary ,data.ticket.description, url)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addDebianBTS(url) {
    var bugNum = url.search.split('bug=').slice(-1)[0];
    console.log(bugNum)
    var bugJson = $.ajax({
        type: "Get",
        url: url,
        crossDomain: true,
        dataType: "html",
        success: function (data) {
            // Get title, removing the trailing " - Debian Bug report"
            var title = $(data).filter('title').text().slice(0, -25);
            var desc = $(data).filter('.message').eq(0).text();
            addCard("BTS", title , desc, url);
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addBugzilla(url) {
    var bugNum = url.search.split('id=').slice(-1)[0];
    var bugOrg = url.hostname.split('.')[1]
    var bugPrefix = url.href.split('show_bug.cgi')[0]
    var bugUrl = bugPrefix + "/jsonrpc.cgi?method=Bug.get&params=[{\"ids\":[" + bugNum + "]}]"
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "json",
        success: function (data) {
            var bugJson = data.result.bugs["0"];
            var num = bugOrg + ": #" + bugJson.id;
            addCard(num, bugJson.summary , "", url);
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function parseLink(tablink) {
    var parser = document.createElement('a');
    parser.href = tablink;
    if(parser.hostname == 'bugs.launchpad.net' && (parser.pathname.indexOf('+bug') > -1)) {
        addLaunchpad(parser);
    }
    else if(parser.hostname == 'github.com' && (parser.pathname.indexOf('issues') > -1)) {
        addGithub(parser);
    }
    else if(parser.hostname == 'bitbucket.org' && (parser.pathname.indexOf('issue') > -1)) {
        addBitbucket(parser);
    }
    else if(parser.hostname == 'sourceforge.net' && (parser.pathname.indexOf('bugs') > -1 || parser.pathname.indexOf('feature-requests') > -1)) {
        addSourceforge(parser);
    }
    else if(parser.pathname.indexOf('show_bug.cgi') > -1) {
        addBugzilla(parser);
    }
    else if(parser.hostname == 'code.google.com' && (parser.pathname.indexOf('detail') > -1)) {
        addGoogle(parser);
    }
    else if(parser.hostname == 'bugs.debian.org' && (parser.pathname.indexOf('bugreport.cgi') > -1)) {
        addDebianBTS(parser);
    }
    else {
        $('#error').show();
    }
}

function addClicked() {
    chrome.tabs.getSelected(null,function(tab) {
        var tablink = tab.url;
        parseLink(tablink)
    });
}

function closePopup() {
    // Close popup and open auth tab
    setTimeout(function() {
        window.close();
        chrome.tabs.create({url: chrome.extension.getURL('settings.html')});
    }, 100);
}

function init() {
    if(!localStorage.trello_token) {
        closePopup();
        return;
    }
    else {
        Trello.authorize({
            interactive:false,
            success: onAuthorize
        });
    }
}

window.addEventListener('load', init);

document.addEventListener('DOMContentLoaded', function () {
    $("#disconnect").click(logout);
    $("#connect").click(init);
    $("#board_list").change(boardSelected);
    $("#add-bug").click(addClicked);
});
<commit_msg>Remove un-needed console.log<commit_after>function closeOnSuccess() {
    setTimeout(function() {
            window.close();
            }, 100);
}

var addCard = function(num, title, bdesc, link) {
    var list = $('#lists_list :selected').val();
    var name = num + " - " + title;
    var desc = link + '\n\n' + bdesc;
    Trello.post("cards", {
        name: name,
        desc: desc,
        idList: list,
        success: closeOnSuccess
    });
}

var getBoards = function(){
    Trello.get("/members/me/boards?filter=open", function(boards) {
        $.each(boards, function(ix, boards) {
            $(new Option(boards.name, boards.id)).appendTo("#board_list");
        });
    });
}

function boardSelected(){
    var board = $('#board_list :selected').val();
    var boardLink = "https://trello.com/board/" + board
    $('#trello-link a').prop('href', boardLink)
    $('#lists_list').find('option').remove();
    if (board == "Select a board") {
        $('#lists_list').append('<option>Select a list</option>');
        $("#add-bug").removeClass("btn-primary");
        $("#add-bug").addClass("disabled");
        $("i").removeClass("icon-white");
    }
    else {
        Trello.get("boards/" + board + "/lists", function(lists) {
            $.each(lists, function(ix, lists) {
                $(new Option(lists.name, lists.id)).appendTo("#lists_list");
            });
        });
        $("#lists_list").val($("#lists_list option:first").val());
        $("#add-bug").addClass("btn-primary");
        $("#add-bug").removeClass("disabled");
        $("i").addClass("icon-white");
    }
}

function onAuthorize() {
    Trello.members.get("me", function(member) {
        $("#fullName").text(member.fullName);
    });
    $('#loggedout').hide();
    $('#loggedin').show();
    getBoards();
}

var logout = function() {
    Trello.deauthorize();
    $('#loggedin').hide();
    $('#loggedout').show();
    $('#lists_list').find('option').remove();
    $('#lists_list').append('<option>Select a list</option>');
    $('#board_list').find('option').remove();
    $('#board_list').append('<option>Select a board</option>');
    $("#add-bug").removeClass("btn-primary");
    $("#add-bug").addClass("disabled");
}

function addGithub(url) {
    var path = url.pathname.split('/');
    var bugNum = path[path.length - 1];
    var bugOwner = path[1];
    var bugRepo = path[2];
    var bugUrl = "https://api.github.com/repos/" + bugOwner + "/" + bugRepo + "/" + "issues/" + bugNum
    bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        dataType: "json",
        success: function (data) {
            var num = bugRepo + ": #" + data.number
            addCard(num, data.title ,data.body, data.html_url)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addBitbucket(url) {
    var path = url.pathname.split('/');
    var bugNum = path[4];
    var bugOwner = path[1];
    var bugRepo = path[2];
    var bugUrl = "https://bitbucket.org/api/1.0/repositories/" + bugOwner + "/" + bugRepo + "/" + "issues/" + bugNum
    bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        dataType: "json",
        success: function (data) {
            var num = bugRepo + ": #" + data.local_id
            addCard(num, data.title ,data.content, url)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addGoogle(url) {
    var path = url.pathname.split('/');
    var bugNum = url.search.split('id=').slice(-1)[0];
    var bugProj = path[2];
    var bugUrl = "https://code.google.com/feeds/issues/p/" + bugProj + "/issues/full?id=" + bugNum
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "xml",
        success: function (data) {
            desc = $(data).find('content').text()
            title = $(data).find("entry").find('title').text();
            var num = bugProj + ": #" + bugNum;
            addCard(num, title, desc, url);
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addLaunchpad(url) {
    var path = url.pathname.split('+bug/').slice(-1)[0];
    var bugNum = path.split('/')[0];
    var bugUrl = "https://api.launchpad.net/1.0/bugs/" + bugNum
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "json",
        success: function (data) {
            var num = "LP: #" + data.id
            addCard(num, data.title ,data.description, data.web_link)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addSourceforge(url) {
    var path = url.pathname.split('/');
    var bugNum = path[4];
    var bugType = path[3];
    var bugProject = path[2];
    var bugUrl = "https://sourceforge.net/rest/p/" + bugProject + "/" + bugType + "/"+ bugNum
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "json",
        success: function (data) {
            var num = "SF: #" + data.ticket.ticket_num
            var url = "https://sourceforge.net/p/" + bugProject + "/" + bugType + "/"+ bugNum
            addCard(num, data.ticket.summary ,data.ticket.description, url)
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addDebianBTS(url) {
    var bugNum = url.search.split('bug=').slice(-1)[0];
    var bugJson = $.ajax({
        type: "Get",
        url: url,
        crossDomain: true,
        dataType: "html",
        success: function (data) {
            // Get title, removing the trailing " - Debian Bug report"
            var title = $(data).filter('title').text().slice(0, -25);
            var desc = $(data).filter('.message').eq(0).text();
            addCard("BTS", title , desc, url);
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function addBugzilla(url) {
    var bugNum = url.search.split('id=').slice(-1)[0];
    var bugOrg = url.hostname.split('.')[1]
    var bugPrefix = url.href.split('show_bug.cgi')[0]
    var bugUrl = bugPrefix + "/jsonrpc.cgi?method=Bug.get&params=[{\"ids\":[" + bugNum + "]}]"
    var bugJson = $.ajax({
        type: "Get",
        url: bugUrl,
        crossDomain: true,
        dataType: "json",
        success: function (data) {
            var bugJson = data.result.bugs["0"];
            var num = bugOrg + ": #" + bugJson.id;
            addCard(num, bugJson.summary , "", url);
        },
        error:  function () {
            $('#error').show();
            }
    });
}

function parseLink(tablink) {
    var parser = document.createElement('a');
    parser.href = tablink;
    if(parser.hostname == 'bugs.launchpad.net' && (parser.pathname.indexOf('+bug') > -1)) {
        addLaunchpad(parser);
    }
    else if(parser.hostname == 'github.com' && (parser.pathname.indexOf('issues') > -1)) {
        addGithub(parser);
    }
    else if(parser.hostname == 'bitbucket.org' && (parser.pathname.indexOf('issue') > -1)) {
        addBitbucket(parser);
    }
    else if(parser.hostname == 'sourceforge.net' && (parser.pathname.indexOf('bugs') > -1 || parser.pathname.indexOf('feature-requests') > -1)) {
        addSourceforge(parser);
    }
    else if(parser.pathname.indexOf('show_bug.cgi') > -1) {
        addBugzilla(parser);
    }
    else if(parser.hostname == 'code.google.com' && (parser.pathname.indexOf('detail') > -1)) {
        addGoogle(parser);
    }
    else if(parser.hostname == 'bugs.debian.org' && (parser.pathname.indexOf('bugreport.cgi') > -1)) {
        addDebianBTS(parser);
    }
    else {
        $('#error').show();
    }
}

function addClicked() {
    chrome.tabs.getSelected(null,function(tab) {
        var tablink = tab.url;
        parseLink(tablink)
    });
}

function closePopup() {
    // Close popup and open auth tab
    setTimeout(function() {
        window.close();
        chrome.tabs.create({url: chrome.extension.getURL('settings.html')});
    }, 100);
}

function init() {
    if(!localStorage.trello_token) {
        closePopup();
        return;
    }
    else {
        Trello.authorize({
            interactive:false,
            success: onAuthorize
        });
    }
}

window.addEventListener('load', init);

document.addEventListener('DOMContentLoaded', function () {
    $("#disconnect").click(logout);
    $("#connect").click(init);
    $("#board_list").change(boardSelected);
    $("#add-bug").click(addClicked);
});
<|endoftext|>


<commit_before>$(document).ready(function(){

  var Domain = "https://channeli.in";
  var Host = "channeli.in"

  /* Extracts Domain name from the url */
  var getDomainName = function (href) {
    var l = document.createElement("a");
    l.href = href;
    return l.hostname;
  }

    if(typeof localStorage['cache_key'] == 'undefined') {
        console.log("heyhey..!!");
        $.get(Domain + '/chrome_ext/check-cache/', {}, function(res){
          if(!(res == 'FAILURE')) {
              $('#main').html(res);
              var new_key = $('input[name="cache_key"]').val();
              if(!(new_key == 'undefined')) {
                localStorage['cache_key'] = new_key;
                localStorage['apps_content'] = res;
                console.log(localStorage['cache_key']);
              }
          }
          else {
            console.log("failure!!");
            console.log("Error occured while fetching data!");
            var html_content = localStorage['apps_content'];
            $('#main').html(html_content);
          }
      })
       .fail( function(res) {
                    console.log("failure!!");
                    console.log("Error occured while fetching data!");
                    var html_content = localStorage['apps_content'];
                    $('#main').html(html_content);
            });
    }
    else {
        console.log("hey..!!");
        $.get( Domain + '/chrome_ext/check-cache/', {'cache_key': localStorage['cache_key']}, function(res){
          console.log("success!!");
          if(!(res == 'FAILURE')) {
            if(typeof res.cache_key == 'undefined') {
                  $('#main').html(res);
                  var new_key = $('input[name="cache_key"]').val();
                  console.log(new_key);
                  if(!(typeof new_key == 'undefined')) {
                      localStorage['cache_key'] = new_key;
                      localStorage['apps_content'] = res;
                      console.log(localStorage['cache_key']);
                  }
              }
              else {
                /* Take data from localstorage */
                console.log("Already have updated version!");
                var html_content = localStorage['apps_content'];
                $('#main').html(html_content);
              }
          }
          else {
            console.log("failure-1!!");
            console.log("Error occured while fetching data-1!");
            var html_content = localStorage['apps_content'];
            $('#main').html(html_content);
          }
        })
        .fail( function(res) {
            console.log("failure-2!!");
            console.log("Error occured while fetching data-2!");
            var html_content = localStorage['apps_content'];
            $('#main').html(html_content);
        });
    }

  var url = Domain + "/check-session/";
  $.post(url, function(res){
    $("#loader").hide();
    if(res.msg == "YES")
    {
      $("#login").hide();
      $("#message").hide();
      $("#user_box").show();
      $("#main").show();
      $("#profile_box").html("

"+
        "

" + res._name + "

" + res.info + "
");
      chrome.browserAction.setIcon({path: "../images/icon_active.png"});
    }
    else if(res.msg == "NO")
    {
      $("#message").hide();
      $("#user_box").hide();
      $("#login").show();
      $("#main").show();
    }
    else if(res.msg == "FAILURE")
    {
      $("#user_box").hide();
      $("#message").show();
      var msg = "Invalid request!";
      $("#message").html("
" + msg + "
");
      $("#login").show();
      $("#main").show();
    }
    else{
      $("#login").hide();
      $("#user_box").hide();
      $("#message").show();
      var msg = "Error occured!";
      $("#message").html("
" + msg + "
");
      $("#main").show();
    }
  });

  $("#logout_btn").on("click", function(){
    var url = Domain + "/logout-user/";
    $.post(url, function(res){
      if(res.msg == "OK")
      {
        $("#message").hide();
        $("#user_box").hide();
        $("#login").show();
        $("#main").show();
        $("#username_field").val('');
        $("#password_field").val('');

        chrome.tabs.query({}, function (tabs) {
          var _tabs = [];
          for (var i = 0; i < tabs.length; i++) {
            if(getDomainName(tabs[i].url) == Host)
            {
              _tabs.push(tabs[i].id);
            }
          }
          for(var j = 0; j < _tabs.length; j++)
          {
            chrome.tabs.reload(_tabs[j]);
          }
        });
        chrome.browserAction.setIcon({path: "../images/icon_inactive.png"});
      }
      else if(res.msg == "FAILURE")
      {
        $("#message").hide();
        $("#user_box").hide();
        $("#login").show();
        $("#main").show();
      }
      else{
        $("#login").hide();
        $("#user_box").hide();
        $("#message").show();
        var msg = "Error occured!";
        $("#message").html("
" + msg + "
");
        $("#main").show();
      }
    });
  });

  $("#login_form").submit(function(e){
    e.preventDefault();
    var url = Domain + "/check-login/";
    var data = $("#login_form").serialize();
    $.post(url, data, function(res){
      if(res.msg == "YES")
      {
        $("#login").hide();
        $("#message").hide();
        $("#user_box").show();
        $("#profile_box").html("

"+
            "

" + res._name + "

" + res.info + "
");
        $("#main").show();

        chrome.tabs.query({}, function (tabs) {
          var _tabs = [];
          for (var i = 0; i < tabs.length; i++) {
            if(getDomainName(tabs[i].url) == Host)
            {
              _tabs.push(tabs[i].id);
            }
          }
          for(var j = 0; j < _tabs.length; j++)
          {
            chrome.tabs.reload(_tabs[j]);
          }
        });
        chrome.browserAction.setIcon({path: "../images/icon_active.png"});
      }
      else if(res.msg == "NO")
      {
        $("#user_box").hide();
        var msg = "Invalid Username or Password!";
        $("#message").show();
        $("#message").html("
" + msg + "
");
        $("#login").show();
        $("#main").show();
      }
      else if(res.msg == "FAILURE")
      {
        $("#user_box").hide();
        var msg = "Invalid request!";
        $("#message").show();
        $("#message").html("
" + msg + "
");
        $("#login").show();
        $("#main").show();
      }
    });
  });
});

<commit_msg>url changed<commit_after>$(document).ready(function(){

  var Domain = "https://channeli.in";
  var Host = "channeli.in"

  /* Extracts Domain name from the url */
  var getDomainName = function (href) {
    var l = document.createElement("a");
    l.href = href;
    return l.hostname;
  }

    if(typeof localStorage['cache_key'] == 'undefined') {
        console.log("heyhey..!!");
        $.get(Domain + '/chrome-ext/check-cache/', {}, function(res){
          if(!(res == 'FAILURE')) {
              $('#main').html(res);
              var new_key = $('input[name="cache_key"]').val();
              if(!(new_key == 'undefined')) {
                localStorage['cache_key'] = new_key;
                localStorage['apps_content'] = res;
                console.log(localStorage['cache_key']);
              }
          }
          else {
            console.log("failure!!");
            console.log("Error occured while fetching data!");
            var html_content = localStorage['apps_content'];
            $('#main').html(html_content);
          }
      })
       .fail( function(res) {
                    console.log("failure!!");
                    console.log("Error occured while fetching data!");
                    var html_content = localStorage['apps_content'];
                    $('#main').html(html_content);
            });
    }
    else {
        console.log("hey..!!");
        $.get( Domain + '/chrome-ext/check-cache/', {'cache_key': localStorage['cache_key']}, function(res){
          console.log("success!!");
          if(!(res == 'FAILURE')) {
            if(typeof res.cache_key == 'undefined') {
                  $('#main').html(res);
                  var new_key = $('input[name="cache_key"]').val();
                  console.log(new_key);
                  if(!(typeof new_key == 'undefined')) {
                      localStorage['cache_key'] = new_key;
                      localStorage['apps_content'] = res;
                      console.log(localStorage['cache_key']);
                  }
              }
              else {
                /* Take data from localstorage */
                console.log("Already have updated version!");
                var html_content = localStorage['apps_content'];
                $('#main').html(html_content);
              }
          }
          else {
            console.log("failure-1!!");
            console.log("Error occured while fetching data-1!");
            var html_content = localStorage['apps_content'];
            $('#main').html(html_content);
          }
        })
        .fail( function(res) {
            console.log("failure-2!!");
            console.log("Error occured while fetching data-2!");
            var html_content = localStorage['apps_content'];
            $('#main').html(html_content);
        });
    }

  var url = Domain + "/check-session/";
  $.post(url, function(res){
    $("#loader").hide();
    if(res.msg == "YES")
    {
      $("#login").hide();
      $("#message").hide();
      $("#user_box").show();
      $("#main").show();
      $("#profile_box").html("

"+
        "

" + res._name + "

" + res.info + "
");
      chrome.browserAction.setIcon({path: "../images/icon_active.png"});
    }
    else if(res.msg == "NO")
    {
      $("#message").hide();
      $("#user_box").hide();
      $("#login").show();
      $("#main").show();
    }
    else if(res.msg == "FAILURE")
    {
      $("#user_box").hide();
      $("#message").show();
      var msg = "Invalid request!";
      $("#message").html("
" + msg + "
");
      $("#login").show();
      $("#main").show();
    }
    else{
      $("#login").hide();
      $("#user_box").hide();
      $("#message").show();
      var msg = "Error occured!";
      $("#message").html("
" + msg + "
");
      $("#main").show();
    }
  });

  $("#logout_btn").on("click", function(){
    var url = Domain + "/logout-user/";
    $.post(url, function(res){
      if(res.msg == "OK")
      {
        $("#message").hide();
        $("#user_box").hide();
        $("#login").show();
        $("#main").show();
        $("#username_field").val('');
        $("#password_field").val('');

        chrome.tabs.query({}, function (tabs) {
          var _tabs = [];
          for (var i = 0; i < tabs.length; i++) {
            if(getDomainName(tabs[i].url) == Host)
            {
              _tabs.push(tabs[i].id);
            }
          }
          for(var j = 0; j < _tabs.length; j++)
          {
            chrome.tabs.reload(_tabs[j]);
          }
        });
        chrome.browserAction.setIcon({path: "../images/icon_inactive.png"});
      }
      else if(res.msg == "FAILURE")
      {
        $("#message").hide();
        $("#user_box").hide();
        $("#login").show();
        $("#main").show();
      }
      else{
        $("#login").hide();
        $("#user_box").hide();
        $("#message").show();
        var msg = "Error occured!";
        $("#message").html("
" + msg + "
");
        $("#main").show();
      }
    });
  });

  $("#login_form").submit(function(e){
    e.preventDefault();
    var url = Domain + "/check-login/";
    var data = $("#login_form").serialize();
    $.post(url, data, function(res){
      if(res.msg == "YES")
      {
        $("#login").hide();
        $("#message").hide();
        $("#user_box").show();
        $("#profile_box").html("

"+
            "

" + res._name + "

" + res.info + "
");
        $("#main").show();

        chrome.tabs.query({}, function (tabs) {
          var _tabs = [];
          for (var i = 0; i < tabs.length; i++) {
            if(getDomainName(tabs[i].url) == Host)
            {
              _tabs.push(tabs[i].id);
            }
          }
          for(var j = 0; j < _tabs.length; j++)
          {
            chrome.tabs.reload(_tabs[j]);
          }
        });
        chrome.browserAction.setIcon({path: "../images/icon_active.png"});
      }
      else if(res.msg == "NO")
      {
        $("#user_box").hide();
        var msg = "Invalid Username or Password!";
        $("#message").show();
        $("#message").html("
" + msg + "
");
        $("#login").show();
        $("#main").show();
      }
      else if(res.msg == "FAILURE")
      {
        $("#user_box").hide();
        var msg = "Invalid request!";
        $("#message").show();
        $("#message").html("
" + msg + "
");
        $("#login").show();
        $("#main").show();
      }
    });
  });
});

<|endoftext|>


<commit_before>// Front end
	// Home
	// View Table
		// Current reservation
		// Waiting List

	// Make a reservation
		// goes to route /reserve
			// which is a form
				//
				// form will push to the database
				// ***** wait list is route /table
				// pops up an alert

// =================
// DEPENDENCIES
// =================
var fs = require('fs');
var mysql = require('mysql');				// the database
var bodyParser = require('body-parser');	// body-parser extract the entire body portion of an incoming request stream
var express = require('express');			//
var path = require('path');					//
var url = require('url');
var http = require("http");
var app = express();
var PORT = 3300; 		// process environment

// =================
// DEPENDENCIES
// =================

var server = http.createServer(handleRequest);

function handleRequest(req, res){

	var urlParts = url.parse(req.url);

	switch (urlParts.pathname) {

		case "/":
			fs.readFile("index.html", function(err, data) {
				res.writeHead(200, { "Content-Type": "text/html" });
				res.end(data);
			});
		break;

		case '/reserve':
			fs.readFile('reserve.html', function(err, data) {
				res.writeHead(200, {'Content-Type': 'text/html'});
				res.end(data);
			});

		break;

		case '/tables':
			fs.readFile('tables.html', function(err, data) {
				res.writeHead(200, {'Content-Type': 'text/html'});
				res.end(data);
			});

		break;

		default:
			fs.readFile('index.html', function(err, data) {
				res.writeHead(200, {'Content-Type': 'text/html'});
				res.end(data);
			})
	}

}
server.listen(PORT, function() {
	console.log('server is listening to PORT: ' + PORT);
});

var forms = [{
	name: "Jason",
	email: "jjson@yahoo.com",
	phone_number:"7738378488"
},{
	name:"Liam",
	email: "Liam7373@yahoo.com",
	phone_number: "7738282273"
}, {
	name: "zach",
	email: "idk244@yahoo.com",
	phone_number: "7747483888"
}];

// connecting to the database
var connection = mysql.createConnection({
    host: 'localhost',
    port: 3300,
    user: 'root',
    password: '',
    database: 'Hot_restaurantDB'
});

//connected to the server

connection.connect(function(err) {
    if (err){
    	console.log('the error is' + err);
	} else {
	    console.log('connected...');
	}
});

// ending the connection
var end = function() {
    connection.end(function(err) {
        // The connection is terminated now
    });
}

// ==============================================
// MYSQL DATABASE
// ==============================================

// dataList = 'SELECT * FROM products';

// ==============================================
// Sets up the Express app to handle data parsing
// ==============================================
// app.use(bodyParser.json());
// // I don't know what this does
// app.use(bodyParser.urlencoded({ extended: true }));
// app.use(bodyParser.text());
// app.use(bodyParser.json({ type: "application/vnd.api+json" }));

// // ==============================================
// // DATA
// // ==============================================

// var forms = [{}];

// // ==============================================
// // ROUTES
// // ==============================================

// // Basic route that sends the user first to the AJAX Page

app.get("/", function(req, res) {
  res.sendFile(path.join(__dirname, "index.html"));
});

app.get("/reserve", function(req, res) {
  res.sendFile(path.join(__dirname, "reserve.html"));
});

app.get("/tables", function(req, res) {
  res.sendFile(path.join(__dirname, "tables.html"));
});

// Search for Specific Character (or all characters) - provides JSON
app.get("/api/:forms?", function(req, res) {
  var chosen = req.params.forms;

  if (chosen) {
    console.log(chosen);

    for (var i = 0; i < forms.length; i++) {
      if (chosen === forms[i].routeName) {
        return res.json(forms[i]);
      }
    }

    return res.json(false);
  }
  return res.json(forms);
});

// Create New Characters - takes in JSON input
app.post("/api/reserve", function(req, res) {
  var newreservation = req.body;
  newreservation.routeName = newreservation.name.replace(/\s+/g, "").toLowerCase();

  console.log(newreservation);

  forms.push("#tableSection");

  res.json(newreservation);
});

<commit_msg>changes<commit_after>// Front end
	// Home
	// View Table
		// Current reservation
		// Waiting List

	// Make a reservation
		// goes to route /reserve
			// which is a form
				//
				// form will push to the database
				// ***** wait list is route /table
				// pops up an alert

// =================
// DEPENDENCIES
// =================
var fs = require('fs');
var mysql = require('mysql');				// the database
var bodyParser = require('body-parser');	// body-parser extract the entire body portion of an incoming request stream
var express = require('express');			//
var path = require('path');					//
var url = require('url');
var http = require("http");
var app = express();
var PORT = 3300; 		// process environment

// =================
// DEPENDENCIES
// =================

var server = http.createServer(handleRequest);

function handleRequest(req, res){

	var urlParts = url.parse(req.url);

	switch (urlParts.pathname) {

		case "/":
			fs.readFile("index.html", function(err, data) {
				res.writeHead(200, { "Content-Type": "text/html" });
				res.end(data);
			});
		break;

		case '/reserve':
			fs.readFile('reserve.html', function(err, data) {
				res.writeHead(200, {'Content-Type': 'text/html'});
				res.end(data);
			});

		break;

		case '/tables':
			fs.readFile('tables.html', function(err, data) {
				res.writeHead(200, {'Content-Type': 'text/html'});
				res.end(data);
			});

		break;

		default:
			fs.readFile('index.html', function(err, data) {
				res.writeHead(200, {'Content-Type': 'text/html'});
				res.end(data);
			})
	}

}
server.listen(PORT, function() {
	console.log('server is listening to PORT: ' + PORT);
});

var forms = [{
	routeName: "name",
	name: "Jason",
	email: "jjson@yahoo.com",
	phone_number:"7738378488"
},{
	routeName: "name",
	name:"Liam",
	email: "Liam7373@yahoo.com",
	phone_number: "7738282273"
}, {
	routeName: "name",
	name: "zach",
	email: "idk244@yahoo.com",
	phone_number: "7747483888"
}];

// connecting to the database
var connection = mysql.createConnection({
    host: 'localhost',
    port: 3300,
    user: 'root',
    password: '',
    database: 'Hot_restaurantDB'
});

//connected to the server

connection.connect(function(err) {
    if (err){
    	console.log('the error is' + err);
	} else {
	    console.log('connected...');
	}
});

// ending the connection
var end = function() {
    connection.end(function(err) {
        // The connection is terminated now
    });
}

// ==============================================
// MYSQL DATABASE
// ==============================================

// dataList = 'SELECT * FROM products';

// ==============================================
// Sets up the Express app to handle data parsing
// ==============================================
// app.use(bodyParser.json());
// // I don't know what this does
// app.use(bodyParser.urlencoded({ extended: true }));
// app.use(bodyParser.text());
// app.use(bodyParser.json({ type: "application/vnd.api+json" }));

// // ==============================================
// // DATA
// // ==============================================

// var forms = [{}];

// // ==============================================
// // ROUTES
// // ==============================================

// // Basic route that sends the user first to the AJAX Page

app.get("/", function(req, res) {
  res.sendFile(path.join(__dirname, "index.html"));
});

app.get("/reserve", function(req, res) {
  res.sendFile(path.join(__dirname, "reserve.html"));
});

app.get("/tables", function(req, res) {
  res.sendFile(path.join(__dirname, "tables.html"));
});

// Search for Specific Character (or all characters) - provides JSON
app.get("/api/:forms?", function(req, res) {
  var chosen = req.params.forms;

  if (chosen) {
    console.log(chosen);

    for (var i = 0; i < forms.length; i++) {
      if (chosen === forms[i].routeName) {
        return res.json(forms[i]);
      }
    }

    return res.json(false);
  }
  return res.json(forms);
});

// Create New Characters - takes in JSON input
app.post("/api/reserve", function(req, res) {
  var newreservation = req.body;
  newreservation.routeName = newreservation.name.replace(/\s+/g, "").toLowerCase();

  console.log(newreservation);

  forms.push("#tableSection");

  res.json(newreservation);
});

<|endoftext|>


<commit_before>import Raven from 'raven-js';
import config from 'config';

if (config.sentry) {
    const options = {
        logger: 'admin',
        release: config.sentry.release,
        tags: config.sentry.tags,
    };

    Raven.config(config.sentry.dsn, options).install();
}

export default Raven;
<commit_msg>Rename JS logger from admin to udata.js<commit_after>import Raven from 'raven-js';
import config from 'config';

if (config.sentry) {
    const options = {
        logger: 'udata.js',  // Allow filtering in Sentry
        release: config.sentry.release,
        tags: config.sentry.tags,
    };

    Raven.config(config.sentry.dsn, options).install();
}

export default Raven;
<|endoftext|>