<commit_before>//todo:
// remove unnecessary constants

exports.COMMON = {
	"BID_PRECISION": 4,
	"CONFIG": "config",
	"DIV_ID": "divID",
	"PARAMS": "params",
	"SIZES": "sizes",
	"HEIGHT": "height",
	"WIDTH": "width",
	"SLOTS": "slots",
	"KEY_GENERATION_PATTERN_VALUE": "kgpv",
	"KEY_VALUE_PAIRS": "kvp",
	"IMPRESSION_ID": "iid"
};

exports.CONFIG = {
	"GLOBAL": "global",
	"ADAPTERS": "adapters",
	"COMMON": "pwt",
	"TIMEOUT": "t",
	"KEY_GENERATION_PATTERN": "kgp",
	"KEY_LOOKUP_MAP": "klm",
	"SERVER_SIDE_KEY": "sk",
	"PUBLISHER_ID": "pubid",
	"PROFILE_ID": "pid",
	"PROFILE_VERSION_ID": "pdvid",
	"LOGGER_URL": "dataURL",
	"TRACKER_URL": "winURL",
	"REV_SHARE": "rev_share",
	"THROTTLE": "throttle",
	"BID_PASS_THROUGH": "pt",
	"GLOBAL_KEY_VALUE": "gkv"
};

exports.MACROS = {
	"WIDTH": "_W_",
	"HEIGHT": "_H_",
	"AD_UNIT_ID": "_AU_",
	"AD_UNIT_INDEX": "_AUI_",
	"INTEGER": "_I_",
	"DIV": "_DIV_"
};

exports.SLOT_STATUS = {
	"CREATED": 0,
	"PARTNERS_CALLED": 1,
	"TARGETING_ADDED": 2,
	"DISPLAYED": 3
};

exports.WRAPPER_TARGETING_KEYS = {
	"BID_ID": "pwtsid",
	"BID_STATUS": "pwtbst",
	"BID_ECPM": "pwtecp",
	"BID_DEAL_ID": "pwtdid",
	"BID_ADAPTER_ID": "pwtpid",
	"PUBLISHER_ID": "pwtpubid",
	"PROFILE_ID": "pwtprofid",
	"PROFILE_VERSION_ID": "pwtverid"
};

//todo: mention all params here and use accordigly
exports.LOGGER_PIXEL_PARAMS = {
	"TIMESTAMP": "tst",
	"PAGE_URL": "purl",
	"TIMEOUT": "to"
};

exports.MESSAGES = {
	"M1": ": In fetchbids.",
	"M2": ": Throttled.",
	"M3": ": adapter must implement the fetchBids() function.",
	"M4": "BidManager: entry ",
	"M5": ": Callback.",
	"M6": "bidAlreadExists : ",
	"M7": ": Exiting from fetchBids.",
	"M8": ". Config not found, ignored.",
	"M9": ". Config ignored.",
	"M10": "Bid is rejected as ecpm is NULL.",
	"M11": "Bid is rejected as ecpm is NaN: ",
	"M12": "Existing bid ecpm: ",
	"M13": ", is lower than new bid ecpm ",
	"M14": ", so we are replacing bid.",
	"M15": ", is greater than new bid ecpm ",
	"M16": ", so we are not replacing bid.",
	"M17": "Post timeout bid, ignored.",
	"M18": "Bid is selected.",
	"M19": ": Found winning adapterID: ",
	"M20": "Bid is rejected as ecpm is empty string.",
	"M21": ": error in respose handler.",
	"M22": "Bid is rejected as ecpm is <= 0.",
	"M23": "Existing bid is default-bid with zero ecpm, thus replacing it with the new bid from partner."
};<commit_msg>added deal-KV-separator<commit_after>//todo:
// remove unnecessary constants

exports.COMMON = {
	"BID_PRECISION": 4,
	"DEAL_KEY_VALUE_SEPARATOR": "_-_",
	"CONFIG": "config",
	"DIV_ID": "divID",
	"PARAMS": "params",
	"SIZES": "sizes",
	"HEIGHT": "height",
	"WIDTH": "width",
	"SLOTS": "slots",
	"KEY_GENERATION_PATTERN_VALUE": "kgpv",
	"KEY_VALUE_PAIRS": "kvp",
	"IMPRESSION_ID": "iid"
};

exports.CONFIG = {
	"GLOBAL": "global",
	"ADAPTERS": "adapters",
	"COMMON": "pwt",
	"TIMEOUT": "t",
	"KEY_GENERATION_PATTERN": "kgp",
	"KEY_LOOKUP_MAP": "klm",
	"SERVER_SIDE_KEY": "sk",
	"PUBLISHER_ID": "pubid",
	"PROFILE_ID": "pid",
	"PROFILE_VERSION_ID": "pdvid",
	"LOGGER_URL": "dataURL",
	"TRACKER_URL": "winURL",
	"REV_SHARE": "rev_share",
	"THROTTLE": "throttle",
	"BID_PASS_THROUGH": "pt",
	"GLOBAL_KEY_VALUE": "gkv"
};

exports.MACROS = {
	"WIDTH": "_W_",
	"HEIGHT": "_H_",
	"AD_UNIT_ID": "_AU_",
	"AD_UNIT_INDEX": "_AUI_",
	"INTEGER": "_I_",
	"DIV": "_DIV_"
};

exports.SLOT_STATUS = {
	"CREATED": 0,
	"PARTNERS_CALLED": 1,
	"TARGETING_ADDED": 2,
	"DISPLAYED": 3
};

exports.WRAPPER_TARGETING_KEYS = {
	"BID_ID": "pwtsid",
	"BID_STATUS": "pwtbst",
	"BID_ECPM": "pwtecp",
	"BID_DEAL_ID": "pwtdid",
	"BID_ADAPTER_ID": "pwtpid",
	"PUBLISHER_ID": "pwtpubid",
	"PROFILE_ID": "pwtprofid",
	"PROFILE_VERSION_ID": "pwtverid"
};

//todo: mention all params here and use accordigly
exports.LOGGER_PIXEL_PARAMS = {
	"TIMESTAMP": "tst",
	"PAGE_URL": "purl",
	"TIMEOUT": "to"
};

exports.MESSAGES = {
	"M1": ": In fetchbids.",
	"M2": ": Throttled.",
	"M3": ": adapter must implement the fetchBids() function.",
	"M4": "BidManager: entry ",
	"M5": ": Callback.",
	"M6": "bidAlreadExists : ",
	"M7": ": Exiting from fetchBids.",
	"M8": ". Config not found, ignored.",
	"M9": ". Config ignored.",
	"M10": "Bid is rejected as ecpm is NULL.",
	"M11": "Bid is rejected as ecpm is NaN: ",
	"M12": "Existing bid ecpm: ",
	"M13": ", is lower than new bid ecpm ",
	"M14": ", so we are replacing bid.",
	"M15": ", is greater than new bid ecpm ",
	"M16": ", so we are not replacing bid.",
	"M17": "Post timeout bid, ignored.",
	"M18": "Bid is selected.",
	"M19": ": Found winning adapterID: ",
	"M20": "Bid is rejected as ecpm is empty string.",
	"M21": ": error in respose handler.",
	"M22": "Bid is rejected as ecpm is <= 0.",
	"M23": "Existing bid is default-bid with zero ecpm, thus replacing it with the new bid from partner."
};<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

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

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";

// Hero Image
var heroReady = false;
var heroImage = new Image();
heroReady.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterReady.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  //x: 0,
  //y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Collision
  if (
    hero.x <= (monster.x + 32)
    && monster.x <= (hero.x + 32)
    && hero.y <= (monster.y + 32)
    && monmster.y <= (hero.y + 32)
  ) {
    ++monstesCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame ||
  w.webkitRequestAnimationFrame ||
  w.msRequestAnimationFrame ||
  w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

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

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";

// Hero Image
var heroReady = false;
var heroImage = new Image();
heroReady.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterReady.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  //x: 0,
  //y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Collision
  if (
    hero.x <= (monster.x + 32)
    && monster.x <= (hero.x + 32)
    && hero.y <= (monster.y + 32)
    && monmster.y <= (hero.y + 32)
  ) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame ||
  w.webkitRequestAnimationFrame ||
  w.msRequestAnimationFrame ||
  w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

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

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";

// Hero Image
var heroReady = false;
var heroImage = new Image();
heroReady.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Enemy Image
var enemyReady = false;
var enemyImage = new Image();
enemyReady.onload = function () {
  heroReady = true;
};
enemyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Collision
  if (
    hero.x <= (monster.x + 32)
    && monster.x <= (hero.x + 32)
    && hero.y <= (monster.y + 32)
    && monmster.y <= (hero.y + 32)
  ) {
    ++monstesCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillTest("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame ||
  w.webkitRequestAnimationFrame ||
  w.msRequestAnimationFrame ||
  w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

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

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";

// Hero Image
var heroReady = false;
var heroImage = new Image();
heroReady.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterReady.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Collision
  if (
    hero.x <= (monster.x + 32)
    && monster.x <= (hero.x + 32)
    && hero.y <= (monster.y + 32)
    && monmster.y <= (hero.y + 32)
  ) {
    ++monstesCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillTest("Monsters caught : " + monstersCaught, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame ||
  w.webkitRequestAnimationFrame ||
  w.msRequestAnimationFrame ||
  w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();
<|endoftext|>


<commit_before>(function(window, document, undefined) {

	// data specifically for the about page
	var aboutData = {
		header: "About Us",
		description: "Learn about the Stanford Sports Analytics Club",
		navbarTitle: "About"
	};

	// Handlebars template for the about page
	var aboutTemplate = [
		'
The Stanford Sports Analytics Club is a student organization dedicated to the quantitative analytics of sports. We seek to both foster a community of Stanford students interested in sports analytics, and to serve as a platform for the sports research performed by the members of this community. Since our inception in the 2014-2015 school year, the club has provided an opportunity for members to learn the skills of sports analytics, perform their own research, engage in meaningful conversations about sports analytics, participate in sports analytics competitions, and interact with leaders in the sports analytics community and sports professionals.
',
		'
If you are interested in participating in the club, please consider joining our mailing list below. A sampling of our work can be found on our blog. Our social media presence includes a Twitter account and a Facebook account. These accounts will both be updated with information regularly during the school year.
'
	].join('\n');

	// populate page with the above data
	populatePage(aboutTemplate, aboutData);

})(this, this.document);
<commit_msg>Template about page<commit_after>(function(window, document, undefined) {

	// data specifically for the about page
	var aboutData = {
		header: "About Us",
		description: "Learn about the Stanford Sports Analytics Club",
		navbarTitle: "About",
		paragraphs: [
			{ text: 'The Stanford Sports Analytics Club is a student organization dedicated to the quantitative analytics of sports. We seek to both foster a community of Stanford students interested in sports analytics, and to serve as a platform for the sports research performed by the members of this community. Since our inception in the 2014-2015 school year, the club has provided an opportunity for members to learn the skills of sports analytics, perform their own research, engage in meaningful conversations about sports analytics, participate in sports analytics competitions, and interact with leaders in the sports analytics community and sports professionals.' },
			{ text: 'If you are interested in participating in the club, please consider joining our mailing list below. A sampling of our work can be found on our blog. Our social media presence includes a Twitter account and a Facebook account. These accounts will both be updated with information regularly during the school year.' }
		]
	};

	// Handlebars template for the about page
	var aboutTemplate = [
		'{{#each pageData.paragraphs}}',
		'
{{{text}}}
',
		'{{/each}}'
	].join('\n');

	// populate page with the above data
	populatePage(aboutTemplate, aboutData);

})(this, this.document);
<|endoftext|>


<commit_before>'use strict';
function solve() {
	const validator = (() => {
		const NAME_LENGTH = {
			MIN: 3,
			MAX: 25
		};

		return {
			validateInstanceOf(obj, type) {
				const result = obj instanceof type;
				return result;
			},
			validateName(name) {
				if (name === undefined) {
					throw new Error('name is undefined');
				}

				if (typeof name !== 'string') {
					throw new Error('name is not a string');
				}

				if (!(NAME_LENGTH.MIN <= name.length && name.length <= NAME_LENGTH.MAX)) {
					throw new Error('incorrect name length');
				}
			},
			validatePagingInput(dataLength, page, size) {
				if (isNaN(page) || isNaN(size)) {
					throw new Error();
				}

				if (dataLength < page * size) {
					throw new Error();
				}

				if (page < 0) {
					throw new Error();
				}

				if (size <= 0) {
					throw new Error();
				}
			}
		};
	})();

	function* IdProvider() {
		let lastId = 0;
		while (true) {
			yield lastId += 1;
		}
	}

	const playerIdPrivider = IdProvider();
	class Player {
		constructor(name) {
			this.id = playerIdPrivider.next().value;
			this.name = name;

			this._playlists = [];
			return this;
		}

		get name() {
			return this._name;
		}

		set name(value) {
			validator.validateName(value);
			this._name = value;
		}

		addPlaylist(playlistToAdd) {
			const inputIsPlayList = validator.validateInstanceOf(playlistToAdd, PlayList);
			if (!inputIsPlayList) {
				throw new Error('Input must be of type PlayList');
			}

			this._playlists.push(playlistToAdd);
			return this;
		}

		getPlaylistById(id) {
			const matches = this._playlists.filter((item) => {
				const isMatch = item.id === id;
				return isMatch;
			});

			let matchingPlaylist = null;
			if (matches.length > 0) {
				matchingPlaylist = matches[0];
			}

			return matchingPlaylist;
		}

		removePlaylist(playlist) {
			let id = playlist.id || playlist;
			let isRemoved = false;
			this._playlists = this._playlists.filter((item) => {
				const isMatch = item.id === id;
				if (isMatch) {
					isRemoved = true;
				}

				return !isMatch;
			});

			if (!isRemoved) {
				throw new Error('Playlist with id not found');
			}

			return this;
		}

		listPlaylists(page, size) {
			page = Number(page);
			size = Number(size);
			validator.validatePagingInput(this._playables.length, page, size);
			let list = [];
			for (let i = 0; i < size; i += 1) {
				const nextIndex = (page * size) + i;
				if (this._playlists[nextIndex]) {
					list.push(this._playlists[nextIndex]);
				} else {
					break;
				}
			}

			return list;
		}

		contains(playable, playlist) {

		}

		search(pattern) {

		}
	}

	const playlistIdProvider = IdProvider();
	class PlayList {
		constructor(name) {
			this.id = playlistIdProvider.next().value;
			this.name = name;

			this._playables = [];
		}

		get name() {
			return this._name;
		}

		set name(value) {
			validator.validateName(value);
			this._name = value;
		}

		addPlayable(playable) {
			this._playables.push(playable);
			return this;
		}

		getPlayableById(id) {
			const matches = this._playables.filter((item) => {
				const isMatch = item.id === id;
				return isMatch;
			});

			let matchingPlayable = null;
			if (matches.length > 0) {
				matchingPlayable = matches[0];
			}

			return matchingPlayable;
		}

		removePlayable(playable) {
			let id = playable.id || playable;
			let isRemoved = false;
			this._playables = this._playables.filter((item) => {
				const isMatch = item.id === id;
				if (isMatch) {
					isRemoved = true;
				}

				return !isMatch;
			});

			if (!isRemoved) {
				throw new Error('Playlist with id not found');
			}

			return this;
		}

		listPlayables(page, size) {
			page = Number(page);
			size = Number(size);
			validator.validatePagingInput(this._playables.length, page, size);

			let list = [];
			for (let i = 0; i < size; i += 1) {
				const nextIndex = (page * size) + i;
				if (this._playables[nextIndex]) {
					list.push(this._playables[nextIndex]);
				} else {
					break;
				}
			}

			return list;
		}
	}

	const playableIdProivider = IdProvider();
	class Playable {
		constructor(title, author) {
			this.id = playableIdProivider.next().value();

			this.title = title;
			this.author = author;
		}

		play() {
			const message = `${this.id}. ${this.title} - ${this.author}`;
			return message;
		}
	}

	class Audio extends Playable {
		constructor(title, author, length) {
			super(title, author);

			this.length = length;
		}

		get length() {
			return this._length;
		}

		set length(value) {
			const length = Number(value);
			if (isNaN(length)) {
				throw new Error();
			}

			if (length <= 0) {
				throw new Error();
			}

			this._length = value;
		}

		play() {
			const message = `${super.play()} - ${this.length}`;
			return message;
		}
	}

	class Video extends Playable {
		constructor(title, author, imdbRating) {
			super(title, author);

			this.imdbRating = imdbRating;
		}

		get imdbRating() {
			return this._rating;
		}

		set imdbRating(value) {
			const rating = Number(value);
			if (isNaN(rating)) {
				throw new Error();
			}

			if (!(1 <= rating && rating <= 5)) {
				throw new Error();
			}

			this._rating = value;
		}
	}

	const module = {
		getPlayer: function (name) {
			return new Player(name);
		},
		getPlaylist: function (name) {
			return new PlayList(name);
		},
		getAudio: function (title, author, length) {
			return new Audio(title, author, length);
		},
		getVideo: function (title, author, imdbRating) {
			return new Video(title, author, imdbRating);
		}
	};

	return module;
}

module.exports = solve;<commit_msg>update<commit_after>'use strict';
function solve() {
	const validator = (() => {
		const NAME_LENGTH = {
			MIN: 3,
			MAX: 25
		};

		return {
			validateInstanceOf(obj, type) {
				const result = obj instanceof type;
				return result;
			},
			validateName(name) {
				if (name === undefined) {
					throw new Error('name is undefined');
				}

				if (typeof name !== 'string') {
					throw new Error('name is not a string');
				}

				if (!(NAME_LENGTH.MIN <= name.length && name.length <= NAME_LENGTH.MAX)) {
					throw new Error('incorrect name length');
				}
			},
			validatePagingInput(dataLength, page, size) {
				if (isNaN(page) || isNaN(size)) {
					throw new Error();
				}

				if (dataLength < page * size) {
					throw new Error();
				}

				if (page < 0) {
					throw new Error();
				}

				if (size <= 0) {
					throw new Error();
				}
			}
		};
	})();

	const utils = (() => {
		return {
			extractPage(data, page, size) {
				let list = [];
				for (let i = 0; i < size; i += 1) {
					const nextIndex = (page * size) + i;
					if (data[nextIndex]) {
						list.push(data[nextIndex]);
					} else {
						break;
					}
				}

				return list;
			}
		}
	})();

	function* IdProvider() {
		let lastId = 0;
		while (true) {
			yield lastId += 1;
		}
	}

	const playerIdPrivider = IdProvider();
	class Player {
		constructor(name) {
			this.id = playerIdPrivider.next().value;
			this.name = name;

			this._playlists = [];
			return this;
		}

		get name() {
			return this._name;
		}

		set name(value) {
			validator.validateName(value);
			this._name = value;
		}

		addPlaylist(playlistToAdd) {
			const inputIsPlayList = validator.validateInstanceOf(playlistToAdd, PlayList);
			if (!inputIsPlayList) {
				throw new Error('Input must be of type PlayList');
			}

			this._playlists.push(playlistToAdd);
			return this;
		}

		getPlaylistById(id) {
			const matches = this._playlists.filter((item) => {
				const isMatch = item.id === id;
				return isMatch;
			});

			let matchingPlaylist = null;
			if (matches.length > 0) {
				matchingPlaylist = matches[0];
			}

			return matchingPlaylist;
		}

		removePlaylist(playlist) {
			let id = playlist.id || playlist;
			let isRemoved = false;
			this._playlists = this._playlists.filter((item) => {
				const isMatch = item.id === id;
				if (isMatch) {
					isRemoved = true;
				}

				return !isMatch;
			});

			if (!isRemoved) {
				throw new Error('Playlist with id not found');
			}

			return this;
		}

		listPlaylists(page, size) {
			page = Number(page);
			size = Number(size);
			validator.validatePagingInput(this._playlists.length, page, size);

			const list = utils.extractPage(this._playlists, page, size);
			return list;
		}

		contains(playable, playlist) {

		}

		search(pattern) {

		}
	}

	const playlistIdProvider = IdProvider();
	class PlayList {
		constructor(name) {
			this.id = playlistIdProvider.next().value;
			this.name = name;

			this._playables = [];
		}

		get name() {
			return this._name;
		}

		set name(value) {
			validator.validateName(value);
			this._name = value;
		}

		addPlayable(playable) {
			this._playables.push(playable);
			return this;
		}

		getPlayableById(id) {
			const matches = this._playables.filter((item) => {
				const isMatch = item.id === id;
				return isMatch;
			});

			let matchingPlayable = null;
			if (matches.length > 0) {
				matchingPlayable = matches[0];
			}

			return matchingPlayable;
		}

		removePlayable(playable) {
			let id = playable.id || playable;
			let isRemoved = false;
			this._playables = this._playables.filter((item) => {
				const isMatch = item.id === id;
				if (isMatch) {
					isRemoved = true;
				}

				return !isMatch;
			});

			if (!isRemoved) {
				throw new Error('Playlist with id not found');
			}

			return this;
		}

		listPlayables(page, size) {
			page = Number(page);
			size = Number(size);
			validator.validatePagingInput(this._playables.length, page, size);

			const list = utils.extractPage(this._playables, page, size);
			return list;
		}
	}

	const playableIdProivider = IdProvider();
	class Playable {
		constructor(title, author) {
			this.id = playableIdProivider.next().value();

			this.title = title;
			this.author = author;
		}

		play() {
			const message = `${this.id}. ${this.title} - ${this.author}`;
			return message;
		}
	}

	class Audio extends Playable {
		constructor(title, author, length) {
			super(title, author);

			this.length = length;
		}

		get length() {
			return this._length;
		}

		set length(value) {
			const length = Number(value);
			if (isNaN(length)) {
				throw new Error();
			}

			if (length <= 0) {
				throw new Error();
			}

			this._length = value;
		}

		play() {
			const message = `${super.play()} - ${this.length}`;
			return message;
		}
	}

	class Video extends Playable {
		constructor(title, author, imdbRating) {
			super(title, author);

			this.imdbRating = imdbRating;
		}

		get imdbRating() {
			return this._rating;
		}

		set imdbRating(value) {
			const rating = Number(value);
			if (isNaN(rating)) {
				throw new Error();
			}

			if (!(1 <= rating && rating <= 5)) {
				throw new Error();
			}

			this._rating = value;
		}
	}

	const module = {
		getPlayer: function (name) {
			return new Player(name);
		},
		getPlaylist: function (name) {
			return new PlayList(name);
		},
		getAudio: function (title, author, length) {
			return new Audio(title, author, length);
		},
		getVideo: function (title, author, imdbRating) {
			return new Video(title, author, imdbRating);
		}
	};

	return module;
}

module.exports = solve;<|endoftext|>


<commit_before>/*
	WebPlotDigitizer - http://arohatgi.info/WebPlotDigitizer

	Version 2.6

	Copyright 2010-2013 Ankit Rohatgi <ankitrohatgi@hotmail.com>

	This file is part of WebPlotDigitizer.

    WebPlotDigitizer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WebPlotDigitizer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WebPlotDigitizer.  If not, see <http://www.gnu.org/licenses/>.

*/

/**
 * @fileoverview X Step With Actual Units Extraction Algorithm
 * @version 2.6
 * @author Ankit Rohatgi ankitrohatgi@hotmail.com
 */

AEObject.getParamList = function () {
	if (plotType === 'XY') {
		return [["X_min","Units",axesAlignmentData[0].toString()],["ΔX Step","Units","0.1"],["X_max","Units",axesAlignmentData[1].toString()],["Y_min","Units",axesAlignmentData[2].toString()],["Y_max","Units",axesAlignmentData[3].toString()],["Line width","Px","30"]];
	} else {
		showPopup('xyAxesOnly');
		return [["X_min","Units", "0"],["ΔX Step","Units","0.1"],["X_max","Units", "0"],["Y_min","Units", "0"],["Y_max","Units", "0"],["Line width","Px","30"]];
	}

	return null;

}

AEObject.run = function () {

	// NOTE: This only works for XY Plot

	if(plotType === 'XY') {

		var xPointsPicked = 0;
		xyData = [];
		pointsPicked = 0;

		resetLayers();

		var dw = canvasWidth;
		var dh = canvasHeight;

		// Get values from UI:
		var param_xmin_el = document.getElementById("pv0");
		var param_delx_el = document.getElementById("pv1");
		var param_xmax_el = document.getElementById("pv2");
		var param_linewidth_el = document.getElementById("pv5");
		var param_ymin_el = document.getElementById("pv3");
		var param_ymax_el = document.getElementById("pv4");

		var param_xmin = parseFloat(param_xmin_el.value);
		var param_delx = parseFloat(param_delx_el.value);
		var param_xmax = parseFloat(param_xmax_el.value);
		var param_linewidth = parseFloat(param_linewidth_el.value);
		var param_ymin = parseFloat(param_ymin_el.value);
		var param_ymax = parseFloat(param_ymax_el.value);

		var blobx = [];
		var bloby = [];

		// Get corresponding pixels:
		for(var xi = param_xmin; xi <= param_xmax; xi += param_delx)
		{
			var xmin_pix, xmax_pix, ymin_pix, ymax_pix, dpix, r_unit_per_pix, step_pix = 1;

			dataToPixel(xi, param_ymin, 'XY');
			xmin_pix = dataToPixelxy[0];
			ymin_pix = dataToPixelxy[1];

			dataToPixel(xi, param_ymax, 'XY');
			xmax_pix = dataToPixelxy[0];
			ymax_pix = dataToPixelxy[1];

			dpix = Math.sqrt((ymax_pix-ymin_pix)*(ymax_pix-ymin_pix) + (xmax_pix-xmin_pix)*(xmax_pix-xmin_pix));

			r_unit_per_pix = (param_ymax-param_ymin)/dpix;

			var blobActive = false;
			var blobEntry = 0;
			var blobExit = 0;
			var blobExitLocked = false;

			for(var ii = 0; ii < dpix; ii++)
			{
				var yi = -ii*step_pix*r_unit_per_pix + param_ymax;
				dataToPixel(xi, yi, 'XY');

				xi_pix = dataToPixelxy[0];
				yi_pix = dataToPixelxy[1];

				if(xi_pix >= 0 && xi_pix < dw && yi_pix >=0 && yi_pix < dh)	{

					if(binaryData[parseInt(yi_pix, 10)][parseInt(xi_pix, 10)] === true)	{

						if(blobActive === false) {
							blobEntry = ii;
							blobExit = blobEntry;
							blobActive = true;
							blobExitLocked = false;
						}
					} else	{
						if(blobExitLocked === false) {
							blobExit == ii;
							blobExitLocked = true;
						}
					}

					if(blobActive === true)	{

						if((ii >= blobEntry + param_linewidth) || (ii === dpix - 1)) {
							blobActive = false;

							if(blobEntry > blobExit) {
								blobExit = ii;
							}

							var mean_ii = (blobEntry + blobExit)/2.0;
							var mean_yi = -mean_ii*step_pix*r_unit_per_pix + param_ymax;

							dataToPixel(xi, mean_yi, 'XY');
							xyData[pointsPicked] = new Array();
							xyData[pointsPicked][0] = parseFloat(dataToPixelxy[0]);
							xyData[pointsPicked][1] = parseFloat(dataToPixelxy[1]);
							pointsPicked = pointsPicked + 1;
						}
					}
				}

			}
		}
	} else {
		showPopup('xyAxesOnly');
	}

}
<commit_msg>minor fix to X Step with Actual Units algo.<commit_after>/*
	WebPlotDigitizer - http://arohatgi.info/WebPlotDigitizer

	Version 2.6

	Copyright 2010-2013 Ankit Rohatgi <ankitrohatgi@hotmail.com>

	This file is part of WebPlotDigitizer.

    WebPlotDigitizer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WebPlotDigitizer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WebPlotDigitizer.  If not, see <http://www.gnu.org/licenses/>.

*/

/**
 * @fileoverview X Step With Actual Units Extraction Algorithm
 * @version 2.6
 * @author Ankit Rohatgi ankitrohatgi@hotmail.com
 */

AEObject.getParamList = function () {
	if (plotType === 'XY') {
		return [["X_min","Units",axesAlignmentData[0].toString()],["ΔX Step","Units","0.1"],["X_max","Units",axesAlignmentData[1].toString()],["Y_min","Units",axesAlignmentData[2].toString()],["Y_max","Units",axesAlignmentData[3].toString()],["Line width","Px","30"]];
	} else {
		showPopup('xyAxesOnly');
		return [["X_min","Units", "0"],["ΔX Step","Units","0.1"],["X_max","Units", "0"],["Y_min","Units", "0"],["Y_max","Units", "0"],["Line width","Px","30"]];
	}

	return null;

}

AEObject.run = function () {

	// NOTE: This only works for XY Plot

	if(plotType === 'XY') {

		var xPointsPicked = 0;
		xyData = [];
		pointsPicked = 0;

		resetLayers();

		var dw = canvasWidth;
		var dh = canvasHeight;

		// Get values from UI:
		var param_xmin_el = document.getElementById("pv0");
		var param_delx_el = document.getElementById("pv1");
		var param_xmax_el = document.getElementById("pv2");
		var param_linewidth_el = document.getElementById("pv5");
		var param_ymin_el = document.getElementById("pv3");
		var param_ymax_el = document.getElementById("pv4");

		var param_xmin = parseFloat(param_xmin_el.value);
		var param_delx = parseFloat(param_delx_el.value);
		var param_xmax = parseFloat(param_xmax_el.value);
		var param_linewidth = parseFloat(param_linewidth_el.value);
		var param_ymin = parseFloat(param_ymin_el.value);
		var param_ymax = parseFloat(param_ymax_el.value);

		var blobx = [];
		var bloby = [];

		// Get corresponding pixels:
		for(var xi = param_xmin; xi <= param_xmax; xi += param_delx)
		{
			var xmin_pix, xmax_pix, ymin_pix, ymax_pix, dpix, r_unit_per_pix, step_pix = 1;

			dataToPixel(xi, param_ymin, 'XY');
			xmin_pix = dataToPixelxy[0];
			ymin_pix = dataToPixelxy[1];

			dataToPixel(xi, param_ymax, 'XY');
			xmax_pix = dataToPixelxy[0];
			ymax_pix = dataToPixelxy[1];

			dpix = Math.sqrt((ymax_pix-ymin_pix)*(ymax_pix-ymin_pix) + (xmax_pix-xmin_pix)*(xmax_pix-xmin_pix));

			r_unit_per_pix = (param_ymax-param_ymin)/dpix;

			var blobActive = false;
			var blobEntry = 0;
			var blobExit = 0;
			var blobExitLocked = false;

			for(var ii = 0; ii <= dpix; ii++)
			{
				var yi = -ii*step_pix*r_unit_per_pix + param_ymax;
				dataToPixel(xi, yi, 'XY');

				xi_pix = dataToPixelxy[0];
				yi_pix = dataToPixelxy[1];

				if(xi_pix >= 0 && xi_pix < dw && yi_pix >=0 && yi_pix < dh)	{

					if(binaryData[parseInt(yi_pix, 10)][parseInt(xi_pix, 10)] === true)	{

						if(blobActive === false) {
							blobEntry = ii;
							blobExit = blobEntry;
							blobActive = true;
							blobExitLocked = false;
						}
					} else	{
						if(blobExitLocked === false) {
							blobExit == ii;
							blobExitLocked = true;
						}
					}

					if(blobActive === true)	{

						if((ii >= blobEntry + param_linewidth) || ((ii <= dpix) && (ii > dpix)) {
							blobActive = false;

							if(blobEntry > blobExit) {
								blobExit = ii;
							}

							var mean_ii = (blobEntry + blobExit)/2.0;
							var mean_yi = -mean_ii*step_pix*r_unit_per_pix + param_ymax;

							dataToPixel(xi, mean_yi, 'XY');
							xyData[pointsPicked] = new Array();
							xyData[pointsPicked][0] = parseFloat(dataToPixelxy[0]);
							xyData[pointsPicked][1] = parseFloat(dataToPixelxy[1]);
							pointsPicked = pointsPicked + 1;
						}
					}
				}

			}
		}
	} else {
		showPopup('xyAxesOnly');
	}

}
<|endoftext|>


<commit_before>define(['views/base_view'], function (baseView) {

    var run = function () {

        module("BaseView");

        test("Test BaseView rendering of compiled template", function () {
            var test_model = new Backbone.Model({name: "Test"}),
                TestView = baseView.extend({
                    template_selector: "#milestone-table-heading",
                    el: "#qunit-fixture"
                }), tv;

            tv = new TestView({model: test_model});
            equal(tv.template_selector, "#milestone-table-heading", "Correct selector");

            tv.render();
            equal(tv.el.firstChild.innerHTML, "Test",
                  "Rendered element contains model's data");
        });

        test("Test getTemplateData", function () {
            var test_model = new Backbone.Model({name: "Test"}),
                TestView = baseView.extend({
                    template_selector: "#milestone-table-heading",
                    el: "#qunit-fixture",
                    getTemplateData: function (data) {
                        data.name = "Changed test";
                        return data;
                    }
                }), tv;

            tv = new TestView({model: test_model});
            tv.render();
            equal(tv.el.firstChild.innerHTML, "Changed test",
                  "Rendered element contains getTemplateData changes");
        });

    };

    return run;

});
<commit_msg>Update base view tests to use Jasmine<commit_after>define(['views/base_view'], function (baseView) {

	jasmine.getFixtures().fixturesPath = 'tests/html_fixtures';

    describe("BaseView", function () {
    	beforeEach(function() {
    		loadFixtures('components/base_view.html');
    	});

        it("Test BaseView rendering of compiled template", function () {
            var test_model = new Backbone.Model({name: "Test"}),
                TestView = baseView.extend({
                    template_selector: "#milestone-table-heading",
                    el: "#qunit-fixture"
                }), tv;

            tv = new TestView({model: test_model});
            since("Correct selector");
            expect(tv.template_selector).toEqual("#milestone-table-heading");

            tv.render();
            since("Rendered element contains model's data");
            expect(tv.el.firstChild.innerHTML).toEqual("Test");
        });

        it("Test getTemplateData", function () {
            var test_model = new Backbone.Model({name: "Test"}),
                TestView = baseView.extend({
                    template_selector: "#milestone-table-heading",
                    el: "#qunit-fixture",
                    getTemplateData: function (data) {
                        data.name = "Changed test";
                        return data;
                    }
                }), tv;

            tv = new TestView({model: test_model});
            tv.render();
            since("Rendered element contains getTemplateData changes");
            expect(tv.el.firstChild.innerHTML).toEqual("Changed test");
        });
    });
});
<|endoftext|>


<commit_before>var canvas = null;
var fps = null;
var connection = false;

var images = {};
var players = {};

var engine = new Game();
//image states
var backgroundReady = false;
var sharkReady = false;
var minnowReady = false;
var barrierReady = false;

var username = document.getElementById("username").innerHTML;
var controls = document.getElementById("controls").innerHTML;

var types = ["shark", "minnow"];
var fishType = types[Math.floor(Math.random()*types.length)];

var client = null;
var player = null;
//main player initiated in the $(document).ready();

//backgroundImage
images.background = new Image();
images.background.onload = function() {
  backgroundReady = true;
};
images.background.src = "/images/background-large.png";

//shark image
images.shark = new Image();
images.shark.onload = function() {
  sharkReady = true;
};
images.shark.src = "/images/sharksprite.png";

// minnow image
images.minnow = new Image();
images.minnow.onload = function() {
  minnowReady = true;
};
images.minnow.src = "/images/fishsprite.png";

//barrier image
images.barrier = new Image();
images.barrier.onload = function() {
  barrierReady = true;
};
images.barrier.src = "/images/barriers.png";

//arrow image
images.arrow = new Image();
images.arrow.onload = function() {
  arrowReady = true;
};
images.arrow.src = "/images/arrow.png";

var keysDown = {};

if(controls === "keyboard"){
    addEventListener("keydown", function(e) {
        keysDown[e.keyCode] = true;
    }, false);

    addEventListener("keyup", function(e) {
        delete keysDown[e.keyCode];
    }, false);
}

if(controls === "joystick"){
    document.getElementById("up").addEventListener("touchstart", function() {
        keysDown[38] = true;
    }, false);

    document.getElementById("up").addEventListener("touchend", function() {
        delete keysDown[38];
    }, false);

    document.getElementById("left").addEventListener("touchstart", function() {
        keysDown[37] = true;
    }, false);

    document.getElementById("left").addEventListener("touchend", function() {
        delete keysDown[37];
    }, false);

    document.getElementById("right").addEventListener("touchstart", function() {
        keysDown[39] = true;
    }, false);

    document.getElementById("right").addEventListener("touchend", function() {
        delete keysDown[39];
    }, false);

    document.getElementById("down").addEventListener("touchstart", function() {
        keysDown[40] = true;
    }, false);

    document.getElementById("down").addEventListener("touchend", function() {
        delete keysDown[40];
    }, false);
}

function handleMotionEvent(event) {
  var x = event.accelerationIncludingGravity.x;
  var y = event.accelerationIncludingGravity.y;
  var z = event.accelerationIncludingGravity.z;

  if(player.isAlive){
    player.pos.x -= x;
    player.pos.y += y;
    player.pos.z += z;
  }
}

if(controls === "tilt"){
    addEventListener("devicemotion", handleMotionEvent, true);
}

fps = null;
canvas = null;
ctx = null;

var sizeX = 50;
var sizeY = 50;
var updateFlag = false;

function GameTick(elapsed) {
  if (updateFlag) {
    client.emit('client update', player);
  }
  updateFlag = !updateFlag;
  fps.update(elapsed);
  if (38 in keysDown && player.isAlive) { // Player holding up
    player.pos.y -= player.speed * elapsed;
  }
  if (40 in keysDown && player.isAlive) { // Player holding down
    player.pos.y += player.speed * elapsed;
  }
  if (37 in keysDown && player.isAlive) { // Player holding left
    player.pos.x -= player.speed * elapsed;
  }
  if (39 in keysDown && player.isAlive) { // Player holding right
    player.pos.x += player.speed * elapsed;
  }
  engine.Collisions(player);
  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw background
  ctx.drawImage(images.background, 0, 0, 750, 450);

  // Draw safe zones
  if (engine.gameRound % 2 === 0) {
    ctx.fillStyle = ctx.fillStyle = "rgba(49, 129, 49, 0.4)";
    ctx.fillRect(engine.canvas.width-engine.safezoneWidth,0,engine.canvas.width,engine.canvas.height);
  } else {
    ctx.fillStyle = ctx.fillStyle = "rgba(49, 129, 49, 0.4)";
    ctx.fillRect(0,0,engine.safezoneWidth,engine.canvas.height);
  }

  // Draw player
  ctx.fillStyle = 'white';
  ctx.font = "12px Helvetica";
  if(player.fishType === "shark"){
    ctx.drawImage(images.shark, player.pos.x, player.pos.y, 50, 28);
    ctx.fillText(player.username, player.pos.x + 5 - (player.username).length, player.pos.y + 33);
  } else {
    ctx.drawImage(images.minnow, player.pos.x, player.pos.y, 25, 14);
    ctx.fillText(player.username, player.pos.x + 5 - (player.username).length, player.pos.y + 33);
  }
  ctx.drawImage(images.arrow, player.pos.x + 15, player.pos.y - 10, 14, 7);

  // Draw players
  for (var entity in players) {
    if (players.hasOwnProperty(entity)) {
      entity = players[entity];
      var x_coord = entity.pos.x;
      var y_coord = entity.pos.y;
      ctx.fillStyle = 'white';
      ctx.font = "12px Helvetica";
      if(entity.fishType === "shark"){
        ctx.drawImage(images.shark, x_coord, y_coord, 50, 28);
        ctx.fillText(entity.username, x_coord + 5 - (entity.username).length, y_coord + 33);
      } else {
        ctx.drawImage(images.minnow, x_coord, y_coord, 25, 14);
        ctx.fillText(entity.username, x_coord + 5 - (entity.username).length, y_coord + 33);
      }
      if(entity.id != player.id){
        if(collisionDetected(entity) && (entity.fishType != player.fishType)){
          if(player.fishType === "minnow"){
            ctx.fillText("(✖╭╮✖)", player.pos.x, player.pos.y + 33);
            player.isAlive = false;
          }
          if(entity.fishType === "minnow"){
            ctx.fillText("(✖╭╮✖)", x_coord + 5, player.pos.y + 33);
            entity.isAlive = false;
          }
        }
      }
    }
  }

  // Draw HUD

}

var collisionDetected = function(otherObject) {
  return (otherObject.pos.x <= (player.pos.x + 32) &&
    player.pos.x <= (otherObject.pos.x + 32) &&
    otherObject.pos.y <= (player.pos.y + 32) &&
    player.pos.y <= (otherObject.pos.y + 32))
}

$(document).ready(function() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  client = io();
  var firstload1 = true;
  var firstload2 = true;
  client.on('onconnected', function(updatedPositions) {
    if(firstload1) {
      console.log("connected");
      // console.log(updatedPositions);
      // players = updatedPositions;
      fps = new FPSMeter("fpsmeter", document.getElementById("fpscontainer"));
      firstload1 = false;
    }
  })
  client.on('user-id', function(userId) {
    if(firstload2) {
      console.log("user-id")
      var initialConfig = engine.Spawn();
      console.log(initialConfig);
      player = new Player(userId, initialConfig.pos, initialConfig.fishType, username);
      engine.Counters(player);
      GameLoopManager.run(GameTick);
      client.emit('client update', player);
      client.emit('join', player);
      firstload2 = false;
    }
  })
  var deleted = [];
  client.on('server update', function(updates) {
    for (var entity in updates) {
      if (updates.hasOwnProperty(entity)) {
        entity = updates[entity];
        if (entity.id !== player.id) {
          players[entity.id] = entity;
        }
        for (var i = 0; i < deleted.length; i++) {
          if (deleted[i] === entity.id) {
            delete players[playerID];
            console.log("deleting ID", playerID);
            console.log("deleted", players[playerID]);
          }
        }
      }
    }
  })
  client.on('remove player', function(playerID) {
    deleted.push(playerID);
  })
  client.on('status update', function(boardState) {
    engine.minnowCount = boardState.minnowCount;
    engine.sharkCount = boardState.sharkCount;
    engine.timer = boardState.timer;
    engine.status = boardState.status;
    updateStatus();
    if (engine.timer === 0 && engine.waiting) {
      engine.waiting = false;
      engine.gameRound++;
      console.log("GAME START!");
    }
  })
})

function updateStatus() {
  if(engine.status === null) {
    $(".status span").html("No connection to the reef :(")
  } else {
    $(".status span").html(engine.status);
  }
}
<commit_msg>[HL] Minor typo fix on y coord.<commit_after>var canvas = null;
var fps = null;
var connection = false;

var images = {};
var players = {};

var engine = new Game();
//image states
var backgroundReady = false;
var sharkReady = false;
var minnowReady = false;
var barrierReady = false;

var username = document.getElementById("username").innerHTML;
var controls = document.getElementById("controls").innerHTML;

var types = ["shark", "minnow"];
var fishType = types[Math.floor(Math.random()*types.length)];

var client = null;
var player = null;
//main player initiated in the $(document).ready();

//backgroundImage
images.background = new Image();
images.background.onload = function() {
  backgroundReady = true;
};
images.background.src = "/images/background-large.png";

//shark image
images.shark = new Image();
images.shark.onload = function() {
  sharkReady = true;
};
images.shark.src = "/images/sharksprite.png";

// minnow image
images.minnow = new Image();
images.minnow.onload = function() {
  minnowReady = true;
};
images.minnow.src = "/images/fishsprite.png";

//barrier image
images.barrier = new Image();
images.barrier.onload = function() {
  barrierReady = true;
};
images.barrier.src = "/images/barriers.png";

//arrow image
images.arrow = new Image();
images.arrow.onload = function() {
  arrowReady = true;
};
images.arrow.src = "/images/arrow.png";

var keysDown = {};

if(controls === "keyboard"){
    addEventListener("keydown", function(e) {
        keysDown[e.keyCode] = true;
    }, false);

    addEventListener("keyup", function(e) {
        delete keysDown[e.keyCode];
    }, false);
}

if(controls === "joystick"){
    document.getElementById("up").addEventListener("touchstart", function() {
        keysDown[38] = true;
    }, false);

    document.getElementById("up").addEventListener("touchend", function() {
        delete keysDown[38];
    }, false);

    document.getElementById("left").addEventListener("touchstart", function() {
        keysDown[37] = true;
    }, false);

    document.getElementById("left").addEventListener("touchend", function() {
        delete keysDown[37];
    }, false);

    document.getElementById("right").addEventListener("touchstart", function() {
        keysDown[39] = true;
    }, false);

    document.getElementById("right").addEventListener("touchend", function() {
        delete keysDown[39];
    }, false);

    document.getElementById("down").addEventListener("touchstart", function() {
        keysDown[40] = true;
    }, false);

    document.getElementById("down").addEventListener("touchend", function() {
        delete keysDown[40];
    }, false);
}

function handleMotionEvent(event) {
  var x = event.accelerationIncludingGravity.x;
  var y = event.accelerationIncludingGravity.y;
  var z = event.accelerationIncludingGravity.z;

  if(player.isAlive){
    player.pos.x -= x;
    player.pos.y += y;
    player.pos.z += z;
  }
}

if(controls === "tilt"){
    addEventListener("devicemotion", handleMotionEvent, true);
}

fps = null;
canvas = null;
ctx = null;

var sizeX = 50;
var sizeY = 50;
var updateFlag = false;

function GameTick(elapsed) {
  if (updateFlag) {
    client.emit('client update', player);
  }
  updateFlag = !updateFlag;
  fps.update(elapsed);
  if (38 in keysDown && player.isAlive) { // Player holding up
    player.pos.y -= player.speed * elapsed;
  }
  if (40 in keysDown && player.isAlive) { // Player holding down
    player.pos.y += player.speed * elapsed;
  }
  if (37 in keysDown && player.isAlive) { // Player holding left
    player.pos.x -= player.speed * elapsed;
  }
  if (39 in keysDown && player.isAlive) { // Player holding right
    player.pos.x += player.speed * elapsed;
  }
  engine.Collisions(player);
  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw background
  ctx.drawImage(images.background, 0, 0, 750, 450);

  // Draw safe zones
  if (engine.gameRound % 2 === 0) {
    ctx.fillStyle = ctx.fillStyle = "rgba(49, 129, 49, 0.4)";
    ctx.fillRect(engine.canvas.width-engine.safezoneWidth,0,engine.canvas.width,engine.canvas.height);
  } else {
    ctx.fillStyle = ctx.fillStyle = "rgba(49, 129, 49, 0.4)";
    ctx.fillRect(0,0,engine.safezoneWidth,engine.canvas.height);
  }

  // Draw player
  ctx.fillStyle = 'white';
  ctx.font = "12px Helvetica";
  if(player.fishType === "shark"){
    ctx.drawImage(images.shark, player.pos.x, player.pos.y, 50, 28);
    ctx.fillText(player.username, player.pos.x + 5 - (player.username).length, player.pos.y + 33);
  } else {
    ctx.drawImage(images.minnow, player.pos.x, player.pos.y, 25, 14);
    ctx.fillText(player.username, player.pos.x + 5 - (player.username).length, player.pos.y + 33);
  }
  ctx.drawImage(images.arrow, player.pos.x + 15, player.pos.y - 10, 14, 7);

  // Draw players
  for (var entity in players) {
    if (players.hasOwnProperty(entity)) {
      entity = players[entity];
      var x_coord = entity.pos.x;
      var y_coord = entity.pos.y;
      ctx.fillStyle = 'white';
      ctx.font = "12px Helvetica";
      if(entity.fishType === "shark"){
        ctx.drawImage(images.shark, x_coord, y_coord, 50, 28);
        ctx.fillText(entity.username, x_coord + 5 - (entity.username).length, y_coord + 33);
      } else {
        ctx.drawImage(images.minnow, x_coord, y_coord, 25, 14);
        ctx.fillText(entity.username, x_coord + 5 - (entity.username).length, y_coord + 33);
      }
      if(entity.id != player.id){
        if(collisionDetected(entity) && (entity.fishType != player.fishType)){
          if(player.fishType === "minnow"){
            ctx.fillText("(✖╭╮✖)", player.pos.x, player.pos.y + 33);
            player.isAlive = false;
          }
          if(entity.fishType === "minnow"){
            ctx.fillText("(✖╭╮✖)", x_coord + 5, y_coord + 33);
            entity.isAlive = false;
          }
        }
      }
    }
  }

  // Draw HUD

}

var collisionDetected = function(otherObject) {
  return (otherObject.pos.x <= (player.pos.x + 32) &&
    player.pos.x <= (otherObject.pos.x + 32) &&
    otherObject.pos.y <= (player.pos.y + 32) &&
    player.pos.y <= (otherObject.pos.y + 32))
}

$(document).ready(function() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  client = io();
  var firstload1 = true;
  var firstload2 = true;
  client.on('onconnected', function(updatedPositions) {
    if(firstload1) {
      console.log("connected");
      // console.log(updatedPositions);
      // players = updatedPositions;
      fps = new FPSMeter("fpsmeter", document.getElementById("fpscontainer"));
      firstload1 = false;
    }
  })
  client.on('user-id', function(userId) {
    if(firstload2) {
      console.log("user-id")
      var initialConfig = engine.Spawn();
      console.log(initialConfig);
      player = new Player(userId, initialConfig.pos, initialConfig.fishType, username);
      engine.Counters(player);
      GameLoopManager.run(GameTick);
      client.emit('client update', player);
      client.emit('join', player);
      firstload2 = false;
    }
  })
  var deleted = [];
  client.on('server update', function(updates) {
    for (var entity in updates) {
      if (updates.hasOwnProperty(entity)) {
        entity = updates[entity];
        if (entity.id !== player.id) {
          players[entity.id] = entity;
        }
        for (var i = 0; i < deleted.length; i++) {
          if (deleted[i] === entity.id) {
            delete players[playerID];
            console.log("deleting ID", playerID);
            console.log("deleted", players[playerID]);
          }
        }
      }
    }
  })
  client.on('remove player', function(playerID) {
    deleted.push(playerID);
  })
  client.on('status update', function(boardState) {
    engine.minnowCount = boardState.minnowCount;
    engine.sharkCount = boardState.sharkCount;
    engine.timer = boardState.timer;
    engine.status = boardState.status;
    updateStatus();
    if (engine.timer === 0 && engine.waiting) {
      engine.waiting = false;
      engine.gameRound++;
      console.log("GAME START!");
    }
  })
})

function updateStatus() {
  if(engine.status === null) {
    $(".status span").html("No connection to the reef :(")
  } else {
    $(".status span").html(engine.status);
  }
}
<|endoftext|>


<commit_before>function normalizePartyName(name) {
  if (name === undefined) {
    return;
  }
  var slashPos = name.indexOf("/");
  var pos = (slashPos == -1) ? name.length : slashPos;
  return name.toLowerCase().replace("-", "_").substring(0, pos);
}

function normalizeBarWidth(bar_width) {
  var bar_min_size = 7;
  return (bar_width < bar_min_size) ? bar_min_size : bar_width;
}

var parties = ["psoe", "pp", "iu", "ap", "indep", "pa", "bng", "pdp", "erc_am", "esquerra_am", "erc", "hb", "ciu", "cds", "par", "eaj_pnv", "ea", "prc", "pr", "uv"];

var normalization = {
  'paro': 'paro_normalizado',
  'envejecimiento': 'envejecimiento_normalizado'
};

var custom_map_style = [{featureType:"administrative.country",elementType:"all",stylers:[{saturation:-100},{visibility:"off"}]},{featureType:"administrative.province",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"administrative.locality",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"road.arterial",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"all",elementType:"labels",stylers:[{visibility:"off"}]},{featureType:"all",elementType:"all",stylers:[{lightness:7},{saturation:-91}]},{featureType:"all",elementType:"all",stylers:[]}];

var tooltipInfo = {
  "Envejecimiento" : {
    content: "Desviación respecto a la media de edad de cada municipio.",
    left: "más mayores",
    right: "más jóvenes",
    legendTop: "Más edad",
    legendBottom:"Menos edad"
  },
  "Edad media" : {
    content: "Desviación respecto a la media de edad de cada municipio.",
    left: "más mayores",
    right: "más jóvenes",
    legendTop: "Más edad",
    legendBottom:"Menos edad"
  },
  "PIB per cápita" : {
    content: "Desviación respecto a la media de edad de cada municipio.",
    left: "más mayores",
    right: "más jóvenes",
    legendTop: "Más % PIB ",
    legendBottom:"Menos % PIB"
  },
  "Tasa de paro" : {
    content: "Lorem ipsum dolor sit amet de, consectetur adipiscing elit. Donec vel libero ipsum, nec commodo ipsum. Sed elementum, odio et congue.",
    left: "más parados",
    right: "menos parados",
    legendTop: "Más % paro",
    legendBottom:"Menos % paro"
  }
};

var table_zoom = {
  12:'gadm4',
  11:'gadm4',
  9:'gadm2',
  8:'gadm2',
  7:'gadm2',
  6:'gadm1'
};

var procesos_electorales = {
  "1987":"68","1988":"68","1989":"68","1990":"68",
  "1991":"69","1992":"69","1993":"69","1994":"69",
  "1995":"70","1996":"70","1997":"70","1998":"70",
  "1999":"71","2000":"71","2001":"71","2002":"71",
  "2003":"72","2004":"72","2005":"72","2006":"72",
  "2007":"73","2008":"73","2009":"73","2010":"73",
  "2011":"74"
};

var graph_hack_year = {
  "1987":"1987","1988":"1987","1989":"1987","1990":"1987",
  "1991":"1991","1992":"1991","1993":"1991","1994":"1991",
  "1995":"1995","1996":"1995","1997":"1995","1998":"1995",
  "1999":"1999","2000":"1999","2001":"1999","2002":"1999",
  "2003":"2003","2004":"2003","2005":"2003","2006":"2003",
  "2007":"2007","2008":"2007","2009":"2007","2010":"2007",
  "2011":"74"
};
<commit_msg>texts for infowindows<commit_after>function normalizePartyName(name) {
  if (name === undefined) {
    return;
  }
  var slashPos = name.indexOf("/");
  var pos = (slashPos == -1) ? name.length : slashPos;
  return name.toLowerCase().replace("-", "_").substring(0, pos);
}

function normalizeBarWidth(bar_width) {
  var bar_min_size = 7;
  return (bar_width < bar_min_size) ? bar_min_size : bar_width;
}

var parties = ["psoe", "pp", "iu", "ap", "indep", "pa", "bng", "pdp", "erc_am", "esquerra_am", "erc", "hb", "ciu", "cds", "par", "eaj_pnv", "ea", "prc", "pr", "uv"];

var normalization = {
  'paro': 'paro_normalizado',
  'envejecimiento': 'envejecimiento_normalizado'
};

var custom_map_style = [{featureType:"administrative.country",elementType:"all",stylers:[{saturation:-100},{visibility:"off"}]},{featureType:"administrative.province",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"administrative.locality",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"road.arterial",elementType:"all",stylers:[{visibility:"off"}]},{featureType:"all",elementType:"labels",stylers:[{visibility:"off"}]},{featureType:"all",elementType:"all",stylers:[{lightness:7},{saturation:-91}]},{featureType:"all",elementType:"all",stylers:[]}];

var tooltipInfo = {
  "Envejecimiento" : {
    content: "Desviación respecto a la media de edad de cada municipio.",
    left: "más mayores",
    right: "más jóvenes",
    legendTop: "Más edad",
    legendBottom:"Menos edad"
  },
  "Edad media" : {
    content: "Desviación respecto a la media de edad de cada municipio.",
    left: "más mayores",
    right: "más jóvenes",
    legendTop: "Más edad",
    legendBottom:"Menos edad"
  },
  "PIB per cápita" : {
    content: "Desviación respecto a la media de edad de cada municipio.",
    left: "más mayores",
    right: "más jóvenes",
    legendTop: "Más % PIB ",
    legendBottom:"Menos % PIB"
  },
  "Tasa de paro" : {
    content: "Lorem ipsum dolor sit amet de, consectetur adipiscing elit. Donec vel libero ipsum, nec commodo ipsum. Sed elementum, odio et congue.",
    left: "más parados",
    right: "menos parados",
    legendTop: "Más % paro",
    legendBottom:"Menos % paro"
  }
};

var textInfoWindow = {
  "Envejecimiento" : {
    before_positive: "Aquí hay un ",
    after_negative: " menos de personas mayores de 65 años, que en el resto de España",
    before_positive: "Aquí hay un ",
    after_positive: " mas de personas mayores de 65 años, que en el resto de España"
  },
  "Tasa de Paro" : {
    before_positive: "La tasa de paro se encuentra a un ",
    after_negative: " por debajo de la media",
    before_positive: "La tasa de paro se encuentra a un ",
    after_positive: " por encima de la media"
  },
  "PIB per cápita" : {
    before_positive: "El PIB per cápita aquí es un ",
    after_negative: " mas bajo que la media nacional",
    before_positive: "El PIB per cápita aquí es un ",
    after_positive: " mas alto que la media nacional"
  },
  "Edad media" : {
    before_positive: "Su población es ",
    after_negative: " años mas jóven que la media nacional",
    before_positive: "Su población es ",
    after_positive: " años mas mayor que la media nacional"
  },
  "Inmigración" : {
    before_positive: "El porcentaje de inmigración en este municipio está ",
    after_negative: " por debajo de la media",
    before_positive: "El porcentaje de inmigración en este municipio está ",
    after_positive: " por encima de la media"
  },
  "Saldo vegetativo": {
    before_positive: "El crecimiento de la población está un ",
    after_negative: " por debajo de la media",
    before_positive: "El crecimiento de la población está un ",
    after_positive: " por encima de la media"
  },
  "Salario medio": {
    before_positive: "El salario medio aquí está un ",
    after_negative: " por debajo de la media",
    before_positive: "El salario medio aquí está un ",
    after_positive: " por encima de la media"
  },
  "Estudios acabados": {
    before_positive: "Un ",
    after_negative: " menos que la media nacional, tiene los estudios secundarios terminados",
    before_positive: "Un ",
    after_positive: " mas que la media nacional, tiene los estudios secundarios terminados"
  },
  "Penetracion internet": {
    before_positive: "Un ",
    after_negative: " menos que la media, tiene acceso a internet aquí",
    before_positive: "Un ",
    after_positive: " mas que la media, tiene acceso a internet aquí"
  }
};

var table_zoom = {
  12:'gadm4',
  11:'gadm4',
  9:'gadm2',
  8:'gadm2',
  7:'gadm2',
  6:'gadm1'
};

var procesos_electorales = {
  "1987":"68","1988":"68","1989":"68","1990":"68",
  "1991":"69","1992":"69","1993":"69","1994":"69",
  "1995":"70","1996":"70","1997":"70","1998":"70",
  "1999":"71","2000":"71","2001":"71","2002":"71",
  "2003":"72","2004":"72","2005":"72","2006":"72",
  "2007":"73","2008":"73","2009":"73","2010":"73",
  "2011":"74"
};

var graph_hack_year = {
  "1987":"1987","1988":"1987","1989":"1987","1990":"1987",
  "1991":"1991","1992":"1991","1993":"1991","1994":"1991",
  "1995":"1995","1996":"1995","1997":"1995","1998":"1995",
  "1999":"1999","2000":"1999","2001":"1999","2002":"1999",
  "2003":"2003","2004":"2003","2005":"2003","2006":"2003",
  "2007":"2007","2008":"2007","2009":"2007","2010":"2007",
  "2011":"74"
};
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import { PureComponent } from 'react';
import nipplejs from 'nipplejs';

class NippleJoystik extends PureComponent {
    componentDidMount(){

      const { onChange } = this.props;

      const options = {
        zone: this.joystick,
        mode: 'static',
        color: 'cyan',
        position: {top: '274px', left: '157px'}
      };

      const manager = nipplejs.create(options);

      manager.on('start end', function(evt, data) {
        console.log('stop all');
        onChange({ x:0, y:0 });
      }).on('move', function(evt, data) {
        let { force, angle: { radian } } = data;

        radian += Math.PI/4;

        const x = force * Math.cos(radian);
        const y = -force * Math.sin(radian);

        onChange({x, y});

      }).on('dir:up plain:up dir:left plain:left dir:down ' +
        'plain:down dir:right plain:right',
        function(evt, data) {
          console.log('stop all');
          onChange({ x:0, y:0 });
        }
      ).on('pressure', function(evt, data) {
        //not used
      });

    }

    render() {
        return

 this.joystick = node} id="nipple-joystick" />

;
    }
};

const connectToPlatform = connect(
  ({ platform:{ offset } }) => ({ x: offset.x, y: offset.y }),
  (dispatch) => ({ onChange: ({ x, y }) => dispatch({ type: 'platformMove', value: { x, y } }) }));

export default connectToPlatform(NippleJoystik);<commit_msg>#13 correction in the web joystick to be aligned with gamepad<commit_after>import { connect } from 'react-redux';
import { PureComponent } from 'react';
import nipplejs from 'nipplejs';

class NippleJoystik extends PureComponent {
    componentDidMount(){

      const { onChange } = this.props;

      const options = {
        zone: this.joystick,
        mode: 'static',
        color: 'cyan',
        position: {top: '274px', left: '157px'}
      };

      const manager = nipplejs.create(options);

      manager.on('start end', function(evt, data) {
        console.log('stop all');
        onChange({ x:0, y:0 });
      }).on('move', function(evt, data) {
        let { force, angle: { radian } } = data;

        radian += Math.PI/4;
        force = force * 1.7;

        const x = force * Math.cos(radian);
        const y = -force * Math.sin(radian);
        onChange({x, y});

      }).on('dir:up plain:up dir:left plain:left dir:down ' +
        'plain:down dir:right plain:right',
        function(evt, data) {
          console.log('stop all');
          onChange({ x:0, y:0 });
        }
      ).on('pressure', function(evt, data) {
        //not used
      });

    }

    render() {
        return

 this.joystick = node} id="nipple-joystick" />

;
    }
};

const connectToPlatform = connect(
  ({ platform:{ offset } }) => ({ x: offset.x, y: offset.y }),
  (dispatch) => ({ onChange: ({ x, y }) => dispatch({ type: 'platformMove', value: { x, y } }) }));

export default connectToPlatform(NippleJoystik);<|endoftext|>


<commit_before>define(module, (exports, require) => {

  var wss = require('ws').Server;
  var qp = require('qp-utility');
  var url = require('qp-library/url');
  var log = require('qp-library/log');
  var websocket = require('qp-library/websocket');

  qp.make(exports, {

    ns: 'qp-library/websocket/server',

    wss: null,
    sockets: [],

    on_connect: null,
    on_connected: null,
    on_message: null,

    init: function(options) {
      this.wss = new wss({
        server: options.http_server,
        port: options.port,
        clientTracking: false,
        verifyClient: this.on_socket_connect
      });
      this.wss.on('connection', this.on_socket_connected);
    },

    stop: function(done) {
      qp.each(this.sockets, (socket) => socket.close());
      this.wss.close(() => {
        if (done) done();
      });
    },

    on_socket_connect: function(info, done) {
      if (this.on_connect) {
        var req_url = url.create({ url: info.req.url });
        this.on_connect(req_url, info.req, function(error, result) {
          if (done && error) {
            done(false, error.code, error.message);
          } else if (done) {
            done(true);
          }
        });
      } else if (done) {
        done(true);
      }
    },

    on_socket_connected: function(ws) {
      var socket = websocket.create({ ws: ws });
      ws.on('error', (e) => this.on_socket_error(socket, e));
      ws.on('close', (code, message) => this.on_socket_close(socket, code, message));
      if (this.on_connected) {
        this.on_connected(socket, (error, connect) => {
          if (error) { socket.close(error.code, error.message); } else {
            this.on_socket_open(socket);
            ws.on('message', (data, flags) => this.on_socket_message(socket, data, flags));
          }
        });
      } else {
        this.on_socket_open(socket);
        ws.on('message', (data, flags) => this.on_socket_message(socket, data, flags));
      }
    },

    on_socket_message: function(socket, data, flags) {
      if (socket.json) data = JSON.parse(data);
      log.socket('MESSAGE', qp.stringify(data));
      if (this.on_message) {
        this.on_message(socket, data, function(error, result) {
          if (error) return socket.send(error); else socket.send(result);
        });
      }
    },

    on_socket_error: function(socket, e) {
      log.socket('ERROR', qp.upper(e.name) + ':', e.message);
    },

    on_socket_open: function(socket, e) {
      log.socket('OPEN', socket.channel);
      qp.push(this.sockets, socket);
    },

    on_socket_close: function(socket, code, message) {
      log.socket('CLOSE', code, message || '');
      qp.remove(this.sockets, socket);
    }

  });

});
<commit_msg>websocket/server; on_connected signature change<commit_after>define(module, (exports, require) => {

  var wss = require('ws').Server;
  var qp = require('qp-utility');
  var url = require('qp-library/url');
  var log = require('qp-library/log');
  var websocket = require('qp-library/websocket');

  qp.make(exports, {

    ns: 'qp-library/websocket/server',

    wss: null,
    sockets: [],

    on_connect: null,
    on_connected: null,
    on_message: null,

    init: function(options) {
      this.wss = new wss({
        server: options.http_server,
        port: options.port,
        clientTracking: false,
        verifyClient: this.on_socket_connect
      });
      this.wss.on('connection', this.on_socket_connected);
    },

    stop: function(done) {
      qp.each(this.sockets, (socket) => socket.close());
      this.wss.close(() => {
        if (done) done();
      });
    },

    on_socket_connect: function(info, done) {
      if (this.on_connect) {
        var req_url = url.create({ url: info.req.url });
        this.on_connect(req_url, info.req, function(error, result) {
          if (done && error) {
            done(false, error.code, error.message);
          } else if (done) {
            done(error === null);
          }
        });
      } else if (done) {
        done(true);
      }
    },

    on_socket_connected: function(ws, req) {
      var socket = websocket.create({ ws: ws });
      ws.on('error', (e) => this.on_socket_error(socket, e));
      ws.on('close', (code, message) => this.on_socket_close(socket, code, message));
      if (this.on_connected) {
        var req_url = url.create({ url: req.url });
        this.on_connected(req_url, socket, req, (error, settings) => {
          if (error) {
            socket.close(error.code, error.message);
          } else {
            qp.merge(socket, settings);
            this.on_socket_open(socket);
            ws.on('message', data => this.on_socket_message(socket, data));
          }
        });
      } else {
        this.on_socket_open(socket);
        ws.on('message', data => this.on_socket_message(socket, data));
      }
    },

    on_socket_message: function(socket, data) {
      if (socket.json) data = JSON.parse(data);
      log.socket('MSG', qp.stringify(data));
      if (this.on_message) {
        this.on_message(socket, data, function(error, result) {
          if (error) socket.send(error); else socket.send(result);
        });
      }
    },

    on_socket_error: function(socket, e) {
      log.socket('ERROR', qp.upper(e.name) + ':', e.message);
    },

    on_socket_open: function(socket, e) {
      log.socket('OPEN', socket.channel);
      qp.push(this.sockets, socket);
    },

    on_socket_close: function(socket, code, message) {
      log.socket('SHUT', code, message || '');
      qp.remove(this.sockets, socket);
    }

  });

});
<|endoftext|>


<commit_before>Template.attachmentsGalery.events({
  'click .js-add-attachment': Popup.open('cardAttachments'),
  'click .js-confirm-delete': Popup.afterConfirm('attachmentDelete',
    function() {
      Attachments.remove(this._id);
      Popup.close();
    }
  ),
  // If we let this event bubble, FlowRouter will handle it and empty the page
  // content, see #101.
  'click .js-download'(event) {
    event.stopPropagation();
  },
  'click .js-add-cover'() {
    Cards.findOne(this.cardId).setCover(this._id);
  },
  'click .js-remove-cover'() {
    Cards.findOne(this.cardId).unsetCover();
  },
  'click .js-preview-image'(evt) {
    Popup.open('previewAttachedImage').call(this, evt);
    // when multiple thumbnails, if click one then another very fast,
    // we might get a wrong width from previous img.
    // when popup reused, onRendered() won't be called, so we cannot get there.
    // here make sure to get correct size when this img fully loaded.
    const img = $('img.preview-large-image')[0];
    if (!img) return;
    const rePosPopup = () => {
      const w = img.width;
      const h = img.height;
      // if the image is too large, we resize & center the popup.
      if (w > 300) {
        $('div.pop-over').css({
          width: (w + 20),
          position: 'absolute',
          left: (window.innerWidth - w)/2,
          top: (window.innerHeight - h)/2,
        });
      }
    };
    const url = $(evt.currentTarget).attr('src');
    if (img.src === url && img.complete)
      rePosPopup();
    else
      img.onload = rePosPopup;
  },
});

Template.previewAttachedImagePopup.events({
  'click .js-large-image-clicked'(){
    Popup.close();
  },
});

Template.cardAttachmentsPopup.events({
  'change .js-attach-file'(evt) {
    const card = this;
    FS.Utility.eachFile(evt, (f) => {
      const file = new FS.File(f);
      file.boardId = card.boardId;
      file.cardId = card._id;
      file.userId = Meteor.userId();

      const attachment = Attachments.insert(file);

      if (attachment && attachment._id && attachment.isImage()) {
        card.setCover(attachment._id);
      }

      Popup.close();
    });
  },
  'click .js-computer-upload'(evt, tpl) {
    tpl.find('.js-attach-file').click();
    evt.preventDefault();
  },
  'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
});

let pastedResults = null;

Template.previewClipboardImagePopup.onRendered(() => {
  // we can paste image from clipboard
  $(document.body).pasteImageReader((results) => {
    if (results.dataURL.startsWith('data:image/')) {
      $('img.preview-clipboard-image').attr('src', results.dataURL);
      pastedResults = results;
    }
  });

  // we can also drag & drop image file to it
  $(document.body).dropImageReader((results) => {
    if (results.dataURL.startsWith('data:image/')) {
      $('img.preview-clipboard-image').attr('src', results.dataURL);
      pastedResults = results;
    }
  });
});

Template.previewClipboardImagePopup.events({
  'click .js-upload-pasted-image'() {
    const results = pastedResults;
    if (results && results.file) {
      const card = this;
      const file = new FS.File(results.file);
      if (!results.name) {
        // if no filename, it's from clipboard. then we give it a name, with ext name from MIME type
        if (typeof results.file.type === 'string') {
          file.name(results.file.type.replace('image/', 'clipboard.'));
        }
      }
      file.updatedAt(new Date());
      file.boardId = card.boardId;
      file.cardId = card._id;
      file.userId = Meteor.userId();
      Attachments.insert(file);
      pastedResults = null;
      $(document.body).pasteImageReader(() => {});
      Popup.close();
    }
  },
});
<commit_msg>Update - auto update card cover with new image uploaded via drag&drop<commit_after>Template.attachmentsGalery.events({
  'click .js-add-attachment': Popup.open('cardAttachments'),
  'click .js-confirm-delete': Popup.afterConfirm('attachmentDelete',
    function() {
      Attachments.remove(this._id);
      Popup.close();
    }
  ),
  // If we let this event bubble, FlowRouter will handle it and empty the page
  // content, see #101.
  'click .js-download'(event) {
    event.stopPropagation();
  },
  'click .js-add-cover'() {
    Cards.findOne(this.cardId).setCover(this._id);
  },
  'click .js-remove-cover'() {
    Cards.findOne(this.cardId).unsetCover();
  },
  'click .js-preview-image'(evt) {
    Popup.open('previewAttachedImage').call(this, evt);
    // when multiple thumbnails, if click one then another very fast,
    // we might get a wrong width from previous img.
    // when popup reused, onRendered() won't be called, so we cannot get there.
    // here make sure to get correct size when this img fully loaded.
    const img = $('img.preview-large-image')[0];
    if (!img) return;
    const rePosPopup = () => {
      const w = img.width;
      const h = img.height;
      // if the image is too large, we resize & center the popup.
      if (w > 300) {
        $('div.pop-over').css({
          width: (w + 20),
          position: 'absolute',
          left: (window.innerWidth - w)/2,
          top: (window.innerHeight - h)/2,
        });
      }
    };
    const url = $(evt.currentTarget).attr('src');
    if (img.src === url && img.complete)
      rePosPopup();
    else
      img.onload = rePosPopup;
  },
});

Template.previewAttachedImagePopup.events({
  'click .js-large-image-clicked'(){
    Popup.close();
  },
});

Template.cardAttachmentsPopup.events({
  'change .js-attach-file'(evt) {
    const card = this;
    FS.Utility.eachFile(evt, (f) => {
      const file = new FS.File(f);
      file.boardId = card.boardId;
      file.cardId = card._id;
      file.userId = Meteor.userId();

      const attachment = Attachments.insert(file);

      if (attachment && attachment._id && attachment.isImage()) {
        card.setCover(attachment._id);
      }

      Popup.close();
    });
  },
  'click .js-computer-upload'(evt, tpl) {
    tpl.find('.js-attach-file').click();
    evt.preventDefault();
  },
  'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'),
});

let pastedResults = null;

Template.previewClipboardImagePopup.onRendered(() => {
  // we can paste image from clipboard
  $(document.body).pasteImageReader((results) => {
    if (results.dataURL.startsWith('data:image/')) {
      $('img.preview-clipboard-image').attr('src', results.dataURL);
      pastedResults = results;
    }
  });

  // we can also drag & drop image file to it
  $(document.body).dropImageReader((results) => {
    if (results.dataURL.startsWith('data:image/')) {
      $('img.preview-clipboard-image').attr('src', results.dataURL);
      pastedResults = results;
    }
  });
});

Template.previewClipboardImagePopup.events({
  'click .js-upload-pasted-image'() {
    const results = pastedResults;
    if (results && results.file) {
      const card = this;
      const file = new FS.File(results.file);
      if (!results.name) {
        // if no filename, it's from clipboard. then we give it a name, with ext name from MIME type
        if (typeof results.file.type === 'string') {
          file.name(results.file.type.replace('image/', 'clipboard.'));
        }
      }
      file.updatedAt(new Date());
      file.boardId = card.boardId;
      file.cardId = card._id;
      file.userId = Meteor.userId();
      const attachment = Attachments.insert(file);

      if (attachment && attachment._id && attachment.isImage()) {
        card.setCover(attachment._id);
      }

      pastedResults = null;
      $(document.body).pasteImageReader(() => {});
      Popup.close();
    }
  },
});
<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    gvm.userId = -1;
    gvm.studentlistName = ko.observable('Name');
    gvm.listId = -1
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AccountTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("EditListTitle");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.myLists = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("myLists");}, gvm);
    gvm.addStudListBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("addStudListBtn");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.firstname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.email = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Email");}, gvm);
    gvm.memberSince = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MemberSince");}, gvm);
    gvm.myProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MyProjects");}, gvm);

    gvm.tabledata = ko.observableArray([]);

    gvm.addTableData = function(id, firstname, lastname, username) {
        // Push data
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tusername: username};
        gvm.tabledata.push(tblOject);

        $('#editbtn-' + id).bind('click', function(event, data) {
            showEditStudentModal(tblOject);
            event.stopPropagation();
        });

        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

}

function showEditStudentModal(tblObject) {
    resetGeneralModal();
    setGeneralModalTitle("Edit Student");
    setGeneralModalBody('<form id="updateStudent"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tfirstname + '" " name="firstname" value="' + tblObject.tfirstname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tlastname + '" name="lastname" value="' + tblObject.tlastname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tusername + '" name="username" value="' + tblObject.tusername + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateStudent(tblObject.tid, $('#updateStudent').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

/*function showNewStudentModal() {
    resetGeneralModal();
    setGeneralModalTitle("Add Student");
    setGeneralModalBody('<form id="newStudentFrom"> \

 \
                <input id="studentComplete"> \

 \
        </form>');
    $.getJSON();

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        addNewStudent($('#newStudentFrom').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}*/

function addNewStudent(serialData, callback) {
    console.log(serialData);
    $.ajax({
        url: "/api/newstudent/" + viewModel.listId,
        type: "POST",
        data: serialData,
        success: function(data) {
            viewModel.addTableData(data['id'], data['firstname'], data['lastname'], data['mail']);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function updateStudent(id, object, callback) {
    $.ajax({
        url: "/api/studentrapport/" + id,
        type: "PUT",
        data: object,
        success: function(data) {
            loadStudentTable();
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function deleteTableItem(id, tblObject){
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: '/api/studentlistrapport/' + $("#page-header").data('value') + '/delete/student/' + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblObject);
                }
            });
        }
    });
}

function loadStudentTable() {
    $.getJSON('/api/studentlistrapporten/students/' + $("#page-header").data('value'), function(data) {
        viewModel.clearTable();
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addTableData(item.id, item.firstname, item.lastname, item.username);
        });
    });
}

function initPage() {
    $.getJSON('/api/studentlistrapport/info/' + $("#page-header").data('value'), function(data) {
        console.log(data[0].id);
        viewModel.studentlistName(data[0].name);
        viewModel.listId = (data[0].id);
    });

    $('#addStudent').click(function(){
        $("#addStudentForm").removeAttr("style");
    });

    $('#addStudentBtn').click(function() {
        $('#addStudentForm').attr("style", "display: none");
    });

    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];
    $('#studentsComplete').autocomplete({ source: availableTags });

    loadStudentTable();
}<commit_msg>fixed autocomplete. Nu laten werken met DB en viewmodel<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    gvm.userId = -1;
    gvm.studentlistName = ko.observable('Name');
    gvm.listId = -1
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AccountTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("EditListTitle");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.myLists = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("myLists");}, gvm);
    gvm.addStudListBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("addStudListBtn");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.firstname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.email = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Email");}, gvm);
    gvm.memberSince = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MemberSince");}, gvm);
    gvm.myProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MyProjects");}, gvm);

    gvm.tabledata = ko.observableArray([]);

    gvm.addTableData = function(id, firstname, lastname, username) {
        // Push data
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tusername: username};
        gvm.tabledata.push(tblOject);

        $('#editbtn-' + id).bind('click', function(event, data) {
            showEditStudentModal(tblOject);
            event.stopPropagation();
        });

        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

}

function showEditStudentModal(tblObject) {
    resetGeneralModal();
    setGeneralModalTitle("Edit Student");
    setGeneralModalBody('<form id="updateStudent"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tfirstname + '" " name="firstname" value="' + tblObject.tfirstname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tlastname + '" name="lastname" value="' + tblObject.tlastname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tusername + '" name="username" value="' + tblObject.tusername + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateStudent(tblObject.tid, $('#updateStudent').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

/*function showNewStudentModal() {
    resetGeneralModal();
    setGeneralModalTitle("Add Student");
    setGeneralModalBody('<form id="newStudentFrom"> \

 \
                <input id="studentComplete"> \

 \
        </form>');
    $.getJSON();

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        addNewStudent($('#newStudentFrom').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}*/

function addNewStudent(serialData, callback) {
    console.log(serialData);
    $.ajax({
        url: "/api/newstudent/" + viewModel.listId,
        type: "POST",
        data: serialData,
        success: function(data) {
            viewModel.addTableData(data['id'], data['firstname'], data['lastname'], data['mail']);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function updateStudent(id, object, callback) {
    $.ajax({
        url: "/api/studentrapport/" + id,
        type: "PUT",
        data: object,
        success: function(data) {
            loadStudentTable();
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function deleteTableItem(id, tblObject){
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: '/api/studentlistrapport/' + $("#page-header").data('value') + '/delete/student/' + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblObject);
                }
            });
        }
    });
}

function loadStudentTable() {
    $.getJSON('/api/studentlistrapporten/students/' + $("#page-header").data('value'), function(data) {
        viewModel.clearTable();
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addTableData(item.id, item.firstname, item.lastname, item.username);
        });
    });
}

function initPage() {
    $.getJSON('/api/studentlistrapport/info/' + $("#page-header").data('value'), function(data) {
        console.log(data[0].id);
        viewModel.studentlistName(data[0].name);
        viewModel.listId = (data[0].id);
    });

    $('#addStudent').click(function(){
        $("#addStudentForm").removeAttr("style");
    });

    $('#addStudentBtn').click(function() {
        $('#addStudentForm').prop('style', 'display: none');
    });

    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];
    $('#studentsComplete').autocomplete({ source: availableTags });

    loadStudentTable();
}<|endoftext|>