<commit_before>/**
 * Created by michael on 23/06/15.
 */
'use strict';

define([

    'states/boot'

],function(Boot){

        function App(){
            this.game = null;
            this.canvas = null;
            this.width = window.innerWidth;// * window.devicePixelRatio;
            this.height = window.innerHeight;// * window.devicePixelRatio;
        }

        App.prototype.run = function(){
            this.game = new Phaser.Game(this.width,this.height,Phaser.AUTO,'',Boot);

            console.log(this.game);
        };

        App.prototype.scaleToScreen = function(sprite,toWith){
            var ratio;

            if(toWith === true){
                ratio = this.width / sprite.width;
                sprite.width = this.width;
                sprite.height = sprite.height * ratio;
            }else{
                ratio = this.height / sprite.height;
                sprite.height = this.height;
                sprite.width = sprite.width * ratio;
            }
        };

        App.prototype.loadRoboParts = function(){
            this.game.load.image('robo_body_0','assets/robotparts/body_0.png');
            this.game.load.image('robo_legs_0','assets/robotparts/legs_0.png');
            this.game.load.image('robo_head_0','assets/robotparts/head_0.png');
            this.game.load.image('robo_arm_left_0','assets/robotparts/arm_left_0.png');
            this.game.load.image('robo_arm_right_0','assets/robotparts/arm_right_0.png');
        };

        App.prototype.makeRobot = function(config,back){
            var robot = this.game.add.group();

            robot.create(24,0,'robo_head_0');
            robot.create(24,32,'robo_body_0');
            robot.create(24,80,'robo_legs_0');
            robot.create(0,32,'robo_arm_left_0');
            robot.create(56,32,'robo_arm_right_0');

            return robot;
        };

        App.prototype.scaleMax = function(object,roomX, roomY){
            var scaleX = roomX / object.width;
            var scaleY = roomY / object.height;

            var scale = 1;

            if(scaleX < scaleY){
                scale = Math.floor(scaleX);
            }else{
                scale = Math.floor(scaleY);
            }

            object.scale.set(scale,scale);
        };

        return new App();

});

<commit_msg>Kombinationstest<commit_after>/**
 * Created by michael on 23/06/15.
 */
'use strict';

define([

    'states/boot'

],function(Boot){

        function App(){
            this.game = null;
            this.canvas = null;
            this.width = window.innerWidth;// * window.devicePixelRatio;
            this.height = window.innerHeight;// * window.devicePixelRatio;
        }

        App.prototype.run = function(){
            this.game = new Phaser.Game(this.width,this.height,Phaser.AUTO,'',Boot);

            console.log(this.game);
        };

        App.prototype.scaleToScreen = function(sprite,toWith){
            var ratio;

            if(toWith === true){
                ratio = this.width / sprite.width;
                sprite.width = this.width;
                sprite.height = sprite.height * ratio;
            }else{
                ratio = this.height / sprite.height;
                sprite.height = this.height;
                sprite.width = sprite.width * ratio;
            }
        };

        App.prototype.loadRoboParts = function(){
            this.game.load.image('robo_body_0','assets/robotparts/body_1.png');
            this.game.load.image('robo_legs_0','assets/robotparts/legs_0.png');
            this.game.load.image('robo_head_0','assets/robotparts/head_2.png');
            this.game.load.image('robo_arm_left_0','assets/robotparts/arm_left_0.png');
            this.game.load.image('robo_arm_right_0','assets/robotparts/arm_right_0.png');
        };

        App.prototype.makeRobot = function(config,back){
            var robot = this.game.add.group();

            robot.create(24,0,'robo_head_0');
            robot.create(24,32,'robo_body_0');
            robot.create(24,80,'robo_legs_0');
            robot.create(0,32,'robo_arm_left_0');
            robot.create(56,32,'robo_arm_right_0');

            return robot;
        };

        App.prototype.scaleMax = function(object,roomX, roomY){
            var scaleX = roomX / object.width;
            var scaleY = roomY / object.height;

            var scale = 1;

            if(scaleX < scaleY){
                scale = Math.floor(scaleX);
            }else{
                scale = Math.floor(scaleY);
            }

            object.scale.set(scale,scale);
        };

        return new App();

});

<|endoftext|>


<commit_before>const fs = require('fs');

/** A Webpack plugin to refresh file mtime values from disk before compiling.
 *  This is used in order to account for SCSS-generated .d.ts files written
 *  as part of compilation so they trigger only a single recompile per write.
 *
 *  All credit for the technique and implementation goes to @reiv. See:
 *  https://github.com/Jimdo/typings-for-css-modules-loader/issues/48#issuecomment-347036461
 */
module.exports = class WatchTimestampsPlugin {
	constructor(patterns) {
		this.patterns = patterns;
	}

	apply(compiler) {
		compiler.plugin('watch-run', (watch, callback) => {
			let patterns = this.patterns;
			let timestamps = watch.fileTimestamps || watch.compiler.fileTimestamps;

			Object.keys(timestamps).forEach(filepath => {
				if (patterns.some(pat => pat instanceof RegExp ? pat.test(filepath) : filepath.indexOf(pat) === 0)) {
					let time = fs.statSync(filepath).mtime;
					if (timestamps instanceof Map) timestamps.set(filepath, time);
					else timestamps[filepath] = time;
				}
			});
			callback();
		});
	}
};
<commit_msg>Remove support for Webpack 3.x and prior from `WatchTimestampsPlugin`.<commit_after>const fs = require('fs');

/** A Webpack plugin to refresh file mtime values from disk before compiling.
 *  This is used in order to account for SCSS-generated .d.ts files written
 *  as part of compilation so they trigger only a single recompile per write.
 *
 *  All credit for the technique and implementation goes to @reiv. See:
 *  https://github.com/Jimdo/typings-for-css-modules-loader/issues/48#issuecomment-347036461
 */
module.exports = class WatchTimestampsPlugin {
	constructor(patterns) {
		this.patterns = patterns;
	}

	apply(compiler) {
		compiler.plugin('watch-run', (watch, callback) => {
			const patterns = this.patterns;
			const timestamps = watch.fileTimestamps;

			Object.keys(timestamps).forEach(filepath => {
				if (patterns.some(pat => pat instanceof RegExp ? pat.test(filepath) : filepath.indexOf(pat) === 0)) {
					let time = fs.statSync(filepath).mtime;
					if (timestamps instanceof Map) timestamps.set(filepath, time);
					else timestamps[filepath] = time;
				}
			});
			callback();
		});
	}
};
<|endoftext|>


<commit_before>
var sidebarOn = false;

function closeSidebar()
{
	$('#mobile-sidebar-container').hide();
	$('#realbody').css('max-width', 'none');
	$('#realbody').css('max-height', 'none');
	$('#realbody').css('overflow', 'auto');

	$('#mobile-sidebar-deactivate').off('click.mobilesidebar');
	sidebarOn = false;
}

function openSidebar()
{
	$('#mobile-sidebar-container').show();
	$('#realbody').css('max-width', '100%');
	$('#realbody').css('max-height', '100%');
	$('#realbody').css('overflow', 'hidden');

	setTimeout(function()
	{
		$('#mobile-sidebar-deactivate').on('click.mobilesidebar', function(e)
		{
			closeSidebar();
			e.preventDefault();
		});
	}, 0);
	sidebarOn = true;
}
<commit_msg>Add animation for mobile.<commit_after>
var sidebarOn = false;

function closeSidebar()
{
	$('#mobile-sidebar-container').hide('slide', {direction: 'right'}, 250);
	$('#realbody').css('max-width', 'none');
	$('#realbody').css('max-height', 'none');
	$('#realbody').css('overflow', 'auto');

	$('#mobile-sidebar-deactivate').off('click.mobilesidebar');
	sidebarOn = false;
}

function openSidebar()
{
	$('#mobile-sidebar-container').show('slide', {direction: 'right'}, 250);
	$('#realbody').css('max-width', '100%');
	$('#realbody').css('max-height', '100%');
	$('#realbody').css('overflow', 'hidden');

	setTimeout(function()
	{
		$('#mobile-sidebar-deactivate').on('click.mobilesidebar', function(e)
		{
			closeSidebar();
			e.preventDefault();
		});
	}, 0);
	sidebarOn = true;
}
<|endoftext|>


<commit_before>function Player(character, controls) {
  this.spawns = [91, 45, 65, 645, 553, 616, 420, 320];
  this.x = this.spawns[Math.floor(Math.random() * this.spawns.length)];
  this.y = 135;
  this.yVel = 0;
  this.defeatedX = 530;
  this.facing = "right";
  this.walking = false;
  this.falling = false;
  this.attacking = false;
  this.blocking = false;
  this.energy = 15;
  this.score = 0;
  this.jumping = true;
  this.score = 0;
  this.tag = "";
  this.health = 20;
  this.speed = 5;
  this.height = 20;
  this.width = 20;
  this.character = character;
  this.scoreId = "#" + this.character + ""
  this.sprite = {
    walkLeft: 'url("./assets/img/' + character + '/walk-left.gif")',
    walkRight: 'url("./assets/img/' + character + '/walk-right.gif")',
    jumpLeft: 'url("./assets/img/' + character + '/jump-left.gif")',
    jumpRight: 'url("./assets/img/' + character + '/jump-right.gif")',
    attackLeft: 'url("./assets/img/' + character + '/attack-left.gif")',
    attackRight: 'url("./assets/img/' + character + '/attack-right.gif")',
    blockLeft: 'url("./assets/img/' + character + '/block-left.gif")',
    blockRight: 'url("./assets/img/' + character + '/block-right.gif")',
    sprintLeft: 'url("./assets/img/' + character + '/sprint-left.gif")',
    sprintRight: 'url("./assets/img/' + character + '/sprint-right.gif")',
    standLeft: 'url("./assets/img/' + character + '/stand-left.gif")',
    standRight: 'url("./assets/img/' + character + '/stand-right.gif")',
    fallLeft: 'url("./assets/img/' + character + '/fall-left.gif")',
    fallRight: 'url("./assets/img/' + character + '/fall-right.gif")'
  };
  this.controls = controls;
}

Player.prototype.move = function() {
  // TODO: move only upon keydown
  if (this.walking === true) {
    switch (this.direction) {
      case 'right':
        this.x += this.speed;
        break;
      case 'left':
        this.x -= this.speed;
        break;
    }
  }
}

Player.prototype.setDirection = function(direction) {
  this.direction = direction;
  if (this.walking === true) {
    switch (this.direction) {
      case 'right':
        this.facing = "right";
        this.$sprite.css('background-image', this.sprite.walkRight);
        break;
      case 'left':
        this.facing = "left";
        this.$sprite.css('background-image', this.sprite.walkLeft);
        break;
    }
  } else {
    switch (this.direction) {
      case 'right':
        this.$sprite.css('background-image', this.sprite.standRight);
        break;
      case 'left':
        this.$sprite.css('background-image', this.sprite.standLeft);
        break;
    }
  }
}

Player.prototype.jump = function() {
  if (this.jumping == false) {
    this.yVel = -15;
    this.falling = false;
    this.jumping = true;
  }
}<commit_msg>Add shield function for Player model to allow player to block incoming attacks<commit_after>function Player(character, controls) {
  this.spawns = [91, 45, 65, 645, 553, 616, 420, 320];
  this.x = this.spawns[Math.floor(Math.random() * this.spawns.length)];
  this.y = 135;
  this.yVel = 0;
  this.defeatedX = 530;
  this.facing = "right";
  this.walking = false;
  this.falling = false;
  this.attacking = false;
  this.blocking = false;
  this.energy = 15;
  this.score = 0;
  this.jumping = true;
  this.score = 0;
  this.tag = "";
  this.health = 20;
  this.speed = 5;
  this.height = 20;
  this.width = 20;
  this.character = character;
  this.scoreId = "#" + this.character + ""
  this.sprite = {
    walkLeft: 'url("./assets/img/' + character + '/walk-left.gif")',
    walkRight: 'url("./assets/img/' + character + '/walk-right.gif")',
    jumpLeft: 'url("./assets/img/' + character + '/jump-left.gif")',
    jumpRight: 'url("./assets/img/' + character + '/jump-right.gif")',
    attackLeft: 'url("./assets/img/' + character + '/attack-left.gif")',
    attackRight: 'url("./assets/img/' + character + '/attack-right.gif")',
    blockLeft: 'url("./assets/img/' + character + '/block-left.gif")',
    blockRight: 'url("./assets/img/' + character + '/block-right.gif")',
    sprintLeft: 'url("./assets/img/' + character + '/sprint-left.gif")',
    sprintRight: 'url("./assets/img/' + character + '/sprint-right.gif")',
    standLeft: 'url("./assets/img/' + character + '/stand-left.gif")',
    standRight: 'url("./assets/img/' + character + '/stand-right.gif")',
    fallLeft: 'url("./assets/img/' + character + '/fall-left.gif")',
    fallRight: 'url("./assets/img/' + character + '/fall-right.gif")'
  };
  this.controls = controls;
}

Player.prototype.move = function() {
  // TODO: move only upon keydown
  if (this.walking === true) {
    switch (this.direction) {
      case 'right':
        this.x += this.speed;
        break;
      case 'left':
        this.x -= this.speed;
        break;
    }
  }
}

Player.prototype.setDirection = function(direction) {
  this.direction = direction;
  if (this.walking === true) {
    switch (this.direction) {
      case 'right':
        this.facing = "right";
        this.$sprite.css('background-image', this.sprite.walkRight);
        break;
      case 'left':
        this.facing = "left";
        this.$sprite.css('background-image', this.sprite.walkLeft);
        break;
    }
  } else {
    switch (this.direction) {
      case 'right':
        this.$sprite.css('background-image', this.sprite.standRight);
        break;
      case 'left':
        this.$sprite.css('background-image', this.sprite.standLeft);
        break;
    }
  }
}

Player.prototype.jump = function() {
  if (this.jumping == false) {
    this.yVel = -15;
    this.falling = false;
    this.jumping = true;
  }
}

Player.prototype.shield = function() {
  if (this.energy > 0) {
    this.blocking = true;
    this.energy -= 1;
    return true;
  } else {
    this.blocking = false;
    this.setDirection(this.direction);
    return false;
  }
}<|endoftext|>


<commit_before>var HTMLLinkElement=function(t){var e={},n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]"),r=function(t,e){return HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(function(t){return e({target:n})}):n.addEventListener(t,e)};return Object.defineProperties(e,{addEventListener:{writable:!1,value:function(t,o){n?r(t,o):o({target:e})}}}),e},TokenList=function(t){this.sift(t).map(this.tokenize,this)};TokenList.prototype.tokenize=function(t){var e=this;(t.text=t.textContent).match(/([^{]*?)(\w|#)(?=\})/g).map(function(t){return function(n){return(e[n]=e[n]||[]).push(t)}}(t))},TokenList.prototype.sift=function(t){for(var e=[],n=/{(\w+|#)}/,r=function(t){return n.test(t.textContent)&&e.push(t)},o=function(t){return Array.from(t).map(function(t){return n.test(t.value)&&e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.nodeType===Node.TEXT_NODE?r(t):o(t.attributes)&&NodeFilter.FILTER_REJECT});i.nextNode(););return e},TokenList.prototype.bind=function(t){var e=this;Object.keys(this).map(function(t){return e[t].map(function(e){return(e.textContent=e.text)&&t})});for(var n in e)e[n].map(function(e,n){return void 0===n&&(n="{"+e+"}"),function(r){return r.textContent=r.textContent.replace(n,t[e])}}(n))};var HTMLTemplateElement=Template=function(t){return Object.assign(document.querySelector("template[name="+t+"]"),{bind:function(t){var e=this;contexts=(o=[]).concat.apply(o,[t]);var n,r=this.cloneNode(!1);return r.innerHTML=contexts.map(function(t){return t}).map(function(t,r){return t="object"==typeof t?t:{self:t},t["#"]=r,n=e.cloneNode(!0),new TokenList(n.content).bind(t),n.innerHTML}).join(""),(this.dependents||[]).map(function(t){return t.remove()}),this.dependents=Array.from(r.content.childNodes),this.after(r.content),this;var o}})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n,r){return void 0===r&&(r=!0),(n.prevent=function(t){return(r=!1)&&n.preventDefault()})&&!1!==t.call(e,n)&&r&&e.render()}},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(e,n){(n=e.target.import)&&this.parse(n.querySelector("template")),t.prototype.onconnect&&t.prototype.onconnect.call(this),this.render()},e.prototype.introspect=function(t,e){(e=(t.match(/^on(.+)$/)||[])[1])&&Object.keys(HTMLElement.prototype).includes(t)&&this.on(e,this[t])},e.prototype.register=function(t){var e=this;Array.from(t.attributes).map(function(t){return t.name}).filter(function(t){return/^on/.test(t)}).map(function(n,r){return(r=/{\s*(\w+)\s*}/.exec(t[n]))&&(r=e[(r||[])[1]])&&(t[n]=e.renderable(r))})},e}(t)},Component=function(t){return function(e){function n(n){var r=this;e.call(this);var o=Object.getOwnPropertyDescriptors(t.prototype);Object.keys(o).map(function(t){return"function"==typeof o[t].value&&(r[t]=r[t].bind(r))}),Object.getOwnPropertyNames(t.prototype).map(this.introspect,this),this.context=this.context||{},this.tokens=new TokenList(this),this.initialize&&this.initialize()}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(){HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onconnect.bind(this))},n.prototype.render=function(){var t=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(e){return new Template(e).bind(t[e])}),Array.from(this.selectAll("*")).concat([this]).map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n.prototype.parse=function(t,e){var n=this;t=t.cloneNode(!0),e=function(e,n,r){return(n=e.getAttribute("slot"))&&(r=t.content.querySelector("slot[name="+n+"]")).parentNode.replaceChild(e,r)};for(var r=0,o=n.selectAll("[slot]");r<o.length;r+=1)e(o[r]);Array.from(t.attributes).map(function(t){return n.setAttribute(t.name,t.value)}),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t){return function(e){return(n=window.customElements).define.apply(n,t.concat([Component(e)]));var n}};Element.prototype=ElementPrototype;<commit_msg>:muscle: bump distribution for dist/snuggsi.min.js<commit_after>var HTMLLinkElement=function(t){var e={},n=document.querySelector("link#"+t+"[rel=import], link[href*="+t+"][rel=import]"),r=function(t,e){return HTMLImports&&!HTMLImports.useNative?HTMLImports.whenReady(function(t){return e({target:n})}):n.addEventListener(t,e)};return Object.defineProperties(e,{addEventListener:{writable:!1,value:function(t,o){n?r(t,o):o({target:e})}}}),e},TokenList=function(t){this.sift(t).map(this.tokenize,this)};TokenList.prototype.tokenize=function(t){var e=this;(t.text=t.textContent).match(/([^{]*?)(\w|#)(?=\})/g).map(function(t){return function(n){return(e[n]=e[n]||[]).push(t)}}(t))},TokenList.prototype.sift=function(t){for(var e=[],n=/{(\w+|#)}/,r=function(t){return n.test(t.textContent)&&e.push(t)},o=function(t){return Array.from(t).map(function(t){return n.test(t.value)&&e.push(t)})},i=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.nodeType===Node.TEXT_NODE?r(t):o(t.attributes)&&NodeFilter.FILTER_REJECT});i.nextNode(););return e},TokenList.prototype.bind=function(t){var e=this;Object.keys(this).map(function(t){return e[t].map(function(e){return(e.textContent=e.text)&&t})});for(var n in e)e[n].map(function(e,n){return void 0===n&&(n="{"+e+"}"),function(r){return r.textContent=r.textContent.replace(n,t[e])}}(n))};var HTMLTemplateElement=Template=function(t){return Object.assign(document.querySelector("template[name="+t+"]"),{bind:function(t){var e=this;contexts=(o=[]).concat.apply(o,[t]);var n,r=this.cloneNode(!1);return r.innerHTML=contexts.map(function(t){return t}).map(function(t,r){return t="object"==typeof t?t:{self:t},t["#"]=r,n=e.cloneNode(!0),new TokenList(n.content).bind(t),n.innerHTML}).join(""),(this.dependents||[]).map(function(t){return t.remove()}),this.dependents=Array.from(r.content.childNodes),this.after(r.content),this;var o}})},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n,r){return void 0===r&&(r=!0),(n.prevent=function(t){return(r=!1)&&n.preventDefault()})&&!1!==t.call(e,n)&&r&&e.render()}},e}(t)},ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.selectAll=function(t){return this.querySelectorAll(t)},e.prototype.select=function(t){return this.selectAll(t)[0]},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(e,n){(n=e.target.import)&&this.parse(n.querySelector("template")),t.prototype.onconnect&&t.prototype.onconnect.call(this),this.render()},e.prototype.reflect=function(t,e){(e=(t.match(/^on(.+)$/)||[])[1])&&Object.keys(HTMLElement.prototype).includes(t)&&this.on(e,this[t])},e.prototype.register=function(t){var e=this;Array.from(t.attributes).map(function(t){return t.name}).filter(function(t){return/^on/.test(t)}).map(function(n,r){return(r=/{\s*(\w+)\s*}/.exec(t[n]))&&(r=e[(r||[])[1]])&&(t[n]=e.renderable(r))})},e}(t)},Component=function(t){return function(e){function n(n){var r=this;e.call(this);var o=Object.getOwnPropertyDescriptors(t.prototype);Object.keys(o).map(function(t){return"function"==typeof o[t].value&&(r[t]=r[t].bind(r))}),Object.getOwnPropertyNames(t.prototype).map(this.reflect,this),this.context=this.context||{},this.tokens=new TokenList(this),this.initialize&&this.initialize()}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(){HTMLLinkElement(this.tagName.toLowerCase()).addEventListener("load",this.onconnect.bind(this))},n.prototype.render=function(){var t=this;this.tokens.bind(this),Array.from(this.selectAll("template[name]")).map(function(t){return t.getAttribute("name")}).map(function(e){return new Template(e).bind(t[e])}),Array.from(this.selectAll("*")).concat([this]).map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n.prototype.parse=function(t,e){var n=this;t=t.cloneNode(!0),e=function(e,n,r){return(n=e.getAttribute("slot"))&&(r=t.content.querySelector("slot[name="+n+"]")).parentNode.replaceChild(e,r)};for(var r=0,o=n.selectAll("[slot]");r<o.length;r+=1)e(o[r]);Array.from(t.attributes).map(function(t){return n.setAttribute(t.name,t.value)}),this.innerHTML=t.innerHTML},n}(EventTarget(ParentNode(GlobalEventHandlers(t))))},ElementPrototype=window.Element.prototype,Element=function(t){return function(e){return(n=window.customElements).define.apply(n,t.concat([Component(e)]));var n}};Element.prototype=ElementPrototype;<|endoftext|>


<commit_before>/* eslint-disable no-var */
// Notice: IE 10 and below is still supported, so disable eslint for the file
// when checking the "var"
;(function () {
  var langPickerTogglerElement = document.querySelector('.lang-picker-toggler')
  var langPickerElement = document.querySelector('.lang-picker')
  var langElements = langPickerElement.querySelectorAll('button')
  // Get the current URL language
  var currentLang = window.location.pathname.split('/')[1] || 'en'
  var currentLangElement = null

  Array.prototype.forEach.call(langElements, function (el) {
    if (el.getAttribute('data-lang') !== currentLang) {
      el.addEventListener('click', function (e) {
        var newLocale = (e.target && e.target.dataset && e.target.dataset.lang) || 'en'
        window.location.assign(window.location.pathname.replace(/\/[a-zA-Z-]+/, '/' + newLocale))
      })
    } else {
      currentLangElement = el
    }
  })

  langPickerTogglerElement.setAttribute('title', currentLangElement.textContent)

  // Remove the current selected language item, because we don't need to choose it
  // any more unless we want to switch to a new language
  langPickerElement.removeChild(currentLangElement.parentNode)

  langPickerTogglerElement.addEventListener('click', function () {
    langPickerElement.classList.toggle('hidden')
    const isAriaExpanded = langPickerTogglerElement.getAttribute('aria-expanded') === 'true'
    langPickerTogglerElement.setAttribute('aria-expanded', !isAriaExpanded)
  })
})()

;(function () {
  var scrollToTop = document.getElementById('scroll-to-top');

  (window.onscroll = function () {
    window.requestAnimationFrame(function () {
      scrollToTop.style.display = window.pageYOffset > window.innerHeight ? 'block' : 'none'
    })
  })()

  scrollToTop.addEventListener('click', function (e) {
    e.preventDefault()
    window.scrollTo(0, 0)
  })
})()

;(function () {
  var contributorCard = document.querySelector('.contributor-card')

  if (!contributorCard) {
    return
  }

  var contributorAvatar = contributorCard.querySelector('#contributor-avatar')
  var contributorUsername = contributorCard.querySelector('#contributor-username')
  var contributorContributions = contributorCard.querySelector('#contributor-contributions')
  var loadingSpinner = contributorCard.querySelector('.spinner-border')

  if (window.IntersectionObserver) {
    var observer = new window.IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.intersectionRatio > 0.5) {
          // In viewport, fetch a random contributor
          fetchRandomContributor()

          observer.unobserve(entry.target)
        }
      })
    },
    { threshold: 0.5 }
    )

    observer.observe(document.querySelector('footer'))
  } else {
    // Does not support IntersectionObserver
    fetchRandomContributor()
  }

  function fetchRandomContributor () {
    var maxContributors
    var fetchDate
    var needToRefetch = false

    if (window.localStorage) {
      maxContributors = window.localStorage.getItem('max_contributors')
      fetchDate = parseInt(window.localStorage.getItem('fetch_date'), 10)
    }

    // If fetch date is a month old (2592000000 ms === 30 days)
    if (Date.now() - fetchDate >= 2592000000) {
      needToRefetch = true
    }

    // If localStorage and data is less than 1 month old, fetch 1 time
    if (maxContributors && !needToRefetch) {
      getContributor(Math.floor(Math.random() * Math.floor(parseInt(maxContributors))) + 1)
    } else {
      getMaxContributors(function (randomPage, lastPage) {
        getContributor(randomPage)

        if (window.localStorage) {
          window.localStorage.setItem('max_contributors', lastPage)
        }
      })
    }
  }

  function getMaxContributors (callback) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1', true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          // Get Headers Links last page to generate a random contributor
          var links = linkParser(xhr.getResponseHeader('Link'))
          var randomPage = Math.floor(Math.random() * Math.floor(parseInt(links.last.page, 10))) + 1

          if (window.localStorage) {
            window.localStorage.setItem('fetch_date', Date.now())
          }
          callback(randomPage, links.last.page)
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function getContributor (randomPage) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1&page=' + randomPage, true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var contributor = JSON.parse(xhr.responseText)[0]

          // Remove loading spinner and show avatar
          loadingSpinner.parentNode.removeChild(loadingSpinner)
          contributorAvatar.classList.remove('hidden')
          // Set new values
          contributorAvatar.src = contributor.avatar_url + '&s=80'
          contributorAvatar.parentElement.href = contributor.html_url
          contributorUsername.textContent = contributor.login
          contributorUsername.href = contributor.html_url
          contributorContributions.textContent = contributor.contributions + ' contributions'
          contributorContributions.parentElement.href = 'https://github.com/nodejs/node/commits?author=' + contributor.login
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function linkParser (linkHeader) {
    var regex = /<([^?]+\?per_page=1&[a-z]+=([\d]+))>;[\s]*rel="([a-z]+)"/g
    var array = []
    var object = {}

    while ((array = regex.exec(linkHeader)) !== null) {
      object[array[3]] = {
        url: array[1],
        page: array[2]
      }
    }

    return object
  }
})()

;(function (d, n) {
  'use strict'

  var osMatch = n.platform.match(/(Win|Mac|Linux)/)
  var os = (osMatch && osMatch[1]) || ''
  var arch = n.userAgent.match(/x86_64|Win64|WOW64/) ||
    n.cpuClass === 'x64'
    ? 'x64'
    : 'x86'
  var buttons = d.querySelectorAll('.home-downloadbutton')
  var downloadHead = d.getElementById('home-downloadhead')
  var dlLocal

  function versionIntoHref (nodeList, filename) {
    var linkEls = Array.prototype.slice.call(nodeList)
    var version
    var el

    for (var i = 0; i < linkEls.length; i++) {
      version = linkEls[i].getAttribute('data-version')
      el = linkEls[i]

      // Windows 64-bit files for 0.x.x need to be prefixed with 'x64/'
      if (os === 'Win' && (version[1] === '0' && arch === 'x64')) {
        el.href += arch + '/'
      }

      el.href += filename.replace('%version%', version)
    }
  }

  if (downloadHead && buttons) {
    dlLocal = downloadHead.getAttribute('data-dl-local')
    switch (os) {
      case 'Mac':
        versionIntoHref(buttons, 'node-%version%.pkg')
        downloadHead.textContent = dlLocal + ' macOS (x64)'
        break
      case 'Win':
        versionIntoHref(buttons, 'node-%version%-' + arch + '.msi')
        downloadHead.textContent = dlLocal + ' Windows (' + arch + ')'
        break
      case 'Linux':
        versionIntoHref(buttons, 'node-%version%-linux-x64.tar.xz')
        downloadHead.textContent = dlLocal + ' Linux (x64)'
        break
    }
  }

  // Windows button on download page
  var winButton = d.getElementById('windows-downloadbutton')
  if (winButton && os === 'Win') {
    var winText = winButton.getElementsByTagName('p')[0]
    winButton.href = winButton.href.replace(/x(86|64)/, arch)
    winText.textContent = winText.textContent.replace(/x(86|64)/, arch)
  }
})(document, navigator)
<commit_msg>main.js: switch to `querySelector` (#3846)<commit_after>/* eslint-disable no-var */
// Notice: IE 10 and below is still supported, so disable eslint for the file
// when checking the "var"
;(function () {
  var langPickerTogglerElement = document.querySelector('.lang-picker-toggler')
  var langPickerElement = document.querySelector('.lang-picker')
  var langElements = langPickerElement.querySelectorAll('button')
  // Get the current URL language
  var currentLang = window.location.pathname.split('/')[1] || 'en'
  var currentLangElement = null

  Array.prototype.forEach.call(langElements, function (el) {
    if (el.getAttribute('data-lang') !== currentLang) {
      el.addEventListener('click', function (e) {
        var newLocale = (e.target && e.target.dataset && e.target.dataset.lang) || 'en'
        window.location.assign(window.location.pathname.replace(/\/[a-zA-Z-]+/, '/' + newLocale))
      })
    } else {
      currentLangElement = el
    }
  })

  langPickerTogglerElement.setAttribute('title', currentLangElement.textContent)

  // Remove the current selected language item, because we don't need to choose it
  // any more unless we want to switch to a new language
  langPickerElement.removeChild(currentLangElement.parentNode)

  langPickerTogglerElement.addEventListener('click', function () {
    langPickerElement.classList.toggle('hidden')
    const isAriaExpanded = langPickerTogglerElement.getAttribute('aria-expanded') === 'true'
    langPickerTogglerElement.setAttribute('aria-expanded', !isAriaExpanded)
  })
})()

;(function () {
  var scrollToTop = document.querySelector('#scroll-to-top');

  (window.onscroll = function () {
    window.requestAnimationFrame(function () {
      scrollToTop.style.display = window.pageYOffset > window.innerHeight ? 'block' : 'none'
    })
  })()

  scrollToTop.addEventListener('click', function (e) {
    e.preventDefault()
    window.scrollTo(0, 0)
  })
})()

;(function () {
  var contributorCard = document.querySelector('.contributor-card')

  if (!contributorCard) {
    return
  }

  var contributorAvatar = contributorCard.querySelector('#contributor-avatar')
  var contributorUsername = contributorCard.querySelector('#contributor-username')
  var contributorContributions = contributorCard.querySelector('#contributor-contributions')
  var loadingSpinner = contributorCard.querySelector('.spinner-border')

  if (window.IntersectionObserver) {
    var observer = new window.IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.intersectionRatio > 0.5) {
          // In viewport, fetch a random contributor
          fetchRandomContributor()

          observer.unobserve(entry.target)
        }
      })
    },
    { threshold: 0.5 }
    )

    observer.observe(document.querySelector('footer'))
  } else {
    // Does not support IntersectionObserver
    fetchRandomContributor()
  }

  function fetchRandomContributor () {
    var maxContributors
    var fetchDate
    var needToRefetch = false

    if (window.localStorage) {
      maxContributors = window.localStorage.getItem('max_contributors')
      fetchDate = parseInt(window.localStorage.getItem('fetch_date'), 10)
    }

    // If fetch date is a month old (2592000000 ms === 30 days)
    if (Date.now() - fetchDate >= 2592000000) {
      needToRefetch = true
    }

    // If localStorage and data is less than 1 month old, fetch 1 time
    if (maxContributors && !needToRefetch) {
      getContributor(Math.floor(Math.random() * Math.floor(parseInt(maxContributors))) + 1)
    } else {
      getMaxContributors(function (randomPage, lastPage) {
        getContributor(randomPage)

        if (window.localStorage) {
          window.localStorage.setItem('max_contributors', lastPage)
        }
      })
    }
  }

  function getMaxContributors (callback) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1', true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          // Get Headers Links last page to generate a random contributor
          var links = linkParser(xhr.getResponseHeader('Link'))
          var randomPage = Math.floor(Math.random() * Math.floor(parseInt(links.last.page, 10))) + 1

          if (window.localStorage) {
            window.localStorage.setItem('fetch_date', Date.now())
          }
          callback(randomPage, links.last.page)
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function getContributor (randomPage) {
    var xhr = new window.XMLHttpRequest()
    xhr.open('GET', 'https://api.github.com/repos/nodejs/node/contributors?per_page=1&page=' + randomPage, true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var contributor = JSON.parse(xhr.responseText)[0]

          // Remove loading spinner and show avatar
          loadingSpinner.parentNode.removeChild(loadingSpinner)
          contributorAvatar.classList.remove('hidden')
          // Set new values
          contributorAvatar.src = contributor.avatar_url + '&s=80'
          contributorAvatar.parentElement.href = contributor.html_url
          contributorUsername.textContent = contributor.login
          contributorUsername.href = contributor.html_url
          contributorContributions.textContent = contributor.contributions + ' contributions'
          contributorContributions.parentElement.href = 'https://github.com/nodejs/node/commits?author=' + contributor.login
        } else {
          return contributorCard.parentNode.removeChild(contributorCard)
        }
      }
    }

    xhr.send()
  }

  function linkParser (linkHeader) {
    var regex = /<([^?]+\?per_page=1&[a-z]+=([\d]+))>;[\s]*rel="([a-z]+)"/g
    var array = []
    var object = {}

    while ((array = regex.exec(linkHeader)) !== null) {
      object[array[3]] = {
        url: array[1],
        page: array[2]
      }
    }

    return object
  }
})()

;(function () {
  'use strict'

  var osMatch = navigator.platform.match(/(Win|Mac|Linux)/)
  var os = (osMatch && osMatch[1]) || ''
  var arch = navigator.userAgent.match(/x86_64|Win64|WOW64/) ||
    navigator.cpuClass === 'x64'
    ? 'x64'
    : 'x86'
  var buttons = document.querySelectorAll('.home-downloadbutton')
  var downloadHead = document.querySelector('#home-downloadhead')
  var dlLocal

  function versionIntoHref (nodeList, filename) {
    var linkEls = Array.prototype.slice.call(nodeList)
    var version
    var el

    for (var i = 0; i < linkEls.length; i++) {
      version = linkEls[i].getAttribute('data-version')
      el = linkEls[i]

      // Windows 64-bit files for 0.x.x need to be prefixed with 'x64/'
      if (os === 'Win' && (version[1] === '0' && arch === 'x64')) {
        el.href += arch + '/'
      }

      el.href += filename.replace('%version%', version)
    }
  }

  if (downloadHead && buttons) {
    dlLocal = downloadHead.getAttribute('data-dl-local')
    switch (os) {
      case 'Mac':
        versionIntoHref(buttons, 'node-%version%.pkg')
        downloadHead.textContent = dlLocal + ' macOS (x64)'
        break
      case 'Win':
        versionIntoHref(buttons, 'node-%version%-' + arch + '.msi')
        downloadHead.textContent = dlLocal + ' Windows (' + arch + ')'
        break
      case 'Linux':
        versionIntoHref(buttons, 'node-%version%-linux-x64.tar.xz')
        downloadHead.textContent = dlLocal + ' Linux (x64)'
        break
    }
  }

  // Windows button on download page
  var winButton = document.querySelector('#windows-downloadbutton')
  if (winButton && os === 'Win') {
    var winText = winButton.querySelector('p')
    winButton.href = winButton.href.replace(/x(86|64)/, arch)
    winText.textContent = winText.textContent.replace(/x(86|64)/, arch)
  }
})()
<|endoftext|>


<commit_before>
$(function() {

    // Populate using an object literal
    WTF.init({
        "heading": [
            "How about:",
            "What about:",
            "Hey, you should write about:",
            "Try writing about:",
            "I know, how about:"
        ],

        "response": [
            "Ugh, I've read this somewhere before. Next!",
            "Yawn, boring!",
            "I think I seen this before",
            "Don't you have anything else?",
            "That's such a lame idea.",
            "I think the admissions officers have seen this before",
            "That's so cliché.",
            "Nahh... it doesn't seem like something I'd write about."
        ],

        "template": [
            "what made you @made_you_emotions when you were in @time",
            "what made you @made_you_emotions when you were @prep_sub",
            "Imagine you were a(n) @object. What would you do? How would you feel?",
            "Describe a time when you were @made_you_emotions",
            "What do you think would make a(n) @object @made_you_emotions",
            "Describe your favorite @object",
            "Imagine @per_evt with @hist_fig. What would you do? What would you two talk about?"

        ],

        "made_you_emotions": [
            "happy",
            "well",
            "okay",
            "very well",
            "clean",
            "strong",
            "beautiful",
            "excited",
            "attracted",
            "empowered",
            "intelligent",
            "smarter",
            "better",
            "brave",
            "calm",
            "delightful",
            "eager",
            "jolly",
            "joyful",
            "kind",
            "nice",
            "sweet",
            "proud",
            "relieved",
            "hopeful",
            "faithful",
            "optimistic",
            "loving",
            "open",
            "understanding",
            "amazed",
            "great",
            "lucky",
            "fortunate",
            "festive",
            "moody",
            "playful",
            "animated",
            "wonderful",
            "thrilled",
            "supportive",
            "inspired",
            "demotivated",
            "upset",
            "shocked",
            "enraged",
            "encouraged",
            "amused",
            "relaxed",
            "confused",
            "shameful",
            "wonderful",
            "thrilled",
            "serene",
            "free",
            "liberated",
            "engrossed",
            "involved",
            "hungry",
            "tired",
            "weak",
            "disgruntled",
            "defeated",
            "embarrassed",
            "foolish",
            "silly",
            "hurt",
            "nervous",
            "bashful",
            "joyful",
            "appreciative",
            "tearful",
            "devastated",
            "horrified",
            "annoyed",
            "melancholic",
            "guilty",
            "jealous",
            "frustrated",
            "selfish",
            "overwhelmed"
        ],

        "time": [
            "kindergarten",
            "first grade",
            "second grade",
            "third grade",
            "fourth grade",
            "fifth grade",
            "sixth grade",
            "seventh grade",
            "eighth grade",
            "ninth grade",
            "tenth grade",
            "eleventh grade",
            "twelfth grade",
            "freshman year",
            "sophomore year",
            "junior year",
            "senior year",
        ],

        "prep_sub": [
            "a child",
            "in school",
            "at home",
            "away from home",
            "out of school",
            "in a car",
            "in a bus",
            "in a plane",
            "in your favorite club",
            "with your best friends",
            "with your parents",
            "with your grandparents",
            "with your favorite teacher",
        ],

        "tones": [
            "fresh",
            "bold",
            "happy",
            "devoted",
            "loving",
            "sympathetic",
            "believing",
            "supportive",
            "enlightened",
            "clever",
            "involved",
            "intent"
        ],

        "object": [
            "glassware",
            "cook book",
            "pot",
            "mixing bowl",
            "tupperware",
            "ziplock bag",
            "water pitcher",
            "magazine",
            "newspaper",
            "book",
            "make-up",
            "hair clip",
            "CD",
            "DVD",
            "candle",
            "crystal",
            "vase",
            "computer",
            "smartphone",
            "MP3 Player",
            "furniture",
            "video game",
            "shirt",
            "short",
            "pants",
            "coat",
            "dress",
            "hat",
            "shoe",
            "sandal",
            "boot",
            "jewelry",
            "purse",
            "coin",
            "cash",
            "pillow",
            "linen set",
            "candle holder",
            "TV",
            "magnet",
            "artwork",
            "pen",
            "pencil",
            "old battery",
            "duck tape",
            "masking tape",
            "manual",
            "coupon",
            "broom",
            "rake",
            "leaf",
            "garden hose",
            "board game",
            "puzzles",
            "deck of cards",
            "old school book/papers",
            "toy",
            "stuffed animal",
            "soda",
            "Amazon Kindle",
            "camera",
            "scanner",
            "GPS device",
            "road map",
            "notebook",
            "voice recorder",
            "grocery list",
            "iPod",
            "iPad",
            "radio",
            "comic book",
            "paper receipt",
            "business card"
        ],

        "hist_fig": [
            "Napoleon",
            "Shakespeare",
            "Abraham Lincoln",
            "George Washington",
            "Aristotle",
            "Alexander the Great",
            "Henry VIII of England",
            "Charles Darwin",
            "Elizabeth I of England",
            "Julius Caesar",
            "Queen Victoria",
            "Martin Luther",
            "Albert Einstein",
            "Christopher Columbus",
            "Issac Newton",
            "Charlemagne",
            "Theodore Roosevelt",
            "Wolfgang Amadeus Mozart",
            "Plato",
            "Louis XIV of France",
            "Ludwig van Beethoven",
            "Ulysses S. Grant",
            "Leonardo da Vinci",
            "Augustus",
            "Carl Linnaeus",
            "Ronald Reagan",
            "Charles Dickens",
            "Benjamin Franklin",
            "Genghis Khan",
            "Charles I of England",
            "Thomas Edison",
            "James I of England",
            "Friedrich Nietzsche",
            "Franklin D. Roosevelt",
            "Sigmund Freud",
            "Alexander Hamilton",
            "Mohandas K. Ghandhi",
            "Woodrow Wilson",
            "J. S. Bach",
            "Galileo Galilei",
            "Oliver Cromwell",
            "James Madison",
            "Mark Twain",
            "Edgar Allan Poe",
            "Joseph Smith, Jr.",
            "Adam Smith",
            "George III of the United Kingdom",
            "Immanuel Kant",
            "James Cook",
            "John Adams",
            "Richard Wagner",
            "Pyotr Ilyich Tchaikovsky",
            "Voltaire",
            "Andrew Jackson",
            "Constantine the Great",
            "Socrates",
            "Elvis Presley",
            "William the Conqueror",
            "John F. Kennedy",
            "Augustine of Hippo",
            "Vincent van Gogh",
            "Nicolaus Copernicus",
            "Robert E. Lee",
            "Oscar Wilde",
            "Charles II of England",
            "Cicero",
            "Jean-Jacques Rousseau",
            "Francis Bacon",
            "Richard Nixon",
            "Louis XVI of France",
            "Charles V, Holy Roman Emperor",
            "King Arthur",
            "Michelangelo",
            "Philip II of Spain",
            "Thomas Aquinas",
            "René Descartes",
            "Nikola Tesla",
            "Harry S. Truman",
            "Dante Alighieri",
            "John Calvin",
            "John Locke",
            "Henry David Thoreau"
        ],

        "per_evt": [
            "at a party",
<<<<<<< HEAD
            "breakfast",
            "lunch",
            "dinner",
=======
            "at breakfast",
            "at lunch",
            "at dinner",
>>>>>>> master
            "having tea with",
            "at Starbucks with",
            "in a meeting",
            "being in a college interview",
            "in class",
            "on a Skype call",
            "being in a Google Hangout",
            "in a car ride",
            "in the library",
            "at a resturant",
            "at a diner",
            "in a conference call",
            "hanging out",
            "walking in the park",
            "jogging",
            "studying with",
            "in a book club"
        ]
    });

});
<commit_msg>Fix minor errors<commit_after>
$(function() {

    // Populate using an object literal
    WTF.init({
        "heading": [
            "How about:",
            "What about:",
            "Hey, you should write about:",
            "Try writing about:",
            "I know, how about:"
        ],

        "response": [
            "Ugh, I've read this somewhere before. Next!",
            "Yawn, boring!",
            "I think I seen this before",
            "Don't you have anything else?",
            "That's such a lame idea.",
            "I think the admissions officers have seen this before",
            "That's so cliché.",
            "Nahh... it doesn't seem like something I'd write about."
        ],

        "template": [
            "what made you @made_you_emotions when you were in @time",
            "what made you @made_you_emotions when you were @prep_sub",
            "Imagine you were a(n) @object. What would you do? How would you feel?",
            "Describe a time when you were @made_you_emotions",
            "What do you think would make a(n) @object @made_you_emotions",
            "Describe your favorite @object",
            "Imagine @per_evt with @hist_fig. What would you do? What would you two talk about?"

        ],

        "made_you_emotions": [
            "happy",
            "well",
            "okay",
            "very well",
            "clean",
            "strong",
            "beautiful",
            "excited",
            "attracted",
            "empowered",
            "intelligent",
            "smarter",
            "better",
            "brave",
            "calm",
            "delightful",
            "eager",
            "jolly",
            "joyful",
            "kind",
            "nice",
            "sweet",
            "proud",
            "relieved",
            "hopeful",
            "faithful",
            "optimistic",
            "loving",
            "open",
            "understanding",
            "amazed",
            "great",
            "lucky",
            "fortunate",
            "festive",
            "moody",
            "playful",
            "animated",
            "wonderful",
            "thrilled",
            "supportive",
            "inspired",
            "demotivated",
            "upset",
            "shocked",
            "enraged",
            "encouraged",
            "amused",
            "relaxed",
            "confused",
            "shameful",
            "wonderful",
            "thrilled",
            "serene",
            "free",
            "liberated",
            "engrossed",
            "involved",
            "hungry",
            "tired",
            "weak",
            "disgruntled",
            "defeated",
            "embarrassed",
            "foolish",
            "silly",
            "hurt",
            "nervous",
            "bashful",
            "joyful",
            "appreciative",
            "tearful",
            "devastated",
            "horrified",
            "annoyed",
            "melancholic",
            "guilty",
            "jealous",
            "frustrated",
            "selfish",
            "overwhelmed"
        ],

        "time": [
            "kindergarten",
            "first grade",
            "second grade",
            "third grade",
            "fourth grade",
            "fifth grade",
            "sixth grade",
            "seventh grade",
            "eighth grade",
            "ninth grade",
            "tenth grade",
            "eleventh grade",
            "twelfth grade",
            "freshman year",
            "sophomore year",
            "junior year",
            "senior year",
        ],

        "prep_sub": [
            "a child",
            "in school",
            "at home",
            "away from home",
            "out of school",
            "in a car",
            "in a bus",
            "in a plane",
            "in your favorite club",
            "with your best friends",
            "with your parents",
            "with your grandparents",
            "with your favorite teacher",
        ],

        "tones": [
            "fresh",
            "bold",
            "happy",
            "devoted",
            "loving",
            "sympathetic",
            "believing",
            "supportive",
            "enlightened",
            "clever",
            "involved",
            "intent"
        ],

        "object": [
            "glassware",
            "cook book",
            "pot",
            "mixing bowl",
            "tupperware",
            "ziplock bag",
            "water pitcher",
            "magazine",
            "newspaper",
            "book",
            "make-up",
            "hair clip",
            "CD",
            "DVD",
            "candle",
            "crystal",
            "vase",
            "computer",
            "smartphone",
            "MP3 Player",
            "furniture",
            "video game",
            "shirt",
            "short",
            "pants",
            "coat",
            "dress",
            "hat",
            "shoe",
            "sandal",
            "boot",
            "jewelry",
            "purse",
            "coin",
            "cash",
            "pillow",
            "linen set",
            "candle holder",
            "TV",
            "magnet",
            "artwork",
            "pen",
            "pencil",
            "old battery",
            "duck tape",
            "masking tape",
            "manual",
            "coupon",
            "broom",
            "rake",
            "leaf",
            "garden hose",
            "board game",
            "puzzles",
            "deck of cards",
            "old school book/papers",
            "toy",
            "stuffed animal",
            "soda",
            "Amazon Kindle",
            "camera",
            "scanner",
            "GPS device",
            "road map",
            "notebook",
            "voice recorder",
            "grocery list",
            "iPod",
            "iPad",
            "radio",
            "comic book",
            "paper receipt",
            "business card"
        ],

        "hist_fig": [
            "Napoleon",
            "Shakespeare",
            "Abraham Lincoln",
            "George Washington",
            "Aristotle",
            "Alexander the Great",
            "Henry VIII of England",
            "Charles Darwin",
            "Elizabeth I of England",
            "Julius Caesar",
            "Queen Victoria",
            "Martin Luther",
            "Albert Einstein",
            "Christopher Columbus",
            "Issac Newton",
            "Charlemagne",
            "Theodore Roosevelt",
            "Wolfgang Amadeus Mozart",
            "Plato",
            "Louis XIV of France",
            "Ludwig van Beethoven",
            "Ulysses S. Grant",
            "Leonardo da Vinci",
            "Augustus",
            "Carl Linnaeus",
            "Ronald Reagan",
            "Charles Dickens",
            "Benjamin Franklin",
            "Genghis Khan",
            "Charles I of England",
            "Thomas Edison",
            "James I of England",
            "Friedrich Nietzsche",
            "Franklin D. Roosevelt",
            "Sigmund Freud",
            "Alexander Hamilton",
            "Mohandas K. Ghandhi",
            "Woodrow Wilson",
            "J. S. Bach",
            "Galileo Galilei",
            "Oliver Cromwell",
            "James Madison",
            "Mark Twain",
            "Edgar Allan Poe",
            "Joseph Smith, Jr.",
            "Adam Smith",
            "George III of the United Kingdom",
            "Immanuel Kant",
            "James Cook",
            "John Adams",
            "Richard Wagner",
            "Pyotr Ilyich Tchaikovsky",
            "Voltaire",
            "Andrew Jackson",
            "Constantine the Great",
            "Socrates",
            "Elvis Presley",
            "William the Conqueror",
            "John F. Kennedy",
            "Augustine of Hippo",
            "Vincent van Gogh",
            "Nicolaus Copernicus",
            "Robert E. Lee",
            "Oscar Wilde",
            "Charles II of England",
            "Cicero",
            "Jean-Jacques Rousseau",
            "Francis Bacon",
            "Richard Nixon",
            "Louis XVI of France",
            "Charles V, Holy Roman Emperor",
            "King Arthur",
            "Michelangelo",
            "Philip II of Spain",
            "Thomas Aquinas",
            "René Descartes",
            "Nikola Tesla",
            "Harry S. Truman",
            "Dante Alighieri",
            "John Calvin",
            "John Locke",
            "Henry David Thoreau"
        ],

        "per_evt": [
            "at a party",
            "breakfast",
            "lunch",
            "dinner",
            "having tea with",
            "at Starbucks with",
            "in a meeting",
            "being in a college interview",
            "in class",
            "on a Skype call",
            "being in a Google Hangout",
            "in a car ride",
            "in the library",
            "at a resturant",
            "at a diner",
            "in a conference call",
            "hanging out",
            "walking in the park",
            "jogging",
            "studying with",
            "in a book club"
        ]
    });

});
<|endoftext|>


<commit_before>/*
 * Init login overlay
 */
$('document').ready(function () {
    $('#modaloverlay').click(function () {
        hideModal();
    });

    $('.modal_box').click(function (e) {
        e.stopPropagation();
    });

    $('#usermanagement').click(function () {
        showLogin();
    });

    $('#loginform').submit(function (e) {
        // Hide the error message
        $('#login_error').hide();

        // Post the form
        $.ajax({
            type: "POST",
            url: "/login/" + encodeURIComponent($('#loginform').find('input[name="email"]').val()),
            data: $('#loginform').serialize(),
            success: function () {
                // Reload page when logged in
                location.reload();
            },
            error: function () {
                // Display error message
                $('#login_error').html(i18n.__("ServiceNotReachableError"));
                $('#login_error').show();
            }
        });

        // Stop form submit via normal post
        e.preventDefault();
    });
});

/*
 * Log out a user from the system
 */
function logoutUser() {
    $.ajax({
        url: 'logout',
        success: function () {
            location.reload();
        }
    });
}

/*
 * Show the login modal
 */
function showLogin() {
    // Clear the form
    $('#login_error').hide();
    $('#loginform')[0].reset();

    // Show the login window
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#login_modal').show();
    $('#modaloverlay').show();
}

/*
 * Show the Yes and No modal with callback
 */
function showYesNoModal(body, callback) {
    // Hide the login window
    $('#login_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#yes_no_modal').show();

    // Fill up the body
    $('#modal_title_body').html = body;

    // Show the modal
    $('#modaloverlay').show();

    $('#ynmodel-y-btn').click(function () {
        callback(true);
        hideModal();
    });

    $('#ynmodal-n-btn').click(function () {
        callback(false);
        hideModal();
    });
}

function showUploadModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').show();

    $('#modaloverlay').show();
}

function showGeneralModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#upload_modal').hide();
    $('#general_modal').show();

    // Show the modal
    $('#modaloverlay').show();
}

function setGeneralModalTitle(title)
{
    $('#general_modal_title').html(title);
}

function setGeneralModalBody(body)
{
    $('#general_modal_body').html(body);
}

function getGeneralModalBody()
{
    return $('#general_modal_body').html();
}

function addGeneralModalButton(text, action)
{
    var button = document.createElement('button');
    $(button).addClass('btn btn-primary inline btn-extra-margin');
    $(button).click(function () {
        action();
    });
    $(button).html(text);
    $('#general_modal_buttons').append(button);
}

function resetGeneralModal()
{
    $('#general_modal_title').empty();
    $('#general_modal_body').empty();
    $('#general_modal_buttons').empty();
}

function hideModal() {
    $('#modaloverlay').hide();
}

$(document).ready(function () {
    $('#uploadformbtn').click(function () {
        // Get the form data. This serializes the entire form. pritty easy huh!
        var form = new FormData($('#uploadform')[0]);

        // Make the ajax call
        $.ajax({
            url: '/api/upload',
            type: 'POST',
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progress, false);
                }
                return myXhr;
            },
            //add beforesend handler to validate or something
            beforeSend: function () {
                $('progress').attr({value: 0, max: 100});
                $('#upload-result').html('Progress: <progress value="0" max="100" id="progressbar"></progress>');
            },
            success: function (res) {
                $('#upload-result').html('
Uploaded files:

');

                $.each(res, function (index, elem) {
                    var div = document.createElement('div');
                    div.className += 'upimage';
                    $('#uploaded-files').append(div);

                    div.innerHTML += '
';
                    div.innerHTML += 'id: ' + elem['id'] + '
';
                    div.innerHTML += 'type: ' + elem['type'] + '
';
                    div.innerHTML += 'name: ' + elem['name'] + '
';
                    div.innerHTML += 'size: ' + elem['size'] + '';
                });
            },
            //add error handler for when a error occurs if you want!
            error: function (xhr, status, error) {
                setGeneralModalTitle('Upload error');
                setGeneralModalBody(xhr.responseText);
                showGeneralModal();

            },
            data: form,
            // this is the important stuf you need to overide the usual post behavior
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e) {
    if (e.lengthComputable) {
        //this makes a nice fancy progress bar
        $('progress').attr({value: e.loaded, max: e.total});
    }
}<commit_msg>updated upload to fit in dptcms<commit_after>/*
 * Init login overlay
 */
$('document').ready(function () {
    $('#modaloverlay').click(function () {
        hideModal();
    });

    $('.modal_box').click(function (e) {
        e.stopPropagation();
    });

    $('#usermanagement').click(function () {
        showLogin();
    });

    $('#loginform').submit(function (e) {
        // Hide the error message
        $('#login_error').hide();

        // Post the form
        $.ajax({
            type: "POST",
            url: "/login/" + encodeURIComponent($('#loginform').find('input[name="email"]').val()),
            data: $('#loginform').serialize(),
            success: function () {
                // Reload page when logged in
                location.reload();
            },
            error: function () {
                // Display error message
                $('#login_error').html(i18n.__("ServiceNotReachableError"));
                $('#login_error').show();
            }
        });

        // Stop form submit via normal post
        e.preventDefault();
    });
});

/*
 * Log out a user from the system
 */
function logoutUser() {
    $.ajax({
        url: 'logout',
        success: function () {
            location.reload();
        }
    });
}

/*
 * Show the login modal
 */
function showLogin() {
    // Clear the form
    $('#login_error').hide();
    $('#loginform')[0].reset();

    // Show the login window
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#login_modal').show();
    $('#modaloverlay').show();
}

/*
 * Show the Yes and No modal with callback
 */
function showYesNoModal(body, callback) {
    // Hide the login window
    $('#login_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#yes_no_modal').show();

    // Fill up the body
    $('#modal_title_body').html = body;

    // Show the modal
    $('#modaloverlay').show();

    $('#ynmodel-y-btn').click(function () {
        callback(true);
        hideModal();
    });

    $('#ynmodal-n-btn').click(function () {
        callback(false);
        hideModal();
    });
}

function showUploadModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').show();

    $('#modaloverlay').show();
}

function showGeneralModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#upload_modal').hide();
    $('#general_modal').show();

    // Show the modal
    $('#modaloverlay').show();
}

function setGeneralModalTitle(title)
{
    $('#general_modal_title').html(title);
}

function setGeneralModalBody(body)
{
    $('#general_modal_body').html(body);
}

function getGeneralModalBody()
{
    return $('#general_modal_body').html();
}

function addGeneralModalButton(text, action)
{
    var button = document.createElement('button');
    $(button).addClass('btn btn-primary inline btn-extra-margin');
    $(button).click(function () {
        action();
    });
    $(button).html(text);
    $('#general_modal_buttons').append(button);
}

function resetGeneralModal()
{
    $('#general_modal_title').empty();
    $('#general_modal_body').empty();
    $('#general_modal_buttons').empty();
}

function hideModal() {
    $('#modaloverlay').hide();
}

$(document).ready(function () {
    $('#uploadformbtn').click(function () {
        // Get the form data. This serializes the entire form. pritty easy huh!
        var form = new FormData($('#uploadform')[0]);

        // Make the ajax call
        $.ajax({
            url: '/api/upload',
            type: 'POST',
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progress, false);
                }
                return myXhr;
            },
            //add beforesend handler to validate or something
            beforeSend: function () {
                $('progress').attr({value: 0, max: 100});
                $('#upload-result').html('Progress: <progress value="0" max="100" id="progressbar"></progress>');
            },
            success: function (res) {
                $('#upload-result').html('
Uploaded files:

');

                $.each(res, function (index, elem) {
                    var div = document.createElement('div');
                    div.className += 'upimage';
                    $('#uploaded-files').append(div);

                    div.innerHTML += '
';
                    div.innerHTML += 'id: ' + elem['id'] + '
';
                    div.innerHTML += 'type: ' + elem['type'] + '
';
                    div.innerHTML += 'name: ' + elem['name'] + '
';
                    div.innerHTML += 'size: ' + elem['size'] + '';
                });
            },
            //add error handler for when a error occurs if you want!
            error: function (xhr, status, error) {
                setGeneralModalTitle('Upload error');
                setGeneralModalBody(xhr.responseText);
                showGeneralModal();

            },
            data: form,
            // this is the important stuf you need to overide the usual post behavior
            //cache: false,
            //contentType: false,
            //processData: false
        });
    });
});

// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e) {
    if (e.lengthComputable) {
        //this makes a nice fancy progress bar
        $('progress').attr({value: e.loaded, max: e.total});
    }
}<|endoftext|>


<commit_before>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl__all'),
    tag2       = $('.android'),
    tag3       = $('.tools_using'),
    tag4       = $('.ubuntu'),
    tag5       = $('.place_your_tag_name_here'),
    tag6       = $('.place_your_tag_name_here');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Codepen embed js
// http://codepen.io/assets/embed/ei.js
// Added on 17 Nov 2013
var CodePenEmbed={width:"100%",init:function(){this.showCodePenEmbeds(),this.listenToParentPostMessages()},showCodePenEmbeds:function(){var e=document.getElementsByClassName("codepen");for(var t=e.length-1;t>-1;t--){var n=this._getParamsFromAttributes(e[t]);n=this._convertOldDataAttributesToNewDataAttributes(n);var r=this._buildURL(n),i=this._buildIFrame(n,r);this._addIFrameToPage(e[t],i)}},_getParamsFromAttributes:function(e){var t={},n=e.attributes;for(var r=0,i=n.length;r<i;r++)name=n[r].name,name.indexOf("data-")===0&&(t[name.replace("data-","")]=n[r].value);return t},_convertOldDataAttributesToNewDataAttributes:function(e){return e.href&&(e["slug-hash"]=e.href),e.type&&(e["default-tab"]=e.type),e.safe&&(e["safe"]=="true"?e.animations="run":e.animations="stop-after-5"),e},_buildURL:function(e){var t=this._getHost(e),n=e.user?e.user:"anon",r="?"+this._getGetParams(e),i=[t,n,"embed",e["slug-hash"]+r].join("/");return i.replace(/\/\//g,"//")},_getHost:function(e){return e.host?e.host:document.location.protocol=="file:"?"http://codepen.io":"//codepen.io"},_getGetParams:function(e){var t="",n=0;for(var r in e)t!==""&&(t+="&"),t+=r+"="+encodeURIComponent(e[r]);return t},_buildIFrame:function(e,t){var n={id:"cp_embed_"+e["slug-hash"].replace("/","_"),src:t,scrolling:"no",frameborder:"0",height:this._getHeight(e),allowTransparency:"true","class":"cp_embed_iframe",style:"width: "+this.width+"; overflow: hidden;"},r="",r},_getHeight:function(e){return e.height?e["height"]=="auto"?300:e.height:300},_addIFrameToPage:function(e,t){if(e.parentNode){var n=document.createElement("div");n.innerHTML=t,e.parentNode.replaceChild(n,e)}else e.innerHTML=t},listenToParentPostMessages:function(){var eventMethod=window.addEventListener?"addEventListener":"attachEvent",eventListener=window[eventMethod],messageEvent=eventMethod=="attachEvent"?"onmessage":"message";eventListener(messageEvent,function(e){try{var dataObj=eval("("+e.data+")"),iframe=document.getElementById("cp_embed_"+dataObj.hash);iframe&&(iframe.height=dataObj.height)}catch(err){}},!1)}};

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Embed codepen after pjax
  CodePenEmbed.init();

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
      identifier = $('#post__title').data('identifier');
  window.disqus_shortname = '';
  window.disqus_identifier = identifier;

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<commit_msg>change hightlight.js<commit_after>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl__all'),
    tag2       = $('.android'),
    tag3       = $('.tools_using'),
    tag4       = $('.ubuntu'),
    tag5       = $('.place_your_tag_name_here'),
    tag6       = $('.place_your_tag_name_here');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});
<|endoftext|>


<commit_before>var app = {};

(function(exports) {
   var settings = {
      gravityAngle : 0,
      gravityMagnitude : 4.8,
      impulseMagnitude : 0.0001,
      targetFPS : 30,
      timeStep : 1 / 30,
      stepSize : 4,
      beachHeight: 50
   }

   var world,
       bodies;

   var gx = [],
       gy = [];

   var changeGravity = function() {
      // smooth
      var sumx = 0,
          sumy = 0;

      for (var i in gx) { sumx += gx[i]; }
      for (var i in gy) { sumy += gy[i]; }

      sumx /= gx.length;
      sumy /= gy.length;

      gx = [];
      gy = [];

      world.gravity({
         x : sumx,
         y : sumy
      });

      var angle = Math.atan(gy/gx);

      bodies.beachball.ApplyImpulse({
         x : -Math.cos(angle) * settings.impulseMagnitude,
         y : Math.sin(angle) * settings.impulseMagnitude
      },
      bodies.beachball.GetWorldCenter());
   };

   $(document).ready(function() {
      var w = $(window);

      // Update the settings once the DOM has been fully loaded
      settings.beachball = {
         x : w.width() / 2 + 'px',
         y : '100px'
      }

      var beachball = $('#beachball'),
          safeZone = $('#safe-zone'),
          dangerZone = $('#danger-zone');

      // Reposition the the sand
      safeZone.css('left', w.width()/2 - safeZone.width()/2 + 'px')
              .css('top', w.height() - settings.beachHeight + 'px');
      dangerZone.css('left', w.width()/2 - dangerZone.width()/2 + 'px')
                .css('top', w.height() - settings.beachHeight + 'px');

      // Set up the box2d components
      world = box2dw.world({
         drawScale : w.width(),
         gravity : {
            x : Math.sin(settings.gravityAngle) * settings.gravityMagnitude,
            y : Math.cos(settings.gravityAngle) * settings.gravityMagnitude
         }
      });

      var beachRadius = parseInt(/([0-9]+)/.exec(dangerZone.css('-webkit-border-top-left-radius'))[1]),
          beachFlat = dangerZone.width() - beachRadius*2;

      // Sensor function for when the beachball falls through the floor
      var onFloorHit = function(sensor, bodyA, bodyB) {
         var body;
         if (bodyA.id == '#beachball') { body = bodyA; }
         else if (bodyB.id == '#beachball') { body = bodyB; }

         if (body) {
            var splashX = ((body.GetPosition().x * world.drawScale) < w.width()/2)
                      ? 0
                      : w.width() - $('#splash').width();

            $('#splash').css('bottom', '0px')
                        .css('left', splashX + 'px')
                        .show(100, function() {
                           $(this).fadeOut(800, function() {
                              exports.reset('game over!
try again!
');
                           });
                        });
         }
      };

      // Set up the bodies.
      // The beach bodies consist of two circles cexportsing the danger zone
      // with a rectangle over the safe zone between them
      bodies = {
         floor : world.body({
            static : true,
            sensorCallback : onFloorHit,
            x : w.width()/2 + 'px',
            y : w.height() + 'px',
            width : w.width() * 4 + 'px',
            height : '10px'
         }),
         beachCenter : world.body({
            shape : 'box',
            x : w.width()/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            width : beachFlat + 'px',
            height : beachRadius * 2 + 'px',
            id : '#dangerZone'
         }),
         beachCapRight : world.body({
            shape : 'circle',
            x : w.width()/2 + beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachCapLeft : world.body({
            shape : 'circle',
            x : w.width()/2 - beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachball : world.body({
            shape : 'circle',
            static : false,
            radius : beachball.width() + 'px',
            x : settings.beachball.x,
            y : settings.beachball.y,
            id : '#beachball'
         })
      }

      var worldLastTimeout = null;

      function step() {
        var delay = settings.timeStep * 1000;
        world.world.Step(settings.timeStep, settings.stepSize, settings.stepSize);

        $.each(world.bodies, function(i, body) {
            if (body.id != undefined) {
               var pos = body.GetPosition(),
                   obj = $(body.id);

               obj.css('left', pos.x * world.drawScale - obj.width()/2 + 'px');
               obj.css('top', pos.y * world.drawScale + 'px');
               obj.rotate(body.GetAngle() / Math.PI * 180);
            }
        });

        world.world.ClearForces();
        worldLastTimeout = setTimeout(step, (delay > 0) ? delay : 0);
      }

      exports.running = false;

      // Pause the simulation
      var pause = exports.pause = function() {
         clearTimeout(worldLastTimeout);
         exports.running = false;
      }

      // Start the simulation if it hasn't been started
      var start = exports.start = function() {
         if (!exports.running) {
            step();
            exports.running = true;
         }
      }

      // Reset the simulation
      var reset = exports.reset  = function(message) {
         pause();
         bodies.beachball.SetAngularVelocity(0);
         bodies.beachball.SetLinearVelocity({
            x : 0,
            y : 0
         });
         bodies.beachball.SetPositionAndAngle({
            x : world.toMeters(settings.beachball.x),
            y : world.toMeters(settings.beachball.y)
         }, 0);
         $(exports).triggerHandler({
            type : 'game.reset',
            message : message
         });
      };

      if (window.DeviceMotionEvent != undefined) {
         var lastGravityInterval = -1,
             gravityDelay = 100;

         window.ondevicemotion = function (e) {
            gx.push(e.accelerationIncludingGravity.x);
            gy.push(e.accelerationIncludingGravity.y);
         }

         $(app).on('game.reset game.stop game.pause', function(e) {
            clearInterval(lastGravityInterval);
         });

         $(app).on('game.start game.unpause', function(e) {
            lastGravityInterval = setInterval(changeGravity, gravityDelay);
         });

         // Start the simulation
         start();
      }
      else {
         $(app).triggerHandler({type: 'game.stop', message: 'gravity not supported in your browser'});
         $('#start').hide();
      }
   });
})(app);

(function(app) {
   var lastInterval = -1,
       c = 0,
       delay = 1000,
       counter = $('#counter');

   var step = function() {
     counter.text(c);
     c += 1;
   }

   $('#start').click(function() {
      $(this).hide();
      $(app).triggerHandler({type: 'game.start'});
   });

   $(app).on('game.reset game.stop', function(e) {
      clearInterval(lastInterval);
      counter.html(e.message || 'beachball madness!');
      c = 0;
      $('#start').show();
   });

   $(app).on('game.start game.unpause', function() {
      lastInterval = setInterval(step, delay);
      step();
   });

   $(app).on('game.pause', function() {
      clearInterval(lastInterval);
   });
})(app);
<commit_msg>Testing<commit_after>var app = {};

(function(app) {
   var settings = {
      impulseMagnitude : 0.0001,
      targetFPS : 30,
      timeStep : 1 / 30,
      stepSize : 4,
      beachHeight: 50
   }

   var Game = function() {};

   var world,
       bodies,
       running,
       gx = [],
       gy = [];

   // Sensor function for when the beachball falls through the floor
   var onFloorHit = function(sensor, bodyA, bodyB) {
      var body;
      if (bodyA.id == '#beachball') { body = bodyA; }
      else if (bodyB.id == '#beachball') { body = bodyB; }

      if (body) {
         $(Game).triggerHandler({type: 'game.wallHit', body: body});
      }
   };

   var worldLastTimeout = -1;
   var worldStep = function() {
     var delay = settings.timeStep * 1000;
     world.world.Step(settings.timeStep, settings.stepSize, settings.stepSize);

     $.each(world.bodies, function(i, body) {
         if (body.id != undefined) {
            var pos = body.GetPosition(),
                obj = $(body.id);

            obj.css('left', pos.x * world.drawScale - obj.width()/2 + 'px');
            obj.css('top', pos.y * world.drawScale + 'px');
            obj.rotate(body.GetAngle() / Math.PI * 180);
         }
     });

     world.world.ClearForces();
     worldLastTimeout = setTimeout(worldStep, (delay > 0) ? delay : 0);
   }

   // Smooth the gravity data from the device and change
   // the gravity of the world.
   var changeGravity = function() {
      var sumx = 0,
          sumy = 0;

      for (var i in gx) { sumx += gx[i]; }
      for (var i in gy) { sumy += gy[i]; }

      sumx /= gx.length;
      sumy /= gy.length;

      gx = [];
      gy = [];

      if (!isNaN(sumx) && !isNaN(sumy)) {

      world.gravity({
         x : sumx,
         y : sumy
      });

      var angle = Math.atan(gy/gx);

      bodies.beachball.ApplyImpulse({
         x : -Math.cos(angle) * settings.impulseMagnitude,
         y : Math.sin(angle) * settings.impulseMagnitude
      },
      bodies.beachball.GetWorldCenter());
      }
   };

   // The initial position of the beachball
   var beachballPosition;

   Game.drawScale = function() {
      return world.drawScale;
   }

   Game.running = function() {
      return running;
   }

   // Pause the simulation
   $(Game).on('game.pause', function() {
      clearTimeout(worldLastTimeout);
      running = false;
   });

   // Start the simulation if it hasn't been started
   $(Game).on('game.start', function() {
      if (!running) {
         worldStep();
         running = true;
      }
   });

   // Reset the simulation
   $(Game).on('game.reset', function(msg) {
      clearTimeout(worldLastTimeout);
      running = false;

      bodies.beachball.SetAngularVelocity(0);
      bodies.beachball.SetLinearVelocity({
         x : 0,
         y : 0
      });
      bodies.beachball.SetPositionAndAngle({
         x : world.toMeters(beachballPosition.x),
         y : world.toMeters(beachballPosition.y)
      }, 0);
   });

   // Call when the DOM has been fully loaded and the game needs to
   // be initialized.
   Game.init = function() {
      var w = $(window),
          beachball = $('#beachball'),
          safeZone = $('#safe-zone'),
          dangerZone = $('#danger-zone');

      beachballPosition = {
         x : w.width() / 2 + 'px',
         y : '100px'
      }

      // Set up the box2d components
      world = box2dw.world({
         drawScale : w.width(),
         gravity : {
            x : 0,
            y : 9.8
         }
      });

      // Reposition the sand
      safeZone.css('left', w.width()/2 - safeZone.width()/2 + 'px')
              .css('top', w.height() - settings.beachHeight + 'px');
      dangerZone.css('left', w.width()/2 - dangerZone.width()/2 + 'px')
                .css('top', w.height() - settings.beachHeight + 'px');

      var beachRadius = parseInt(/([0-9]+)/.exec(dangerZone.css('-webkit-border-top-left-radius'))[1]),
          beachFlat = dangerZone.width() - beachRadius*2;

      // Set up the bodies.
      // The beach bodies consist of two circles capping the danger zone
      // with a rectangle over the safe zone between them
      bodies = {
         floor : world.body({
            static : true,
            sensorCallback : onFloorHit,
            x : w.width()/2 + 'px',
            y : w.height() + 'px',
            width : w.width() * 4 + 'px',
            height : '10px'
         }),
         beachCenter : world.body({
            shape : 'box',
            x : w.width()/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            width : beachFlat + 'px',
            height : beachRadius * 2 + 'px',
            id : '#dangerZone'
         }),
         beachCapRight : world.body({
            shape : 'circle',
            x : w.width()/2 + beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachCapLeft : world.body({
            shape : 'circle',
            x : w.width()/2 - beachFlat/2 + 'px',
            y : w.height() - settings.beachHeight + beachRadius + 'px',
            radius : beachRadius + 'px'
         }),
         beachball : world.body({
            shape : 'circle',
            static : false,
            radius : beachball.width() + 'px',
            x : beachballPosition.x,
            y : beachballPosition.y,
            id : '#beachball'
         })
      }

      if (window.DeviceMotionEvent != 1) {
         var lastGravityInterval = -1,
             gravityDelay = 100;

         window.ondevicemotion = function (e) {
            gx.push(e.accelerationIncludingGravity.x);
            gy.push(e.accelerationIncludingGravity.y);
         }

         $(Game).on('game.reset game.stop game.pause', function(e) {
            clearInterval(lastGravityInterval);
         });

         $(Game).on('game.start game.unpause', function(e) {
            lastGravityInterval = setInterval(changeGravity, gravityDelay);
         });

         // Start the simulation
         $(Game).triggerHandler({type : 'game.start' });
      }
      else {
         $(Game).triggerHandler({type : 'game.notLoaded', reason : 'gravity not supported in your browser'});
      }
   };

   app.game = Game;
   app.settings = settings;

})(app);

// UI
(function(app) {
   $(document).ready(function() {
      var game = app.game,
          counterLastInterval = -1,
          c = 0,
          delay = 1000,
          counter = $('#counter');

      var step = function() {
        counter.text(c);
        c += 1;
      }

      game.init();

      $('#start').click(function() {
         $(this).hide();
         $(game).triggerHandler({type: 'game.start'});
      });

      $(game).on('game.reset game.stop', function(e) {
         clearInterval(counterLastInterval);
         counter.html(e.message || 'beachball madness!');
         c = 0;
         $('#start').show();
      });

      $(game).on('game.start game.unpause', function() {
         counterLastInterval = setInterval(step, delay);
         step();
      });

      $(game).on('game.pause', function() {
         clearInterval(counterLastInterval);
      });

      $(game).on('game.notLoaded', function(reason) {
         $('#counter').html(reason);
         $('#start').hide();
      });

      $(game).on('game.wallHit', function(e) {
         var drawScale = game.drawScale(),
             w = $(window);

         var splashX = ((e.body.GetPosition().x * drawScale) < w.width()/2)
                   ? 0
                   : w.width() - $('#splash').width();

         $('#splash').css('bottom', '0px')
                     .css('left', splashX + 'px')
                     .show(100, function() {
                        $(this).fadeOut(800, function() {
                           $(game).triggerHandler({type : 'game.reset', message : 'game over!
try again!
'});
                        });
                     });
      });
   });
})(app);
<|endoftext|>


<commit_before>// pollRoute.js

var express = require('express');
var router = express.Router();
var pollValidator = require('../helper/pollValidator');
var voteValidator = require('../helper/voteValidator');
var MongoClient = require('mongodb').MongoClient;
var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/polls';
var Poll = require('../model/Poll').init(mongoURI, MongoClient);
var shortid = require('shortid');

/**
 *
 * URI /poll/submit
 *
 * Receives ajax request and stores polls to db.
 * - Validate submition
 * - Create unique url for each poll
 *
 **/
router.post('/submit', function(req, res) {
    var poll = req.body;
    pollValidator(poll, function(err) {
        if (err) {
            res.json({error: err});
        } else {
            var pollUrl = shortid.generate();
            poll.url = pollUrl;

            Poll.save(poll, function(err) {
                if (err) {
                    console.log(err);
                    res.json({error: 'db error'});
                }else {
                    console.log('sending json...');
                    res.json(pollUrl);
                }
            });

        }
    });
});

router.get('/:id',function(req,res){
    var poll=req.params;
    Poll.get(poll.id,function(err,data) {
        if (err) {
            console.log(err);
            res.json({error: 'db error'});
        }else{
            console.log(poll.id);
            console.log(data);
            res.json(data);
        }
    })
});

router.post('/vote', function(req, res) {
    var poll = req.body;
    var url=poll.url;
    var option=poll.choice;
    voteValidator(poll, function(err) {
        if (err) {
            res.json({error: err});
        } else {

//$inc:{choices[option].vote : 1}

            Poll.update({ "url": url },
                {  },
                { upsert: true },function (err, numUpdated) {
                if (err) {
                    console.log(err);
                } else if (numUpdated) {
                    console.log('Updated Successfully %d document(s).', numUpdated);
                } else {
                    console.log('No document found with defined "find" criteria!');
                }});

        }
    });
});

module.exports = router;
<commit_msg>completed vote update operation<commit_after>// pollRoute.js

var express = require('express');
var router = express.Router();
var pollValidator = require('../helper/pollValidator');
var voteValidator = require('../helper/voteValidator');
var MongoClient = require('mongodb').MongoClient;
var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost:27017/polls';
var Poll = require('../model/Poll').init(mongoURI, MongoClient);
var shortid = require('shortid');

/**
 *
 * URI /poll/submit
 *
 * Receives ajax request and stores polls to db.
 * - Validate submition
 * - Create unique url for each poll
 *
 **/
router.post('/submit', function(req, res) {
    var poll = req.body;
    pollValidator(poll, function(err) {
        if (err) {
            res.json({error: err});
        } else {
            var pollUrl = shortid.generate();
            poll.url = pollUrl;
            for(var i=0;i<poll.choices.length;i++){
                poll[i].vote=0;
            }

            Poll.save(poll, function(err) {
                if (err) {
                    console.log(err);
                    res.json({error: 'db error'});
                }else {
                    console.log('sending json...');
                    res.json(pollUrl);
                }
            });

        }
    });
});

router.get('/:id',function(req,res){
    var poll=req.params;
    Poll.get(poll.id,function(err,data) {
        if (err) {
            console.log(err);
            res.json({error: 'db error'});
        }else{
            console.log(poll.id);
            console.log(data);
            res.json(data);
        }
    })
});

router.post('/vote', function(req, res) {
    var poll = req.body;
    var url=poll.url;
    var option=poll.choice;
    voteValidator(poll, function(err) {
        if (err) {
            res.json({error: err});
        } else {

//$inc:{choices[option].vote : 1}

            Poll.update({ "url": url ,"choices.name":option },
                {$inc:{"choices.$.vote":1 } },
                { upsert: true },function (err, numUpdated) {
                if (err) {
                    console.log(err);
                } else if (numUpdated) {
                    console.log('Updated Successfully %d document(s).', numUpdated);
                } else {
                    console.log('No document found with defined "find" criteria!');
                }});

        }
    });
});

module.exports = router;
<|endoftext|>