<commit_before>var tap = require("tap")
  , test = tap.test
  , plan = tap.plan
  , account
  , creature
  , resource;

//
// Testing metadata
//
var testDatasource = "memory";

test("load resource module", function (t) {
  resource = require('../');
  t.ok(resource, "object loaded")
  t.end()
});

test("define creature resource - with datasource config", function (t) {
  creature = resource.define('creature', { config: { datasource: testDatasource }});

  creature.property('life', {
    "type": "number"
  });

  creature.property('metadata', {
    "type": "object"
  });

  creature.property('items', {
    "type": "array"
  });

  t.type(creature.config, 'object', 'configuration defined - creature.config is object');
  t.equal(testDatasource, creature.config.datasource, ('configuration defined - creature.config.datasource == "' + testDatasource + '"'));

  t.type(creature.methods, 'object', 'methods defined - creature.methods is object');
  t.type(creature.methods.create, 'function', 'methods defined - methods.create is function');
  t.type(creature.methods.get, 'function', 'methods defined - methods.get is function');
  t.type(creature.methods.find, 'function', 'methods defined - methods.find is function');
  t.type(creature.methods.destroy, 'function', 'methods defined - methods.destroy is function');

  t.type(creature.create, 'function', 'methods hoisted - creature.create is function');
  t.type(creature.get, 'function', 'methods hoisted - creature.get is function');
  t.type(creature.find, 'function', 'methods hoisted - creature.find is function');
  t.type(creature.destroy, 'function', 'methods hoisted - creature.destroy is function');

  t.end()
});

test("define account resource - with datasource config", function (t) {
  account = resource.define('account', { config: { datasource: testDatasource }});

  account.property('name', {
    "type": "string"
  });

  account.property('email', {
    "type": "string"
  });

  t.type(account.config, 'object', 'configuration defined - account.config is object');
  t.equal(testDatasource, account.config.datasource, ('configuration defined - account.config.datasource == "' + testDatasource + '"'));

  t.end()
});

//
// A simple data object to use for testing resource properties of type "object"
//
var data = {
  "foo": "bar",
  "abc": 123,
  "data" : {
    "prop1" : "foo",
    "prop2" : "bar"
  }
},
items = [
  { "foo": "bar" },
  { "abc": 123 }
];

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("executing creature.create", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property currently has serialization issue
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.create - when already created", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property current has serialization issue
  }, function(err, result){
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'bobby already exists', 'bobby already exists');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result) {
    t.equal(result.length, 1, 'one creature');
    t.end();
  });
});

test("executing creature.create - with bad input", function (t) {
  creature.create({ id: 'larry', life: "abc" }, function(err, result){
    t.type(err, 'object', 'continues correct validation error - err is object');
    t.type(err.errors, 'object', 'continues correct validation error - err.errors is object');
    t.equal(err.errors.length, 1, 'continues correct validation error - one validation error');
    t.equal(err.errors[0].attribute, 'type', 'continues correct validation error - attribute == "type"');
    t.equal(err.errors[0].property, 'life', 'continues correct validation error - property == "life"');
    t.equal(err.errors[0].expected, 'number', 'continues correct validation error - expected == "number"');
    t.equal(err.errors[0].actual, 'string', 'continues correct validation error - actual == "string"');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('larry', function(err, result){
    t.type(err, 'object', 'could not find larry');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 1);
    t.end();
  });
});

test("executing creature.update", function (t) {
  creature.update({ id: 'bobby', life: 9999 , items: items }, function(err, result){
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 9999, 'updated bobby - result.life == 9999');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.update - when creature does not exist", function (t) {
  creature.update({ id: 'larry' }, function (err, result) {
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'larry not found', 'could not find larry');
    t.end();
  });
});

test("executing creature.updateOrCreate - with a new id", function (t) {
  creature.updateOrCreate({ id: 'larry', items: items  }, function (err, result) {
    t.type(err, 'null', 'created larry - no error');
    t.type(result, 'object', 'created larry - result is object');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.updateOrCreate = with existing id", function (t) {
  creature.updateOrCreate({ id: 'bobby', life: 5, items: items  }, function (err, result) {
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 5, 'updated bobby - result.life == 5');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing account.create with same id as a creature", function (t) {
  account.create({
    id: 'bobby'
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.end();
  });
});

test("executing creature.destroy", function (t) {
  t.plan(2);
  creature.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
  creature.destroy('larry', function(err, result){
    t.type(result, 'null', 'destroyed larry');
  });
});

test("executing account.destroy", function (t) {
  t.plan(1);
  account.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'object', 'could not find bobby');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("persist creature to couchdb", function (t) {
  creature.persist({ name: "big-test", type: "couchdb", options: { cache: false }});
  t.end();
});<commit_msg>[persistence] [test] added a new test case with space resource that shows unintended (or just really confusing) behavior in default properties<commit_after>var tap = require("tap")
  , test = tap.test
  , plan = tap.plan
  , account
  , creature
  , resource;

//
// Utility testing functions
//
function isEmpty(o){
  for(var i in o){
      if(o.hasOwnProperty(i)){
          return false;
      }
  }
  return true;
}

//
// Testing metadata
//
var testDatasource = "memory";

test("load resource module", function (t) {
  resource = require('../');
  t.ok(resource, "object loaded");
  t.end();
});

test("define creature resource - with datasource config", function (t) {
  creature = resource.define('creature', { config: { datasource: testDatasource }});

  creature.property('life', {
    "type": "number"
  });

  creature.property('metadata', {
    "type": "object"
  });

  creature.property('items', {
    "type": "array"
  });

  t.type(creature.config, 'object', 'configuration defined - creature.config is object');
  t.equal(testDatasource, creature.config.datasource, ('configuration defined - creature.config.datasource == "' + testDatasource + '"'));

  t.type(creature.methods, 'object', 'methods defined - creature.methods is object');
  t.type(creature.methods.create, 'function', 'methods defined - methods.create is function');
  t.type(creature.methods.get, 'function', 'methods defined - methods.get is function');
  t.type(creature.methods.find, 'function', 'methods defined - methods.find is function');
  t.type(creature.methods.destroy, 'function', 'methods defined - methods.destroy is function');

  t.type(creature.create, 'function', 'methods hoisted - creature.create is function');
  t.type(creature.get, 'function', 'methods hoisted - creature.get is function');
  t.type(creature.find, 'function', 'methods hoisted - creature.find is function');
  t.type(creature.destroy, 'function', 'methods hoisted - creature.destroy is function');

  t.end();
});

test("define account resource - with datasource config", function (t) {
  account = resource.define('account', { config: { datasource: testDatasource }});

  account.property('name', {
    "type": "string"
  });

  account.property('email', {
    "type": "string"
  });

  t.type(account.config, 'object', 'configuration defined - account.config is object');
  t.equal(testDatasource, account.config.datasource, ('configuration defined - account.config.datasource == "' + testDatasource + '"'));

  t.end();
});

test("define space resource - with datasource config", function(t) {
  space = resource.define('space', { config: { datasource: testDatasource }});

  space.property('id', {
    description: 'the name of the space',
    type: 'string',
    required: true
  });

  space.property('resources', {
    description: 'the resources present in this space',
    type: 'object',
    default: {}
  });

  t.type(space.config, 'object', 'configuration defined - space.config is object');
  t.equal(testDatasource, space.config.datasource, ('configuration defined - space.config.datasource == "' + testDatasource + '"'));

  t.type(space.methods, 'object', 'methods defined - space.methods is object');
  t.type(space.methods.create, 'function', 'methods defined - methods.create is function');
  t.type(space.methods.get, 'function', 'methods defined - methods.get is function');
  t.type(space.methods.find, 'function', 'methods defined - methods.find is function');
  t.type(space.methods.destroy, 'function', 'methods defined - methods.destroy is function');

  t.type(space.create, 'function', 'methods hoisted - space.create is function');
  t.type(space.get, 'function', 'methods hoisted - space.get is function');
  t.type(space.find, 'function', 'methods hoisted - space.find is function');
  t.type(space.destroy, 'function', 'methods hoisted - space.destroy is function');

  t.end();
});

//
// A simple data object to use for testing resource properties of type "object"
//
var data = {
  "foo": "bar",
  "abc": 123,
  "data" : {
    "prop1" : "foo",
    "prop2" : "bar"
  }
},
items = [
  { "foo": "bar" },
  { "abc": 123 }
];

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

test("executing creature.create", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property currently has serialization issue
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.create - when already created", function (t) {
  creature.create({
    id: 'bobby',
    metadata: data,
    items: items // array property current has serialization issue
  }, function(err, result){
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'bobby already exists', 'bobby already exists');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.type(result.metadata, 'object', 'metadata is object');
    t.equal(result.metadata.foo, 'bar');
    t.equal(result.metadata.abc, 123);
    t.equal(result.metadata.data.prop1, 'foo');
    t.equal(result.metadata.data.prop2, 'bar');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result) {
    t.equal(result.length, 1, 'one creature');
    t.end();
  });
});

test("executing creature.create - with bad input", function (t) {
  creature.create({ id: 'larry', life: "abc" }, function(err, result){
    t.type(err, 'object', 'continues correct validation error - err is object');
    t.type(err.errors, 'object', 'continues correct validation error - err.errors is object');
    t.equal(err.errors.length, 1, 'continues correct validation error - one validation error');
    t.equal(err.errors[0].attribute, 'type', 'continues correct validation error - attribute == "type"');
    t.equal(err.errors[0].property, 'life', 'continues correct validation error - property == "life"');
    t.equal(err.errors[0].expected, 'number', 'continues correct validation error - expected == "number"');
    t.equal(err.errors[0].actual, 'string', 'continues correct validation error - actual == "string"');
    t.end();
  });
});

test("executing creature.get", function (t) {
  creature.get('larry', function(err, result){
    t.type(err, 'object', 'could not find larry');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 1);
    t.end();
  });
});

test("executing creature.update", function (t) {
  creature.update({ id: 'bobby', life: 9999 , items: items }, function(err, result){
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 9999, 'updated bobby - result.life == 9999');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.update - when creature does not exist", function (t) {
  creature.update({ id: 'larry' }, function (err, result) {
    t.type(err, 'object', 'an error');
    t.equal(!result, true, 'no result');
    t.equal(err.message, 'larry not found', 'could not find larry');
    t.end();
  });
});

test("executing creature.updateOrCreate - with a new id", function (t) {
  creature.updateOrCreate({ id: 'larry', items: items  }, function (err, result) {
    t.type(err, 'null', 'created larry - no error');
    t.type(result, 'object', 'created larry - result is object');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing create.updateOrCreate = with existing id", function (t) {
  creature.updateOrCreate({ id: 'bobby', life: 5, items: items  }, function (err, result) {
    t.type(err, 'null', 'updated bobby - no error');
    t.type(result, 'object', 'updated bobby - result is object');
    t.equal(result.life, 5, 'updated bobby - result.life == 5');
    t.type(result.items, Array, 'items is array');
    t.end();
  });
});

test("executing account.create with same id as a creature", function (t) {
  account.create({
    id: 'bobby'
  }, function(err, result){
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'result is object');
    t.equal(result.id, 'bobby', 'id is correct');
    t.end();
  });
});

test("creating a space", function(t) {
  space.create({id: "big"}, function(err, result) {
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'space instance is object');
    t.type(result.id, 'string', 'space instance id is string');
    t.equal(result.id, 'big', 'space instance id is correct');
    t.type(result.resources, 'object', 'space instance resources is object');
    t.equal(isEmpty(result.resources), true, 'space instance resources is empty');
    t.end();
  });
});

test("add creature to space", function(t) {
  space.get('big', function(err, _space) {
    t.type(err, 'null', 'no error');
    _space.resources['creature'] = ['bobby'];
    _space.save(function(err, result) {
      t.type(err, 'null', 'no error');
      t.type(result, 'object', 'space instance is object');
      t.type(result.id, 'string', 'space instance id is string');
      t.equal(result.id, 'big', 'space instance id is correct');
      t.type(result.resources, 'object', 'space instance resources is object');
      t.equal(result.resources.creature.length, 1, 'space instance resources is correct');
      t.equal(result.resources.creature[0], 'bobby', 'space instance resources is correct');
      t.end();
    });
  });
});

test("create another new space", function(t) {
  space.create({id: "big2"}, function(err, result) {
    t.type(err, 'null', 'no error');
    t.type(result, 'object', 'space instance is object');
    t.type(result.id, 'string', 'space instance id is string');
    t.equal(result.id, 'big2', 'space instance id is correct');
    t.type(result.resources, 'object', 'space instance resources is object');
    t.equal(isEmpty(result.resources), true, 'space instance resources is empty');
    t.end();
  });
});

test("executing space.destroy", function (t) {
  t.plan(2);
  space.destroy('big', function(err, result){
    t.type(result, 'null', 'destroyed space big');
  });
  space.destroy('big2', function(err, result){
    t.type(result, 'null', 'destroyed space big2');
  });
});

test("executing space.all", function (t) {
  space.all(function(err, result){
    t.equal(result.length, 0, 'no spaces');
    t.end();
  });
});

test("executing creature.destroy", function (t) {
  t.plan(2);
  creature.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
  creature.destroy('larry', function(err, result){
    t.type(result, 'null', 'destroyed larry');
  });
});

test("executing account.destroy", function (t) {
  t.plan(1);
  account.destroy('bobby', function(err, result){
    t.type(result, 'null', 'destroyed bobby');
  });
});

test("executing creature.get", function (t) {
  creature.get('bobby', function(err, result){
    t.type(err, 'object', 'could not find bobby');
    t.end();
  });
});

test("executing creature.all", function (t) {
  creature.all(function(err, result){
    t.equal(result.length, 0, 'no creatures');
    t.end();
  });
});

/*
test("persist creature to couchdb", function (t) {
  creature.persist({ name: "big-test", type: "couchdb", options: { cache: false }});
  t.end();
});
*/<|endoftext|>


<commit_before>/*
	Created by Devsome
	thanks to imDevinC https://github.com/ImDevinC/pkgo-discord for the functions
	edited for https://github.com/modrzew/pokeminer
*/
var Discord = require("discord.js");
var request = require("request");
var NodeGeocoder = require('node-geocoder');
var fs = require("fs");

// Loading my Configs
var config = require("./bot/config.json");
var locale = require("./locales/pokemon."+config.locale+".json");

var clientBot = new Discord.Client();

var alreadySeen = [];
var joinUrl = "https://discordapp.com/oauth2/authorize?client_id=" + config.app_id + "&scope=bot&permissions=";
var mapUrl = 'http://maps.google.com/maps?&z=10&ll={0}+{1}&q={0}+{1}';
var options = {
  provider: 'google',
  httpAdapter: 'https',
  apiKey: config.gmap_key,
  formatter: null
};
var geocoder = NodeGeocoder(options);

clientBot.on("ready", function () {
	console.log("\n[INFO]\tTo add me visit this url:\n\t" + joinUrl + "\n\n");
	console.log("[INFO]\tReady to begin!");
	console.log("[INFO]\tYou're connected to [ " + clientBot.servers.length + " ] Servers with [" + clientBot.channels.length + "] Channels!");

	clientBot.setPlayingGame( config.games[Math.floor(Math.random() * (config.games.length))] );
});

clientBot.on('disconnected', function() {
	console.log("Disconnted ? Let me reconnect asap...");
	clientBot.loginWithToken(config.token);
});

clientBot.on("error", function (error) {
	console.log("Caught error: " + error);
});

// CMD+C at terminal
process.on("SIGINT", function () {
	console.log("\n Whoa wait, let me logout first...");
	clientBot.logout();
	process.exit(1);
});

function checkPokemon() {
	request('http://' + config.getServer + '/discord', (err, res, body) => {
		if (err) {
			console.log(err);
			return;
		}
		if (200 != res.statusCode) {
			console.log('Invalid response code: ' + res.statusCode);
			return;
		}
		parsePokemon(JSON.parse(body));
	});
}

function parsePokemon(results) {
	var config = require("./bot/config.json");
	if (!Object.keys(results) || Object.keys(results).length < 1) {
		return;
	}
	foundPokemon = [];
	for (pokemon in results) {
		if(config.pokeShow.indexOf(results[pokemon].pokemon_id) >= 0 ) {
			// found
		} else {
			continue; // not found
		}
		foundPokemon.push(results[pokemon].key);
		if (alreadySeen.indexOf(results[pokemon].key) > -1) {
			continue;
		}

		newPokemonSighted(results[pokemon]);
		alreadySeen.push(results[pokemon].key);
	}

	clearStalePokemon(foundPokemon);
}

function clearStalePokemon(pokemons) {
	var oldSeen = alreadySeen;
	for (id in oldSeen) {
		var pokemon = pokemons.indexOf(oldSeen[id]);
		if (pokemon > -1) {
			continue;
	}

	var index = alreadySeen.indexOf(oldSeen[id]);
		alreadySeen.splice(index, 1);
	}
}

function newPokemonSighted(pokemon) {
	var diff = new Date(pokemon.disappear_time * 1000) - Date.now();
	diff = Math.floor(diff / 1000);
	diff = Math.floor(diff / 60);
	min_diff = diff % 60;
	var url = mapUrl.split('{0}').join(pokemon.lat);
	url = url.split('{1}').join(pokemon.lng);

	geocoder.reverse({lat:pokemon.lat, lon:pokemon.lng}, function(err, res) {
		var streetName = res[0].formattedAddress;
		var message = '**' + pokemon.name + '** (' + pokemon.pokemon_id + ') gesichtet ! Verschwindet in **' + min_diff + '** minuten \n'+streetName+'';
		clientBot.sendFile( config.channelID , __dirname + "/bot/img/"+ pokemon.pokemon_id +".png" , pokemon.pokemon_id +".png", message, (err, msg) => {
			if (err) {
				clientBot.sendMessage(config.channelID, "I do not have the rights to send a **file** :cry:!");
			}
		});
	});
}

clientBot.on("message", function (msg) {

	if(msg.author.id != clientBot.user.id && msg.content[0] === '!'){
		var cmdTxt = msg.content.split(" ")[0].substring(1);
		var suffix = msg.content.substring(cmdTxt.length+2);

		if( cmdTxt == "read" ) {
			var config = require( __dirname + '/bot/config.json' );
			var buffer = config.pokeShow + '';
			var array = buffer.split(',');
			var showPokemon = "";
			array.sort();
			for(var i in array)
			{
				showPokemon += array[i] + " " + locale[array[i]] + "\n";
			}

			clientBot.sendMessage(msg.channel, "Das sind die Eingetragenen Pokémon\n```\n" + showPokemon + "```", function(err, msg){
				//
			});
		}

		if( cmdTxt == "add" ) {
			if (suffix) {
				var config = require( __dirname + '/bot/config.json' );

				var newItem = parseInt(suffix);
				var array = config.pokeShow;

				if (array.indexOf(newItem) == -1) {
					array.push(newItem);
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** wurde gespeichert :rainbow: ", function(err, msg){
						//
					});
				} else {
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** ist schon in der Liste :warning:  ", function(err, msg){
						//
					});
				}
				config.pokeShow = config.pokeShow;
				fs.writeFileSync( __dirname + '/bot/config.json' , JSON.stringify(config));
				delete require.cache[ __dirname + '/bot/config.json' ]
			} else {
				clientBot.sendMessage(msg.channel, "Bitte gib eine ID an, zum Beispiel:  ``!add 1``  :point_up:", function(err, msg){
					//
				});
			}
		}

		if( cmdTxt == "del" ) {
			if (suffix) {
				var config = require( __dirname + '/bot/config.json' );

				var newItem = parseInt(suffix);
				var array = config.pokeShow;

				if (array.indexOf(newItem) == -1) {
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** befindet sich nicht in der Liste :warning:  ", function(err, msg){
						//
					});
				} else {
					var i = array.indexOf(newItem);
					if(i != -1) {
						array.splice(i, 1);
					}
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** wurde gelöscht :rainbow: ", function(err, msg){
						//
					});
				}
				config.pokeShow = config.pokeShow;
				fs.writeFileSync( __dirname + '/bot/config.json' , JSON.stringify(config));
				delete require.cache[ __dirname + '/bot/config.json' ]
			} else {
				clientBot.sendMessage(msg.channel, "Bitte gib eine ID an, zum Beispiel:  ``!del 1``  :point_up:", function(err, msg){
					//
				});
			}
		}

	} else if (msg.author != clientBot.user && msg.isMentioned(clientBot.user)) { // If someone @called the Bot
			clientBot.sendMessage(msg.channel ,msg.author + ", mit ``!add 1`` kannst du Pokemon hinzufügen & ``!del 1`` es wieder löschen ! :cool:");
	}

});

/* TOKEN */
clientBot.loginWithToken(config.token, (err, token) => {
	if (err) { console.log(err); setTimeout(() => { process.exit(1); }, 2000); }
	if (!token) { console.log(" WARN " + " failed to connect"); setTimeout(() => { process.exit(0); }, 2000); }
});

/* Changing game playing */
setInterval(() => {
	clientBot.setPlayingGame(config.games[Math.floor(Math.random() * (config.games.length))]);
}, (10 * 1000) * 60); //change playing game every 10 minutes

/* checking for new pokemon */
setInterval(() => {
	checkPokemon();
}, (config.CheckMinutes * 1000) * 10); //checking for Pokemon every x minutes
<commit_msg>array sorting correctly<commit_after>/*
	Created by Devsome
	thanks to imDevinC https://github.com/ImDevinC/pkgo-discord for the functions
	edited for https://github.com/modrzew/pokeminer
*/
var Discord = require("discord.js");
var request = require("request");
var NodeGeocoder = require('node-geocoder');
var fs = require("fs");

// Loading my Configs
var config = require("./bot/config.json");
var locale = require("./locales/pokemon."+config.locale+".json");

var clientBot = new Discord.Client();

var alreadySeen = [];
var joinUrl = "https://discordapp.com/oauth2/authorize?client_id=" + config.app_id + "&scope=bot&permissions=";
var mapUrl = 'http://maps.google.com/maps?&z=10&ll={0}+{1}&q={0}+{1}';
var options = {
  provider: 'google',
  httpAdapter: 'https',
  apiKey: config.gmap_key,
  formatter: null
};
var geocoder = NodeGeocoder(options);

clientBot.on("ready", function () {
	console.log("\n[INFO]\tTo add me visit this url:\n\t" + joinUrl + "\n\n");
	console.log("[INFO]\tReady to begin!");
	console.log("[INFO]\tYou're connected to [ " + clientBot.servers.length + " ] Servers with [" + clientBot.channels.length + "] Channels!");

	clientBot.setPlayingGame( config.games[Math.floor(Math.random() * (config.games.length))] );
});

clientBot.on('disconnected', function() {
	console.log("Disconnted ? Let me reconnect asap...");
	clientBot.loginWithToken(config.token);
});

clientBot.on("error", function (error) {
	console.log("Caught error: " + error);
});

// CMD+C at terminal
process.on("SIGINT", function () {
	console.log("\n Whoa wait, let me logout first...");
	clientBot.logout();
	process.exit(1);
});

function checkPokemon() {
	request('http://' + config.getServer + '/discord', (err, res, body) => {
		if (err) {
			console.log(err);
			return;
		}
		if (200 != res.statusCode) {
			console.log('Invalid response code: ' + res.statusCode);
			return;
		}
		parsePokemon(JSON.parse(body));
	});
}

function parsePokemon(results) {
	var config = require("./bot/config.json");
	if (!Object.keys(results) || Object.keys(results).length < 1) {
		return;
	}
	foundPokemon = [];
	for (pokemon in results) {
		if(config.pokeShow.indexOf(results[pokemon].pokemon_id) >= 0 ) {
			// found
		} else {
			continue; // not found
		}
		foundPokemon.push(results[pokemon].key);
		if (alreadySeen.indexOf(results[pokemon].key) > -1) {
			continue;
		}

		newPokemonSighted(results[pokemon]);
		alreadySeen.push(results[pokemon].key);
	}

	clearStalePokemon(foundPokemon);
}

function clearStalePokemon(pokemons) {
	var oldSeen = alreadySeen;
	for (id in oldSeen) {
		var pokemon = pokemons.indexOf(oldSeen[id]);
		if (pokemon > -1) {
			continue;
	}

	var index = alreadySeen.indexOf(oldSeen[id]);
		alreadySeen.splice(index, 1);
	}
}

function newPokemonSighted(pokemon) {
	var diff = new Date(pokemon.disappear_time * 1000) - Date.now();
	diff = Math.floor(diff / 1000);
	diff = Math.floor(diff / 60);
	min_diff = diff % 60;
	var url = mapUrl.split('{0}').join(pokemon.lat);
	url = url.split('{1}').join(pokemon.lng);

	geocoder.reverse({lat:pokemon.lat, lon:pokemon.lng}, function(err, res) {
		var streetName = res[0].formattedAddress;
		var message = '**' + pokemon.name + '** (' + pokemon.pokemon_id + ') gesichtet ! Verschwindet in **' + min_diff + '** minuten \n'+streetName+'';
		clientBot.sendFile( config.channelID , __dirname + "/bot/img/"+ pokemon.pokemon_id +".png" , pokemon.pokemon_id +".png", message, (err, msg) => {
			if (err) {
				clientBot.sendMessage(config.channelID, "I do not have the rights to send a **file** :cry:!");
			}
		});
	});
}

clientBot.on("message", function (msg) {

	if(msg.author.id != clientBot.user.id && msg.content[0] === '!'){
		var cmdTxt = msg.content.split(" ")[0].substring(1);
		var suffix = msg.content.substring(cmdTxt.length+2);

		if( cmdTxt == "read" ) {
			var config = require( __dirname + '/bot/config.json' );
			var buffer = config.pokeShow + '';
			var array = buffer.split(',');
			var showPokemon = "";
			array.sort( function(a,b) { return b - a; } );
			for(var i in array)
			{
				showPokemon += array[i] + " " + locale[array[i]] + "\n";
			}

			clientBot.sendMessage(msg.channel, "Das sind die Eingetragenen Pokémon\n```\n" + showPokemon + "```", function(err, msg){
				//
			});
		}

		if( cmdTxt == "add" ) {
			if (suffix) {
				var config = require( __dirname + '/bot/config.json' );

				var newItem = parseInt(suffix);
				var array = config.pokeShow;

				if (array.indexOf(newItem) == -1) {
					array.push(newItem);
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** wurde gespeichert :rainbow: ", function(err, msg){
						//
					});
				} else {
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** ist schon in der Liste :warning:  ", function(err, msg){
						//
					});
				}
				config.pokeShow = config.pokeShow;
				fs.writeFileSync( __dirname + '/bot/config.json' , JSON.stringify(config));
				delete require.cache[ __dirname + '/bot/config.json' ]
			} else {
				clientBot.sendMessage(msg.channel, "Bitte gib eine ID an, zum Beispiel:  ``!add 1``  :point_up:", function(err, msg){
					//
				});
			}
		}

		if( cmdTxt == "del" ) {
			if (suffix) {
				var config = require( __dirname + '/bot/config.json' );

				var newItem = parseInt(suffix);
				var array = config.pokeShow;

				if (array.indexOf(newItem) == -1) {
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** befindet sich nicht in der Liste :warning:  ", function(err, msg){
						//
					});
				} else {
					var i = array.indexOf(newItem);
					if(i != -1) {
						array.splice(i, 1);
					}
					clientBot.sendMessage(msg.channel, "Pokémon **"+suffix+" - "+locale[suffix]+"** wurde gelöscht :rainbow: ", function(err, msg){
						//
					});
				}
				config.pokeShow = config.pokeShow;
				fs.writeFileSync( __dirname + '/bot/config.json' , JSON.stringify(config));
				delete require.cache[ __dirname + '/bot/config.json' ]
			} else {
				clientBot.sendMessage(msg.channel, "Bitte gib eine ID an, zum Beispiel:  ``!del 1``  :point_up:", function(err, msg){
					//
				});
			}
		}

	} else if (msg.author != clientBot.user && msg.isMentioned(clientBot.user)) { // If someone @called the Bot
			clientBot.sendMessage(msg.channel ,msg.author + ", mit ``!add 1`` kannst du Pokemon hinzufügen & ``!del 1`` es wieder löschen ! :cool:");
	}

});

/* TOKEN */
clientBot.loginWithToken(config.token, (err, token) => {
	if (err) { console.log(err); setTimeout(() => { process.exit(1); }, 2000); }
	if (!token) { console.log(" WARN " + " failed to connect"); setTimeout(() => { process.exit(0); }, 2000); }
});

/* Changing game playing */
setInterval(() => {
	clientBot.setPlayingGame(config.games[Math.floor(Math.random() * (config.games.length))]);
}, (10 * 1000) * 60); //change playing game every 10 minutes

/* checking for new pokemon */
setInterval(() => {
	checkPokemon();
}, (config.CheckMinutes * 1000) * 10); //checking for Pokemon every x minutes
<|endoftext|>


<commit_before>import createObservable from './createObservable'
import createHOCFromMapper from './createHOCFromMapper'
import { config as obsConfig } from '../setObservableConfig'

const updateProps = subscriber =>
  createHOCFromMapper((props$, obs) => [
    createObservable(observer =>
      obsConfig.toESObservable(props$).subscribe({
        next: subscriber(observer.next),
        error: typeof observer.error === 'function' ? observer.error : undefined,
        complete: typeof observer.complete === 'function' ? observer.complete : undefined,
      }),
    ),
    obs,
  ])

export default updateProps
<commit_msg>perf: keep binding<commit_after>import createObservable from './createObservable'
import createHOCFromMapper from './createHOCFromMapper'
import { config as obsConfig } from '../setObservableConfig'

const updateProps = subscriber =>
  createHOCFromMapper((props$, obs) => [
    createObservable(observer =>
      obsConfig.toESObservable(props$).subscribe({
        next: subscriber(observer.next),
        error: typeof observer.error === 'function' ? error => observer.error(error) : undefined,
        complete: typeof observer.complete === 'function' ? value => observer.complete(value) : undefined,
      }),
    ),
    obs,
  ])

export default updateProps
<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

// We use an incrementing count of SVG to ensure unique IDs. We could also hash
// the contents as duplicate SVGs share styles, but this is easier.
let svgIndex = 0;

/**
 * This rewrites SVGs so we can safely inline them into our pages, as well as
 * adding an optional className.
 *
 * The basic issue is that SVGs use "#foo" references for clip-paths and so on,
 * however, when inlined these become global. We rewrite all IDs so they're
 * unique.
 *
 * @param {string} raw
 * @param {string} className
 * @returns {string}
 */
const updateSvgForInclude = (raw, options = {label: '', hidden: false, className: ''}) => {
  if (!raw) {
    return '';
  }

  let {label, hidden, className} = options;

  if (hidden) {
    raw = raw.replace('<svg', `<svg aria-hidden="true"`);
  } else if (label) {
    raw = raw.replace('<svg', `<svg role="img" aria-label="${label}"`)
  } else {
    throw new Error(`SVGs must provide a label or set hidden to true.
    If you're using icon() or svg() you may have forgotten the label argument.
    A good label should be action focused: e.g. "Search" instead of "Magnifying glass".
    ${raw}`);
  }

  const localIndex = ++svgIndex;
  const suffix = '_' + localIndex.toString(36);

  if (className) {
    raw = raw.replace('<svg', `<svg class="${className}"`);
  }

  // Replace id="bar"
  raw = raw.replace(/\bid="(.+?)"/g, (_, id) => {
    return `id="${id}${suffix}"`;
  });

  // Replace href="#bar" (this will also work on xlink:href=...)
  raw = raw.replace(/\bhref="#(.+?)"/g, (_, id) => {
    return `href="#${id}${suffix}"`;
  });

  // Replace url(#bar)
  raw = raw.replace(/\burl\(#(.+?)\)/g, (_, id) => {
    return `url(#${id}${suffix})`;
  });

  return raw;
};

module.exports = {updateSvgForInclude};
<commit_msg>fix grumpy linter<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

// We use an incrementing count of SVG to ensure unique IDs. We could also hash
// the contents as duplicate SVGs share styles, but this is easier.
let svgIndex = 0;

/**
 * This rewrites SVGs so we can safely inline them into our pages, as well as
 * adding an optional className.
 *
 * The basic issue is that SVGs use "#foo" references for clip-paths and so on,
 * however, when inlined these become global. We rewrite all IDs so they're
 * unique.
 *
 * @param {string} raw
 * @param {{ label?: string, hidden?: boolean, className?: string }} options
 * @returns {string}
 */
const updateSvgForInclude = (
  raw,
  options = {label: '', hidden: false, className: ''}
) => {
  if (!raw) {
    return '';
  }

  const {label, hidden, className} = options;

  if (hidden) {
    raw = raw.replace('<svg', '<svg aria-hidden="true"');
  } else if (label) {
    raw = raw.replace('<svg', `<svg role="img" aria-label="${label}"`);
  } else {
    throw new Error(`SVGs must provide a label or set hidden to true.
    If you're using icon() or svg() you may have forgotten the label argument.
    A good label should be action focused: e.g. 'Search' instead of 'Magnifying glass'.
    ${raw}`);
  }

  const localIndex = ++svgIndex;
  const suffix = '_' + localIndex.toString(36);

  if (className) {
    raw = raw.replace('<svg', `<svg class="${className}"`);
  }

  // Replace id="bar"
  raw = raw.replace(/\bid="(.+?)"/g, (_, id) => {
    return `id="${id}${suffix}"`;
  });

  // Replace href="#bar" (this will also work on xlink:href=...)
  raw = raw.replace(/\bhref="#(.+?)"/g, (_, id) => {
    return `href="#${id}${suffix}"`;
  });

  // Replace url(#bar)
  raw = raw.replace(/\burl\(#(.+?)\)/g, (_, id) => {
    return `url(#${id}${suffix})`;
  });

  return raw;
};

module.exports = {updateSvgForInclude};
<|endoftext|>


<commit_before>var MS = (function (MS) {
  var widgets = MS.widgets = MS.widgets || {};
  widgets.SuggestPicker = Class.create({

  options : {
    'showKey' : true,
    'showTooltip' : true,
    'showDeleteTool' : true,
    'enableSort' : true,
    'showClearTool' : true,
    'inputType': 'hidden',
    'listInsertionEltSelector' : null,
    'listInsertionPosition' : 'after',
  },
  initialize: function(element, suggest, options) {
    this.options = Object.extend(Object.clone(this.options), options || { });
    this.input = element;
    this.suggest = suggest;
    this.inputName = this.input.name;
    this.input.name = this.input.name + "__suggested";
    this.suggest.options.callback = this.acceptSuggestion.bind(this);
    this.list = new Element('ul', {'class' : 'accepted-suggestions'});
    var listInsertionElement;
    if (!this.options.listInsertionEltSelector || !(listInsertionElement = this.input.up().down(this.options.listInsertionEltSelector))) {
      listInsertionElement = this.input;
    }
    var insertion = {};
    insertion[this.options.listInsertionPosition] = this.list;
    listInsertionElement.insert(insertion);
    if (this.options.showClearTool) {
      this.clearTool = new Element('span', {'class' : 'clear-tool delete-tool invisible', 'title' : 'Clear the list of selected suggestions'}).update('Delete all ✖');
      this.clearTool.observe('click', this.clearAcceptedList.bindAsEventListener(this));
      this.list.insert({'after': this.clearTool});
    }
    if (typeof(this.options.onItemAdded) == "function") {
      this.onItemAdded = this.options.onItemAdded;
    }
  },

  acceptAddItem : function (key, value, info) {
    var input = $(this.getInputId(key));
    if (input) {
      input.checked = true;
      Event.fire(input, 'suggest:change');
      input.scrollTo();
      return false;
    }
    return true;
  },

  acceptSuggestion : function(obj) {
    if (this.acceptAddItem(obj.id || obj.value, obj.value, obj.info)) {
      this.addItem(obj.id || obj.value, obj.value, obj.info);
    }
    this.input.value = "";
    return false;
  },

  addItem : function(key, value, info) {
    if (!key) {
      return;
    }
    var id = this.getInputId(key);
    var listItem = new Element("li");
    var displayedValue = new Element("label", {"class": "accepted-suggestion", "for" : id});
    // insert input
    var inputOptions = {"type" : this.options.inputType, "name" : this.inputName, "id" : id, "value" : key};
    if (this.options.inputType == 'checkbox') {
      inputOptions.checked = 'checked';
    }
    displayedValue.insert({'bottom' : new Element("input", inputOptions)});
    // if the key should be displayed, insert it
    if (this.options.showKey) {
      displayedValue.insert({'bottom' : new Element("span", {"class": "key"}).update("[" + key.escapeHTML() + "]")});
      displayedValue.insert({'bottom' : new Element("span", {"class": "sep"}).update(" ")});
    }
    // insert the displayed value
    displayedValue.insert({'bottom' : new Element("span", {"class": "value"}).update(value.escapeHTML())});
    listItem.appendChild(displayedValue);
    // delete tool
    if (this.options.showDeleteTool) {
      var deleteTool = new Element("span", {'class': "delete-tool", "title" : "Delete this term"}).update('✖');
      deleteTool.observe('click', this.removeItem.bindAsEventListener(this));
      listItem.appendChild(deleteTool);
    }
    // tooltip, if information exists and the options state there should be a tooltip
    if (this.options.showTooltip && info) {
      listItem.appendChild(new Element("div", {class : "tooltip"}).update(info));
    }
    this.list.appendChild(listItem);
    this.updateListTools();
    this.onItemAdded($(id))
  },

  onItemAdded : function (element) {
  },

  removeItem : function(event) {
    var item = event.findElement('li');
    item.remove();
    this.input.value = "";
    this.updateListTools();
  },

  clearAcceptedList : function () {
    this.list.update("");
    this.updateListTools();
  },

  updateListTools : function () {
    if (this.clearTool) {
      if (this.list.select('li .accepted-suggestion').length > 0) {
        this.clearTool.removeClassName('invisible');
      } else {
        this.clearTool.addClassName('invisible');
      }
    }
    if (this.options.enableSort && this.list.select('li .accepted-suggestion').length > 0 && typeof(Sortable) != "undefined") {
      Sortable.create(this.list);
    }
  },

  getInputId : function(key) {
    return this.inputName + "_" + key;
  }
});
  return MS;
}(MS || {}));
<commit_msg>[ux] making sure the item that was just selected in the form is visible<commit_after>var MS = (function (MS) {
  var widgets = MS.widgets = MS.widgets || {};
  widgets.SuggestPicker = Class.create({

  options : {
    'showKey' : true,
    'showTooltip' : true,
    'showDeleteTool' : true,
    'enableSort' : true,
    'showClearTool' : true,
    'inputType': 'hidden',
    'listInsertionEltSelector' : null,
    'listInsertionPosition' : 'after',
  },
  initialize: function(element, suggest, options) {
    this.options = Object.extend(Object.clone(this.options), options || { });
    this.input = element;
    this.suggest = suggest;
    this.inputName = this.input.name;
    this.input.name = this.input.name + "__suggested";
    this.suggest.options.callback = this.acceptSuggestion.bind(this);
    this.list = new Element('ul', {'class' : 'accepted-suggestions'});
    var listInsertionElement;
    if (!this.options.listInsertionEltSelector || !(listInsertionElement = this.input.up().down(this.options.listInsertionEltSelector))) {
      listInsertionElement = this.input;
    }
    var insertion = {};
    insertion[this.options.listInsertionPosition] = this.list;
    listInsertionElement.insert(insertion);
    if (this.options.showClearTool) {
      this.clearTool = new Element('span', {'class' : 'clear-tool delete-tool invisible', 'title' : 'Clear the list of selected suggestions'}).update('Delete all ✖');
      this.clearTool.observe('click', this.clearAcceptedList.bindAsEventListener(this));
      this.list.insert({'after': this.clearTool});
    }
    if (typeof(this.options.onItemAdded) == "function") {
      this.onItemAdded = this.options.onItemAdded;
    }
  },

  acceptAddItem : function (key, value, info) {
    var input = $(this.getInputId(key));
    if (input) {
      input.checked = true;
      Event.fire(input, 'suggest:change');
      this.ensureVisible(input);
      return false;
    }
    return true;
  },

  ensureVisible : function (element) {
    if (element.viewportOffset().top > document.viewport.getDimensions().height) {
      if (element.viewportOffset().top - this.input.viewportOffset().top < document.viewport.getDimensions().height) {
        this.input.scrollTo();
      } else {
        element.scrollTo();
      }
    }
  },

  acceptSuggestion : function(obj) {
    if (this.acceptAddItem(obj.id || obj.value, obj.value, obj.info)) {
      this.addItem(obj.id || obj.value, obj.value, obj.info);
    }
    this.input.value = "";
    return false;
  },

  addItem : function(key, value, info) {
    if (!key) {
      return;
    }
    var id = this.getInputId(key);
    var listItem = new Element("li");
    var displayedValue = new Element("label", {"class": "accepted-suggestion", "for" : id});
    // insert input
    var inputOptions = {"type" : this.options.inputType, "name" : this.inputName, "id" : id, "value" : key};
    if (this.options.inputType == 'checkbox') {
      inputOptions.checked = 'checked';
    }
    displayedValue.insert({'bottom' : new Element("input", inputOptions)});
    // if the key should be displayed, insert it
    if (this.options.showKey) {
      displayedValue.insert({'bottom' : new Element("span", {"class": "key"}).update("[" + key.escapeHTML() + "]")});
      displayedValue.insert({'bottom' : new Element("span", {"class": "sep"}).update(" ")});
    }
    // insert the displayed value
    displayedValue.insert({'bottom' : new Element("span", {"class": "value"}).update(value.escapeHTML())});
    listItem.appendChild(displayedValue);
    // delete tool
    if (this.options.showDeleteTool) {
      var deleteTool = new Element("span", {'class': "delete-tool", "title" : "Delete this term"}).update('✖');
      deleteTool.observe('click', this.removeItem.bindAsEventListener(this));
      listItem.appendChild(deleteTool);
    }
    // tooltip, if information exists and the options state there should be a tooltip
    if (this.options.showTooltip && info) {
      listItem.appendChild(new Element("div", {class : "tooltip"}).update(info));
    }
    this.list.appendChild(listItem);
    this.updateListTools();
    this.onItemAdded($(id))
  },

  onItemAdded : function (element) {
  },

  removeItem : function(event) {
    var item = event.findElement('li');
    item.remove();
    this.input.value = "";
    this.updateListTools();
  },

  clearAcceptedList : function () {
    this.list.update("");
    this.updateListTools();
  },

  updateListTools : function () {
    if (this.clearTool) {
      if (this.list.select('li .accepted-suggestion').length > 0) {
        this.clearTool.removeClassName('invisible');
      } else {
        this.clearTool.addClassName('invisible');
      }
    }
    if (this.options.enableSort && this.list.select('li .accepted-suggestion').length > 0 && typeof(Sortable) != "undefined") {
      Sortable.create(this.list);
    }
  },

  getInputId : function(key) {
    return this.inputName + "_" + key;
  }
});
  return MS;
}(MS || {}));
<|endoftext|>


<commit_before>'use strict';

/* global queryRegExSelector, queryRegExSelectorAll, getYouTubeHtml5VideoUrl */
Polymer('polymer-hypervideo', {
  publish: {
    currentTime: 0,
    duration: null,
    actorsOffset: {}
  },
  created: function() {
  },
  ready: function() {
    var that = this;
    var spinner;
    var video = that.$.hypervideo;
    var container = that.$.container;

    var onMutation = function(observer, mutations) {
      var nodes = [];
      var chapters = [];
      for (var i = 0, lenI = mutations.length; i < lenI; i++) {
        var mutation = mutations[i];
        if (mutation.addedNodes) {
          for (var j = 0, lenJ = mutation.addedNodes.length; j < lenJ; j++) {
            if (/^polymer-data-/gi.test(mutation.addedNodes[j].nodeName)) {
              nodes.push(mutation.addedNodes[j]);
            }
          }
        }
      }
      if (nodes.length) {
        positionDataAnnotations(nodes);
        updateTimelineAnnotations(nodes);
      }
      that.onMutation(that, onMutation);
    };

    that.onMutation(that, onMutation);

    var CORS_PROXY = document.location.origin + '/cors/';
    document.addEventListener('trackready', function(e) {
      console.log('Received event (document): trackready');
      var data = e.detail;
      var track = document.createElement('track');
      var cuesRead = false;
      track.addEventListener('load', function(e) {
        if (!cuesRead) {
          console.log('Received event (track): load');
          cuesRead = true;
          return readCues(e.target.track.cues, data.kind);
        }
      }, false);
      track.addEventListener('cuechange', function() {
        console.log('Fired event: hypervideocuechange');
        that.fire(
          'hypervideocuechange',
          {
            activeCues: track.track.activeCues
          }
        );
      });
      var trackLoadedInterval = setInterval(function() {
        if (track.readyState >= 2) {
          clearInterval(trackLoadedInterval);
          if (!cuesRead) {
            console.log('Received event (track): readyState');
            cuesRead = true;
            return readCues(track.track.cues, data.kind);
          }
        }
      }, 100);
      track.src = data.src;
      track.default = true;
      track.kind = data.kind;
      if (track.kind === 'subtitles' || track.kind === 'captions') {
        track.srclang = 'en';
        track.track.mode = 'showing';
      } else if (track.kind === 'chapters') {
        var canvas = document.createElement('canvas');
        canvas.width = video.width;
        canvas.height = video.height;
        var ctx = canvas.getContext('2d');
        that.ctx = ctx;
        that.canvas = canvas;
      }
      video.appendChild(track);
    }, false);

    document.addEventListener('webcomponentstocready', function() {
      console.log('Received event (document): webcomponentstocready');
      // get all child <polymer-*> child nodes
      var webComponents = queryRegExSelectorAll(that, /^polymer-/gi);
      console.log('Fired event: webcomponentstoc');
      that.fire(
        'webcomponentstoc',
        {
          webComponentsToC: webComponents
        }
      );
    }, false);

    var updateTimelineAnnotations = function(opt_nodes) {
      // get all child <polymer-data-*> child nodes
      var dataAnnotations =
          opt_nodes || queryRegExSelectorAll(that, /^polymer-data-/gi);
      var annotations = [];
      dataAnnotations.forEach(function(annotation) {
        var type;
        if (/actor/gi.test(annotation.nodeName)) {
          type = 'actors';
        } else if (/overlay/gi.test(annotation.nodeName)) {
          type = 'overlays';
        } else {
          type = 'annotations';
        }
        annotations.push({
          start: parseInt(annotation.getAttribute('start'), 10),
          end: parseInt(annotation.getAttribute('end'), 10),
          type: type
        });
      });
      console.log('Fired event: dataannotations');
      that.fire(
        'dataannotations',
        {
          dataAnnotations: annotations
        }
      );

    };

    document.addEventListener('timelineready', function() {
      console.log('Received event (document): timelineready');
      updateTimelineAnnotations();
    }, false);

    // listen for events coming from the timeline component
    document.addEventListener('currenttimeupdate', function(e) {
      // console.log('Received event (document): currenttimeupdate');
      var data = e.detail;
      video.currentTime = data.currentTime;
      video.play();
    }, false);

    document.addEventListener('requeststillframes', function(e) {
      console.log('Received event (document): requeststillframes');
      spinner = showSpinner();
      var cues = e.detail.cues;
      if (!cues) {
        return;
      }
      var functions = [];
      cues.forEach(function(cue) {
        var start = cue.start;
        if (start > video.duration) {
          return;
        }
        functions.push({
          cue: cue,
          func: function() {
            video.currentTime = start;
          }
        });
      });
      var getNextStillFrame = function() {
        console.log('Received event (video): seeked');
        that.ctx.drawImage(video, 0, 0, video.clientWidth,
            video.clientHeight);
        var img = document.createElement('img');
        img.setAttribute('class', 'hypervideo');
        var url = that.canvas.toDataURL();
        img.src = url;
        var cue = functions[processedStillFrames].cue;
        console.log('Fired event: receivestillframe');
        that.fire(
          'receivestillframe',
          {
            img: img,
            text: cue.text,
            start: cue.start,
            end: cue.end
          }
        );
        processedStillFrames++;
        if (functions[processedStillFrames]) {
          return functions[processedStillFrames].func();
        } else {
          video.removeEventListener('seeked', getNextStillFrame);
          video.currentTime = 0;
          that.fire('allstillframesreceived');
          spinner.remove();
        }
      };
      var processedStillFrames = 0;
      video.addEventListener('seeked', getNextStillFrame);
      functions[processedStillFrames].func();
    });

    var initializeVideo = function() {
      // either add sources for regular video
      if (that.src) {
        that.src.split(/\s/g).forEach(function(src) {
          var source = document.createElement('source');
          source.src = src;
          video.appendChild(source);
        });
      // or add sources for YouTube video
      } else if (that.youtubevideoid) {
        getYouTubeHtml5VideoUrl(that.youtubevideoid,
            function(err, videoSources) {
          if (err) {
            return;
          }
          for (var videoSource in videoSources) {
            videoSource = videoSources[videoSource];
            var source = document.createElement('source');
            source.src = CORS_PROXY +
                encodeURIComponent(videoSource.original_url);
            source.type = videoSource.type.replace(/\+/g, ' ')
                .replace(/"/g, '\"');
            video.appendChild(source);
          }
        });
      }
      // determine video dimensions
      if (that.width) {
        that.width = parseInt(that.width, 10);
      } else {
        that.width = 400;
      }
      video.width = that.width;
      if (that.height) {
        that.height = parseInt(that.height, 10);
      } else {
        that.height = 225;
      }
      video.height = that.height;
      // add poster
      if (that.poster) {
        video.poster = that.poster;
      }
      // mute video
      if (that.muted !== null && that.muted !== 'false') {
        video.muted = true;
      }
    };

    var showSpinner = function() {
      // show spinner while the hypervideo gets prepared
      var splashDiv = document.createElement('div');
      splashDiv.classList.add('spinner');
      var splashSpinner = document.createElement('div');
      splashSpinner.classList.add('progress');
      splashDiv.appendChild(splashSpinner);
      splashDiv.style.width = video.width + 'px';
      splashDiv.style.height = video.height + 'px';
      splashDiv.style.position = 'absolute';
      splashDiv.style.top = video.offsetTop + 'px';
      splashDiv.style.left = video.offsetLeft + 'px';
      splashSpinner.style.position = 'relative';
      splashSpinner.style.top = (video.offsetHeight / 2 - 60 / 2) + 'px';
      splashSpinner.style.left = (video.offsetWidth / 2 - 60 / 2) + 'px';
      var loadingDiv = document.createElement('div');
      loadingDiv.textContent = '*';
      splashSpinner.appendChild(loadingDiv);
      container.appendChild(splashDiv);
      return splashDiv;
    };

    var positionDataAnnotations = function(opt_nodes) {
      // positions data annotations on top of the video
      var polymerData =
          opt_nodes || queryRegExSelectorAll(that, /^polymer-data-/gi);
      polymerData.forEach(function(node) {
        node.style.position = 'absolute';
        node.style.top = (video.offsetTop + 0.66 * video.offsetHeight) +
            'px';
        node.style.left = (video.offsetLeft + (0.05 * that.width)) + 'px';
        node.style.width = (0.9 * that.width) + 'px';
        node.style.display = 'none';
      });
    };

    var readCues = function(cues, kind) {
      if (!cues) {
        return;
      }
      var cueData = [];
      for (var i = 0, lenI = cues.length; i < lenI; i++) {
        var cue = cues.item ? cues.item(i) : cues[i];
        cueData.push({
          start: parseInt(cue.startTime, 10),
          end: parseInt(cue.endTime, 10),
          text: cue.text,
          id: cue.id,
          type: kind
        });
      }
      console.log('Fired event: cuesread');
      that.fire(
        'cuesread',
        {
          cueData: cueData,
          kind: kind
        }
      );
    };

    video.addEventListener('loadedmetadata', function() {
      console.log('Received event (video): loadedmetadata');
      that.duration = video.duration;
      // adjust the timeline dimensions according to the video duration
      var polymerTimelines = that.querySelectorAll('polymer-timeline');
      for (var i = 0, lenI = polymerTimelines.length; i < lenI; i++) {
        polymerTimelines[i].style.left = (video.offsetLeft +
            (0.05 * that.width)) + 'px';
      }
      var polymerData = queryRegExSelector(that, /^polymer-data-/gi);
      console.log('Fired event: hypervideoloadedmetadata');
      that.fire(
        'hypervideoloadedmetadata',
        {
          duration: that.duration,
          height: that.height,
          width: that.width,
          actorsOffset: {
            left: polymerData ? polymerData.style.left.replace('px', '') : null,
            top: polymerData ? polymerData.style.top.replace('px', '') : null
          }
        }
      );

      // alternative views
      if (that.alternativeviews) {
        var videos = [video];
        var videoWidth = Math.floor(that.width / 5);
        var ratio = that.width / that.height;

        function showControls(e) {
          return e.target.setAttribute('controls', true);
        }

        var hideControls = function hideControls(e) {
          return e.target.removeAttribute('controls');
        };

        var playAll = function playAll() {
          for (var i = 0; i < videos.length; i++) {
            videos[i].play();
          }
        };

        var pauseAll = function pauseAll() {
          for (var i = 0; i < videos.length; i++) {
            videos[i].pause();
          }
        };

        var seekAll = function seekAll(e) {
          for (var i = 0; i < videos.length; i++) {
            var currentVideo = videos[i];
            if (currentVideo === e.target) {
              continue;
            }
            currentVideo.currentTime = e.target.currentTime;
          }
        };

        var transitionend = function transitioned(e) {
          for (var i = 0; i < videos.length; i++) {
            var currentVideo = videos[i];
            if (currentVideo.classList.contains('small')) {
              currentVideo.style.zIndex = 1000;
            } else {
              currentVideo.style.zIndex = 'auto';
            }
          }
        };

        var makeBig = function makeBig(e) {
          for (var i = 0, j = 0; i < videos.length; i++) {
            var currentVideo = videos[i];
            if (currentVideo === e.target) {
              currentVideo.width = that.width;
              currentVideo.height = that.width / ratio;
              currentVideo.style.top = 0;
              currentVideo.style.left = 0;
              currentVideo.style.zIndex = 10000;
              currentVideo.classList.remove('small');
              currentVideo.classList.add('big');
              currentVideo.addEventListener('mouseover', showControls);
              currentVideo.addEventListener('mouseout', hideControls);
              currentVideo.addEventListener('seeked', seekAll);
            } else {
              currentVideo.width = videoWidth;
              currentVideo.height = videoWidth / ratio;
              // Change position with
              // polymer-hypervideo::shadow video.small { margin-top: 150px; }
              currentVideo.style.top = that.height + 'px';
              currentVideo.style.left = (j * videoWidth) + 'px';
              currentVideo.classList.remove('big');
              currentVideo.classList.add('small');
              currentVideo.removeEventListener('mouseover', showControls);
              currentVideo.removeEventListener('mouseout', hideControls);
              currentVideo.removeEventListener('seeked', seekAll);
              currentVideo.removeAttribute('controls');
              j++;
            }
          }
        };

        that.alternativeviews.split(/\s/).forEach(function(views) {
          views = JSON.parse(views);
          var content = container.querySelector('content');
          for (var videoSource in views) {
            if (video.currentSrc.indexOf(videoSource) === -1) {
              continue;
            }
            for (var id in views[videoSource]) {
              var alternativeView = views[videoSource][id];
              var viewVideo = document.createElement('video');
              var viewSource = document.createElement('source');
              viewSource.src = alternativeView.src;
              viewVideo.appendChild(viewSource);
              viewVideo.id = id;
              viewVideo.setAttribute('title', alternativeView.title);
              viewVideo.classList.add('hypervideo');
              video.parentNode.insertBefore(viewVideo, content);
              videos.push(viewVideo);
            }
          }
        });

        (function init() {
          for (var i = 0; i < videos.length; i++) {
            var currentVideo = videos[i];

            currentVideo.addEventListener('play', playAll);

            currentVideo.addEventListener('pause', pauseAll);

            currentVideo.addEventListener('click', makeBig);

            currentVideo.addEventListener('transitionend', transitionend);

            if (i === 0) {
              currentVideo.width = that.width;
              currentVideo.height = that.height;
              currentVideo.style.top = 0;
              currentVideo.style.left = 0;
              currentVideo.classList.add('big');
              currentVideo.addEventListener('mouseover', showControls);
              currentVideo.addEventListener('mouseout', hideControls);
              currentVideo.addEventListener('seeked', seekAll);
              currentVideo.muted = false;
            } else {
              currentVideo.style.left = ((i - 1) * videoWidth) + 'px';
              // Change position with
              // polymer-hypervideo::shadow video.small { margin-top: 150px; }
              currentVideo.style.top =that.height + 'px';
              currentVideo.width = videoWidth;
              currentVideo.height = videoWidth / ratio;
              currentVideo.classList.add('small');
              currentVideo.muted = true;
            }
          }
        })();
      }

    }, false);

    // publish timeupdate events
    video.addEventListener('timeupdate', function() {
      // console.log('Received event (video): timeupdate');
      that.currentTime = video.currentTime;
      // console.log('Fired event: hypervideotimeupdate');
      that.fire(
        'hypervideotimeupdate',
        {
          currentTime: that.currentTime
        }
      );
    }, false);

    spinner = showSpinner();
    setTimeout(function() {
      initializeVideo();
      positionDataAnnotations();
      spinner.remove();
    }, 50);
  },
  pause: function() {
    return this.$.hypervideo.pause();
  },
  play: function() {
    return this.$.hypervideo.play();
  }
});<commit_msg>Corrected function declaration.<commit_after>'use strict';

/* global queryRegExSelector, queryRegExSelectorAll, getYouTubeHtml5VideoUrl */
Polymer('polymer-hypervideo', {
  publish: {
    currentTime: 0,
    duration: null,
    actorsOffset: {}
  },
  created: function() {
  },
  ready: function() {
    var that = this;
    var spinner;
    var video = that.$.hypervideo;
    var container = that.$.container;

    var onMutation = function(observer, mutations) {
      var nodes = [];
      var chapters = [];
      for (var i = 0, lenI = mutations.length; i < lenI; i++) {
        var mutation = mutations[i];
        if (mutation.addedNodes) {
          for (var j = 0, lenJ = mutation.addedNodes.length; j < lenJ; j++) {
            if (/^polymer-data-/gi.test(mutation.addedNodes[j].nodeName)) {
              nodes.push(mutation.addedNodes[j]);
            }
          }
        }
      }
      if (nodes.length) {
        positionDataAnnotations(nodes);
        updateTimelineAnnotations(nodes);
      }
      that.onMutation(that, onMutation);
    };

    that.onMutation(that, onMutation);

    var CORS_PROXY = document.location.origin + '/cors/';
    document.addEventListener('trackready', function(e) {
      console.log('Received event (document): trackready');
      var data = e.detail;
      var track = document.createElement('track');
      var cuesRead = false;
      track.addEventListener('load', function(e) {
        if (!cuesRead) {
          console.log('Received event (track): load');
          cuesRead = true;
          return readCues(e.target.track.cues, data.kind);
        }
      }, false);
      track.addEventListener('cuechange', function() {
        console.log('Fired event: hypervideocuechange');
        that.fire(
          'hypervideocuechange',
          {
            activeCues: track.track.activeCues
          }
        );
      });
      var trackLoadedInterval = setInterval(function() {
        if (track.readyState >= 2) {
          clearInterval(trackLoadedInterval);
          if (!cuesRead) {
            console.log('Received event (track): readyState');
            cuesRead = true;
            return readCues(track.track.cues, data.kind);
          }
        }
      }, 100);
      track.src = data.src;
      track.default = true;
      track.kind = data.kind;
      if (track.kind === 'subtitles' || track.kind === 'captions') {
        track.srclang = 'en';
        track.track.mode = 'showing';
      } else if (track.kind === 'chapters') {
        var canvas = document.createElement('canvas');
        canvas.width = video.width;
        canvas.height = video.height;
        var ctx = canvas.getContext('2d');
        that.ctx = ctx;
        that.canvas = canvas;
      }
      video.appendChild(track);
    }, false);

    document.addEventListener('webcomponentstocready', function() {
      console.log('Received event (document): webcomponentstocready');
      // get all child <polymer-*> child nodes
      var webComponents = queryRegExSelectorAll(that, /^polymer-/gi);
      console.log('Fired event: webcomponentstoc');
      that.fire(
        'webcomponentstoc',
        {
          webComponentsToC: webComponents
        }
      );
    }, false);

    var updateTimelineAnnotations = function(opt_nodes) {
      // get all child <polymer-data-*> child nodes
      var dataAnnotations =
          opt_nodes || queryRegExSelectorAll(that, /^polymer-data-/gi);
      var annotations = [];
      dataAnnotations.forEach(function(annotation) {
        var type;
        if (/actor/gi.test(annotation.nodeName)) {
          type = 'actors';
        } else if (/overlay/gi.test(annotation.nodeName)) {
          type = 'overlays';
        } else {
          type = 'annotations';
        }
        annotations.push({
          start: parseInt(annotation.getAttribute('start'), 10),
          end: parseInt(annotation.getAttribute('end'), 10),
          type: type
        });
      });
      console.log('Fired event: dataannotations');
      that.fire(
        'dataannotations',
        {
          dataAnnotations: annotations
        }
      );

    };

    document.addEventListener('timelineready', function() {
      console.log('Received event (document): timelineready');
      updateTimelineAnnotations();
    }, false);

    // listen for events coming from the timeline component
    document.addEventListener('currenttimeupdate', function(e) {
      // console.log('Received event (document): currenttimeupdate');
      var data = e.detail;
      video.currentTime = data.currentTime;
      video.play();
    }, false);

    document.addEventListener('requeststillframes', function(e) {
      console.log('Received event (document): requeststillframes');
      spinner = showSpinner();
      var cues = e.detail.cues;
      if (!cues) {
        return;
      }
      var functions = [];
      cues.forEach(function(cue) {
        var start = cue.start;
        if (start > video.duration) {
          return;
        }
        functions.push({
          cue: cue,
          func: function() {
            video.currentTime = start;
          }
        });
      });
      var getNextStillFrame = function() {
        console.log('Received event (video): seeked');
        that.ctx.drawImage(video, 0, 0, video.clientWidth,
            video.clientHeight);
        var img = document.createElement('img');
        img.setAttribute('class', 'hypervideo');
        var url = that.canvas.toDataURL();
        img.src = url;
        var cue = functions[processedStillFrames].cue;
        console.log('Fired event: receivestillframe');
        that.fire(
          'receivestillframe',
          {
            img: img,
            text: cue.text,
            start: cue.start,
            end: cue.end
          }
        );
        processedStillFrames++;
        if (functions[processedStillFrames]) {
          return functions[processedStillFrames].func();
        } else {
          video.removeEventListener('seeked', getNextStillFrame);
          video.currentTime = 0;
          that.fire('allstillframesreceived');
          spinner.remove();
        }
      };
      var processedStillFrames = 0;
      video.addEventListener('seeked', getNextStillFrame);
      functions[processedStillFrames].func();
    });

    var initializeVideo = function() {
      // either add sources for regular video
      if (that.src) {
        that.src.split(/\s/g).forEach(function(src) {
          var source = document.createElement('source');
          source.src = src;
          video.appendChild(source);
        });
      // or add sources for YouTube video
      } else if (that.youtubevideoid) {
        getYouTubeHtml5VideoUrl(that.youtubevideoid,
            function(err, videoSources) {
          if (err) {
            return;
          }
          for (var videoSource in videoSources) {
            videoSource = videoSources[videoSource];
            var source = document.createElement('source');
            source.src = CORS_PROXY +
                encodeURIComponent(videoSource.original_url);
            source.type = videoSource.type.replace(/\+/g, ' ')
                .replace(/"/g, '\"');
            video.appendChild(source);
          }
        });
      }
      // determine video dimensions
      if (that.width) {
        that.width = parseInt(that.width, 10);
      } else {
        that.width = 400;
      }
      video.width = that.width;
      if (that.height) {
        that.height = parseInt(that.height, 10);
      } else {
        that.height = 225;
      }
      video.height = that.height;
      // add poster
      if (that.poster) {
        video.poster = that.poster;
      }
      // mute video
      if (that.muted !== null && that.muted !== 'false') {
        video.muted = true;
      }
    };

    var showSpinner = function() {
      // show spinner while the hypervideo gets prepared
      var splashDiv = document.createElement('div');
      splashDiv.classList.add('spinner');
      var splashSpinner = document.createElement('div');
      splashSpinner.classList.add('progress');
      splashDiv.appendChild(splashSpinner);
      splashDiv.style.width = video.width + 'px';
      splashDiv.style.height = video.height + 'px';
      splashDiv.style.position = 'absolute';
      splashDiv.style.top = video.offsetTop + 'px';
      splashDiv.style.left = video.offsetLeft + 'px';
      splashSpinner.style.position = 'relative';
      splashSpinner.style.top = (video.offsetHeight / 2 - 60 / 2) + 'px';
      splashSpinner.style.left = (video.offsetWidth / 2 - 60 / 2) + 'px';
      var loadingDiv = document.createElement('div');
      loadingDiv.textContent = '*';
      splashSpinner.appendChild(loadingDiv);
      container.appendChild(splashDiv);
      return splashDiv;
    };

    var positionDataAnnotations = function(opt_nodes) {
      // positions data annotations on top of the video
      var polymerData =
          opt_nodes || queryRegExSelectorAll(that, /^polymer-data-/gi);
      polymerData.forEach(function(node) {
        node.style.position = 'absolute';
        node.style.top = (video.offsetTop + 0.66 * video.offsetHeight) +
            'px';
        node.style.left = (video.offsetLeft + (0.05 * that.width)) + 'px';
        node.style.width = (0.9 * that.width) + 'px';
        node.style.display = 'none';
      });
    };

    var readCues = function(cues, kind) {
      if (!cues) {
        return;
      }
      var cueData = [];
      for (var i = 0, lenI = cues.length; i < lenI; i++) {
        var cue = cues.item ? cues.item(i) : cues[i];
        cueData.push({
          start: parseInt(cue.startTime, 10),
          end: parseInt(cue.endTime, 10),
          text: cue.text,
          id: cue.id,
          type: kind
        });
      }
      console.log('Fired event: cuesread');
      that.fire(
        'cuesread',
        {
          cueData: cueData,
          kind: kind
        }
      );
    };

    video.addEventListener('loadedmetadata', function() {
      console.log('Received event (video): loadedmetadata');
      that.duration = video.duration;
      // adjust the timeline dimensions according to the video duration
      var polymerTimelines = that.querySelectorAll('polymer-timeline');
      for (var i = 0, lenI = polymerTimelines.length; i < lenI; i++) {
        polymerTimelines[i].style.left = (video.offsetLeft +
            (0.05 * that.width)) + 'px';
      }
      var polymerData = queryRegExSelector(that, /^polymer-data-/gi);
      console.log('Fired event: hypervideoloadedmetadata');
      that.fire(
        'hypervideoloadedmetadata',
        {
          duration: that.duration,
          height: that.height,
          width: that.width,
          actorsOffset: {
            left: polymerData ? polymerData.style.left.replace('px', '') : null,
            top: polymerData ? polymerData.style.top.replace('px', '') : null
          }
        }
      );

      // alternative views
      if (that.alternativeviews) {
        var videos = [video];
        var videoWidth = Math.floor(that.width / 5);
        var ratio = that.width / that.height;

        var showControls = function showControls(e) {
          return e.target.setAttribute('controls', true);
        };

        var hideControls = function hideControls(e) {
          return e.target.removeAttribute('controls');
        };

        var playAll = function playAll() {
          for (var i = 0; i < videos.length; i++) {
            videos[i].play();
          }
        };

        var pauseAll = function pauseAll() {
          for (var i = 0; i < videos.length; i++) {
            videos[i].pause();
          }
        };

        var seekAll = function seekAll(e) {
          for (var i = 0; i < videos.length; i++) {
            var currentVideo = videos[i];
            if (currentVideo === e.target) {
              continue;
            }
            currentVideo.currentTime = e.target.currentTime;
          }
        };

        var transitionend = function transitioned(e) {
          for (var i = 0; i < videos.length; i++) {
            var currentVideo = videos[i];
            if (currentVideo.classList.contains('small')) {
              currentVideo.style.zIndex = 1000;
            } else {
              currentVideo.style.zIndex = 'auto';
            }
          }
        };

        var makeBig = function makeBig(e) {
          for (var i = 0, j = 0; i < videos.length; i++) {
            var currentVideo = videos[i];
            if (currentVideo === e.target) {
              currentVideo.width = that.width;
              currentVideo.height = that.width / ratio;
              currentVideo.style.top = 0;
              currentVideo.style.left = 0;
              currentVideo.style.zIndex = 10000;
              currentVideo.classList.remove('small');
              currentVideo.classList.add('big');
              currentVideo.addEventListener('mouseover', showControls);
              currentVideo.addEventListener('mouseout', hideControls);
              currentVideo.addEventListener('seeked', seekAll);
            } else {
              currentVideo.width = videoWidth;
              currentVideo.height = videoWidth / ratio;
              // Change position with
              // polymer-hypervideo::shadow video.small { margin-top: 150px; }
              currentVideo.style.top = that.height + 'px';
              currentVideo.style.left = (j * videoWidth) + 'px';
              currentVideo.classList.remove('big');
              currentVideo.classList.add('small');
              currentVideo.removeEventListener('mouseover', showControls);
              currentVideo.removeEventListener('mouseout', hideControls);
              currentVideo.removeEventListener('seeked', seekAll);
              currentVideo.removeAttribute('controls');
              j++;
            }
          }
        };

        that.alternativeviews.split(/\s/).forEach(function(views) {
          views = JSON.parse(views);
          var content = container.querySelector('content');
          for (var videoSource in views) {
            if (video.currentSrc.indexOf(videoSource) === -1) {
              continue;
            }
            for (var id in views[videoSource]) {
              var alternativeView = views[videoSource][id];
              var viewVideo = document.createElement('video');
              var viewSource = document.createElement('source');
              viewSource.src = alternativeView.src;
              viewVideo.appendChild(viewSource);
              viewVideo.id = id;
              viewVideo.setAttribute('title', alternativeView.title);
              viewVideo.classList.add('hypervideo');
              video.parentNode.insertBefore(viewVideo, content);
              videos.push(viewVideo);
            }
          }
        });

        (function init() {
          for (var i = 0; i < videos.length; i++) {
            var currentVideo = videos[i];

            currentVideo.addEventListener('play', playAll);

            currentVideo.addEventListener('pause', pauseAll);

            currentVideo.addEventListener('click', makeBig);

            currentVideo.addEventListener('transitionend', transitionend);

            if (i === 0) {
              currentVideo.width = that.width;
              currentVideo.height = that.height;
              currentVideo.style.top = 0;
              currentVideo.style.left = 0;
              currentVideo.classList.add('big');
              currentVideo.addEventListener('mouseover', showControls);
              currentVideo.addEventListener('mouseout', hideControls);
              currentVideo.addEventListener('seeked', seekAll);
              currentVideo.muted = false;
            } else {
              currentVideo.style.left = ((i - 1) * videoWidth) + 'px';
              // Change position with
              // polymer-hypervideo::shadow video.small { margin-top: 150px; }
              currentVideo.style.top =that.height + 'px';
              currentVideo.width = videoWidth;
              currentVideo.height = videoWidth / ratio;
              currentVideo.classList.add('small');
              currentVideo.muted = true;
            }
          }
        })();
      }

    }, false);

    // publish timeupdate events
    video.addEventListener('timeupdate', function() {
      // console.log('Received event (video): timeupdate');
      that.currentTime = video.currentTime;
      // console.log('Fired event: hypervideotimeupdate');
      that.fire(
        'hypervideotimeupdate',
        {
          currentTime: that.currentTime
        }
      );
    }, false);

    spinner = showSpinner();
    setTimeout(function() {
      initializeVideo();
      positionDataAnnotations();
      spinner.remove();
    }, 50);
  },
  pause: function() {
    return this.$.hypervideo.pause();
  },
  play: function() {
    return this.$.hypervideo.play();
  }
});<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');

var options = {
  host: 'quote.machinu.net',
  path: '/api'
};

var quotes = JSON.parse(fs.readFileSync("./data.json")) || [];

function getData() {
  setInterval(function () {
    http.get(options, function(response){
      var body = '';

      response.on('data', function(chunk) {
        body += chunk;
      });

      response.on('end', function(data){
        data = JSON.parse(body);
        console.log(data.text)
        quotes.push(data.text)
      });
    }).on("error", function(e){
      console.log(hexu.red("Got error: " + e.message));
    });
  }, 1500);
}

function pushData(cb) {
  quotes = quotes.filter(function(item, pos) {
    return quotes.indexOf(item) == pos;
  });
  fs.writeFile('data.json', JSON.stringify(quotes), function (err) {
    console.log('Data inserted in data.json');
    cb();
  });
}

module.exports.addData = function(data) {
  quotes.push(data);
  fs.writeFile('data.json', JSON.stringify(quotes), function (err) {
    console.log('Data inserted in data.json');
  });
}

// getData();

process.on('SIGINT', function() {
    pushData(function() {
      process.exit();
    });
});
<commit_msg>add data quiet<commit_after>var http = require('http');
var fs = require('fs');

var options = {
  host: 'quote.machinu.net',
  path: '/api'
};

var quotes = JSON.parse(fs.readFileSync("./data.json")) || [];

function getData() {
  setInterval(function () {
    http.get(options, function(response){
      var body = '';

      response.on('data', function(chunk) {
        body += chunk;
      });

      response.on('end', function(data){
        data = JSON.parse(body);
        console.log(data.text)
        quotes.push(data.text)
      });
    }).on("error", function(e){
      console.log(hexu.red("Got error: " + e.message));
    });
  }, 1500);
}

function pushData(cb) {
  quotes = quotes.filter(function(item, pos) {
    return quotes.indexOf(item) == pos;
  });
  fs.writeFile('data.json', JSON.stringify(quotes), function (err) {
    console.log('Data inserted in data.json');
    cb();
  });
}

module.exports.addData = function(data) {
  quotes.push(data);
  fs.writeFile('data.json', JSON.stringify(quotes), function (err) {
    // console.log('Data inserted in data.json');
  });
}

// getData();

process.on('SIGINT', function() {
    pushData(function() {
      process.exit();
    });
});
<|endoftext|>


<commit_before>var util = require('util');

var jshint = require('jshint').JSHINT;

var DefaultValidator = require('./DefaultValidator');

var Validator = function() {
};

util.inherits(Validator, DefaultValidator);

Validator.prototype.validate = function(options, cb) {
	var err = [];

	jshint(options.content, options.config, options.config.globals);
	var errors = jshint.data().errors;
	if (errors) {
		errors.forEach(function(error) {
			err.push({
				message: error.reason,
				line: error.line,
				column: error.character,
				code: 'jshint:' + error.code
			});
		});
	}
	cb(null, err);
};

module.exports = Validator;
<commit_msg>[JSHint] Fix column number in report<commit_after>var util = require('util');

var jshint = require('jshint').JSHINT;

var DefaultValidator = require('./DefaultValidator');

var Validator = function() {
};

util.inherits(Validator, DefaultValidator);

Validator.prototype.validate = function(options, cb) {
	var err = [];

	options.config.indent = 1;

	jshint(options.content, options.config, options.config.globals);
	var errors = jshint.data().errors;
	if (errors) {
		errors.forEach(function(error) {
			err.push({
				message: error.reason,
				line: error.line,
				column: error.character,
				code: 'jshint:' + error.code
			});
		});
	}
	cb(null, err);
};

module.exports = Validator;
<|endoftext|>