<commit_before>
// dépendances

	const 	path = require('path'),
			fs = require('fs'),
			q = require('q');

// module

	module.exports = function (Container) {

		// attributes

			var
				m_tabCategories = [],
				m_sBufferFilePath = path.join(__dirname, 'backup.json');

		// methods

			// private

				function _load() {

					var deferred = q.defer();

						try {

							fs.readFile(m_sBufferFilePath, { encoding : 'utf8' } , function (err, data) {

								if (err) {
									deferred.reject('Impossible de lire les données enregistrée : ' + ((err.message) ? err.message : err) + '.');
								}
								else {

									try {
										m_tabCategories = JSON.parse(data);
										deferred.resolve();
									}
									catch (e) {
										deferred.reject('Impossible de lire les données enregistrée : ' + ((err.message) ? err.message : err) + '.');
									}

								}

							});

						}
						catch(e) {
							deferred.reject((e.message) ? e.message : e);
						}

					return deferred.promise;

				}

				function _save() {

					var deferred = q.defer();

						try {

							fs.writeFile(m_sBufferFilePath, JSON.stringify(m_tabCategories), { encoding : 'utf8' } , function (err, data) {

								if (err) {
									deferred.reject('Impossible de sauvegarder les données : ' + ((err.message) ? err.message : err) + '.');
								}
								else {
									deferred.resolve();
								}

							});

						}
						catch (e) {
							deferred.reject('Impossible de sauvegarder les données : ' + ((err.message) ? err.message : err) + '.');
						}

					return deferred.promise;

				}

				function _loadCategories() {

					var tabCategories = [];

					if (0 < m_tabCategories.length) {

						m_tabCategories.forEach(function(category) {

							tabCategories.push({
								code : category.code,
								name : category.name
							});

						});

						Container.get('websockets').emit('plugins.videos.categories', tabCategories);

					}
					else {

						_load().then(function() {

							m_tabCategories.forEach(function(category) {

								tabCategories.push({
									code : category.code,
									name : category.name
								});

							});

							Container.get('websockets').emit('plugins.videos.categories', tabCategories);

						});

					}

				}

				function _loadVideosByCategory(p_stCategory) {

					var tabVideos = [];

						m_tabCategories.forEach(function(category) {

							if (category.code === p_stCategory.code) {
								tabVideos = category.videos;
							}

						});

					Container.get('websockets').emit('plugins.videos.videos', tabVideos);

				}

				function _formateVideo(video) {

					video.url = video.url 	.replace('http:', 'https:')
											.replace('m.', '')
											.replace('//youtu', '//www.youtu')
											.replace('youtu.be/', 'youtube.com/watch?v=')
											.replace(/&(.*)/, '');

					video.urlembeded = video.url 	.replace('.com/', '.com/embed/')
													.replace('watch?v=', '');

					if (!video.code || '' == video.code) {

						if (1 < video.url.split('=').length) {
							video.code = video.url.split('=')[1];
						}
						else {
							video.code = video.name;
						}

					}

					return video;

				}

		// constructor

			// events

				Container.get('websockets').onDisconnect(function(socket) {

					// categories

						socket.removeAllListeners('plugins.videos.category.add');
						socket.removeAllListeners('plugins.videos.category.edit');
						socket.removeAllListeners('plugins.videos.category.delete');

					// videos

						socket.removeAllListeners('plugins.videos.videos');

						socket.removeAllListeners('plugins.videos.video.add');
						socket.removeAllListeners('plugins.videos.video.edit');
						socket.removeAllListeners('plugins.videos.video.delete');

						socket.removeAllListeners('plugins.videos.video.play');

				})
				.onLog(function(socket) {

					_loadCategories();

					// categories

						socket.on('plugins.videos.category.add', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.category.add');
							}

							var bFound = false;

								m_tabCategories.forEach(function(category) {

									if (category.code === data.code) {
										bFound = true;
									}

								});

							if (bFound) {
								socket.emit('plugins.videos.error', 'Cette catégorie existe déjà.');
							}
							else {

								data = {
									code : data.name,
									name : data.name,
									videos : []
								};

								m_tabCategories.push(data);

								_save().then(function() {

									Container.get('websockets').emit('plugins.videos.category.added', {
										code : data.name,
										name : data.name
									});

								})
								.catch(function(err) {
									socket.emit('plugins.videos.error', err);
								});

							}

						})
						.on('plugins.videos.category.edit', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.category.edit');
							}

							var bFound = false;

								m_tabCategories.forEach(function(category, key) {

									if (category.code === data.code) {
										bFound = true;
										m_tabCategories[key].name = data.name;
									}

								});

							if (!bFound) {
								socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
							}
							else {

								_save().then(function() {

									Container.get('websockets').emit('plugins.videos.category.edited', {
										code : data.code,
										name : data.name
									});

								})
								.catch(function(err) {
									socket.emit('plugins.videos.error', err);
								});

							}

						})
						.on('plugins.videos.category.delete', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.category.delete');
							}

							m_tabCategories.forEach(function(category, key) {

								if (category.code === data.code) {
									m_tabCategories.splice(key, 1);
								}

							});

							_save().then(_loadCategories)
							.catch(function(err) {
								socket.emit('plugins.videos.error', err);
							});

						});

					// videos

						socket.on('plugins.videos.videos', _loadVideosByCategory)

						.on('plugins.videos.video.add', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.video.add');
							}

							if (!data || !data.video || !data.video.name || !data.video.url) {
								socket.emit('plugins.videos.error', 'Des données sont manquantes.');
							}
							else {

								var bCategoryFound = false, stVideo = false;

									m_tabCategories.forEach(function(category, key) {

										if (category.code === data.category.code) {

											bCategoryFound = true;

											stVideo = _formateVideo(data.video);

											category.videos.forEach(function(video, vidkey) {

												if (video.code === stVideo.code) {
													stVideo = false;
												}

											});

											if (stVideo) {
												m_tabCategories[key].videos.push(stVideo);
											}

										}

									});

								if (!bCategoryFound) {
									socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
								}
								else if (!stVideo) {
									socket.emit('plugins.videos.error', 'Cette vidéo est déjà enregistrée.');
								}
								else {

									_save().then(function() {
										Container.get('websockets').emit('plugins.videos.video.added', stVideo);
									})
									.catch(function(err) {
										socket.emit('plugins.videos.error', err);
									});

								}

							}

						})
						.on('plugins.videos.video.edit', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.video.edit');
							}

							if (!data || !data.video || !data.video.name || !data.video.url || !data.video.code) {
								socket.emit('plugins.videos.error', 'Des données sont manquantes.');
							}
							else {

								var bCategoryFound = false, stVideo = false;

									m_tabCategories.forEach(function(category, catkey) {

										if (category.code === data.category.code) {

											bCategoryFound = true;

											category.videos.forEach(function(video, vidkey) {

												if (video.code === data.video.code) {
													stVideo = _formateVideo(data.video);
													m_tabCategories[catkey].videos[vidkey] = stVideo;
												}

											});

										}

									});

								if (!bCategoryFound) {
									socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
								}
								else if (!stVideo) {
									socket.emit('plugins.videos.error', 'Impossible de trouver cette vidéo.');
								}
								else {

									_save().then(function() {
										Container.get('websockets').emit('plugins.videos.video.edited', stVideo);
									})
									.catch(function(err) {
										socket.emit('plugins.videos.error', err);
									});

								}

							}

						})
						.on('plugins.videos.video.delete', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.video.delete');
							}

							var bCategoryFound = false, bVideoFound = false;

								m_tabCategories.forEach(function(category, catkey) {

									if (category.code === data.category.code) {

										bCategoryFound = true;

										category.videos.forEach(function(video, vidkey) {

											if (video.code === data.video.code) {
												bVideoFound = true;
												m_tabCategories[catkey].videos.splice(vidkey, 1);
											}

										});

									}

								});

							if (!bCategoryFound) {
								socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
							}
							else if (!bVideoFound) {
								socket.emit('plugins.videos.error', 'Impossible de trouver cette vidéo.');
							}
							else {

								_save().then(function() {
									_loadVideosByCategory(data.category);
								})
								.catch(function(err) {
									socket.emit('plugins.videos.error', err);
								});

							}

						});

						// action

							socket.on('plugins.videos.video.playsound', function (data) {

								if (Container.get('conf').get('debug')) {
									Container.get('logs').log('plugins.videos.video.playsound');
								}

								if (!data) {
									Container.get('logs').err('play video - données manquantes');
									socket.emit('plugins.videos.error', 'Données manquantes');
								}
								else if (!data.child) {
									Container.get('logs').err('play video - aucun enfant choisi');
									socket.emit('plugins.videos.error', 'Aucun enfant choisi');
								}
								else if (!data.video) {
									Container.get('logs').err('play video - aucune vidéo choisie');
									socket.emit('plugins.videos.error', 'Aucune vidéo choisie');
								}
								else {
									Container.get('childssockets').emitTo(data.child.token, 'media.sound.play', data.video);
								}

							});

							socket.on('plugins.videos.video.playvideo', function (data) {

								if (Container.get('conf').get('debug')) {
									Container.get('logs').log('plugins.videos.video.playvideo');
								}

								if (!data) {
									Container.get('logs').err('play video - données manquantes');
									socket.emit('plugins.videos.error', 'Données manquantes');
								}
								else if (!data.child) {
									Container.get('logs').err('play video - aucun enfant choisi');
									socket.emit('plugins.videos.error', 'Aucun enfant choisi');
								}
								else if (!data.video) {
									Container.get('logs').err('play video - aucune vidéo choisie');
									socket.emit('plugins.videos.error', 'Aucune vidéo choisie');
								}
								else {
									Container.get('childssockets').emitTo(data.child.token, 'media.video.play', data.video);
								}

							});

				});

	};<commit_msg>suppression de la dépendance avec q<commit_after>
// dépendances

	const 	path = require('path'),
			fs = require('fs');

// module

	module.exports = function (Container) {

		// attributes

			var
				m_tabCategories = [],
				m_sBufferFilePath = path.join(__dirname, 'backup.json');

		// methods

			// private

				function _load() {

					return new Promise(function(resolve, reject) {

						try {

							fs.readFile(m_sBufferFilePath, { encoding : 'utf8' } , function (err, data) {

								if (err) {
									reject('Impossible de lire les données enregistrée : ' + ((err.message) ? err.message : err) + '.');
								}
								else {

									try {
										m_tabCategories = JSON.parse(data);
										resolve();
									}
									catch (e) {
										reject('Impossible de lire les données enregistrée : ' + ((err.message) ? err.message : err) + '.');
									}

								}

							});

						}
						catch(e) {
							reject((e.message) ? e.message : e);
						}

					});

				}

				function _save() {

					return new Promise(function(resolve, reject) {

						try {

							fs.writeFile(m_sBufferFilePath, JSON.stringify(m_tabCategories), { encoding : 'utf8' } , function (err, data) {

								if (err) {
									reject('Impossible de sauvegarder les données : ' + ((err.message) ? err.message : err) + '.');
								}
								else {
									resolve();
								}

							});

						}
						catch (e) {
							reject('Impossible de sauvegarder les données : ' + ((err.message) ? err.message : err) + '.');
						}

					});

				}

				function _loadCategories() {

					var tabCategories = [];

					if (0 < m_tabCategories.length) {

						m_tabCategories.forEach(function(category) {

							tabCategories.push({
								code : category.code,
								name : category.name
							});

						});

						Container.get('websockets').emit('plugins.videos.categories', tabCategories);

					}
					else {

						_load().then(function() {

							m_tabCategories.forEach(function(category) {

								tabCategories.push({
									code : category.code,
									name : category.name
								});

							});

							Container.get('websockets').emit('plugins.videos.categories', tabCategories);

						});

					}

				}

				function _loadVideosByCategory(p_stCategory) {

					var tabVideos = [];

						m_tabCategories.forEach(function(category) {

							if (category.code === p_stCategory.code) {
								tabVideos = category.videos;
							}

						});

					Container.get('websockets').emit('plugins.videos.videos', tabVideos);

				}

				function _formateVideo(video) {

					video.url = video.url 	.replace('http:', 'https:')
											.replace('m.', '')
											.replace('//youtu', '//www.youtu')
											.replace('youtu.be/', 'youtube.com/watch?v=')
											.replace(/&(.*)/, '');

					video.urlembeded = video.url 	.replace('.com/', '.com/embed/')
													.replace('watch?v=', '');

					if (!video.code || '' == video.code) {

						if (1 < video.url.split('=').length) {
							video.code = video.url.split('=')[1];
						}
						else {
							video.code = video.name;
						}

					}

					return video;

				}

		// constructor

			// events

				Container.get('websockets').onDisconnect(function(socket) {

					// categories

						socket.removeAllListeners('plugins.videos.category.add');
						socket.removeAllListeners('plugins.videos.category.edit');
						socket.removeAllListeners('plugins.videos.category.delete');

					// videos

						socket.removeAllListeners('plugins.videos.videos');

						socket.removeAllListeners('plugins.videos.video.add');
						socket.removeAllListeners('plugins.videos.video.edit');
						socket.removeAllListeners('plugins.videos.video.delete');

						socket.removeAllListeners('plugins.videos.video.play');

				})
				.onLog(function(socket) {

					_loadCategories();

					// categories

						socket.on('plugins.videos.category.add', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.category.add');
							}

							var bFound = false;

								m_tabCategories.forEach(function(category) {

									if (category.code === data.code) {
										bFound = true;
									}

								});

							if (bFound) {
								socket.emit('plugins.videos.error', 'Cette catégorie existe déjà.');
							}
							else {

								data = {
									code : data.name,
									name : data.name,
									videos : []
								};

								m_tabCategories.push(data);

								_save().then(function() {

									Container.get('websockets').emit('plugins.videos.category.added', {
										code : data.name,
										name : data.name
									});

								})
								.catch(function(err) {
									socket.emit('plugins.videos.error', err);
								});

							}

						})
						.on('plugins.videos.category.edit', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.category.edit');
							}

							var bFound = false;

								m_tabCategories.forEach(function(category, key) {

									if (category.code === data.code) {
										bFound = true;
										m_tabCategories[key].name = data.name;
									}

								});

							if (!bFound) {
								socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
							}
							else {

								_save().then(function() {

									Container.get('websockets').emit('plugins.videos.category.edited', {
										code : data.code,
										name : data.name
									});

								})
								.catch(function(err) {
									socket.emit('plugins.videos.error', err);
								});

							}

						})
						.on('plugins.videos.category.delete', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.category.delete');
							}

							m_tabCategories.forEach(function(category, key) {

								if (category.code === data.code) {
									m_tabCategories.splice(key, 1);
								}

							});

							_save().then(_loadCategories)
							.catch(function(err) {
								socket.emit('plugins.videos.error', err);
							});

						});

					// videos

						socket.on('plugins.videos.videos', _loadVideosByCategory)

						.on('plugins.videos.video.add', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.video.add');
							}

							if (!data || !data.video || !data.video.name || !data.video.url) {
								socket.emit('plugins.videos.error', 'Des données sont manquantes.');
							}
							else {

								var bCategoryFound = false, stVideo = false;

									m_tabCategories.forEach(function(category, key) {

										if (category.code === data.category.code) {

											bCategoryFound = true;

											stVideo = _formateVideo(data.video);

											category.videos.forEach(function(video, vidkey) {

												if (video.code === stVideo.code) {
													stVideo = false;
												}

											});

											if (stVideo) {
												m_tabCategories[key].videos.push(stVideo);
											}

										}

									});

								if (!bCategoryFound) {
									socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
								}
								else if (!stVideo) {
									socket.emit('plugins.videos.error', 'Cette vidéo est déjà enregistrée.');
								}
								else {

									_save().then(function() {
										Container.get('websockets').emit('plugins.videos.video.added', stVideo);
									})
									.catch(function(err) {
										socket.emit('plugins.videos.error', err);
									});

								}

							}

						})
						.on('plugins.videos.video.edit', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.video.edit');
							}

							if (!data || !data.video || !data.video.name || !data.video.url || !data.video.code) {
								socket.emit('plugins.videos.error', 'Des données sont manquantes.');
							}
							else {

								var bCategoryFound = false, stVideo = false;

									m_tabCategories.forEach(function(category, catkey) {

										if (category.code === data.category.code) {

											bCategoryFound = true;

											category.videos.forEach(function(video, vidkey) {

												if (video.code === data.video.code) {
													stVideo = _formateVideo(data.video);
													m_tabCategories[catkey].videos[vidkey] = stVideo;
												}

											});

										}

									});

								if (!bCategoryFound) {
									socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
								}
								else if (!stVideo) {
									socket.emit('plugins.videos.error', 'Impossible de trouver cette vidéo.');
								}
								else {

									_save().then(function() {
										Container.get('websockets').emit('plugins.videos.video.edited', stVideo);
									})
									.catch(function(err) {
										socket.emit('plugins.videos.error', err);
									});

								}

							}

						})
						.on('plugins.videos.video.delete', function (data) {

							if (Container.get('conf').get('debug')) {
								Container.get('logs').log('plugins.videos.video.delete');
							}

							var bCategoryFound = false, bVideoFound = false;

								m_tabCategories.forEach(function(category, catkey) {

									if (category.code === data.category.code) {

										bCategoryFound = true;

										category.videos.forEach(function(video, vidkey) {

											if (video.code === data.video.code) {
												bVideoFound = true;
												m_tabCategories[catkey].videos.splice(vidkey, 1);
											}

										});

									}

								});

							if (!bCategoryFound) {
								socket.emit('plugins.videos.error', 'Impossible de trouver cette catégorie.');
							}
							else if (!bVideoFound) {
								socket.emit('plugins.videos.error', 'Impossible de trouver cette vidéo.');
							}
							else {

								_save().then(function() {
									_loadVideosByCategory(data.category);
								})
								.catch(function(err) {
									socket.emit('plugins.videos.error', err);
								});

							}

						});

						// action

							socket.on('plugins.videos.video.playsound', function (data) {

								if (Container.get('conf').get('debug')) {
									Container.get('logs').log('plugins.videos.video.playsound');
								}

								if (!data) {
									Container.get('logs').err('play video - données manquantes');
									socket.emit('plugins.videos.error', 'Données manquantes');
								}
								else if (!data.child) {
									Container.get('logs').err('play video - aucun enfant choisi');
									socket.emit('plugins.videos.error', 'Aucun enfant choisi');
								}
								else if (!data.video) {
									Container.get('logs').err('play video - aucune vidéo choisie');
									socket.emit('plugins.videos.error', 'Aucune vidéo choisie');
								}
								else {
									Container.get('childssockets').emitTo(data.child.token, 'media.sound.play', data.video);
								}

							});

							socket.on('plugins.videos.video.playvideo', function (data) {

								if (Container.get('conf').get('debug')) {
									Container.get('logs').log('plugins.videos.video.playvideo');
								}

								if (!data) {
									Container.get('logs').err('play video - données manquantes');
									socket.emit('plugins.videos.error', 'Données manquantes');
								}
								else if (!data.child) {
									Container.get('logs').err('play video - aucun enfant choisi');
									socket.emit('plugins.videos.error', 'Aucun enfant choisi');
								}
								else if (!data.video) {
									Container.get('logs').err('play video - aucune vidéo choisie');
									socket.emit('plugins.videos.error', 'Aucune vidéo choisie');
								}
								else {
									Container.get('childssockets').emitTo(data.child.token, 'media.video.play', data.video);
								}

							});

				});

	};<|endoftext|>


<commit_before>process.env.NODE_ENV = ( process.env.NODE_ENV && ( process.env.NODE_ENV ).trim().toLowerCase() == 'production' ) ? 'production' : 'development';

const http = require('http'), crypto = require('crypto'), exec = require('child_process').exec,
apps = require(__dirname+'/apps.json'), config = require(__dirname+'/config.json'), logger = require('log4js').getLogger();

Array.prototype.last = () => {
    return this[this.length - 1];
}

const server = http.createServer((req, res) => {
    if(req.method == 'POST') {
        for(let app in apps) {
            if(apps[app].url == req.url) {
                logger.info(app+' POST Reveived');
                let body = '';
                req.on('data', (data) => {
                    body += data;
                });
                req.on('end', () => {
                    let hash = 'sha1='+crypto.createHmac('sha1', apps[app].secret).update(body).digest('hex');
                    if(hash == req.headers['x-hub-signature']) {
                        logger.info("Hash validation success");
                        let executeCommand = '';
                        if(typeof req.ref == 'string') {
                            let branch = req.ref.split('/')[req.ref.length - 1];
                            logger.info('brench: '+branch);
                            if(typeof apps[app].branch[req.ref.split('/')[req.ref.length - 1]] == 'string') {
                                executeCommand = apps[app].branch[req.ref.last];
                                logger.info(branch+" has execute commands");
                            } else if(typeof apps[app].default == 'string' ) {
                                executeCommand = apps[app].default;
                                logger.info("default command");
                            } else {
                                executeCommand = null;
                                logger.info("not has command");
                            }
                        } else {
                            executeCommand = null;
                        }

                        if(executeCommand != null) {
                            exec(executeCommand, (err, stdout, stderr) => {
                                logger.info('====== command exex ======');
                                logger.info(stdout);
                                logger.info('====== command exec ======');
                                if(err) {
                                    logger.error('====== command error ======');
                                    logger.error(err);
                                    logger.error('====== command error ======');
                                }
                                if(stderr) {
                                    logger.error('====== command stderr ======');
                                    logger.error(stderr);
                                    logger.error('====== command stderr ======');
                                }
                                res.writeHead(200, {'Content-Type': 'text/html'});
                                res.end('post received');
                            });
                        } else {
                            res.writeHead(200, {'Content-Type': 'text/html'});
                            res.end('');
                        }
                    } else {
                        res.status(400);
                        logger.error('Key is not match!');
                        logger.info('Github key is '+req.headers['x-hub-signature']);
                        logger.info('and local task key is '+hash);
                        res.writeHead(400, {'Content-Type': 'text/html'});
                        res.end('Key is not match');
                    }
                });
            }
        }
    } else {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('');
    }
});

server.listen(config.http_port, () => {
    logger.info('HTTP Listening!');
    logger.info('address: '+server.address().address);
    logger.info('port: '+server.address().port);
});<commit_msg>로그, 비정상작동 등 수정<commit_after>process.env.NODE_ENV = ( process.env.NODE_ENV && ( process.env.NODE_ENV ).trim().toLowerCase() == 'production' ) ? 'production' : 'development';

const http = require('http'), crypto = require('crypto'), exec = require('child_process').exec,
apps = require(__dirname+'/apps.json'), config = require(__dirname+'/config.json'), logger = require('log4js').getLogger();

Array.prototype.last = () => {
    return this[this.length - 1];
}

const server = http.createServer((req, res) => {
    if(req.method == 'POST') {
        for(let app in apps) {
            if(apps[app].url == req.url) {
                logger.info(app+' POST Reveived');
                let body = '';
                req.on('data', (data) => {
                    body += data;
                });
                req.on('end', () => {
                    let hash = 'sha1='+crypto.createHmac('sha1', apps[app].secret).update(body).digest('hex');
                    if(hash == req.headers['x-hub-signature']) {
                        logger.info("Hash validation success");
                        let executeCommand = '';
                        if(typeof body.ref == 'string') {
                            let branch = body.ref.split('/')[req.ref.length - 1];
                            logger.info('brench: '+branch);
                            if(typeof apps[app].branch[branch] == 'string') {
                                executeCommand = apps[app].branch[req.ref.last];
                                logger.info(branch+" has execute commands");
                            } else if(typeof apps[app].default == 'string' ) {
                                executeCommand = apps[app].default;
                                logger.info("default command");
                            } else {
                                executeCommand = null;
                                logger.info("not has command");
                            }
                        } else {
                            logger.info("brench not found");
                            logger.debug(body.ref);
                            executeCommand = null;
                        }

                        if(executeCommand != null) {
                            exec(executeCommand, (err, stdout, stderr) => {
                                logger.info('====== command exex ======');
                                logger.info(stdout);
                                logger.info('====== command exec ======');
                                if(err) {
                                    logger.error('====== command error ======');
                                    logger.error(err);
                                    logger.error('====== command error ======');
                                }
                                if(stderr) {
                                    logger.error('====== command stderr ======');
                                    logger.error(stderr);
                                    logger.error('====== command stderr ======');
                                }
                                res.writeHead(200, {'Content-Type': 'text/html'});
                                res.end('post received');
                            });
                        } else {
                            res.writeHead(200, {'Content-Type': 'text/html'});
                            res.end('');
                        }
                    } else {
                        res.status(400);
                        logger.error('Key is not match!');
                        logger.info('Github key is '+req.headers['x-hub-signature']);
                        logger.info('and local task key is '+hash);
                        res.writeHead(400, {'Content-Type': 'text/html'});
                        res.end('Key is not match');
                    }
                });
            }
        }
    } else {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('');
    }
});

server.listen(config.http_port, () => {
    logger.info('HTTP Listening!');
    logger.info('address: '+server.address().address);
    logger.info('port: '+server.address().port);
});<|endoftext|>


<commit_before>var dexecure = {
	"server": {
		"www.ozaria.com": "ozaria.dexecure.net"
	},
	"firstPartyDomain": [
		"www.ozaria.com"
	],
	"optimisationsEnabled": true,
	"debugMode": false,
	"imageMatchRegex": "\\.jpe?g|\\.png",
	"pagesEnabled": [
		""
	]
};"use strict";function isFirstPartyDomain(e){for(var r=new URL(e),o=dexecure.firstPartyDomain,t=o.length-1;t>=0;t--)if(o[t].toLowerCase()==r.host.toLowerCase())return!0;return!1}function changeToDexecureURL(e){var r=new URL(e);return dexecure.debugMode&&console.log("inputURL is ",e),dexecure.debugMode&&console.log("inputURL.hostname is ",e.hostname),r.hostname=dexecure.server[r.hostname],dexecure.debugMode&&console.log("changedURL.hostname is ",r.hostname),r.pathname.startsWith("/file") ? r.searchParams.set("resize", "none") : null,dexecure.debugMode&&console.log("changedURL is ",r.href),r.href}function isPageEnabled(e){return!0}dexecure.optimisationsEnabled&&(self.addEventListener("install",function(e){dexecure.debugMode&&console.log("install triggered"),e.waitUntil(self.skipWaiting())}),self.addEventListener("activate",function(e){e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",function(e){dexecure.debugMode&&console.log("fetch triggered");var r={};e.request.headers.has("Accept")&&(r.Accept=e.request.headers.get("Accept"));var o=new Headers(r),t=new RegExp(dexecure.imageMatchRegex,"i");if(dexecure.debugMode&&console.log("input url is ",e.request.url),isPageEnabled(e.request.referrer)&&t.test(e.request.url.toLowerCase())&&isFirstPartyDomain(e.request.url)){var n=changeToDexecureURL(e.request.url);n=decodeURIComponent(n),dexecure.debugMode&&console.log("output url is ",n),e.respondWith(fetch(n,{mode:"cors",headers:o}).then(function(r){if(r.ok)return r;throw dexecure.debugMode&&console.log("Responding with original image as optimiser was not reachable ",e.request.url),new Error("Unable to fetch optimised image")}).catch(function(r){return dexecure.debugMode&&(console.log("Sending original image as an error occured when trying to optimise ",e.request.url),console.log("The error was ",r)),fetch(e.request)}))}}));
<commit_msg>Update dexecure config for js/css files (#323)<commit_after>var dexecure = {
	"server": {
		"www.ozaria.com": "ozaria.dexecure.net",
		"staging.ozaria.com": "ozaria-staging.dexecure.net"
	},
	"firstPartyDomain": [
		"www.ozaria.com",
		"staging.ozaria.com"
	],
	"optimisationsEnabled": true,
	"debugMode": false,
	"imageMatchRegex": "\\.jpe?g|\\.png|\\.js(\\?.*)?(#.*)?$|\\.css",
	"ignoreRegex": "(aether_worker|worker_world).js", // Ignore URLs that execute as a new web worker
	"pagesEnabled": [
		""
	]
};"use strict";function isFirstPartyDomain(e){for(var r=new URL(e),o=dexecure.firstPartyDomain,t=o.length-1;t>=0;t--)if(o[t].toLowerCase()==r.host.toLowerCase())return!0;return!1}function changeToDexecureURL(e){var r=new URL(e);return dexecure.debugMode&&console.log("inputURL is ",e),dexecure.debugMode&&console.log("inputURL.hostname is ",e.hostname),r.hostname=dexecure.server[r.hostname],dexecure.debugMode&&console.log("changedURL.hostname is ",r.hostname),r.pathname.startsWith("/file") ? r.searchParams.set("resize", "none") : null,dexecure.debugMode&&console.log("changedURL is ",r.href),r.href}function isPageEnabled(e){return!0}dexecure.optimisationsEnabled&&(self.addEventListener("install",function(e){dexecure.debugMode&&console.log("install triggered"),e.waitUntil(self.skipWaiting())}),self.addEventListener("activate",function(e){e.waitUntil(self.clients.claim())}),self.addEventListener("fetch",function(e){dexecure.debugMode&&console.log("fetch triggered");var r={};e.request.headers.has("Accept")&&(r.Accept=e.request.headers.get("Accept"));var o=new Headers(r),t=new RegExp(dexecure.imageMatchRegex,"i"),t1=new RegExp(dexecure.ignoreRegex,"i");if(dexecure.debugMode&&console.log("input url is ",e.request.url),isPageEnabled(e.request.referrer)&&t.test(e.request.url.toLowerCase())&&!t1.test(e.request.url.toLowerCase())&&isFirstPartyDomain(e.request.url)){var n=changeToDexecureURL(e.request.url);n=decodeURIComponent(n),dexecure.debugMode&&console.log("output url is ",n),e.respondWith(fetch(n,{mode:"cors",headers:o}).then(function(r){if(r.ok)return r;throw dexecure.debugMode&&console.log("Responding with original image as optimiser was not reachable ",e.request.url),new Error("Unable to fetch optimised image")}).catch(function(r){return dexecure.debugMode&&(console.log("Sending original image as an error occured when trying to optimise ",e.request.url),console.log("The error was ",r)),fetch(e.request)}))}}));
<|endoftext|>


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

    addToHomescreen();

    var chart = Morris.Line({
        element: 'speedtest-chart',
        data: [],
        xkey: 'dateTime',
        ykeys: ['ping', 'download', 'upload'],
        labels: ['Ping [ms]', 'Down [Mbit/s]', 'Up [Mbit/s]'],
        lineColors: ['rgb(110, 110, 245)', 'rgb(234, 27, 19)', 'rgb(230, 100, 19)'],
        smooth: false,
        resize: true,
        continuousLine: true
    });

    function round(number, decimalPlaces) {
        decimalPlaces = decimalPlaces ? decimalPlaces : 0;
        var factor = Math.pow(10, decimalPlaces);
        return Math.round(number * factor) / factor;
    }

    function refresh() {
        $.ajax({
            type: 'GET',
            cache: false,
            url: 'log.php'
        }).done(function(log) {
            if (log.length === 0)
                alert('There are no log entries yet.');
            var chartData = [];
            for (var i = 0; i < log.length; i++) {
                chartData.push({
                    dateTime: log[i][0],
                    ping:     round(log[i][1], 0),
                    download: round(log[i][2], 1),
                    upload:   round(log[i][3], 1)
                });
            }
            chart.setData(chartData);
        }).fail(function() {
            alert('Log data could not be fetched :(');
        });
    }

    $(function () {
        $(window).focus(function() {
            refresh()
        });
        refresh();
    });
}());
<commit_msg>Hide point marks on lines<commit_after>(function() {
    'use strict';

    addToHomescreen();

    var chart = Morris.Line({
        element: 'speedtest-chart',
        data: [],
        xkey: 'dateTime',
        ykeys: ['ping', 'download', 'upload'],
        labels: ['Ping [ms]', 'Down [Mbit/s]', 'Up [Mbit/s]'],
        lineColors: ['rgb(110, 110, 245)', 'rgb(234, 27, 19)', 'rgb(230, 100, 19)'],
        pointSize: 0,
        smooth: false,
        resize: true,
        continuousLine: true
    });

    function round(number, decimalPlaces) {
        decimalPlaces = decimalPlaces ? decimalPlaces : 0;
        var factor = Math.pow(10, decimalPlaces);
        return Math.round(number * factor) / factor;
    }

    function refresh() {
        $.ajax({
            type: 'GET',
            cache: false,
            url: 'log.php'
        }).done(function(log) {
            if (log.length === 0)
                alert('There are no log entries yet.');
            var chartData = [];
            for (var i = 0; i < log.length; i++) {
                chartData.push({
                    dateTime: log[i][0],
                    ping:     round(log[i][1], 0),
                    download: round(log[i][2], 1),
                    upload:   round(log[i][3], 1)
                });
            }
            chart.setData(chartData);
        }).fail(function() {
            alert('Log data could not be fetched :(');
        });
    }

    $(function () {
        $(window).focus(function() {
            refresh()
        });
        refresh();
    });
}());
<|endoftext|>


<commit_before>searchSciHub = function(word){
  var query = word.selectionText;
  chrome.tabs.create({url: "http://sci-hub.io/" + query});
};

chrome.contextMenus.create({
  title: "Search DOI in sci-hub",
  contexts:["selection"],
  onclick: searchSciHub
});
<commit_msg>changed into sci-hub.cc because the old one (.io) is blocked<commit_after>searchSciHub = function(word){
  var query = word.selectionText;
  chrome.tabs.create({url: "http://sci-hub.cc/" + query});
};

chrome.contextMenus.create({
  title: "Search DOI in sci-hub",
  contexts:["selection"],
  onclick: searchSciHub
});
<|endoftext|>


<commit_before>gameUI.firePlayerBullet = function() {
  if (game.time.now > gameUI.bulletTime) {
    playerBullets = gameState.groups.playerBullets.getFirstExists(false)
    if (playerBullets) {
      playerBullets.reset(gameState.player.body.x + 16, gameState.player.body.y + 16)
      playerBullets.lifespan = 4000
      playerBullets.body.velocity.x = 1000
    }
  }
}

gameUI.fireBossAlienBullet = function(){
  if (game.time.now > gameUI.bulletTime) {
    bossAlienBullets = gameState.groups.bossAlienBullets.getFirstExists(false)
    if (bossAlienBullets) {
      bossAlienBullets.reset(gameState.bossAlien.body.x, gameState.bossAlien.body.y + (gameState.bossAlien.height / 2))
      bossAlienBullets.lifespan = 4000
      bossAlienBullets.body.velocity.x = -500
    }
  }
}

gameUI.spawnAliens = function(){
  // position the block of aliens
  aliens.x = 1230
  aliens.y = 285
  for (var y = 0; y < 4; y++) {
    for (var x = 0; x < 5; x++) {
      var alien = aliens.create(x * 70, y * 70, 'invader') // space between aliens
      alien.health = 10
      alien.damage = 50
      alien.body.bounce.y = 1
      alien.body.bounce.x = 1
      alien.anchor.x = 0.5
      alien.anchor.y = 0.5
      game.physics.arcade.enable(alien)
    }
  }
  gameUI.sendAliens()
}

gameUI.scatterAliens = function(){
  gameState.groups.aliens.forEach(function(alien){
    alien.body.velocity.y = gameUI.getRandomInt(-20, 20)
    alien.body.velocity.x = gameUI.getRandomInt(-20, 0)
  })
  gameState.groups.aliens.setAll('body.collideWorldBounds', true)
  gameUI.alienScatterEnabled = false
}

gameUI.sendAliens = function(){
  var tween = game.add.tween(aliens).to(
    { x: 60 },
    20000,
    Phaser.Easing.Linear.None,
    true)
  // gameState.groups.aliens.setAll('body.velocity.x', -200)
}

gameUI.updateScore = function(){
   gameUI.score += 10
   gameUI.scoreObject.text = "Score: " + gameUI.score
 }

gameUI.aliensExist = function(){
  return (gameState.groups.aliens.countLiving() > 0)
}

gameUI.hitAlien = function(bullet, alien){
  alien.health -= bullet.damage
  if (alien.health <= 0) gameUI.killAlien(alien)
  bullet.kill()
}

gameUI.killAlien = function(alien){
  var explosion = gameState.groups.explosions.getFirstExists(false)
  explosion.reset(alien.body.x, alien.body.y)
  alien.kill()
  explosion.play('explosion', 30, false, true)
  gameUI.updateScore()
}
gameUI.wipeAlien = function(alien){
  alien.kill()
}

gameUI.killAllAliens = function(){
  gameState.groups.aliens.forEach(gameUI.wipeAlien)
  gameState.bossAlien.kill()
}

gameUI.aliensDead = function(){
  return (gameState.groups.aliens.countLiving() === 0 && !gameState.bossAlien.alive)
}

gameUI.spawnAlienBoss = function(){
  bossAlien = gameState.bossAlien = game.add.sprite(900, 250, 'diamond')
  game.physics.arcade.enable(bossAlien)
  bossAlien.enableBody = true
  game.physics.arcade.enable(bossAlien)
  bossAlien.scale.setTo(1,1)
  bossAlien.anchor.x = 0.5
  bossAlien.anchor.y = 0.5

  var bossTween = game.add.tween(bossAlien).to(
  { x:400 },
  15000,
  Phaser.Easing.Linear.None,
  true,
  0,
  1000,
  true)
}

gameUI.upgradeGun= function(){
  gameUI.gunLevel++
  gameUI.firePlayerGunRate = Math.floor(gameUI.firePlayerGunRate * .75)+1
}

gameUI.shrinkBoss = function(boss, bullet){
  bullet.kill()
  gameState.bossAlien.scale.x *= .8 // makes boss 80% of size when hit
  gameState.bossAlien.scale.y *= .8
  if (gameState.bossAlien.scale.x <= 1) boss.kill() // boss dies at scale 1
}

gameUI.growBoss = function(){
  gameState.bossAlien.scale.x *= 1.25 // makes boss 125% of size
  gameState.bossAlien.scale.y *= 1.25
}

gameUI.hitPlayer = function(player, objectThatHits){
  objectThatHits.kill() // object that collides with player
  player.health -= objectThatHits.damage
  // if Player dies, kill him/her & reset the round & subtract 10% points
  if (player.health <= 0) {
    player.kill()
  }
}

gameUI.playerDead = function(player){
  return player.health <= 0
}

gameUI.respawnPlayer = function(){
  var player = gameState.player = game.add.sprite(32, game.world.height - 150, 'dude')
  game.physics.arcade.enable(player)
  player.body.bounce.y = 0.2
  player.body.collideWorldBounds = true
  player.health = 100
}

gameUI.getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
<commit_msg>aliens only come to first row that player spawn in<commit_after>gameUI.firePlayerBullet = function() {
  if (game.time.now > gameUI.bulletTime) {
    playerBullets = gameState.groups.playerBullets.getFirstExists(false)
    if (playerBullets) {
      playerBullets.reset(gameState.player.body.x + 16, gameState.player.body.y + 16)
      playerBullets.lifespan = 4000
      playerBullets.body.velocity.x = 1000
    }
  }
}

gameUI.fireBossAlienBullet = function(){
  if (game.time.now > gameUI.bulletTime) {
    bossAlienBullets = gameState.groups.bossAlienBullets.getFirstExists(false)
    if (bossAlienBullets) {
      bossAlienBullets.reset(gameState.bossAlien.body.x, gameState.bossAlien.body.y + (gameState.bossAlien.height / 2))
      bossAlienBullets.lifespan = 4000
      bossAlienBullets.body.velocity.x = -500
    }
  }
}

gameUI.spawnAliens = function(){
  // position the block of aliens
  aliens.x = 1230
  aliens.y = 285
  for (var y = 0; y < 4; y++) {
    for (var x = 0; x < 5; x++) {
      var alien = aliens.create(x * 70, y * 70, 'invader') // space between aliens
      alien.health = 10
      alien.damage = 50
      alien.body.bounce.y = 1
      alien.body.bounce.x = 1
      alien.anchor.x = 0.5
      alien.anchor.y = 0.5
      game.physics.arcade.enable(alien)
    }
  }
  gameUI.sendAliens()
}

gameUI.scatterAliens = function(){
  gameState.groups.aliens.forEach(function(alien){
    alien.body.velocity.y = gameUI.getRandomInt(-20, 20)
    alien.body.velocity.x = gameUI.getRandomInt(-20, 0)
  })
  gameState.groups.aliens.setAll('body.collideWorldBounds', true)
  gameUI.alienScatterEnabled = false
}

gameUI.sendAliens = function(){
  var tween = game.add.tween(aliens)
  .to(
    { x: 90 },
    2000,
    Phaser.Easing.Linear.None,
    true)
}

gameUI.updateScore = function(){
   gameUI.score += 10
   gameUI.scoreObject.text = "Score: " + gameUI.score
 }

gameUI.aliensExist = function(){
  return (gameState.groups.aliens.countLiving() > 0)
}

gameUI.hitAlien = function(bullet, alien){
  alien.health -= bullet.damage
  if (alien.health <= 0) gameUI.killAlien(alien)
  bullet.kill()
}

gameUI.killAlien = function(alien){
  var explosion = gameState.groups.explosions.getFirstExists(false)
  explosion.reset(alien.body.x, alien.body.y)
  alien.kill()
  explosion.play('explosion', 30, false, true)
  gameUI.updateScore()
}
gameUI.wipeAlien = function(alien){
  alien.kill()
}

gameUI.killAllAliens = function(){
  gameState.groups.aliens.forEach(gameUI.wipeAlien)
  gameState.bossAlien.kill()
}

gameUI.aliensDead = function(){
  return (gameState.groups.aliens.countLiving() === 0 && !gameState.bossAlien.alive)
}

gameUI.spawnAlienBoss = function(){
  bossAlien = gameState.bossAlien = game.add.sprite(900, 250, 'diamond')
  game.physics.arcade.enable(bossAlien)
  bossAlien.enableBody = true
  game.physics.arcade.enable(bossAlien)
  bossAlien.scale.setTo(1,1)
  bossAlien.anchor.x = 0.5
  bossAlien.anchor.y = 0.5

  var bossTween = game.add.tween(bossAlien).to(
  { x:400 },
  15000,
  Phaser.Easing.Linear.None,
  true,
  0,
  1000,
  true)
}

gameUI.upgradeGun= function(){
  gameUI.gunLevel++
  gameUI.firePlayerGunRate = Math.floor(gameUI.firePlayerGunRate * .75)+1
}

gameUI.shrinkBoss = function(boss, bullet){
  bullet.kill()
  gameState.bossAlien.scale.x *= .8 // makes boss 80% of size when hit
  gameState.bossAlien.scale.y *= .8
  if (gameState.bossAlien.scale.x <= 1) boss.kill() // boss dies at scale 1
}

gameUI.growBoss = function(){
  gameState.bossAlien.scale.x *= 1.25 // makes boss 125% of size
  gameState.bossAlien.scale.y *= 1.25
}

gameUI.hitPlayer = function(player, objectThatHits){
  objectThatHits.kill() // object that collides with player
  player.health -= objectThatHits.damage
  // if Player dies, kill him/her & reset the round & subtract 10% points
  if (player.health <= 0) {
    player.kill()
  }
}

gameUI.playerDead = function(player){
  return player.health <= 0
}

gameUI.respawnPlayer = function(){
  var player = gameState.player = game.add.sprite(32, game.world.height - 150, 'dude')
  game.physics.arcade.enable(player)
  player.body.bounce.y = 0.2
  player.body.collideWorldBounds = true
  player.health = 100
}

gameUI.getRandomInt = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
<|endoftext|>


<commit_before>// Handlebars Helpers
Handlebars.registerHelper('pluralize', function(count, singular, plural) {
  if (count === 1) {
    return String(count) + " " + singular;
  } else {
    if (typeof plural === "string") {
      return String(count) + " " + plural;
    } else {
      return String(count) + " " + singular + "s";
    }
  }
});

Handlebars.registerHelper('dist', function(miles) {
  var MILES_TO_FEET = 5280;
  if (miles >= 1) {
    return  miles.toFixed(1) + " miles";
  }
  else{
    var feet = Math.round(miles * MILES_TO_FEET);
    return (feet == 1) ? "1 foot" : feet + " feet";
  }
});

Handlebars.registerHelper('timeAgo', function(time) {
  var units = [
    { name: "second", limit: 60, in_seconds: 1 },
    { name: "minute", limit: 3600, in_seconds: 60 },
    { name: "hour", limit: 86400, in_seconds: 3600  },
    { name: "day", limit: 604800, in_seconds: 86400 },
    { name: "week", limit: 2629743, in_seconds: 604800  },
    { name: "month", limit: 31556926, in_seconds: 2629743 },
    { name: "year", limit: null, in_seconds: 31556926 }
  ];
  var diff = (new Date() - new Date(time)) / 1000;
  if (diff < 5) return "now";

  var i = 0, unit;
  while (unit = units[i++]) {
    if (diff < unit.limit || !unit.limit){
      diff =  Math.floor(diff / unit.in_seconds);
      return diff + " " + unit.name + (diff>1 ? "s" : "");
    }
  }
});

// Array helpers
Array.prototype.updateDropsArray = function (func, oldArray, otherArray, limit){
  var newArray = this;
  newArray.forEach(function(dropData){
    // console.log(dropData)
    if ($.inArray(dropData.id, oldArray.map(function(obj){return obj.id;})) == -1 ){//its not in the clickable drops so add it
        if (oldArray.length>=limit){
          oldArray.pop();
        }//check the threshold and see the length of clickable
        func(dropData);
      }
    var outIndex =  $.inArray(dropData.id, otherArray.map(function(obj){return obj.id;}));
    if (outIndex != -1){//it was outside but now inside so remove that from the old outside
      debugger;
      var kill = oldArray[outIndex];
      kill.marker.setMap(null);//not needed but take it off the map before destorying incase of ZOMBIE points
      // delete kill;
      oldArray.splice(outIndex,1);
    }
  });
};

// jQuery helpers
$.fn.exists = function () {
    return this.length !== 0;
};
<commit_msg>added debounce as a helper method<commit_after>// Handlebars Helpers
Handlebars.registerHelper('pluralize', function(count, singular, plural) {
  if (count === 1) {
    return String(count) + " " + singular;
  } else {
    if (typeof plural === "string") {
      return String(count) + " " + plural;
    } else {
      return String(count) + " " + singular + "s";
    }
  }
});

Handlebars.registerHelper('dist', function(miles) {
  var MILES_TO_FEET = 5280;
  if (miles >= 1) {
    return  miles.toFixed(1) + " miles";
  }
  else{
    var feet = Math.round(miles * MILES_TO_FEET);
    return (feet == 1) ? "1 foot" : feet + " feet";
  }
});

Handlebars.registerHelper('timeAgo', function(time) {
  var units = [
    { name: "second", limit: 60, in_seconds: 1 },
    { name: "minute", limit: 3600, in_seconds: 60 },
    { name: "hour", limit: 86400, in_seconds: 3600  },
    { name: "day", limit: 604800, in_seconds: 86400 },
    { name: "week", limit: 2629743, in_seconds: 604800  },
    { name: "month", limit: 31556926, in_seconds: 2629743 },
    { name: "year", limit: null, in_seconds: 31556926 }
  ];
  var diff = (new Date() - new Date(time)) / 1000;
  if (diff < 5) return "now";

  var i = 0, unit;
  while (unit = units[i++]) {
    if (diff < unit.limit || !unit.limit){
      diff =  Math.floor(diff / unit.in_seconds);
      return diff + " " + unit.name + (diff>1 ? "s" : "");
    }
  }
});

// Array helpers
Array.prototype.updateDropsArray = function (func, oldArray, otherArray, limit){
  var newArray = this;
  newArray.forEach(function(dropData){
    // console.log(dropData)
    if ($.inArray(dropData.id, oldArray.map(function(obj){return obj.id;})) == -1 ){//its not in the clickable drops so add it
        if (oldArray.length>=limit){
          oldArray.pop();
        }//check the threshold and see the length of clickable
        func(dropData);
      }
    var outIndex =  $.inArray(dropData.id, otherArray.map(function(obj){return obj.id;}));
    if (outIndex != -1){//it was outside but now inside so remove that from the old outside
      debugger;
      var kill = oldArray[outIndex];
      kill.marker.setMap(null);//not needed but take it off the map before destorying incase of ZOMBIE points
      // delete kill;
      oldArray.splice(outIndex,1);
    }
  });
};

// jQuery helpers
$.fn.exists = function () {
    return this.length !== 0;
};

function debounce(func, delay){
  var timeoutID = null;
  return function(){
      var context = this, args = arguments;
      clearTimeout(timeoutID);
      timeoutID = setTimeout(function(){
        func.apply(context, args);
      }, delay);
    };
};
<|endoftext|>


<commit_before>var old; // Old CpuInfo

window.onload = function() {
  var cpu = document.querySelector('#info');
  chrome.system.cpu.getInfo(function(c) {
    cpu.innerHTML += '
model name	' + c.modelName +
                     '
';
    cpu.innerHTML += '
arch name	' + c.archName + '
';
    cpu.innerHTML += '
feature	' + c.features + '
';
  });

  chrome.system.cpu.getInfo(function(c) {
    old = c;
  });
  UpdateAll();
  window.setInterval(UpdateAll, 1000);
};

function Byte2MiB(byte) {
  return byte/1048576;
}

function Byte2GiB(byte) {
  return byte/1073741824;
}

function UpdateCpu() {
  var cpu = document.querySelector('#usage');
  cpu.innerHTML = '
cpu	' +
                  'user	' +
                  'kernel	' +
                  'idle
';
  chrome.system.cpu.getInfo(function(c) {
    for (var i = 0; i < c.numOfProcessors; i++) {
      var total = c.processors[i].usage.total - old.processors[i].usage.total;
      var user = c.processors[i].usage.user - old.processors[i].usage.user;
      var kernel = c.processors[i].usage.kernel -
                   old.processors[i].usage.kernel;
      var idle = c.processors[i].usage.idle - old.processors[i].usage.idle;
      cpu.innerHTML += '
' + i + '	' +
                       '' + Math.round(user/total*100) + '	' +
                       '' + Math.round(kernel/total*100) + '	' +
                       '' + Math.round(idle/total*100) + '
';
    }
    old = c;
  });
}

function UpdateMem() {
  var mem = document.querySelector('#memory');
  mem.innerHTML = '
total (MiB)'+
                  '	available (MiB)
';
  chrome.system.memory.getInfo(function(m) {
    mem.innerHTML += '
' + Math.round(m.capacity/1048576) +
                     '	' + Math.round(m.availableCapacity/1048576) +
                     '
';
  });
}

function UpdateStorage() {
  var sto = document.querySelector('#storage');
  sto.innerHTML = '
id	' +
                  'name	' +
                  'type	' +
                  'capacity (MiB)
';
  chrome.system.storage.getInfo(function(s) {
    for (var i = 0; i < s.length; i++) {
      sto.innerHTML += '
' + s[i].id +
                       '	' + s[i].name +
                       '	' + s[i].type +
                       '	' + Math.round(Byte2MiB(s[i].capacity)) +
                       '
';
    }
  });
}

function UpdateDisplay() {
  var lcd = document.querySelector('#display');
  lcd.innerHTML = '
primary	name	' +
                  'resolution	' +
                  'dpi	';
  chrome.system.display.getInfo(function(d) {
    for (var i = 0; i < d.length; i++) {
      lcd.innerHTML += '
' + d[i].isPrimary +
                       '	' + d[i].name +
                       '	' + d[i].bounds.width +
                       'x' + d[i].bounds.height +
                       '	' + d[i].dpiX + '
';
    }
  });
}

function UpdateAll() {
  UpdateCpu();
  UpdateMem();
  UpdateStorage();
  UpdateDisplay();
}
<commit_msg>fix window flashing issue by revising innerHTML usage<commit_after>var old; // Old CpuInfo

window.onload = function() {
  var cpu = document.querySelector('#info');
  chrome.system.cpu.getInfo(function(c) {
    cpu.innerHTML += '
model name	' + c.modelName +
                     '
';
    cpu.innerHTML += '
arch name	' + c.archName + '
';
    cpu.innerHTML += '
feature	' + c.features + '
';
  });

  chrome.system.cpu.getInfo(function(c) {
    old = c;
  });
  UpdateAll();
  window.setInterval(UpdateAll, 1000);
};

function Byte2MiB(byte) {
  return byte/1048576;
}

function Byte2GiB(byte) {
  return byte/1073741824;
}

function UpdateCpu() {
  var cpu = document.querySelector('#usage');
  var htm = '
cpu	' +
                  'user	' +
                  'kernel	' +
                  'idle
';
  chrome.system.cpu.getInfo(function(c) {
    for (var i = 0; i < c.numOfProcessors; i++) {
      var total = c.processors[i].usage.total - old.processors[i].usage.total;
      var user = c.processors[i].usage.user - old.processors[i].usage.user;
      var kernel = c.processors[i].usage.kernel -
                   old.processors[i].usage.kernel;
      var idle = c.processors[i].usage.idle - old.processors[i].usage.idle;
      htm += '
' + i + '	' +
                       '' + Math.round(user/total*100) + '	' +
                       '' + Math.round(kernel/total*100) + '	' +
                       '' + Math.round(idle/total*100) + '
';
    }
    cpu.innerHTML = htm;
    old = c;
  });
}

function UpdateMem() {
  var mem = document.querySelector('#memory');
  var htm = '
total (MiB)'+
                  '	available (MiB)
';
  chrome.system.memory.getInfo(function(m) {
    htm += '
' + Math.round(m.capacity/1048576) +
                     '	' + Math.round(m.availableCapacity/1048576) +
                     '
';
    mem.innerHTML = htm;
  });
}

function UpdateStorage() {
  var sto = document.querySelector('#storage');
  var htm = '
id	' +
                  'name	' +
                  'type	' +
                  'capacity (MiB)
';
  chrome.system.storage.getInfo(function(s) {
    for (var i = 0; i < s.length; i++) {
      htm += '
' + s[i].id +
                       '	' + s[i].name +
                       '	' + s[i].type +
                       '	' + Math.round(Byte2MiB(s[i].capacity)) +
                       '
';
    }
    sto.innerHTML = htm;
  });
}

function UpdateDisplay() {
  var lcd = document.querySelector('#display');
  var htm = '
primary	name	' +
                  'resolution	' +
                  'dpi	';
  chrome.system.display.getInfo(function(d) {
    for (var i = 0; i < d.length; i++) {
      htm += '
' + d[i].isPrimary +
                       '	' + d[i].name +
                       '	' + d[i].bounds.width +
                       'x' + d[i].bounds.height +
                       '	' + d[i].dpiX + '
';
    }
    lcd.innerHTML = htm;
  });
}

function UpdateAll() {
  UpdateCpu();
  UpdateMem();
  UpdateStorage();
  UpdateDisplay();
}
<|endoftext|>


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

  $ (".project").each(function(i) {
    //console.log("TEST!");
    //console.log(this);
    $(this).click(function() {
      // $(element.id).css("test", "test");
      // targeted = element.target.id
      // targeted_id = targeted.split("-");
      clickedButton = $(this).attr("id");
      clickedButtonId = ("#").concat(clickedButton)
      clickedButtonElement = (".").concat(clickedButton)
      clickedButtonActual = ("pick-").concat(clickedButton);

      console.log("CLICKED:");
      console.log(clickedButton);

      if(!$(clickedButtonElement).is(':visible')) {
        $(clickedButtonElement).fadeToggle("fast", "swing", function() {
          $(clickedButtonElement).css("display", "inline-block");
        });
        console.log("IS VISIBLE, TURNING OFF")
      }
      else {
        $(clickedButtonElement).fadeToggle("fast", "swing");
        console.log("IS INVISIBLE, TURNING OFF")
      }

      $(clickedButtonActual).toggleClass("btn-success");
      console.log("DONE:");
      console.log(clickedButtonActual)
    });
  });

  /*
  $(".pick-addition").click(function()
    {
      $(".addition").fadeToggle("fast", "swing", function () {
        $(".addition").css("display", "inline-block");
      });
      $(".pick-addition").toggleClass("btn-success");
    });

  $(".pick-window").click(function()
    {
      $(".window").fadeToggle("fast","swing");
      $(".pick-window").toggleClass("btn-success");
    });

  $(".pick-door").click(function()
    {
      $(".door").fadeToggle("fast","swing");
      $(".pick-door").toggleClass("btn-success");
    });

  $(".pick-wall").click(function()
    {
      $(".wall").fadeToggle("fast","swing");
      $(".pick-wall").toggleClass("btn-success");
    });

  $(".pick-siding").click(function()
    {
      $(".siding").fadeToggle("fast","swing");
      $(".pick-siding").toggleClass("btn-success");
    });

  $(".pick-floor").click(function()
    {
      $(".floor").fadeToggle("fast","swing");
      $(".pick-floor").toggleClass("btn-success");
    });

  $(".pick-cover").click(function()
    {
      $(".cover").fadeToggle("fast","swing");
      $(".pick-cover").toggleClass("btn-success");
    });

  $(".pick-pool").click(function()
    {
      $(".pool").fadeToggle("fast","swing");
      $(".pick-pool").toggleClass("btn-success");
    });

  $(".pick-deck").click(function()
    {
      $(".deck").fadeToggle("fast","swing");
      $(".pick-deck").toggleClass("btn-success");
    });

  $(".pick-acs-struct").click(function()
    {
      $(".acs-struct").fadeToggle("fast","swing");
      $(".pick-acs-struct").toggleClass("btn-success");
    });
    */

 });<commit_msg>Add refactored javascript for click action on sidebar projects<commit_after>$(document).ready(function() {
  $ (".project").each(function(i) {
    $(this).click(function() {
      clickedButton = $(this).attr("id");
      buttonId = ("#").concat(clickedButton)
      chosenProject = (".").concat(clickedButton)
      clickedButtonClass = ("pick-").concat(clickedButton);

      $(chosenProject).toggleClass("displayed");
      $(clickedButtonClass).toggleClass("btn-success");
    });
  });

  /*
  $(".pick-addition").click(function()
    {
      $(".addition").fadeToggle("fast", "swing", function () {
        $(".addition").css("display", "inline-block");
      });
      $(".pick-addition").toggleClass("btn-success");
    });

  $(".pick-window").click(function()
    {
      $(".window").fadeToggle("fast","swing");
      $(".pick-window").toggleClass("btn-success");
    });

  $(".pick-door").click(function()
    {
      $(".door").fadeToggle("fast","swing");
      $(".pick-door").toggleClass("btn-success");
    });

  $(".pick-wall").click(function()
    {
      $(".wall").fadeToggle("fast","swing");
      $(".pick-wall").toggleClass("btn-success");
    });

  $(".pick-siding").click(function()
    {
      $(".siding").fadeToggle("fast","swing");
      $(".pick-siding").toggleClass("btn-success");
    });

  $(".pick-floor").click(function()
    {
      $(".floor").fadeToggle("fast","swing");
      $(".pick-floor").toggleClass("btn-success");
    });

  $(".pick-cover").click(function()
    {
      $(".cover").fadeToggle("fast","swing");
      $(".pick-cover").toggleClass("btn-success");
    });

  $(".pick-pool").click(function()
    {
      $(".pool").fadeToggle("fast","swing");
      $(".pick-pool").toggleClass("btn-success");
    });

  $(".pick-deck").click(function()
    {
      $(".deck").fadeToggle("fast","swing");
      $(".pick-deck").toggleClass("btn-success");
    });

  $(".pick-acs-struct").click(function()
    {
      $(".acs-struct").fadeToggle("fast","swing");
      $(".pick-acs-struct").toggleClass("btn-success");
    });
    */

 });<|endoftext|>


<commit_before><commit_msg>Update project covjson-reader to 0.3.2<commit_after><|endoftext|>


<commit_before>var _prum = [['id', '549d6b20abe53d5f54d29579'],
             ['mark', 'firstbyte', (new Date()).getTime()]];
(function() {
    var s = document.getElementsByTagName('script')[0]
      , p = document.createElement('script');
    p.async = 'async';
    p.src = '//rum-static.pingdom.net/prum.min.js';
    s.parentNode.insertBefore(p, s);
})();
<commit_msg>Delete pingdom.js<commit_after><|endoftext|>


<commit_before>// = require_self

(function ($) {
  'use strict'
  window.GOVUK = window.GOVUK || {}

  var takeSurveyLink = function (text, className) {
    className = className ? 'class="' + className + '"' : ''
    return '' + text + ''
  }

  var templateBase = function (children) {
    return (
      '
' +
      '
' +
      '    Close' +
      '
Tell us what you think of GOV.UK
' +
           children +
      '
' +
      '
'
    )
  }

  var URL_SURVEY_TEMPLATE = templateBase(
    '
' +
      takeSurveyLink('Take the 3 minute survey', 'survey-primary-link') +
    '  This will open a short survey on another website' +
    '
'
  )
  var EMAIL_SURVEY_TEMPLATE = templateBase(
    '
' +
    '  ' +
    '    Take a short survey to give us your feedback' +
    '  ' +
    '
' +
    '<form id="email-survey-form" action="/contact/govuk/email-survey-signup" method="post" class="js-hidden" aria-hidden="true">' +
    '
' +
    '
We’ll send you a link to a feedback form. It only takes 2 minutes to fill in.
 Don’t worry: we won’t send you spam or share your email address with anyone.
' +
    '    ' +
    '      Email Address' +
    '    ' +
    '    <input name="email_survey_signup[survey_id]" type="hidden" value="">' +
    '    <input name="email_survey_signup[survey_source]" type="hidden" value="">' +
    '    <input class="survey-form-input" name="email_survey_signup[email_address]" id="survey-email-address" type="text" aria-describedby="survey-form-description">' +
    '    <button class="survey-form-button" type="submit">Send me the survey</button>' +
         takeSurveyLink('Don’t have an email address?') +
    '
' +
    '</form>' +
    '
' +
    '  Thanks, we’ve sent you an email with a link to the survey.' +
    '
' +
    '
' +
    '  Sorry, we’re unable to send you an email right now.  Please try again later.' +
    '
'
  )
  var SURVEY_SEEN_TOO_MANY_TIMES_LIMIT = 2

  /* This data structure is explained in `doc/surveys.md` */
  var userSurveys = {
    defaultSurvey: {
      url: 'https://www.smartsurvey.co.uk/s/gov_uk',
      identifier: 'user_satisfaction_survey',
      frequency: 10,
      surveyType: 'email'
    },
    smallSurveys: [
    ],

    init: function () {
      if (userSurveys.canShowAnySurvey()) {
        var activeSurvey = userSurveys.getActiveSurvey(userSurveys.defaultSurvey, userSurveys.smallSurveys)
        if (activeSurvey !== undefined) {
          userSurveys.displaySurvey(activeSurvey)
        }
      }
    },

    canShowAnySurvey: function() {
      if (userSurveys.pathInBlacklist()) {
        return false
      } else if (userSurveys.otherNotificationVisible()) {
        return false
      } else if (userSurveys.userCompletedTransaction()) {
        // We don't want any survey appearing for users who have completed a
        // transaction as they may complete the survey with the department's
        // transaction in mind as opposed to the GOV.UK content.
        return false
      } else if ($('#user-satisfaction-survey-container').length <= 0) {
        return false
      } else {
        return true
      }
    },

    getActiveSurveys: function (surveys) {
      return $.grep(surveys, function (survey, _index) {
        if (userSurveys.currentTime() >= survey.startTime && userSurveys.currentTime() <= survey.endTime) {
          if (typeof (survey.activeWhen) === 'function') {
            return survey.activeWhen()
          } else {
            return true
          }
        }
      })
    },

    getDisplayableSurveys: function (surveys) {
      return $.grep(surveys, function (survey, _index) {
        return userSurveys.isSurveyToBeDisplayed(survey)
      })
    },

    getActiveSurvey: function (defaultSurvey, smallSurveys) {
      var activeSurveys = userSurveys.getActiveSurveys(smallSurveys)
      var allSurveys = [defaultSurvey].concat(activeSurveys)
      var displayableSurveys = userSurveys.getDisplayableSurveys(allSurveys)

      if (displayableSurveys.length < 1) {
        return displayableSurveys[0]
      } else {
        // At this point, if there are multiple surveys that could be shown
        // it is fair to roll the dice and pick one; we've already considered
        // frequency in isSurveyToBeDisplayed so we don't need to worry about
        // it here
        return displayableSurveys[Math.floor(Math.random() * displayableSurveys.length)]
      }
    },

    displaySurvey: function (survey) {
      var surveyContainer = $('#user-satisfaction-survey-container')
      if (survey.surveyType === 'email') {
        userSurveys.displayEmailSurvey(survey, surveyContainer)
      } else if ((survey.surveyType === 'url') || (survey.surveyType === undefined)) {
        userSurveys.displayURLSurvey(survey, surveyContainer)
      } else {
        return
      }
      userSurveys.incrementSurveySeenCounter(survey)
      userSurveys.trackEvent(survey.identifier, 'banner_shown', 'Banner has been shown')
    },

    displayURLSurvey: function (survey, surveyContainer) {
      surveyContainer.append(survey.template || URL_SURVEY_TEMPLATE)
      userSurveys.setURLSurveyLink(survey)
      userSurveys.setURLSurveyEventHandlers(survey)
    },

    displayEmailSurvey: function (survey, surveyContainer) {
      surveyContainer.append(survey.template || EMAIL_SURVEY_TEMPLATE)

      var $surveyId = $('#email-survey-form input[name="email_survey_signup[survey_id]"]')
      var $surveySource = $('#email-survey-form input[name="email_survey_signup[survey_source]"]')

      $surveyId.val(survey.identifier)
      $surveySource.val(userSurveys.currentPath())

      userSurveys.setURLSurveyLink(survey)
      userSurveys.setEmailSurveyEventHandlers(survey)
    },

    setURLSurveyLink: function (survey) {
      var $surveyLink = $('#take-survey')
      var surveyUrl = survey.url

      // Smart survey can record the URL of the survey link if passed through as a query param
      if ((/smartsurvey/.test(surveyUrl)) && (surveyUrl.indexOf('?c=') === -1)) {
        surveyUrl += '?c=' + userSurveys.currentPath()
      }

      $surveyLink.attr('href', surveyUrl)
    },

    setEmailSurveyEventHandlers: function (survey) {
      var $emailSurveyOpen = $('#email-survey-open')
      var $emailSurveyCancel = $('#user-survey-cancel')
      var $emailSurveyPre = $('#email-survey-pre')
      var $emailSurveyForm = $('#email-survey-form')
      var $emailSurveyPostSuccess = $('#email-survey-post-success')
      var $emailSurveyPostFailure = $('#email-survey-post-failure')
      var $emailSurveyField = $('#survey-email-address')
      var $takeSurvey = $('#take-survey')

      $takeSurvey.click(function () {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        userSurveys.trackEvent(survey.identifier, 'no_email_link', 'User taken survey via no email link')
      })

      $emailSurveyOpen.click(function (e) {
        survey.surveyExpanded = true
        userSurveys.trackEvent(survey.identifier, 'email_survey_open', 'Email survey opened')
        $emailSurveyPre.addClass('js-hidden').attr('aria-hidden', 'true')
        $emailSurveyForm.removeClass('js-hidden').attr('aria-hidden', 'false')
        $emailSurveyField.focus()
        e.stopPropagation()
        return false
      })

      $emailSurveyCancel.click(function (e) {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        if (survey.surveyExpanded) {
          userSurveys.trackEvent(survey.identifier, 'email_survey_cancel', 'Email survey cancelled')
        } else {
          userSurveys.trackEvent(survey.identifier, 'banner_no_thanks', 'No thanks clicked')
        }
        e.stopPropagation()
        return false
      })

      $emailSurveyForm.submit(function (e) {
        var successCallback = function () {
          $emailSurveyForm.addClass('js-hidden').attr('aria-hidden', 'true')
          $emailSurveyPostSuccess.removeClass('js-hidden').attr('aria-hidden', 'false')
          $emailSurveyPostSuccess.focus()
          userSurveys.setSurveyTakenCookie(survey)
          userSurveys.trackEvent(survey.identifier, 'email_survey_taken', 'Email survey taken')
          userSurveys.trackEvent(survey.identifier, 'banner_taken', 'User taken survey')
        }
        var errorCallback = function () {
          $emailSurveyForm.addClass('js-hidden').attr('aria-hidden', 'true')
          $emailSurveyPostFailure.removeClass('js-hidden').attr('aria-hidden', 'false')
          $emailSurveyPostFailure.focus()
        }
        var surveyFormUrl = $emailSurveyForm.attr('action')
        // make sure the survey form is a js url
        if (!(/\.js$/.test(surveyFormUrl))) {
          surveyFormUrl += '.js'
        }

        $.ajax({
          type: 'POST',
          url: surveyFormUrl,
          dataType: 'json',
          data: $emailSurveyForm.serialize(),
          success: successCallback,
          error: errorCallback,
          statusCode: {
            500: errorCallback
          }
        })
        e.stopPropagation()
        return false
      })
    },

    setURLSurveyEventHandlers: function (survey) {
      var $emailSurveyCancel = $('#user-survey-cancel')
      var $takeSurvey = $('#take-survey')

      $emailSurveyCancel.click(function (e) {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        userSurveys.trackEvent(survey.identifier, 'banner_no_thanks', 'No thanks clicked')
        e.stopPropagation()
        return false
      })
      $takeSurvey.click(function () {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        userSurveys.trackEvent(survey.identifier, 'banner_taken', 'User taken survey')
      })
    },

    isSurveyToBeDisplayed: function (survey) {
      if (GOVUK.cookie(userSurveys.surveyTakenCookieName(survey)) === 'true') {
        return false
      } else if (userSurveys.surveyHasBeenSeenTooManyTimes(survey)) {
        return false
      } else {
        return userSurveys.randomNumberMatches(survey.frequency)
      }
    },

    pathInBlacklist: function () {
      var blackList = new RegExp('^/(?:' +
        /service-manual/.source +
        // add more blacklist paths in the form:
        // + /|path-to\/blacklist/.source
        ')(?:\/|$)'
      )
      return blackList.test(userSurveys.currentPath())
    },

    userCompletedTransaction: function () {
      var path = userSurveys.currentPath()

      function stringContains (str, substr) {
        return str.indexOf(substr) > -1
      }

      if (stringContains(path, '/done') ||
          stringContains(path, '/transaction-finished') ||
          stringContains(path, '/driving-transaction-finished')) {
        return true
      }
    },

    trackEvent: function (identifier, action, label) {
      window.GOVUK.analytics.trackEvent(identifier, action, {
        label: label,
        value: 1,
        nonInteraction: true
      })
    },

    setSurveyTakenCookie: function (survey) {
      window.GOVUK.cookie(userSurveys.surveyTakenCookieName(survey), true, { days: 30 * 3 })
    },

    incrementSurveySeenCounter: function (survey) {
      var cookieName = userSurveys.surveySeenCookieName(survey)
      var seenCount = (userSurveys.surveySeenCount(survey) + 1)
      var cooloff = userSurveys.seenTooManyTimesCooloff(survey)
      if (cooloff) {
        window.GOVUK.cookie(cookieName, seenCount, { days: cooloff })
      } else {
        window.GOVUK.cookie(cookieName, seenCount)
      }
    },

    seenTooManyTimesCooloff: function (survey) {
      if (survey.seenTooManyTimesCooloff) {
        return extractNumber(survey.seenTooManyTimesCooloff, undefined, 1)
      } else {
        return undefined
      }
    },

    hideSurvey: function (_survey) {
      $('#user-satisfaction-survey').removeClass('visible').attr('aria-hidden', 'true')
    },

    randomNumberMatches: function (frequency) {
      return (Math.floor(Math.random() * frequency) === 0)
    },

    otherNotificationVisible: function () {
      var notificationIds = [
        '.govuk-emergency-banner:visible',
        '#global-cookie-message:visible',
        '#global-browser-prompt:visible',
        '#taxonomy-survey:visible'
      ]
      return $(notificationIds.join(', ')).length > 0
    },

    surveyHasBeenSeenTooManyTimes: function (survey) {
      return (userSurveys.surveySeenCount(survey) >= userSurveys.surveySeenTooManyTimesLimit(survey))
    },

    surveySeenTooManyTimesLimit: function (survey) {
      var limitValue = survey.seenTooManyTimesLimit
      if (String(limitValue).toLowerCase() === 'unlimited') {
        return Infinity
      } else {
        return extractNumber(limitValue, SURVEY_SEEN_TOO_MANY_TIMES_LIMIT, 1)
      }
    },

    surveySeenCount: function (survey) {
      return extractNumber(GOVUK.cookie(userSurveys.surveySeenCookieName(survey)), 0, 0)
    },

    surveyTakenCookieName: function (survey) {
      return generateCookieName('taken_' + survey.identifier)
    },

    surveySeenCookieName: function (survey) {
      return generateCookieName('survey_seen_' + survey.identifier)
    },

    currentTime: function () { return new Date().getTime() },
    currentPath: function () { return window.location.pathname }
  }

  var generateCookieName = function (cookieName) {
      // taken_user_satisfaction_survey => takenUserSatisfactionSurvey
    var cookieStub = cookieName.replace(/(\_\w)/g, function (m) {
      return m.charAt(1).toUpperCase()
    })
    return 'govuk_' + cookieStub
  }

  var extractNumber = function (value, defaultValue, limit) {
    var parsedValue = parseInt(value, 10)
    if (isNaN(parsedValue) || (parsedValue < limit)) {
      return defaultValue
    } else {
      return parsedValue
    }
  }

  window.GOVUK.userSurveys = userSurveys

  $(document).ready(function () {
    if (window.GOVUK.userSurveys) {
      window.GOVUK.userSurveys.init()
    }
  })
})(window.jQuery)
<commit_msg>Make the default survey appear 1 in 6 times<commit_after>// = require_self

(function ($) {
  'use strict'
  window.GOVUK = window.GOVUK || {}

  var takeSurveyLink = function (text, className) {
    className = className ? 'class="' + className + '"' : ''
    return '' + text + ''
  }

  var templateBase = function (children) {
    return (
      '
' +
      '
' +
      '    Close' +
      '
Tell us what you think of GOV.UK
' +
           children +
      '
' +
      '
'
    )
  }

  var URL_SURVEY_TEMPLATE = templateBase(
    '
' +
      takeSurveyLink('Take the 3 minute survey', 'survey-primary-link') +
    '  This will open a short survey on another website' +
    '
'
  )
  var EMAIL_SURVEY_TEMPLATE = templateBase(
    '
' +
    '  ' +
    '    Take a short survey to give us your feedback' +
    '  ' +
    '
' +
    '<form id="email-survey-form" action="/contact/govuk/email-survey-signup" method="post" class="js-hidden" aria-hidden="true">' +
    '
' +
    '
We’ll send you a link to a feedback form. It only takes 2 minutes to fill in.
 Don’t worry: we won’t send you spam or share your email address with anyone.
' +
    '    ' +
    '      Email Address' +
    '    ' +
    '    <input name="email_survey_signup[survey_id]" type="hidden" value="">' +
    '    <input name="email_survey_signup[survey_source]" type="hidden" value="">' +
    '    <input class="survey-form-input" name="email_survey_signup[email_address]" id="survey-email-address" type="text" aria-describedby="survey-form-description">' +
    '    <button class="survey-form-button" type="submit">Send me the survey</button>' +
         takeSurveyLink('Don’t have an email address?') +
    '
' +
    '</form>' +
    '
' +
    '  Thanks, we’ve sent you an email with a link to the survey.' +
    '
' +
    '
' +
    '  Sorry, we’re unable to send you an email right now.  Please try again later.' +
    '
'
  )
  var SURVEY_SEEN_TOO_MANY_TIMES_LIMIT = 2

  /* This data structure is explained in `doc/surveys.md` */
  var userSurveys = {
    defaultSurvey: {
      url: 'https://www.smartsurvey.co.uk/s/gov_uk',
      identifier: 'user_satisfaction_survey',
      frequency: 6,
      surveyType: 'email'
    },
    smallSurveys: [
    ],

    init: function () {
      if (userSurveys.canShowAnySurvey()) {
        var activeSurvey = userSurveys.getActiveSurvey(userSurveys.defaultSurvey, userSurveys.smallSurveys)
        if (activeSurvey !== undefined) {
          userSurveys.displaySurvey(activeSurvey)
        }
      }
    },

    canShowAnySurvey: function() {
      if (userSurveys.pathInBlacklist()) {
        return false
      } else if (userSurveys.otherNotificationVisible()) {
        return false
      } else if (userSurveys.userCompletedTransaction()) {
        // We don't want any survey appearing for users who have completed a
        // transaction as they may complete the survey with the department's
        // transaction in mind as opposed to the GOV.UK content.
        return false
      } else if ($('#user-satisfaction-survey-container').length <= 0) {
        return false
      } else {
        return true
      }
    },

    getActiveSurveys: function (surveys) {
      return $.grep(surveys, function (survey, _index) {
        if (userSurveys.currentTime() >= survey.startTime && userSurveys.currentTime() <= survey.endTime) {
          if (typeof (survey.activeWhen) === 'function') {
            return survey.activeWhen()
          } else {
            return true
          }
        }
      })
    },

    getDisplayableSurveys: function (surveys) {
      return $.grep(surveys, function (survey, _index) {
        return userSurveys.isSurveyToBeDisplayed(survey)
      })
    },

    getActiveSurvey: function (defaultSurvey, smallSurveys) {
      var activeSurveys = userSurveys.getActiveSurveys(smallSurveys)
      var allSurveys = [defaultSurvey].concat(activeSurveys)
      var displayableSurveys = userSurveys.getDisplayableSurveys(allSurveys)

      if (displayableSurveys.length < 1) {
        return displayableSurveys[0]
      } else {
        // At this point, if there are multiple surveys that could be shown
        // it is fair to roll the dice and pick one; we've already considered
        // frequency in isSurveyToBeDisplayed so we don't need to worry about
        // it here
        return displayableSurveys[Math.floor(Math.random() * displayableSurveys.length)]
      }
    },

    displaySurvey: function (survey) {
      var surveyContainer = $('#user-satisfaction-survey-container')
      if (survey.surveyType === 'email') {
        userSurveys.displayEmailSurvey(survey, surveyContainer)
      } else if ((survey.surveyType === 'url') || (survey.surveyType === undefined)) {
        userSurveys.displayURLSurvey(survey, surveyContainer)
      } else {
        return
      }
      userSurveys.incrementSurveySeenCounter(survey)
      userSurveys.trackEvent(survey.identifier, 'banner_shown', 'Banner has been shown')
    },

    displayURLSurvey: function (survey, surveyContainer) {
      surveyContainer.append(survey.template || URL_SURVEY_TEMPLATE)
      userSurveys.setURLSurveyLink(survey)
      userSurveys.setURLSurveyEventHandlers(survey)
    },

    displayEmailSurvey: function (survey, surveyContainer) {
      surveyContainer.append(survey.template || EMAIL_SURVEY_TEMPLATE)

      var $surveyId = $('#email-survey-form input[name="email_survey_signup[survey_id]"]')
      var $surveySource = $('#email-survey-form input[name="email_survey_signup[survey_source]"]')

      $surveyId.val(survey.identifier)
      $surveySource.val(userSurveys.currentPath())

      userSurveys.setURLSurveyLink(survey)
      userSurveys.setEmailSurveyEventHandlers(survey)
    },

    setURLSurveyLink: function (survey) {
      var $surveyLink = $('#take-survey')
      var surveyUrl = survey.url

      // Smart survey can record the URL of the survey link if passed through as a query param
      if ((/smartsurvey/.test(surveyUrl)) && (surveyUrl.indexOf('?c=') === -1)) {
        surveyUrl += '?c=' + userSurveys.currentPath()
      }

      $surveyLink.attr('href', surveyUrl)
    },

    setEmailSurveyEventHandlers: function (survey) {
      var $emailSurveyOpen = $('#email-survey-open')
      var $emailSurveyCancel = $('#user-survey-cancel')
      var $emailSurveyPre = $('#email-survey-pre')
      var $emailSurveyForm = $('#email-survey-form')
      var $emailSurveyPostSuccess = $('#email-survey-post-success')
      var $emailSurveyPostFailure = $('#email-survey-post-failure')
      var $emailSurveyField = $('#survey-email-address')
      var $takeSurvey = $('#take-survey')

      $takeSurvey.click(function () {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        userSurveys.trackEvent(survey.identifier, 'no_email_link', 'User taken survey via no email link')
      })

      $emailSurveyOpen.click(function (e) {
        survey.surveyExpanded = true
        userSurveys.trackEvent(survey.identifier, 'email_survey_open', 'Email survey opened')
        $emailSurveyPre.addClass('js-hidden').attr('aria-hidden', 'true')
        $emailSurveyForm.removeClass('js-hidden').attr('aria-hidden', 'false')
        $emailSurveyField.focus()
        e.stopPropagation()
        return false
      })

      $emailSurveyCancel.click(function (e) {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        if (survey.surveyExpanded) {
          userSurveys.trackEvent(survey.identifier, 'email_survey_cancel', 'Email survey cancelled')
        } else {
          userSurveys.trackEvent(survey.identifier, 'banner_no_thanks', 'No thanks clicked')
        }
        e.stopPropagation()
        return false
      })

      $emailSurveyForm.submit(function (e) {
        var successCallback = function () {
          $emailSurveyForm.addClass('js-hidden').attr('aria-hidden', 'true')
          $emailSurveyPostSuccess.removeClass('js-hidden').attr('aria-hidden', 'false')
          $emailSurveyPostSuccess.focus()
          userSurveys.setSurveyTakenCookie(survey)
          userSurveys.trackEvent(survey.identifier, 'email_survey_taken', 'Email survey taken')
          userSurveys.trackEvent(survey.identifier, 'banner_taken', 'User taken survey')
        }
        var errorCallback = function () {
          $emailSurveyForm.addClass('js-hidden').attr('aria-hidden', 'true')
          $emailSurveyPostFailure.removeClass('js-hidden').attr('aria-hidden', 'false')
          $emailSurveyPostFailure.focus()
        }
        var surveyFormUrl = $emailSurveyForm.attr('action')
        // make sure the survey form is a js url
        if (!(/\.js$/.test(surveyFormUrl))) {
          surveyFormUrl += '.js'
        }

        $.ajax({
          type: 'POST',
          url: surveyFormUrl,
          dataType: 'json',
          data: $emailSurveyForm.serialize(),
          success: successCallback,
          error: errorCallback,
          statusCode: {
            500: errorCallback
          }
        })
        e.stopPropagation()
        return false
      })
    },

    setURLSurveyEventHandlers: function (survey) {
      var $emailSurveyCancel = $('#user-survey-cancel')
      var $takeSurvey = $('#take-survey')

      $emailSurveyCancel.click(function (e) {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        userSurveys.trackEvent(survey.identifier, 'banner_no_thanks', 'No thanks clicked')
        e.stopPropagation()
        return false
      })
      $takeSurvey.click(function () {
        userSurveys.setSurveyTakenCookie(survey)
        userSurveys.hideSurvey(survey)
        userSurveys.trackEvent(survey.identifier, 'banner_taken', 'User taken survey')
      })
    },

    isSurveyToBeDisplayed: function (survey) {
      if (GOVUK.cookie(userSurveys.surveyTakenCookieName(survey)) === 'true') {
        return false
      } else if (userSurveys.surveyHasBeenSeenTooManyTimes(survey)) {
        return false
      } else {
        return userSurveys.randomNumberMatches(survey.frequency)
      }
    },

    pathInBlacklist: function () {
      var blackList = new RegExp('^/(?:' +
        /service-manual/.source +
        // add more blacklist paths in the form:
        // + /|path-to\/blacklist/.source
        ')(?:\/|$)'
      )
      return blackList.test(userSurveys.currentPath())
    },

    userCompletedTransaction: function () {
      var path = userSurveys.currentPath()

      function stringContains (str, substr) {
        return str.indexOf(substr) > -1
      }

      if (stringContains(path, '/done') ||
          stringContains(path, '/transaction-finished') ||
          stringContains(path, '/driving-transaction-finished')) {
        return true
      }
    },

    trackEvent: function (identifier, action, label) {
      window.GOVUK.analytics.trackEvent(identifier, action, {
        label: label,
        value: 1,
        nonInteraction: true
      })
    },

    setSurveyTakenCookie: function (survey) {
      window.GOVUK.cookie(userSurveys.surveyTakenCookieName(survey), true, { days: 30 * 3 })
    },

    incrementSurveySeenCounter: function (survey) {
      var cookieName = userSurveys.surveySeenCookieName(survey)
      var seenCount = (userSurveys.surveySeenCount(survey) + 1)
      var cooloff = userSurveys.seenTooManyTimesCooloff(survey)
      if (cooloff) {
        window.GOVUK.cookie(cookieName, seenCount, { days: cooloff })
      } else {
        window.GOVUK.cookie(cookieName, seenCount)
      }
    },

    seenTooManyTimesCooloff: function (survey) {
      if (survey.seenTooManyTimesCooloff) {
        return extractNumber(survey.seenTooManyTimesCooloff, undefined, 1)
      } else {
        return undefined
      }
    },

    hideSurvey: function (_survey) {
      $('#user-satisfaction-survey').removeClass('visible').attr('aria-hidden', 'true')
    },

    randomNumberMatches: function (frequency) {
      return (Math.floor(Math.random() * frequency) === 0)
    },

    otherNotificationVisible: function () {
      var notificationIds = [
        '.govuk-emergency-banner:visible',
        '#global-cookie-message:visible',
        '#global-browser-prompt:visible',
        '#taxonomy-survey:visible'
      ]
      return $(notificationIds.join(', ')).length > 0
    },

    surveyHasBeenSeenTooManyTimes: function (survey) {
      return (userSurveys.surveySeenCount(survey) >= userSurveys.surveySeenTooManyTimesLimit(survey))
    },

    surveySeenTooManyTimesLimit: function (survey) {
      var limitValue = survey.seenTooManyTimesLimit
      if (String(limitValue).toLowerCase() === 'unlimited') {
        return Infinity
      } else {
        return extractNumber(limitValue, SURVEY_SEEN_TOO_MANY_TIMES_LIMIT, 1)
      }
    },

    surveySeenCount: function (survey) {
      return extractNumber(GOVUK.cookie(userSurveys.surveySeenCookieName(survey)), 0, 0)
    },

    surveyTakenCookieName: function (survey) {
      return generateCookieName('taken_' + survey.identifier)
    },

    surveySeenCookieName: function (survey) {
      return generateCookieName('survey_seen_' + survey.identifier)
    },

    currentTime: function () { return new Date().getTime() },
    currentPath: function () { return window.location.pathname }
  }

  var generateCookieName = function (cookieName) {
      // taken_user_satisfaction_survey => takenUserSatisfactionSurvey
    var cookieStub = cookieName.replace(/(\_\w)/g, function (m) {
      return m.charAt(1).toUpperCase()
    })
    return 'govuk_' + cookieStub
  }

  var extractNumber = function (value, defaultValue, limit) {
    var parsedValue = parseInt(value, 10)
    if (isNaN(parsedValue) || (parsedValue < limit)) {
      return defaultValue
    } else {
      return parsedValue
    }
  }

  window.GOVUK.userSurveys = userSurveys

  $(document).ready(function () {
    if (window.GOVUK.userSurveys) {
      window.GOVUK.userSurveys.init()
    }
  })
})(window.jQuery)
<|endoftext|>


<commit_before>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
/*-------------------------------------------------------------------------------------*/
function display_login_info() {

  if (document.URL.split('?')[0].split('/')[3] == "login")
    return;

  var e = document.getElementById("login_info");
  if (e == null)
    return;

  var info = get_login_info();

  if (info.is_logged_in) {
      e.innerHTML = "You are logged in as "
	+ info.user+ '   Log out';
  }
  else {
    var data = encodeURIComponent(document.URL);
    e.innerHTML = "Log in";
  }
}
/*-------------------------------------------------------------------------------------*/
function do_log_out() {

 var xmlhttp = get_xmlhttp();

 xmlhttp.open("GET", "/welcome/do_log_out", false);
 xmlhttp.send();

 display_login_info();
}

/*-----------------------------------------------------------------------*/
function default_functions(xmlhttp) {

  var funcs = _.keys(xmlhttp);
  var func_patt = /^on/;

  for (var i=0; i<funcs.length; i++) {
    if (func_patt.test(funcs[i])) {
	xmlhttp[funcs[i]] = closure (funcs[i]);
    }
  }
}
/*-----------------------------------------------------------------------*/

function closure(str) {

  return function () { console.log(str + " function called.");};
}

/*-------------------------------------------------------------------------------------*/
function get_xmlhttp() {

  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  default_functions(xmlhttp);
  return xmlhttp;
}

/*-------------------------------------------------------------------------------------*/
function get_json(url) {

 var xmlhttp = get_xmlhttp();

 xmlhttp.open("GET", url, false);
 xmlhttp.send();

 return jQuery.parseJSON(xmlhttp.responseText);
}

/*-------------------------------------------------------------------------------------*/
function get_login_info() {

 return get_json("/welcome/check_login");
}
/*-------------------------------------------------------------------------------------*/
<commit_msg>displaying event information for xmlhttp events<commit_after>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
/*-------------------------------------------------------------------------------------*/
function display_login_info() {

  if (document.URL.split('?')[0].split('/')[3] == "login")
    return;

  var e = document.getElementById("login_info");
  if (e == null)
    return;

  var info = get_login_info();

  if (info.is_logged_in) {
      e.innerHTML = "You are logged in as "
	+ info.user+ '   Log out';
  }
  else {
    var data = encodeURIComponent(document.URL);
    e.innerHTML = "Log in";
  }
}
/*-------------------------------------------------------------------------------------*/
function do_log_out() {

 var xmlhttp = get_xmlhttp();

 xmlhttp.open("GET", "/welcome/do_log_out", false);
 xmlhttp.send();

 display_login_info();
}

/*-----------------------------------------------------------------------*/
function default_functions(xmlhttp) {

  var funcs = _.keys(xmlhttp);
  var func_patt = /^on/;

  for (var i=0; i<funcs.length; i++) {
    if (func_patt.test(funcs[i])) {
	xmlhttp[funcs[i]] = closure (funcs[i]);
    }
  }
}
/*-----------------------------------------------------------------------*/

function closure(str) {

  return function (e) {
    console.log(str + " function called.");
    console.log(e);
  };
}

/*-------------------------------------------------------------------------------------*/
function get_xmlhttp() {

  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  default_functions(xmlhttp);
  return xmlhttp;
}

/*-------------------------------------------------------------------------------------*/
function get_json(url) {

  var xmlhttp = get_xmlhttp();

  xmlhttp.open("GET", url, false);
  xmlhttp.send();

  return jQuery.parseJSON(xmlhttp.responseText);
}

/*-------------------------------------------------------------------------------------*/
function get_login_info() {

  return get_json("/welcome/check_login");
}
/*-------------------------------------------------------------------------------------*/
<|endoftext|>


<commit_before>$(document).on('ready', evenOutSpacing);
$(window).on('resize', evenOutSpacing);

function evenOutSpacing(){
  var windowHeight = $( window ).height();
  var mainHeight = $(".main").height();
  var marginTop = (windowHeight - mainHeight) / 2;

  $(".main").css("margin-top", marginTop);

  //get width of window, divide by 3
  var thirdWidth = $(".main").width() / 3;

  var tables = $(".main table");
  for (var i = 0; i < tables.length; i++){
    $(tables[i]).css("width", thirdWidth - 5);

  }

}

<commit_msg>fixes flicker bug<commit_after>$(document).on('ready', evenOutSpacing);
$(window).on('resize', evenOutSpacing);

function evenOutSpacing(){

  //get width of window, divide by 3
  var thirdWidth = $(".main").width() / 3;

  var tables = $(".main table");
  for (var i = 0; i < tables.length; i++){
    $(tables[i]).css("width", thirdWidth - 5);
  }

  var windowHeight = $( window ).height();
  var mainHeight = $(".main").height();
  var marginTop = (windowHeight - mainHeight) / 2;

  $(".main").css("margin-top", marginTop);
}

<|endoftext|>