<commit_before>log(['---------------','GAME', '---------------']);

window.addEventListener('load', (function(){

    //Stuff
    var dom_characters, dom_hands, the_chosen_one, count_alives;
    var characters = getCharacters();
    var container = document.getElementById('character_container');
    var hand_container = document.getElementById('hands');
    var step = 0;
    var indexKill = 0;
    var canKill = false;
    var canClue = true;
    var limitReach = false;
    var clue_index = 0;
    var memoryKilled = 0;
    var step_kills = [];
    var dom_content = document.getElementById('content');
    init();

    var listClueCharacter = generateListClue(the_chosen_one);
    launchClue();

    function init(){
    	log('-> Init');
    	createCharacters();
    	the_chosen_one = createTheChosenOne();
    	launchStep();

    	for(var i = 0 ; i < dom_characters.length; i++){
    	    dom_hands[i].addEventListener("click", killCharacter);
    	}
    }

    function handlers(){
      document.getElementById('home').addEventListener('click', nav_home);
      document.getElementById('text_clue').addEventListener('click', help_clue);
      document.getElementById('replay').addEventListener('click', replay_sound);
      document.getElementById('clue').addEventListener('click', launchClue);
    }

    function nav_home(){
      console.log('nav_home');
    }

    function help_clue(){
      console.log('help_clue');
      printContent(listClueCharacter[clue_index-1].prefix + ' ' + listClueCharacter[clue_index-1].attribut);
    }

    function replay_sound(){
      console.log('replay_sound');
       playClue(listClueCharacter[clue_index-1]);
    }

    function printContent(c){
      dom_content.textContent = c;
    }

    function createCharacters(){
    	log('-> Creation of the Characters');
    	for (var i = 0 ; i < characters.length ; i++){
    	    var c = document.createElement('img');
    	    c.setAttribute("id", i);
    	    c.setAttribute("class", "character");
            c.src = 'ressource/img/characters/' + (characters[i].id + 1) + '.png';
    	    container.appendChild(c);

          var h = document.createElement('img');
          h.setAttribute("id", i);
          h.setAttribute("class", "hands");
          h.src = 'ressource/img/characters/' + 'hands_' + (characters[i].id + 1) + '.png';
          hand_container.appendChild(h);

    	}
    	dom_characters = document.getElementsByClassName("character");
      dom_hands = document.getElementsByClassName("hands");
    	count_alives = characters.length;
    }

    function createTheChosenOne(){
	log('-> Choose The Chosen One');
	var roll = Math.floor((Math.random() * characters.length) + 1);
	log(['The Chosen One is character ' + roll, characters[roll-1]]);
	return characters[roll-1];
    }

  function launchStep(){
    log('-> Launch Step');
    log('Etape : ' + step);

    handlers();
  }

    function launchClue(){
    	cleanKills();

	if (clue_index > listClueCharacter.length) {
	    return;
	}

	console.log("INDEX KILL  = " + indexKill);

	if (indexKill == 11) {
	    for (index = 0; index < characters.length; index++) {
		if (characters[index].isDead == false) {
		    if (the_chosen_one.id == characters[index].id) {
			console.log("WIN THE GAME");
			endGame();
		    }
		    else {
			console.log("YOU ARE FAIL");
			endGame();
		    }
		}
	    }
	}

    	log('-> Launch Clue');

    	if(canClue){
          document.getElementById('clue').style.display="inline-block";
          dom_content.textContent = "";
    	    playClue(listClueCharacter[clue_index]);
    	    log(the_chosen_one);

    	    log('CLUE : ' + listClueCharacter[clue_index].prefix + ' ' + listClueCharacter[clue_index].attribut);

    	    clue_index += 1;
    	    step += 1;
    	    log('Etape : ' + step);
    	    canKill = true;
    	    canClue = false;

    	}else{
    	    log("CAN'T CLUE FOR NOW");
    	}
    }

    function killCharacter(e){

    	log('-> Action Character');
    	checkLimit();

	if (indexKill == 11) {
	    return ;
	}

	if (characters[e.target.id].id == the_chosen_one.id) {
	    console.log("............................... error target GAME OVER");
	    //endGame();
	}

    	if(canKill){
    	    if(step_kills.indexOf(e.target.id)>=0) {
    		log('REVIVE '+e.target.id);
    		dom_characters[e.target.id].setAttribute('class', 'character');
    		step_kills.splice(step_kills.indexOf(e.target.id),1);
    		memoryKilled -= 1;
    		log(memoryKilled);
    		if(memoryKilled <= 0){
    		    canClue = false;
    		}
    		if(limitReach==true){
    		    limitReach = false;
    		}
    	    }else{
    		if(limitReach==true){
    		    log('CAN NOT KILL : LIMIT');
    		}else{
		    indexKill += 1;
    		    log('KILL '+e.target.id);
    		    dom_characters[e.target.id].setAttribute('class', 'character dead animated bounce');
    		    step_kills.push(e.target.id);
    		    canClue = true;
    		    memoryKilled += 1;
    		    log(memoryKilled);
    		}
    	    }
    	}else{
    	    log('CAN NOT KILL');
    	}
    }

    function cleanKills(){
	memoryKilled = 0;

	correctError(null, null);
	for(var i = 0; i<step_kills.length; i++){
	    characters[step_kills[i]]['isDead'] = step;
	}

	var deads_char = document.getElementsByClassName('dead');
	var nb_lefts = characters.length - deads_char.length;
	count_alives = nb_lefts;
	log('Alive : '+count_alives);

	for(var i = 0; i<characters.length; i++){
	    if(characters[i]["isDead"]){
		log(characters[i]);
		dom_characters[i].style.opacity=0;
		// var c = characters[i];
		// var r = clue;
		// correctError(c, r);
	    }
	}
	step_kills = [];
    }

    function endGame(){
	log('-> endGame');
	canKill = canClue = false;
	document.location.href = "endGame.html"
	// correctError();
    }

    function correctError(character, r) {
	// log('-> correctError');
	// console.log(r[clue_index].prefix);
	// console.log(r[clue_index].attribut);

	// var p = r[clue_index].prefix;
	// var a = r[clue_index].attribut;

	// if(p == 'She has' || p == 'He has'){
	//   if(
	//     (a == 'brown mustache' && character.mustache == "brown") ||
	//     (a == 'blond mustache' && character.mustache == "blond") ||
	//     (a == 'beard' && character.beard == "") ||
	//     (a == 'blond hair' && character.hair == "blond") ||
	//     (a == 'black hair' && character.hair == "black") ||
	//     (a == 'brown hair' && character.hair == "brown") ||
	//     (a == 'red hair' && character.hair == "red") ||
	//     (a == 'green eye' && character.eye == "green") ||
	//     (a == 'brown eye' && character.eye == "green") ||
	//     (a == 'blue eye' && character.eye == "green") ||
	//     (a == 'hat' && character.hat == "") ||
	//     (a == 'green mask' && character.mask == "green") ||
	//     (a == 'blue mask' && character.mask == "blue") ||
	//     (a == 'red mask' && character.mask == "red") ||
	//     (a == 'black mask' && character.mask == "black")
	//     ){
	//     console.log('JUSTE');
	//   }else{
	//     console.log('FAUX');
	//   }
	// }else{
	//   if(
	//     (a == 'mustache' && character.mustache == null) ||
	//     (a == 'beard' && character.beard == null) ||
	//     (a == 'hair' && character.hair == null) ||
	//     (a == 'hat' && character.hat == null) ||
	//     (a == 'mask' && character.mask == null)
	//     ){
	//     console.log('JUSTE');
	//   }else{
	//     console.log('FAUX');
	//   }
	// }

	// if(clue_index == 0){

	// }

    }

    function checkLimit(){
	var last_char = document.getElementsByClassName('dead');
	console.log('DEBUG :');
	console.log(last_char.length);
	if(last_char.length == characters.length-1){
	    console.log('ATTENTION NE PEUX PAS SUPPRIMER LE DERNIER');
	    limitReach = true;
	}
    }

    function getKilledCharacters(){
    	var tab = [];
    	for(var i = 0; i<characters.length; i++){
  	    if(characters[i]['isDead']){
    		tab[i] = characters[i];
  	    }
    	}
    	return tab;
    }

}));

<commit_msg>save data error<commit_after>log(['---------------','GAME', '---------------']);

window.addEventListener('load', (function(){

    //Stuff
    var dom_characters, dom_hands, the_chosen_one, count_alives;
    var characters = getCharacters();
    var container = document.getElementById('character_container');
    var hand_container = document.getElementById('hands');
    var step = 0;
    var indexKill = 0;
    var canKill = false;
    var canClue = true;
    var limitReach = false;
    var clue_index = 0;
    var memoryKilled = 0;
    var step_kills = [];
    var dom_content = document.getElementById('content');
    var Error = {
	this.setp;
	this.character;
	this.currentWrongClue;
    }
    var error;
    init();

    var listClueCharacter = generateListClue(the_chosen_one);
    launchClue();

    function init(){
    	log('-> Init');
    	createCharacters();
    	the_chosen_one = createTheChosenOne();
    	launchStep();

    	for(var i = 0 ; i < dom_characters.length; i++){
    	    dom_hands[i].addEventListener("click", killCharacter);
    	}
    }

    function handlers(){
      document.getElementById('home').addEventListener('click', nav_home);
      document.getElementById('text_clue').addEventListener('click', help_clue);
      document.getElementById('replay').addEventListener('click', replay_sound);
      document.getElementById('clue').addEventListener('click', launchClue);
    }

    function nav_home(){
      console.log('nav_home');
    }

    function help_clue(){
      console.log('help_clue');
      printContent(listClueCharacter[clue_index-1].prefix + ' ' + listClueCharacter[clue_index-1].attribut);
    }

    function replay_sound(){
      console.log('replay_sound');
       playClue(listClueCharacter[clue_index-1]);
    }

    function printContent(c){
      dom_content.textContent = c;
    }

    function createCharacters(){
    	log('-> Creation of the Characters');
    	for (var i = 0 ; i < characters.length ; i++){
    	    var c = document.createElement('img');
    	    c.setAttribute("id", i);
    	    c.setAttribute("class", "character");
            c.src = 'ressource/img/characters/' + (characters[i].id + 1) + '.png';
    	    container.appendChild(c);

          var h = document.createElement('img');
          h.setAttribute("id", i);
          h.setAttribute("class", "hands");
          h.src = 'ressource/img/characters/' + 'hands_' + (characters[i].id + 1) + '.png';
          hand_container.appendChild(h);

    	}
    	dom_characters = document.getElementsByClassName("character");
      dom_hands = document.getElementsByClassName("hands");
    	count_alives = characters.length;
    }

    function createTheChosenOne(){
	log('-> Choose The Chosen One');
	var roll = Math.floor((Math.random() * characters.length) + 1);
	log(['The Chosen One is character ' + roll, characters[roll-1]]);
	return characters[roll-1];
    }

  function launchStep(){
    log('-> Launch Step');
    log('Etape : ' + step);

    handlers();
  }

    function launchClue(){
    	cleanKills();

	if (clue_index > listClueCharacter.length) {
	    return;
	}

	console.log("INDEX KILL  = " + indexKill);

	if (indexKill == 11) {
	    for (index = 0; index < characters.length; index++) {
		if (characters[index].isDead == false) {
		    if (the_chosen_one.id == characters[index].id) {
			console.log("WIN THE GAME");
			endGame();
		    }
		    else {
			console.log("YOU ARE FAIL");
			endGame();
		    }
		}
	    }
	}

    	log('-> Launch Clue');

    	if(canClue){
          document.getElementById('clue').style.display="inline-block";
          dom_content.textContent = "";
    	    playClue(listClueCharacter[clue_index]);
    	    log(the_chosen_one);

    	    log('CLUE : ' + listClueCharacter[clue_index].prefix + ' ' + listClueCharacter[clue_index].attribut);

    	    clue_index += 1;
    	    step += 1;
    	    log('Etape : ' + step);
    	    canKill = true;
    	    canClue = false;

    	}else{
    	    log("CAN'T CLUE FOR NOW");
    	}
    }

    function killCharacter(e){

    	log('-> Action Character');
    	checkLimit();

	if (indexKill == 11) {
	    return ;
	}

	if (characters[e.target.id].id == the_chosen_one.id) {
	    console.log("............................... error target GAME OVER");
	    error = new Error();
	    error.character = the_chosen_one;
	    error.currentWrongClue = listClueCharacter[clue_index];
	    //endGame();
	}

    	if(canKill){
    	    if(step_kills.indexOf(e.target.id)>=0) {
    		log('REVIVE '+e.target.id);
    		dom_characters[e.target.id].setAttribute('class', 'character');
    		step_kills.splice(step_kills.indexOf(e.target.id),1);
    		memoryKilled -= 1;
    		log(memoryKilled);
    		if(memoryKilled <= 0){
    		    canClue = false;
    		}
    		if(limitReach==true){
    		    limitReach = false;
    		}
    	    }else{
    		if(limitReach==true){
    		    log('CAN NOT KILL : LIMIT');
    		}else{
		    indexKill += 1;
    		    log('KILL '+e.target.id);
    		    dom_characters[e.target.id].setAttribute('class', 'character dead animated bounce');
    		    step_kills.push(e.target.id);
    		    canClue = true;
    		    memoryKilled += 1;
    		    log(memoryKilled);
    		}
    	    }
    	}else{
    	    log('CAN NOT KILL');
    	}
    }

    function cleanKills(){
	memoryKilled = 0;

	correctError(null, null);
	for(var i = 0; i<step_kills.length; i++){
	    characters[step_kills[i]]['isDead'] = step;
	}

	var deads_char = document.getElementsByClassName('dead');
	var nb_lefts = characters.length - deads_char.length;
	count_alives = nb_lefts;
	log('Alive : '+count_alives);

	for(var i = 0; i<characters.length; i++){
	    if(characters[i]["isDead"]){
		log(characters[i]);
		dom_characters[i].style.opacity=0;
		// var c = characters[i];
		// var r = clue;
		// correctError(c, r);
	    }
	}
	step_kills = [];
    }

    function endGame(){
	log('-> endGame');
	canKill = canClue = false;
	document.location.href = "endGame.html"
	// correctError();
    }

    function correctError(character, r) {
	// log('-> correctError');
	// console.log(r[clue_index].prefix);
	// console.log(r[clue_index].attribut);

	// var p = r[clue_index].prefix;
	// var a = r[clue_index].attribut;

	// if(p == 'She has' || p == 'He has'){
	//   if(
	//     (a == 'brown mustache' && character.mustache == "brown") ||
	//     (a == 'blond mustache' && character.mustache == "blond") ||
	//     (a == 'beard' && character.beard == "") ||
	//     (a == 'blond hair' && character.hair == "blond") ||
	//     (a == 'black hair' && character.hair == "black") ||
	//     (a == 'brown hair' && character.hair == "brown") ||
	//     (a == 'red hair' && character.hair == "red") ||
	//     (a == 'green eye' && character.eye == "green") ||
	//     (a == 'brown eye' && character.eye == "green") ||
	//     (a == 'blue eye' && character.eye == "green") ||
	//     (a == 'hat' && character.hat == "") ||
	//     (a == 'green mask' && character.mask == "green") ||
	//     (a == 'blue mask' && character.mask == "blue") ||
	//     (a == 'red mask' && character.mask == "red") ||
	//     (a == 'black mask' && character.mask == "black")
	//     ){
	//     console.log('JUSTE');
	//   }else{
	//     console.log('FAUX');
	//   }
	// }else{
	//   if(
	//     (a == 'mustache' && character.mustache == null) ||
	//     (a == 'beard' && character.beard == null) ||
	//     (a == 'hair' && character.hair == null) ||
	//     (a == 'hat' && character.hat == null) ||
	//     (a == 'mask' && character.mask == null)
	//     ){
	//     console.log('JUSTE');
	//   }else{
	//     console.log('FAUX');
	//   }
	// }

	// if(clue_index == 0){

	// }

    }

    function checkLimit(){
	var last_char = document.getElementsByClassName('dead');
	console.log('DEBUG :');
	console.log(last_char.length);
	if(last_char.length == characters.length-1){
	    console.log('ATTENTION NE PEUX PAS SUPPRIMER LE DERNIER');
	    limitReach = true;
	}
    }

    function getKilledCharacters(){
    	var tab = [];
    	for(var i = 0; i<characters.length; i++){
  	    if(characters[i]['isDead']){
    		tab[i] = characters[i];
  	    }
    	}
    	return tab;
    }

}));

<|endoftext|>


<commit_before>const amount = document.querySelector('#amount');
const rate = document.querySelector('#rate');
const years = document.querySelector('#years');
const result = document.querySelector('#result');

const amount$ = Rx.Observable.fromEvent(amount, 'input')
  .map(event => event.target.value)
  .startWith(amount.value);

const rate$ = Rx.Observable.fromEvent(rate, 'input')
  .map(event => event.target.value)
  .startWith(rate.value);

const years$ = Rx.Observable.fromEvent(years, 'input')
  .map(event => event.target.value)
  .startWith(years.value);

Rx.Observable.combineLatest(
  amount$,
  rate$,
  years$,
  (amount, rate, years)=> (parseInt(amount) + (amount / 100 * rate) * years)
).subscribe((x)=> result.innerHTML = `Total debt: £${x}`);
<commit_msg>Refactored the first example to make testing easier.<commit_after>const amount = document.querySelector('#amount');
const rate = document.querySelector('#rate');
const years = document.querySelector('#years');
const result = document.querySelector('#result');

// Helper function to get a stream of values from each input.
const inputStreamGenerator = (element) => {
  return Rx.Observable.fromEvent(element, 'input')
    .map(event => event.target.value)
    .startWith(element.value);
};

const amount$ = inputStreamGenerator(amount);
const rate$ = inputStreamGenerator(rate);
const years$ = inputStreamGenerator(years);

const calculateDebt = (amount, rate, years) => {
  return parseInt(amount) + (amount / 100 * rate) * years
};

// Merge the latest values from each stream and update the output.
Rx.Observable.combineLatest(
  amount$,
  rate$,
  years$,
  (amount, rate, years) => calculateDebt(amount, rate, years)
).subscribe((x)=> result.innerHTML = `Total debt: £${x}`);
<|endoftext|>


<commit_before>'use strict';

const AbstractModule = require('../Core/AbstractModule');

class Xvideos extends AbstractModule {
  get name () {
    return 'xVideos';
  }

  get firstpage () {
    return 1;
  }

  videoUrl (page) {
    return `https://www.xvideos.com/?k=${this.query}&p=${page || this.firstpage}`;
  }

  videoParser ($) {
    let videos = $('#content .mozaique .thumb-block');

    return videos.map((i, video) => {
      video = $.load($(video).find('.thumb script').text().match(/(<.*>)/).pop());
      let description = video.find('p');

      return {
        title: description.eq(0).text(),
        url: 'https://xvideos.com' + $('a').attr('href'),
        duration: description.find('strong').text(),
        thumb: $('img').attr('src')
      };
    }).get();
  }
};

module.exports = Xvideos;
<commit_msg>firstpage<commit_after>'use strict';

const AbstractModule = require('../Core/AbstractModule');

class Xvideos extends AbstractModule {
  get name () {
    return 'xVideos';
  }

  get firstpage () {
    return 0;
  }

  videoUrl (page) {
    return `https://www.xvideos.com/?k=${this.query}&p=${page || this.firstpage}`;
  }

  videoParser ($) {
    let videos = $('#content .mozaique .thumb-block');

    return videos.map((i, video) => {
      video = $.load($(video).find('.thumb script').text().match(/(<.*>)/).pop());
      let description = video.find('p');

      return {
        title: description.eq(0).text(),
        url: 'https://xvideos.com' + $('a').attr('href'),
        duration: description.find('strong').text(),
        thumb: $('img').attr('src')
      };
    }).get();
  }
};

module.exports = Xvideos;
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var spawn = require('child_process').spawn;
var yeoman = require('yeoman-generator');

var AppGenerator = module.exports = function Appgenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  // setup the test-framework property, Gruntfile template will need this
  this.testFramework = options['test-framework'] || 'mocha';

  // for hooks to resolve on mocha by default
  if (!options['test-framework']) {
    options['test-framework'] = 'mocha';
  }

  // resolved to mocha by default (could be switched to jasmine for instance)
  this.hookFor('test-framework', { as: 'app' });

  this.indexFile = this.readFileAsString(path.join(this.sourceRoot(), 'index.html'));
  this.mainCoffeeFile = 'console.log "\'Allo from CoffeeScript!"';

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(AppGenerator, yeoman.generators.Base);

AppGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  console.log(this.yeoman);
  console.log('Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.');

  var prompts = [{
    type: 'checkbox',
    name: 'features',
    message: 'What more would you like?',
    choices: [{
      name: 'Twitter Bootstrap for Sass',
      value: 'compassBootstrap',
      checked: true
    }, {
      name: 'RequireJS',
      value: 'includeRequireJS',
      checked: true
    }, {
      name: 'Autoprefixer for your CSS',
      value: 'autoprefixer',
      checked: true
    }]
  }];

  this.prompt(prompts, function (answers) {
    var features = answers.features;

    // manually deal with the response, get back and store the results.
    // we change a bit this way of doing to automatically do this in the self.prompt() method.
    this.compassBootstrap = features.indexOf('compassBootstrap') !== -1;
    this.includeRequireJS = features.indexOf('includeRequireJS') !== -1;
    this.autoprefixer = features.indexOf('autoprefixer') !== -1;

    cb();
  }.bind(this));
};

AppGenerator.prototype.gruntfile = function gruntfile() {
  this.template('Gruntfile.js');
};

AppGenerator.prototype.packageJSON = function packageJSON() {
  this.template('_package.json', 'package.json');
};

AppGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

AppGenerator.prototype.bower = function bower() {
  this.copy('bowerrc', '.bowerrc');
  this.copy('_bower.json', 'bower.json');
};

AppGenerator.prototype.jshint = function jshint() {
  this.copy('jshintrc', '.jshintrc');
};

AppGenerator.prototype.editorConfig = function editorConfig() {
  this.copy('editorconfig', '.editorconfig');
};

AppGenerator.prototype.h5bp = function h5bp() {
  this.copy('favicon.ico', 'app/favicon.ico');
  this.copy('404.html', 'app/404.html');
  this.copy('robots.txt', 'app/robots.txt');
  this.copy('htaccess', 'app/.htaccess');
};

AppGenerator.prototype.bootstrapImg = function bootstrapImg() {
  if (this.compassBootstrap) {
    this.copy('glyphicons-halflings.png', 'app/images/glyphicons-halflings.png');
    this.copy('glyphicons-halflings-white.png', 'app/images/glyphicons-halflings-white.png');
  }
};

AppGenerator.prototype.bootstrapJs = function bootstrapJs() {
  // TODO: create a Bower component for this
  if (this.compassBootstrap) {
    this.copy('bootstrap.js', 'app/scripts/vendor/bootstrap.js');
  }
};

AppGenerator.prototype.mainStylesheet = function mainStylesheet() {
  if (this.compassBootstrap) {
    this.copy('main.scss', 'app/styles/main.scss');
  } else {
    this.copy('main.css', 'app/styles/main.css');
  }
};

AppGenerator.prototype.writeIndex = function writeIndex() {
  // prepare default content text
  var defaults = ['HTML5 Boilerplate'];
  var contentText = [
    '
',
    '
',
    '
\'Allo, \'Allo!
',
    '
You now have
',
    '
'
  ];

  if (!this.includeRequireJS) {
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/main.js', [
      'bower_components/jquery/jquery.js',
      'scripts/main.js'
    ]);

    this.indexFile = this.appendFiles({
      html: this.indexFile,
      fileType: 'js',
      optimizedPath: 'scripts/coffee.js',
      sourceFileList: ['scripts/hello.js'],
      searchPath: '.tmp'
    });
  }

  if (this.compassBootstrap) {
    defaults.push('Twitter Bootstrap');
  }

  if (this.compassBootstrap && !this.includeRequireJS) {
    // wire Twitter Bootstrap plugins
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
      'bower_components/sass-bootstrap/js/bootstrap-affix.js',
      'bower_components/sass-bootstrap/js/bootstrap-alert.js',
      'bower_components/sass-bootstrap/js/bootstrap-dropdown.js',
      'bower_components/sass-bootstrap/js/bootstrap-tooltip.js',
      'bower_components/sass-bootstrap/js/bootstrap-modal.js',
      'bower_components/sass-bootstrap/js/bootstrap-transition.js',
      'bower_components/sass-bootstrap/js/bootstrap-button.js',
      'bower_components/sass-bootstrap/js/bootstrap-popover.js',
      'bower_components/sass-bootstrap/js/bootstrap-typeahead.js',
      'bower_components/sass-bootstrap/js/bootstrap-carousel.js',
      'bower_components/sass-bootstrap/js/bootstrap-scrollspy.js',
      'bower_components/sass-bootstrap/js/bootstrap-collapse.js',
      'bower_components/sass-bootstrap/js/bootstrap-tab.js'
    ]);
  }

  if (this.includeRequireJS) {
    defaults.push('RequireJS');
  }

  // iterate over defaults and create content string
  defaults.forEach(function (el) {
    contentText.push('
' + el  +'
');
  });

  contentText = contentText.concat([
    '
',
    '
installed.
',
    '
Enjoy coding! - Yeoman
',
    '
',
    '
',
    ''
  ]);

  // append the default content
  this.indexFile = this.indexFile.replace('', '\n' + contentText.join('\n'));
};

// TODO(mklabs): to be put in a subgenerator like rjs:app
AppGenerator.prototype.requirejs = function requirejs() {
  if (!this.includeRequireJS) {
    return;
  }

  this.indexFile = this.appendScripts(this.indexFile, 'scripts/main.js', ['bower_components/requirejs/require.js'], {
    'data-main': 'scripts/main'
  });

  // add a basic amd module
  this.write('app/scripts/app.js', [
    '/*global define */',
    'define([], function () {',
    '    \'use strict\';\n',
    '    return \'\\\'Allo \\\'Allo!\';',
    '});'
  ].join('\n'));

  this.template('require_main.js', 'app/scripts/main.js');
};

AppGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.mkdir('app/styles');
  this.mkdir('app/images');
  this.write('app/index.html', this.indexFile);
  this.write('app/scripts/hello.coffee', this.mainCoffeeFile);
  if (!this.includeRequireJS) {
    this.write('app/scripts/main.js', 'console.log(\'\\\'Allo \\\'Allo!\');');
  }
};
<commit_msg>Add --skip-install-message, --skip-welcome-message<commit_after>'use strict';
var util = require('util');
var path = require('path');
var spawn = require('child_process').spawn;
var yeoman = require('yeoman-generator');

var AppGenerator = module.exports = function Appgenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  // setup the test-framework property, Gruntfile template will need this
  this.testFramework = options['test-framework'] || 'mocha';

  // for hooks to resolve on mocha by default
  if (!options['test-framework']) {
    options['test-framework'] = 'mocha';
  }

  // resolved to mocha by default (could be switched to jasmine for instance)
  this.hookFor('test-framework', { as: 'app' });

  this.indexFile = this.readFileAsString(path.join(this.sourceRoot(), 'index.html'));
  this.mainCoffeeFile = 'console.log "\'Allo from CoffeeScript!"';

  this.on('end', function () {
    this.installDependencies({
      skipInstall: options['skip-install'],
      skipMessage: options['skip-install-message']
    });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(AppGenerator, yeoman.generators.Base);

AppGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  if (!this.options['skip-welcome-message']) {
    console.log(this.yeoman);
    console.log('Out of the box I include HTML5 Boilerplate, jQuery and Modernizr.');
  }

  var prompts = [{
    type: 'checkbox',
    name: 'features',
    message: 'What more would you like?',
    choices: [{
      name: 'Twitter Bootstrap for Sass',
      value: 'compassBootstrap',
      checked: true
    }, {
      name: 'RequireJS',
      value: 'includeRequireJS',
      checked: true
    }, {
      name: 'Autoprefixer for your CSS',
      value: 'autoprefixer',
      checked: true
    }]
  }];

  this.prompt(prompts, function (answers) {
    var features = answers.features;

    // manually deal with the response, get back and store the results.
    // we change a bit this way of doing to automatically do this in the self.prompt() method.
    this.compassBootstrap = features.indexOf('compassBootstrap') !== -1;
    this.includeRequireJS = features.indexOf('includeRequireJS') !== -1;
    this.autoprefixer = features.indexOf('autoprefixer') !== -1;

    cb();
  }.bind(this));
};

AppGenerator.prototype.gruntfile = function gruntfile() {
  this.template('Gruntfile.js');
};

AppGenerator.prototype.packageJSON = function packageJSON() {
  this.template('_package.json', 'package.json');
};

AppGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

AppGenerator.prototype.bower = function bower() {
  this.copy('bowerrc', '.bowerrc');
  this.copy('_bower.json', 'bower.json');
};

AppGenerator.prototype.jshint = function jshint() {
  this.copy('jshintrc', '.jshintrc');
};

AppGenerator.prototype.editorConfig = function editorConfig() {
  this.copy('editorconfig', '.editorconfig');
};

AppGenerator.prototype.h5bp = function h5bp() {
  this.copy('favicon.ico', 'app/favicon.ico');
  this.copy('404.html', 'app/404.html');
  this.copy('robots.txt', 'app/robots.txt');
  this.copy('htaccess', 'app/.htaccess');
};

AppGenerator.prototype.bootstrapImg = function bootstrapImg() {
  if (this.compassBootstrap) {
    this.copy('glyphicons-halflings.png', 'app/images/glyphicons-halflings.png');
    this.copy('glyphicons-halflings-white.png', 'app/images/glyphicons-halflings-white.png');
  }
};

AppGenerator.prototype.bootstrapJs = function bootstrapJs() {
  // TODO: create a Bower component for this
  if (this.compassBootstrap) {
    this.copy('bootstrap.js', 'app/scripts/vendor/bootstrap.js');
  }
};

AppGenerator.prototype.mainStylesheet = function mainStylesheet() {
  if (this.compassBootstrap) {
    this.copy('main.scss', 'app/styles/main.scss');
  } else {
    this.copy('main.css', 'app/styles/main.css');
  }
};

AppGenerator.prototype.writeIndex = function writeIndex() {
  // prepare default content text
  var defaults = ['HTML5 Boilerplate'];
  var contentText = [
    '
',
    '
',
    '
\'Allo, \'Allo!
',
    '
You now have
',
    '
'
  ];

  if (!this.includeRequireJS) {
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/main.js', [
      'bower_components/jquery/jquery.js',
      'scripts/main.js'
    ]);

    this.indexFile = this.appendFiles({
      html: this.indexFile,
      fileType: 'js',
      optimizedPath: 'scripts/coffee.js',
      sourceFileList: ['scripts/hello.js'],
      searchPath: '.tmp'
    });
  }

  if (this.compassBootstrap) {
    defaults.push('Twitter Bootstrap');
  }

  if (this.compassBootstrap && !this.includeRequireJS) {
    // wire Twitter Bootstrap plugins
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
      'bower_components/sass-bootstrap/js/bootstrap-affix.js',
      'bower_components/sass-bootstrap/js/bootstrap-alert.js',
      'bower_components/sass-bootstrap/js/bootstrap-dropdown.js',
      'bower_components/sass-bootstrap/js/bootstrap-tooltip.js',
      'bower_components/sass-bootstrap/js/bootstrap-modal.js',
      'bower_components/sass-bootstrap/js/bootstrap-transition.js',
      'bower_components/sass-bootstrap/js/bootstrap-button.js',
      'bower_components/sass-bootstrap/js/bootstrap-popover.js',
      'bower_components/sass-bootstrap/js/bootstrap-typeahead.js',
      'bower_components/sass-bootstrap/js/bootstrap-carousel.js',
      'bower_components/sass-bootstrap/js/bootstrap-scrollspy.js',
      'bower_components/sass-bootstrap/js/bootstrap-collapse.js',
      'bower_components/sass-bootstrap/js/bootstrap-tab.js'
    ]);
  }

  if (this.includeRequireJS) {
    defaults.push('RequireJS');
  }

  // iterate over defaults and create content string
  defaults.forEach(function (el) {
    contentText.push('
' + el  +'
');
  });

  contentText = contentText.concat([
    '
',
    '
installed.
',
    '
Enjoy coding! - Yeoman
',
    '
',
    '
',
    ''
  ]);

  // append the default content
  this.indexFile = this.indexFile.replace('', '\n' + contentText.join('\n'));
};

// TODO(mklabs): to be put in a subgenerator like rjs:app
AppGenerator.prototype.requirejs = function requirejs() {
  if (!this.includeRequireJS) {
    return;
  }

  this.indexFile = this.appendScripts(this.indexFile, 'scripts/main.js', ['bower_components/requirejs/require.js'], {
    'data-main': 'scripts/main'
  });

  // add a basic amd module
  this.write('app/scripts/app.js', [
    '/*global define */',
    'define([], function () {',
    '    \'use strict\';\n',
    '    return \'\\\'Allo \\\'Allo!\';',
    '});'
  ].join('\n'));

  this.template('require_main.js', 'app/scripts/main.js');
};

AppGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.mkdir('app/styles');
  this.mkdir('app/images');
  this.write('app/index.html', this.indexFile);
  this.write('app/scripts/hello.coffee', this.mainCoffeeFile);
  if (!this.includeRequireJS) {
    this.write('app/scripts/main.js', 'console.log(\'\\\'Allo \\\'Allo!\');');
  }
};
<|endoftext|>


<commit_before>// ==UserScript==
// @author      Robert Slifka (github @rslifka)
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepage    https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        Fate of All Fools
// @require     https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.css
// @run-at      document-start
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// @version     346
// ==/UserScript==
<commit_msg>AUTO-CREATED Release Artifact v347 c/o Travis<commit_after>// ==UserScript==
// @author      Robert Slifka (github @rslifka)
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepage    https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        Fate of All Fools
// @require     https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.css
// @run-at      document-start
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// @version     347
// ==/UserScript==
<|endoftext|>


<commit_before>// note: sourced from the Internet (don't recall where exactly)
window.mobilecheck = function() {
	var check = false;
	(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
	if(!check)
		window.alert("Best viewed on mobile. Larger display support coming soon!");
}<commit_msg>center alignment and updated mobile prompt<commit_after>// note: sourced from the Internet (don't recall where exactly)
window.mobilecheck = function() {
	var check = false;
	(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
	if(!check)
		window.alert("Best viewed on iPhone SE (built for one-handed displays).\nTo view in responsive mode: CMD+Alt+R on Safari after enabling the develop menu, or CMD+Shift+I, then CMD+Shift+M on Chrome (replace CMD with CTRL for Windows).");
}<|endoftext|>


<commit_before>'use strict';

// Formulas are deprecated, we're now using meter, accumulate, aggregate
// and rate Javascript functions instead

module.exports = {
  resource_id: 'analytics',
  measures: [
    {
      name: 'classifiers',
      unit: 'INSTANCE'
    },
    {
      name: 'classifier_api_calls',
      unit: 'CALL'
    },
    {
      name: 'training_event_api_calls',
      unit: 'CALL'
    }],
  metrics: [
    {
      name: 'classifier_instances',
      unit: 'INSTANCE',
      formula: 'AVG({classifier})'
    },
    {
      name: 'classifier_api_calls',
      unit: 'CALL',
      formula: 'SUM({classifier_api.calls})'
    },
    {
      name: 'training_event_api_calls',
      unit: 'CALL',
      formula: 'SUM({training_event_api_calls})'
    }]
};

<commit_msg>Add header comment to sample resource config<commit_after>'use strict';

// A sample analytics service that uses metering formulas

// Formulas are deprecated, we're now using meter, accumulate, aggregate
// and rate Javascript functions instead

module.exports = {
  resource_id: 'analytics',
  measures: [
    {
      name: 'classifiers',
      unit: 'INSTANCE'
    },
    {
      name: 'classifier_api_calls',
      unit: 'CALL'
    },
    {
      name: 'training_event_api_calls',
      unit: 'CALL'
    }],
  metrics: [
    {
      name: 'classifier_instances',
      unit: 'INSTANCE',
      formula: 'AVG({classifier})'
    },
    {
      name: 'classifier_api_calls',
      unit: 'CALL',
      formula: 'SUM({classifier_api.calls})'
    },
    {
      name: 'training_event_api_calls',
      unit: 'CALL',
      formula: 'SUM({training_event_api_calls})'
    }]
};

<|endoftext|>


<commit_before>Parse.initialize("FwVMmzHookZZ5j9F9ILc2E5MT5ufabuV7hCXKSeu");
Parse.serverURL = 'http://129.25.12.218:1337/parse';
var Submission = Parse.Object.extend("CSSGridGarden");

var game = {
  language: window.location.hash.substring(1) || 'en',
  level: parseInt(localStorage.level, 10) || 0,
  answers: (localStorage.answers && JSON.parse(localStorage.answers)) || {},
  solved: (localStorage.solved && JSON.parse(localStorage.solved)) || [],
  user: localStorage.user || '',
  changed: false,

  start: function() {
    game.translate();

    $('#level-counter .total').text(levels.length);
    $('#editor').show();
    $('#share').hide();

    if (!localStorage.user) {
      game.user = '' + (new Date()).getTime() + Math.random().toString(36).slice(1);
      localStorage.setItem('user', game.user);
    }

    this.setHandlers();
    this.loadMenu();
    game.loadLevel(levels[game.level]);
  },

  setHandlers: function() {
    $('#next').on('click', function() {
      $('#code').focus();

      if ($(this).hasClass('disabled')) {
        if (!$('.treatment').hasClass('animated')) {
          game.tryagain();
        }

        return;
      }

      $('.treatment').fadeOut(1000, 'linear', function() {
        $('.carrot, .weed').addClass('correct');
      });
      $('.arrow, #next').addClass('disabled');

      setTimeout(function() {
        if (game.level >= levels.length - 1) {
          game.win();
        } else {
          game.next();
        }
      }, 2500);
    });

    $('#code').on('keydown', function(e) {
      if (e.keyCode === 13) {

        if (e.ctrlKey || e.metaKey) {
          e.preventDefault();
          game.check();
          $('#next').click();
          return;
        }

        var max = $(this).data('lines');
        var code = $(this).val();
        var trim = code.trim();
        var codeLength = code.split('\n').length;
        var trimLength = trim.split('\n').length;

        if (codeLength >= max) {

          if (codeLength === trimLength) {
            e.preventDefault();
            $('#next').click();
          } else {
            $('#code').focus().val('').val(trim);
          }
        }
      }
    }).on('input', game.debounce(game.check, 500))
    .on('input', function() {
      game.changed = true;
    });

    $('#editor').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      $(this).removeClass();
    });

    $('#labelReset').on('click', function() {
      var warningReset = messages.warningReset[game.language] || messages.warningReset.en;
      var r = confirm(warningReset);

      if (r) {
        game.level = 0;
        game.answers = {};
        game.solved = [];
        game.loadLevel(levels[0]);

        $('.level-marker').removeClass('solved');
      }
    });

    $(window).on('beforeunload', function() {
      game.saveAnswer();
      localStorage.setItem('level', game.level);
      localStorage.setItem('answers', JSON.stringify(game.answers));
      localStorage.setItem('solved', JSON.stringify(game.solved));
    }).on('hashchange', function() {
      game.language = window.location.hash.substring(1) || 'en';
      game.translate();

      $('#tweet iframe').remove();
      var html = 'Tweet ' +
                 'Follow @thomashpark';
      $('#tweet').html(html);
      twttr.widgets.load();

      if (game.language === 'en') {
        history.replaceState({}, document.title, './');
      }
    });
  },

  prev: function() {
    this.level--;

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  next: function() {
    this.level++;

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  loadMenu: function() {
    levels.forEach(function(level, i) {
      var levelMarker = $('').addClass('level-marker').attr('data-level', i).text(i+1);

      if ($.inArray(level.name, game.solved) !== -1) {
        levelMarker.addClass('solved');
      }

      levelMarker.appendTo('#levels');
    });

    $('.level-marker').on('click', function() {
      game.saveAnswer();

      var level = $(this).attr('data-level');
      game.level = parseInt(level, 10);
      game.loadLevel(levels[level]);
    });

    $('#level-indicator').on('click', function() {
      $('#levelsWrapper').toggle();
    });

    $('.arrow.left').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.prev();
    });

    $('.arrow.right').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.next();
    });
  },

  loadLevel: function(level) {
    $('#editor').show();
    $('#share').hide();
    $('#plants, #garden').removeClass().attr('style', '').empty();
    $('#soil, #overlay').removeClass().attr('style', '');
    $('#levelsWrapper').hide();
    $('.level-marker').removeClass('current').eq(this.level).addClass('current');
    $('#level-counter .current').text(this.level + 1);
    $('#before').text(level.before);
    $('#after').text(level.after);
    $('#next').addClass('disabled');

    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);

    $('.arrow.disabled').removeClass('disabled');

    if (this.level === 0) {
      $('.arrow.left').addClass('disabled');
    }

    if (this.level === levels.length - 1) {
      $('.arrow.right').addClass('disabled');
    }

    var answer = game.answers[level.name];
    $('#code').val(answer).focus();

    this.loadDocs();

    var lines = Object.keys(level.style).length;
    $('#code').height(20 * lines).data("lines", lines);

    var string = level.board;
    var markup = '';
    var colors = {
      'c': 'carrot',
      'w': 'weed'
    };

    for (var i = 0; i < string.length; i++) {
      var c = string.charAt(i);
      var color = colors[c];

      var plant = $('
').addClass('plant ' + color).data('color', color);
      var treatment = $('
').addClass('treatment ' + color).data('color', color);

      $('
').addClass('bg').appendTo(plant);
      $('
').addClass('bg').appendTo(treatment);

      $('#plants').append(plant);
      $('#garden').append(treatment);
    }

    var classes = level.classes;

    if (classes) {
      for (var rule in classes) {
        $(rule).addClass(classes[rule]);
      }
    }

    var selector = level.selector || '';
    $('#plants ' + selector).css(level.style);

    game.changed = false;
    game.applyStyles();
    game.check();
  },

  loadDocs: function() {
    $('#instructions code').each(function() {
      var code = $(this);
      var text = code.text();

      if (text in docs) {
        code.addClass('help');
        code.on('mouseenter', function(e) {
          if ($('#instructions .tooltip').length === 0) {
            var html = docs[text][game.language] || docs[text].en;
            var tooltipX = code.offset().left;
            var tooltipY = code.offset().top + code.height() + 13;
            $('

').html(html).css({top: tooltipY, left: tooltipX}).appendTo($('#instructions'));
          }
        }).on('mouseleave', function() {
          $('#instructions .tooltip').remove();
        });
      }
    });
  },

  applyStyles: function() {
    var level = levels[game.level];
    var code = $('#code').val();
    var selector = level.selector || '';
    $('#garden ' +  selector).attr('style', code);

    if (!selector) {
      if (code) {
        $('#soil, #overlay').attr('style', code);
      } else {
        $('#soil, #overlay').attr('style', '');
      }
    }

    game.saveAnswer();
  },

  check: function() {
    game.applyStyles();

    var level = levels[game.level];
    var plants = {};
    var treatments = {};
    var correct = true;

    $('.treatment').each(function() {
      var position = $(this).position();
      position.top = Math.floor(position.top);
      position.left = Math.floor(position.left);
      position.width = Math.floor($(this).width());
      position.height = Math.floor($(this).height());

      var key = JSON.stringify(position);
      var val = $(this).data('color');
      treatments[key] = val;
    });

    $('.plant').each(function() {
      var position = $(this).position();

      position.top = Math.floor(position.top);
      position.left = Math.floor(position.left);
      position.width = Math.floor($(this).width());
      position.height = Math.floor($(this).height());

      var key = JSON.stringify(position);
      var val = $(this).data('color');

      if (!(key in treatments) || treatments[key] !== val) {
        correct = false;
      }
    });

    var submission = new Submission();

    if (correct) {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'correct',
        eventLabel: $('#code').val()
      });

      submission.save({
        timeStamp: (new Date()).getTime(),
        user: game.user,
        levelName: level.name,
        changed: game.changed,
        input: $('#code').val(),
        result: 'correct'
      });

      if ($.inArray(level.name, game.solved) === -1) {
        game.solved.push(level.name);
      }

      $('[data-level=' + game.level + ']').addClass('solved');
      $('#next').removeClass('disabled');
    } else {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'incorrect',
        eventLabel: $('#code').val()
      });

      submission.save({
        timeStamp: (new Date()).getTime(),
        user: game.user,
        levelName: level.name,
        changed: game.changed,
        input: $('#code').val(),
        result: 'incorrect'
      });

      $('#next').addClass('disabled');
    }
  },

  saveAnswer: function() {
    var level = levels[this.level];
    game.answers[level.name] = $('#code').val();
  },

  tryagain: function() {
    $('#editor').addClass('animated shake');
  },

  win: function() {
    var solution = $('#code').val();

    this.loadLevel(levelWin);

    $('#editor').hide();
    $('#code').val(solution);
    $('#share').show();
  },

  transform: function() {
    var scale = 1 + ((Math.random() / 5) - 0.2);
    var rotate = 360 * Math.random();
    scale = 1;
    rotate = 0;

    return {'transform': 'scale(' + scale + ') rotate(' + rotate + 'deg)'};
  },

  translate: function() {
    document.title = messages.title[game.language] || messages.title.en;
    $('html').attr('lang', game.language);

    var level = levels[game.level];
    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);
    game.loadDocs();

    $('.translate').each(function() {
      var label = $(this).attr('id');
      var text = messages[label][game.language] || messages[label].en;

      $('#' + label).text(text);
    });
  },

  debounce: function(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  }
};

$(document).ready(function() {
  game.start();

  var d = document.documentElement.style;

  if (!('gridArea' in d)) {
    var warning = messages.warningUnsupported[game.language] || messages.warningUnsupported.en;
    $('#editor, #level-counter, #instructions').hide();
    $('
' + warning + '
').insertAfter($('#editor'));
  }
});
<commit_msg>fix rounding errors when checking solution, closes #15<commit_after>Parse.initialize("FwVMmzHookZZ5j9F9ILc2E5MT5ufabuV7hCXKSeu");
Parse.serverURL = 'http://129.25.12.218:1337/parse';
var Submission = Parse.Object.extend("CSSGridGarden");

var game = {
  language: window.location.hash.substring(1) || 'en',
  level: parseInt(localStorage.level, 10) || 0,
  answers: (localStorage.answers && JSON.parse(localStorage.answers)) || {},
  solved: (localStorage.solved && JSON.parse(localStorage.solved)) || [],
  user: localStorage.user || '',
  changed: false,

  start: function() {
    game.translate();

    $('#level-counter .total').text(levels.length);
    $('#editor').show();
    $('#share').hide();

    if (!localStorage.user) {
      game.user = '' + (new Date()).getTime() + Math.random().toString(36).slice(1);
      localStorage.setItem('user', game.user);
    }

    this.setHandlers();
    this.loadMenu();
    game.loadLevel(levels[game.level]);
  },

  setHandlers: function() {
    $('#next').on('click', function() {
      $('#code').focus();

      if ($(this).hasClass('disabled')) {
        if (!$('.treatment').hasClass('animated')) {
          game.tryagain();
        }

        return;
      }

      $('.treatment').fadeOut(1000, 'linear', function() {
        $('.carrot, .weed').addClass('correct');
      });
      $('.arrow, #next').addClass('disabled');

      setTimeout(function() {
        if (game.level >= levels.length - 1) {
          game.win();
        } else {
          game.next();
        }
      }, 2500);
    });

    $('#code').on('keydown', function(e) {
      if (e.keyCode === 13) {

        if (e.ctrlKey || e.metaKey) {
          e.preventDefault();
          game.check();
          $('#next').click();
          return;
        }

        var max = $(this).data('lines');
        var code = $(this).val();
        var trim = code.trim();
        var codeLength = code.split('\n').length;
        var trimLength = trim.split('\n').length;

        if (codeLength >= max) {

          if (codeLength === trimLength) {
            e.preventDefault();
            $('#next').click();
          } else {
            $('#code').focus().val('').val(trim);
          }
        }
      }
    }).on('input', game.debounce(game.check, 500))
    .on('input', function() {
      game.changed = true;
    });

    $('#editor').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      $(this).removeClass();
    });

    $('#labelReset').on('click', function() {
      var warningReset = messages.warningReset[game.language] || messages.warningReset.en;
      var r = confirm(warningReset);

      if (r) {
        game.level = 0;
        game.answers = {};
        game.solved = [];
        game.loadLevel(levels[0]);

        $('.level-marker').removeClass('solved');
      }
    });

    $(window).on('beforeunload', function() {
      game.saveAnswer();
      localStorage.setItem('level', game.level);
      localStorage.setItem('answers', JSON.stringify(game.answers));
      localStorage.setItem('solved', JSON.stringify(game.solved));
    }).on('hashchange', function() {
      game.language = window.location.hash.substring(1) || 'en';
      game.translate();

      $('#tweet iframe').remove();
      var html = 'Tweet ' +
                 'Follow @thomashpark';
      $('#tweet').html(html);
      twttr.widgets.load();

      if (game.language === 'en') {
        history.replaceState({}, document.title, './');
      }
    });
  },

  prev: function() {
    this.level--;

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  next: function() {
    this.level++;

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  loadMenu: function() {
    levels.forEach(function(level, i) {
      var levelMarker = $('').addClass('level-marker').attr('data-level', i).text(i+1);

      if ($.inArray(level.name, game.solved) !== -1) {
        levelMarker.addClass('solved');
      }

      levelMarker.appendTo('#levels');
    });

    $('.level-marker').on('click', function() {
      game.saveAnswer();

      var level = $(this).attr('data-level');
      game.level = parseInt(level, 10);
      game.loadLevel(levels[level]);
    });

    $('#level-indicator').on('click', function() {
      $('#levelsWrapper').toggle();
    });

    $('.arrow.left').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.prev();
    });

    $('.arrow.right').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.next();
    });
  },

  loadLevel: function(level) {
    $('#editor').show();
    $('#share').hide();
    $('#plants, #garden').removeClass().attr('style', '').empty();
    $('#soil, #overlay').removeClass().attr('style', '');
    $('#levelsWrapper').hide();
    $('.level-marker').removeClass('current').eq(this.level).addClass('current');
    $('#level-counter .current').text(this.level + 1);
    $('#before').text(level.before);
    $('#after').text(level.after);
    $('#next').addClass('disabled');

    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);

    $('.arrow.disabled').removeClass('disabled');

    if (this.level === 0) {
      $('.arrow.left').addClass('disabled');
    }

    if (this.level === levels.length - 1) {
      $('.arrow.right').addClass('disabled');
    }

    var answer = game.answers[level.name];
    $('#code').val(answer).focus();

    this.loadDocs();

    var lines = Object.keys(level.style).length;
    $('#code').height(20 * lines).data("lines", lines);

    var string = level.board;
    var markup = '';
    var colors = {
      'c': 'carrot',
      'w': 'weed'
    };

    for (var i = 0; i < string.length; i++) {
      var c = string.charAt(i);
      var color = colors[c];

      var plant = $('
').addClass('plant ' + color).data('color', color);
      var treatment = $('
').addClass('treatment ' + color).data('color', color);

      $('
').addClass('bg').appendTo(plant);
      $('
').addClass('bg').appendTo(treatment);

      $('#plants').append(plant);
      $('#garden').append(treatment);
    }

    var classes = level.classes;

    if (classes) {
      for (var rule in classes) {
        $(rule).addClass(classes[rule]);
      }
    }

    var selector = level.selector || '';
    $('#plants ' + selector).css(level.style);

    game.changed = false;
    game.applyStyles();
    game.check();
  },

  loadDocs: function() {
    $('#instructions code').each(function() {
      var code = $(this);
      var text = code.text();

      if (text in docs) {
        code.addClass('help');
        code.on('mouseenter', function(e) {
          if ($('#instructions .tooltip').length === 0) {
            var html = docs[text][game.language] || docs[text].en;
            var tooltipX = code.offset().left;
            var tooltipY = code.offset().top + code.height() + 13;
            $('

').html(html).css({top: tooltipY, left: tooltipX}).appendTo($('#instructions'));
          }
        }).on('mouseleave', function() {
          $('#instructions .tooltip').remove();
        });
      }
    });
  },

  applyStyles: function() {
    var level = levels[game.level];
    var code = $('#code').val();
    var selector = level.selector || '';
    $('#garden ' +  selector).attr('style', code);

    if (!selector) {
      if (code) {
        $('#soil, #overlay').attr('style', code);
      } else {
        $('#soil, #overlay').attr('style', '');
      }
    }

    game.saveAnswer();
  },

  check: function() {
    game.applyStyles();

    var level = levels[game.level];
    var plants = {};
    var treatments = {};
    var correct = true;

    $('.treatment').each(function() {
      var position = $(this).position();

      position.top = Math.round(position.top);
      position.left = Math.round(position.left);
      position.width = Math.round(parseFloat(window.getComputedStyle(this).width));
      position.height = Math.round(parseFloat(window.getComputedStyle(this).height));

      var key = JSON.stringify(position);
      var val = $(this).data('color');
      treatments[key] = val;
    });

    $('.plant').each(function() {
      var position = $(this).position();

      position.top = Math.round(position.top);
      position.left = Math.round(position.left);
      position.width = Math.round(parseFloat(window.getComputedStyle(this).width));
      position.height = Math.round(parseFloat(window.getComputedStyle(this).height));

      var key = JSON.stringify(position);
      var val = $(this).data('color');

      if (!(key in treatments) || treatments[key] !== val) {
        correct = false;
      }
    });

    var submission = new Submission();

    if (correct) {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'correct',
        eventLabel: $('#code').val()
      });

      submission.save({
        timeStamp: (new Date()).getTime(),
        user: game.user,
        levelName: level.name,
        changed: game.changed,
        input: $('#code').val(),
        result: 'correct'
      });

      if ($.inArray(level.name, game.solved) === -1) {
        game.solved.push(level.name);
      }

      $('[data-level=' + game.level + ']').addClass('solved');
      $('#next').removeClass('disabled');
    } else {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'incorrect',
        eventLabel: $('#code').val()
      });

      submission.save({
        timeStamp: (new Date()).getTime(),
        user: game.user,
        levelName: level.name,
        changed: game.changed,
        input: $('#code').val(),
        result: 'incorrect'
      });

      $('#next').addClass('disabled');
    }
  },

  saveAnswer: function() {
    var level = levels[this.level];
    game.answers[level.name] = $('#code').val();
  },

  tryagain: function() {
    $('#editor').addClass('animated shake');
  },

  win: function() {
    var solution = $('#code').val();

    this.loadLevel(levelWin);

    $('#editor').hide();
    $('#code').val(solution);
    $('#share').show();
  },

  transform: function() {
    var scale = 1 + ((Math.random() / 5) - 0.2);
    var rotate = 360 * Math.random();
    scale = 1;
    rotate = 0;

    return {'transform': 'scale(' + scale + ') rotate(' + rotate + 'deg)'};
  },

  translate: function() {
    document.title = messages.title[game.language] || messages.title.en;
    $('html').attr('lang', game.language);

    var level = levels[game.level];
    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);
    game.loadDocs();

    $('.translate').each(function() {
      var label = $(this).attr('id');
      var text = messages[label][game.language] || messages[label].en;

      $('#' + label).text(text);
    });
  },

  debounce: function(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  }
};

$(document).ready(function() {
  game.start();

  var d = document.documentElement.style;

  if (!('gridArea' in d)) {
    var warning = messages.warningUnsupported[game.language] || messages.warningUnsupported.en;
    $('#editor, #level-counter, #instructions').hide();
    $('
' + warning + '
').insertAfter($('#editor'));
  }
});
<|endoftext|>


<commit_before>require("./styles/main.scss");
import flowtype from 'flowtype';
import Remarkable from 'remarkable';
import hljs from 'highlight.js';

// Wait for DOM content to load

document.addEventListener("DOMContentLoaded", function(event) {

  console.log("DOM Content loaded");

  var markdownViewer = document.getElementById('markdownViewer');
  if (!markdownViewer) {
    return;
  }

  // Now just to set up markdownParser.set
  var markdownParser = new Remarkable({
    breaks: true,
    typographer: true,
    // This highlights languages
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(lang, str).value;
        } catch (err) {}
      }

      try {
        return hljs.highlightAuto(str).value;
      } catch (err) {}

      return ''; // use external default escaping
    },
  });

  flowtype(markdownViewer, {
    maxWidth: '800px',
    minWidth: '300px',
    lineRatio: 1.45,
    min: 14,
    max: 22
  });

  // Set some props from the data we just received from SN.
  // This is where we output the message onto html I think.
  window.addEventListener("message", function(event){

    console.log("message received");

    window.noteText = event.data.text || "";
    window.noteId = event.data.id;
    markdownViewer.innerHTML = markdownParser.render(window.noteText);
  }, false);

  // postMessage is how we communicate with Standard Notes
  if (window.parent != window) {
    window.parent.postMessage({status: 'ready'}, '*');
  };

});

<commit_msg>Update index<commit_after>require("./styles/main.scss");
import flowtype from 'flowtype';
import Remarkable from 'remarkable';
import hljs from 'highlight.js';

// Wait for DOM content to load

document.addEventListener("DOMContentLoaded", function(event) {

  console.log("DOM Content loaded");

  // postMessage is how we communicate with Standard Notes
  if (window.parent != window) {
    window.parent.postMessage({status: 'ready'}, '*');
    console.log('message posted')
  };

  // Set some props from the data we just received from SN.
  // This is where we output the message onto html I think.
  window.addEventListener("message", function(event){
    console.log("message received");

    window.noteText = event.data.text || "";
    window.noteId = event.data.id;
    markdownViewer.innerHTML = markdownParser.render(window.noteText);
  }, false);

  var markdownViewer = document.getElementById('markdownViewer');
  if (!markdownViewer) {
    return;
  }

  // Now just to set up markdownParser.set
  var markdownParser = new Remarkable({
    breaks: true,
    typographer: true,
    // This highlights languages
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(lang, str).value;
        } catch (err) {}
      }

      try {
        return hljs.highlightAuto(str).value;
      } catch (err) {}

      return ''; // use external default escaping
    },
  });

  flowtype(markdownViewer, {
    maxWidth: '800px',
    minWidth: '300px',
    lineRatio: 1.45,
    min: 14,
    max: 22
  });

  markdownViewer.innerHTML = markdownParser.render(window.noteText);
  console.log(window)
});

<|endoftext|>


<commit_before>/**
 * Created by carl.hand on 30/03/2017.
 */
import React from 'react';
import ReactDOM from 'react-dom';
// import css from './app.css';
require('./app.css');
import Player from './components/Player'
import Counter from './components/Counter'
import AddButton from './components/Add'
import Stopwatch from './components/Stopwatch'
import update from 'immutability-helper';

var Application = React.createClass({
    getInitialState: function () {
      return ({
          nextId: 2,
          Players: [
              {
                  name: "Carl",
                  score: 23,
              },
              {
                  name: "Lee",
                  score: 20,
              }
          ],
          title: "Scoreboard",
          time: 20,
          startInterval: ""
      });
    },

    handleIncrement: function(index, delta) {
        var Players = this.state.Players;
        var newScore = Players[index].score += delta;
        this.setState({
            score: newScore
        });
        if (newScore >= 30) {
            alert(Players[index].name + " is the winner");
            this.replaceState(this.getInitialState());
        }
    },

    handleDecrement: function (index, delta) {
        var Players = this.state.Players;
        var newScore = Players[index].score -= delta;
        this.setState({
            score: newScore
        });
    },

    onAdd: function (newName) {
        var Players = this.state.Players;
        if (newName === "") {
            console.log("Please enter a name");
        }
        else {
            Players.push({
                name: newName,
                score: 0,
                id: this.state.nextId
            });
            this.state.nextId++;
        }
        this.setState({
            Players: Players
        });
    },

    onRemove: function (name) {
      var Players = this.state.Players;
        Players.map(function (player, index) {
            if (player.name === name) {
                Players.splice(index, 1);
            }
            else if (name === "") {
                console.log("Please enter a name");
            }
            else {
                console.log(name + " does not exist");
            }
        });
        this.setState({
            Players: Players
        });
    },

    startGame: function() {
        var intervalID = setInterval(function() {
            var newTime = this.state.time;
            if (newTime > 0) {
                this.setState({
                    time: newTime - 1
                });
            }
            else {
                alert("GAME OVER");
                clearInterval(intervalID);
                this.setState({
                    time: 0
                });
                this.replaceState(this.getInitialState());
            }
        }.bind(this), 1000);
    },

    resetGame: function() {
        setInterval(function() {
            clearInterval(this.state.startInterval);
        }.bind(this), 0);
        this.replaceState(this.getInitialState());
    },

    render: function() {
        return (

                <Stopwatch start={this.startGame} reset={this.resetGame} time={this.state.time}/>

{this.state.title}

                    {this.state.Players.map((player, index) => {
                        return <Player id={index} name={player.name} key={index} score={player.score} onIncrement={this.handleIncrement} onDecrement={this.handleDecrement} />
                    })}
                    <AddButton addPlayer={this.onAdd} removePlayer={this.onRemove} />

        );
    }
});

ReactDOM.render(<Application />,
document.getElementById("app"));<commit_msg>removed deprecated resetState method calls and set my own state<commit_after>/**
 * Created by carl.hand on 30/03/2017.
 */
import React from 'react';
import ReactDOM from 'react-dom';
// import css from './app.css';
require('./app.css');
import Player from './components/Player'
import Counter from './components/Counter'
import AddButton from './components/Add'
import Stopwatch from './components/Stopwatch'
import update from 'immutability-helper';

var Application = React.createClass({
    getInitialState: function () {
      return ({
          nextId: 2,
          Players: [
              {
                  name: "Carl",
                  score: 23,
              },
              {
                  name: "Lee",
                  score: 20,
              }
          ],
          title: "Scoreboard",
          time: 5,
          startInterval: ""
      });
    },

    handleIncrement: function(index, delta) {
        var Players = this.state.Players;
        var newScore = Players[index].score += delta;
        this.setState({
            score: newScore
        });

        if (newScore >= 30) {
            alert(Players[index].name + " is the winner");
            this.replaceState(this.getInitialState());
        }
    },

    handleDecrement: function (index, delta) {
        var Players = this.state.Players;
        var newScore = Players[index].score -= delta;
        this.setState({
            score: newScore
        });
    },

    onAdd: function (newName) {
        var Players = this.state.Players;
        if (newName === "") {
            console.log("Please enter a name");
        }
        else {
            Players.push({
                name: newName,
                score: 0,
                id: this.state.nextId
            });
            this.state.nextId++;
        }

        this.setState({
            Players: Players
        });
    },

    onRemove: function (name) {
      var Players = this.state.Players;
        Players.map(function (player, index) {

            if (player.name === name) {
                Players.splice(index, 1);
            }
            else if (name === "") {
                console.log("Please enter a name");
            }
            else {
                console.log(name + " does not exist");
            }
        });

        this.setState({
            Players: Players
        });
    },

    startGame: function() {
        var intervalID = setInterval(function() {
            var newTime = this.state.time;
            if (newTime > 0) {
                this.setState({
                    time: newTime - 1
                });
            }
            else {
                alert("GAME OVER");
                clearInterval(intervalID);
            }
        }.bind(this), 1000);

        this.setState({
            startInterval: intervalID
        });
    },

    resetGame: function() {
        this.setState({
            time: 5
        });
        clearInterval(this.state.startInterval);
    },

    render: function() {
        return (

                <Stopwatch start={this.startGame} reset={this.resetGame} time={this.state.time}/>

{this.state.title}

                    {this.state.Players.map((player, index) => {
                        return <Player id={index} name={player.name} key={index} score={player.score} onIncrement={this.handleIncrement} onDecrement={this.handleDecrement} />
                    })}
                    <AddButton addPlayer={this.onAdd} removePlayer={this.onRemove} />

        );
    }
});

ReactDOM.render(<Application />,
document.getElementById("app"));<|endoftext|>


<commit_before>/**
 * @author Rob Taylor [manix84@gmail.com]
 */
define('utils/array/toObject', function () {
    /**
     * Converts an array to an object with the array values as keys and empty strings as the value. Note that
     * objects can't have duplicate keys, hence there is a chance that duplicates will be missing from the
     * object. This function works best with array values of strings and is handy for 'for ... in ...' loops
     * or if .... in .... style checking
     * @exports utils/array/toObject
     * @example // Array
     * toObject(['hello', 'world']) // RESULT {'hello': '', 'world': ''}
     * @param {array} array - A the array to be converted
     * @returns {object} The newly created object
     */
    var toObject = function (arrayObj) {
        var i = 0,
            outputObj = {};

        for (; i < arrayObj.length; i++) {
            outputObj[arrayObj[i]] = '';
        }

        return outputObj;
    };

    return toObject;
});
<commit_msg>Relocation array/toObject references.<commit_after>/**
 * @author Rob Taylor [manix84@gmail.com]
 */
define('array/toObject', function () {
    /**
     * Converts an array to an object with the array values as keys and empty strings as the value. Note that
     * objects can't have duplicate keys, hence there is a chance that duplicates will be missing from the
     * object. This function works best with array values of strings and is handy for 'for ... in ...' loops
     * or if .... in .... style checking
     * @exports array/toObject
     * @example // Array
     * toObject(['hello', 'world']) // RESULT {'hello': '', 'world': ''}
     * @param {array} array - A the array to be converted
     * @returns {object} The newly created object
     */
    var toObject = function (arrayObj) {
        var i = 0,
            outputObj = {};

        for (; i < arrayObj.length; i++) {
            outputObj[arrayObj[i]] = '';
        }

        return outputObj;
    };

    return toObject;
});
<|endoftext|>


<commit_before>import createViperService from '../../../../server/services/viperService';

describe('viper service', () => {
  let fakeDB;
  let viperService;

  function setup() {
    fakeDB = { raw: x => x };
    fakeDB.select = sinon.stub().returns(fakeDB);
    fakeDB.table = sinon.stub().returns(fakeDB);

    viperService = createViperService(fakeDB);
  }

  describe('selecting a viper rating', () => {
    before(() => setup());

    it('returns a viper rating for a known nomis id', () => {
      fakeDB.where = sinon.stub().resolves([{ nomisId: 'A123', rating: 0.90 }]);

      return viperService.rating('A123')
        .then((result) => {
          expect(fakeDB.select.callCount).to.eql(1);
          expect(fakeDB.table.callCount).to.eql(1);
          expect(fakeDB.table.lastCall.args[0]).to.eql('viper');
          expect(fakeDB.where.callCount).to.eql(1);
          expect(fakeDB.where.lastCall.args[0]).to.eql('nomis_id');
          expect(fakeDB.where.lastCall.args[1]).to.eql('A123');
          expect(result).to.equal(0.90);
        });
    });

    it('returns null for an unknown nomis id', () => {
      fakeDB.where = sinon.stub().resolves([]);

      return viperService.rating('A123')
        .then((result) => {
          expect(result).to.equal(null);
        });
    });
  });

  describe('db errors', () => {
    before(() => setup());

    it('passes on the db error', () => {
      fakeDB.where = sinon.stub().rejects(new Error('Connection failed or something'));

      return expect(viperService.rating('A123'))
        .to.be.rejectedWith(Error, 'Connection failed or something');
    });
  });
});
<commit_msg>CSRA-493: Remove call count checks from unit test<commit_after>import createViperService from '../../../../server/services/viperService';

describe('viper service', () => {
  let fakeDB;
  let viperService;

  function setup() {
    fakeDB = { raw: x => x };
    fakeDB.select = sinon.stub().returns(fakeDB);
    fakeDB.table = sinon.stub().returns(fakeDB);

    viperService = createViperService(fakeDB);
  }

  describe('selecting a viper rating', () => {
    before(() => setup());

    it('returns a viper rating for a known nomis id', () => {
      fakeDB.where = sinon.stub().resolves([{ nomisId: 'A123', rating: 0.90 }]);

      return viperService.rating('A123')
        .then((result) => {
          expect(fakeDB.table.lastCall.args[0]).to.eql('viper');
          expect(fakeDB.where.lastCall.args[0]).to.eql('nomis_id');
          expect(fakeDB.where.lastCall.args[1]).to.eql('A123');
          expect(result).to.equal(0.90);
        });
    });

    it('returns null for an unknown nomis id', () => {
      fakeDB.where = sinon.stub().resolves([]);

      return viperService.rating('A123')
        .then((result) => {
          expect(result).to.equal(null);
        });
    });
  });

  describe('db errors', () => {
    before(() => setup());

    it('passes on the db error', () => {
      fakeDB.where = sinon.stub().rejects(new Error('Connection failed or something'));

      return expect(viperService.rating('A123'))
        .to.be.rejectedWith(Error, 'Connection failed or something');
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.java',
  name: 'Skeleton',

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      name: 'name',
      expression: function(of) {
        return this.of.name + 'Skeleton';
      }
    },
    {
      name: 'package',
      expression: function(of) {
        return this.of.package;
      }
    },
    {
      name: 'id',
      expression: function(name, package) {
        return package + '.' + name;
      }
    }
  ],

  methods: [
    function buildJavaClass(cls) {
      cls = cls || foam.java.Class.create();

      cls.package = this.package;
      cls.name    = this.name;
      cls.extends = 'foam.box.AbstractSkeleton',

      foam.core.FObjectProperty.create({
        name: 'delegate',
        type: this.of.id
      }).buildJavaClass(cls);

      cls.method({
        type: 'void',
        visibility: 'public',
        name: 'send',
        args: [ { name: 'message', type: 'foam.box.Message' } ],
        body: this.sendMethodCode()
      });

      cls.method({
        type: 'void',
        visibility: 'public',
        name: 'setDelegateObject',
        args: [ { name: 'obj', type: 'Object' } ],
        body: "setDelegate((" + this.of.id + ") obj);"
      });

      return cls;
    }
  ],

  templates: [
    {
      name: 'sendMethodCode',
      template: `if ( ! ( message.getObject() instanceof foam.box.RPCMessage) ) {
      // TODO return an error?
      return;
    }

    foam.box.RPCMessage rpc      = (foam.box.RPCMessage) message.getObject();
    foam.box.Box        replyBox = (foam.box.Box) message.getAttributes().get("replyBox");
    Object              result   = null;

    try {
      switch ( rpc.getName() ) {<%
  var methods = this.of.getOwnAxiomsByClass(foam.core.Method);
  for ( var i = 0 ; i < methods.length ; i++ ) {
    var m = methods[i];
    var hasReturn = m.javaType && m.javaType !== 'void';%>
        case "<%= m.name %>":
          <% if ( hasReturn ) { %>result = <% } %>getDelegate().<%= m.name %>(
          <%
    for ( var j = 0 ; j < m.args.length ; j++ ) {
      if ( m.args[j].type == 'Context' ) {
        %>getMessageX(message)<%
      } else if ( foam.core.AbstractEnum.isSubClass(this.__context__.lookup(m.args[j].type, true)) ) {
        %>rpc.getArgs() != null && rpc.getArgs().length > <%= j %> ? (<%= m.args[j].javaType %>) rpc.getArgs()[<%= j %>] : null<%
      } else {
        if ( {byte: 1, double: 1, float: 1, int: 1, long: 1, short: 1 }[m.args[j].javaType] ) {
          %>to<%= m.args[j].javaType %><%
        } else {
          %>(<%= m.args[j].javaType %>)<%
        }
        %>(rpc.getArgs() != null && rpc.getArgs().length > <%= j %> ? rpc.getArgs()[<%= j %>] : null)<%
      }
      if ( j != m.args.length - 1 ) { %>,
            <% }
      }
    %>);
        break;
    <%
  }%>
        default: throw new RuntimeException("Method not found: " + rpc.getName());
      }
    } catch (Throwable t) {
      ((foam.nanos.logger.Logger) getMessageX(message).get("logger")).debug("returning skeleton exception", t);
      message.replyWithException(t);

      return;
    }

    if ( replyBox != null ) {
      foam.box.RPCReturnMessage reply = (foam.box.RPCReturnMessage)getX().create(foam.box.RPCReturnMessage.class);
      if ( result != null ) {
        reply.setData(result);
      }

      foam.box.Message message1 = getX().create(foam.box.Message.class);
      message1.setObject(reply);
      replyBox.send(message1);
    }`
    }
  ]
});
<commit_msg>Don't output unused result for for skeletons that have no return value.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.java',
  name: 'Skeleton',

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      name: 'name',
      expression: function(of) {
        return this.of.name + 'Skeleton';
      }
    },
    {
      name: 'package',
      expression: function(of) {
        return this.of.package;
      }
    },
    {
      name: 'id',
      expression: function(name, package) {
        return package + '.' + name;
      }
    }
  ],

  methods: [
    function buildJavaClass(cls) {
      cls = cls || foam.java.Class.create();

      cls.package = this.package;
      cls.name    = this.name;
      cls.extends = 'foam.box.AbstractSkeleton',

      foam.core.FObjectProperty.create({
        name: 'delegate',
        type: this.of.id
      }).buildJavaClass(cls);

      cls.method({
        type: 'void',
        visibility: 'public',
        name: 'send',
        args: [ { name: 'message', type: 'foam.box.Message' } ],
        body: this.sendMethodCode()
      });

      cls.method({
        type: 'void',
        visibility: 'public',
        name: 'setDelegateObject',
        args: [ { name: 'obj', type: 'Object' } ],
        body: "setDelegate((" + this.of.id + ") obj);"
      });

      return cls;
    }
  ],

  templates: [
    {
      name: 'sendMethodCode',
      template: `if ( ! ( message.getObject() instanceof foam.box.RPCMessage) ) {
      // TODO return an error?
      return;
    }

    foam.box.RPCMessage rpc      = (foam.box.RPCMessage) message.getObject();
    foam.box.Box        replyBox = (foam.box.Box) message.getAttributes().get("replyBox");
    <% if ( hasReturn ) { %>Object              result   = null;<% } %>

    try {
      switch ( rpc.getName() ) {<%
  var methods = this.of.getOwnAxiomsByClass(foam.core.Method);
  for ( var i = 0 ; i < methods.length ; i++ ) {
    var m = methods[i];
    var hasReturn = m.javaType && m.javaType !== 'void';%>
        case "<%= m.name %>":
          <% if ( hasReturn ) { %>result = <% } %>getDelegate().<%= m.name %>(
          <%
    for ( var j = 0 ; j < m.args.length ; j++ ) {
      if ( m.args[j].type == 'Context' ) {
        %>getMessageX(message)<%
      } else if ( foam.core.AbstractEnum.isSubClass(this.__context__.lookup(m.args[j].type, true)) ) {
        %>rpc.getArgs() != null && rpc.getArgs().length > <%= j %> ? (<%= m.args[j].javaType %>) rpc.getArgs()[<%= j %>] : null<%
      } else {
        if ( {byte: 1, double: 1, float: 1, int: 1, long: 1, short: 1 }[m.args[j].javaType] ) {
          %>to<%= m.args[j].javaType %><%
        } else {
          %>(<%= m.args[j].javaType %>)<%
        }
        %>(rpc.getArgs() != null && rpc.getArgs().length > <%= j %> ? rpc.getArgs()[<%= j %>] : null)<%
      }
      if ( j != m.args.length - 1 ) { %>,
            <% }
      }
    %>);
        break;
    <%
  }%>
        default: throw new RuntimeException("Method not found: " + rpc.getName());
      }
    } catch (Throwable t) {
      ((foam.nanos.logger.Logger) getMessageX(message).get("logger")).debug("returning skeleton exception", t);
      message.replyWithException(t);

      return;
    }

    if ( replyBox != null ) {
      foam.box.RPCReturnMessage reply = (foam.box.RPCReturnMessage)getX().create(foam.box.RPCReturnMessage.class);
      <% if ( hasReturn ) { %>if ( result != null ) {
        reply.setData(result);
      }<% } %>

      foam.box.Message message1 = getX().create(foam.box.Message.class);
      message1.setObject(reply);
      replyBox.send(message1);
    }`
    }
  ]
});
<|endoftext|>