<commit_before>/*
 * setup.js: Titanium CLI setup command
 *
 * Copyright (c) 2012, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	afs = appc.fs,
	prompt = require('prompt'),
	async = require('async'),
	exec = require('child_process').exec,
	i18n = appc.i18n(__dirname),
	__ = i18n.__,
	__n = i18n.__n;

exports.desc = __('run the setup wizard');

exports.config = function (logger, config, cli) {
	return {
		noAuth: true,
		flags: {
			advanced: {
				abbr: 'a',
				desc: __('prompts for all configuration options')
			}
		}
	};
};

exports.run = function (logger, config, cli) {
	logger.log(__('Enter %s at any time to quit', 'ctrl-c'.cyan) + '\n');

	appc.ios.detect(function (env) {
		var validate = require('revalidator').validate,
			distNames = env && env.certs.distNames.map(function (name) {
				var m = name.match(/^([^(]+?)*/);
				return m && m[0].trim();
			}),
			props = {
				'user.name': {
					default: config.user.name,
					description: __('What is your name?').bold + ' ' + __('(this is used as the default for the "author" field in the tiapp.xml or module manifest file when creating new projects)').grey,
					errorMsg: __('Invalid name'),
					conform: function (value) {
						return !!value.trim()
					}
				},
				'user.email': {
					default: config.user.email,
					description: __('What is your email address used for logging into the Appcelerator Network?').bold,
					errorMsg: __('Invalid e-mail address'),
					conform: function (value) {
						return !!value.trim()
					}
				},
				'user.locale': {
					default: config.user.locale,
					description: __('What would you like as your default locale?').bold + ' ' + __('(examples: "en", "de", "fr")').grey,
					errorMsg: __('Invalid locale'),
					conform: function (value) {
						return !!value.trim()
					}

				},
				'app.idprefix': {
					advanced: true,
					default: config.app.idprefix,
					description: __('What is your prefix for application IDs?').bold + ' ' + __('(example: com.mycompany)').grey
				},
				'app.publisher': {
					advanced: true,
					default: config.app.publisher,
					description: __('Used for populating the "publisher" field in new projects:').bold
				},
				'app.url': {
					advanced: true,
					default: config.app.url,
					description: __('Used for populating the "url" field in new projects:').bold
				},
				'app.sdk': {
					default: cli.env.getSDK(config.user.sdk).name,
					description: __('What Titanium SDK would you like to use by default?').bold,
					conform: function (value) {
						if (!cli.env.sdks[value]) {
							throw new appc.exception(__('Invalid Titanium SDK'));
						}
						return true;
					}
				},
				'app.workspace': {
					default: config.app.workspace,
					description: __('Path to your workspace where your projects should be created:').bold,
					conform: function (value) {
						if (!afs.exists(afs.resolvePath(value))) {
							throw new appc.exception(__('Invalid workspace directory'));
						}
						return true;
					}
				},
				'cli.colors': {
					advanced: true,
					default: !!config.cli.colors,
					description: __('Enable colors in the CLI?').bold,
					before: function (value) {
						return value === 'true';
					},
					conform: function (value) {
						if (!/^true|false$/.test(value)) {
							throw new appc.exception(__('Please specify %s or %s', 'true', 'false'));
						}
						return true;
					}
				},
				'cli.logLevel': {
					advanced: true,
					default: config.cli.logLevel || 'info',
					description: __('Default logging output level').bold,
					conform: function (value) {
						if (logger.getLevels().indexOf(value.toLowerCase()) == -1) {
							throw new appc.exception(
								__('Invalid log level'),
								[__('Available log levels:')].concat(logger.getLevels().map(function (level) {
									return '    ' + level.cyan;
								}))
							);
						}
						return true;
					}
				},
				'cli.prompt': {
					advanced: true,
					default: config.cli.hasOwnProperty('prompt') ? !!config.cli.prompt : true,
					description: __('Would you like to be prompted for missing options and arguments?').bold,
					before: function (value) {
						return value === 'true';
					},
					conform: function (value) {
						if (!/^true|false$/.test(value)) {
							throw new appc.exception(__('Please specify %s or %s', 'true', 'false'));
						}
						return true;
					}
				},
				'cli.failOnWrongSDK': {
					advanced: true,
					default: !!config.cli.failOnWrongSDK || false,
					description: __('Fail if trying to compile an app on different version in the tiapp.xml?').bold,
					before: function (value) {
						return value === 'true';
					},
					conform: function (value) {
						if (!/^true|false$/.test(value)) {
							throw new appc.exception(__('Please specify %s or %s', 'true', 'false'));
						}
						return true;
					}
				},
				'android.sdkPath': {
					default: config.android && config.android.sdkPath,
					description: __('Path to the Android SDK:').bold + ' ' + __('(this is needed for building Android apps)').grey,
					conform: function (value) {
						if (value && !afs.exists(afs.resolvePath(value))) {
							throw new appc.exception(__('Invalid Android SDK path'));
						}
						return true;
					}
				},
				'android.ndkPath': {
					advanced: true,
					default: config.android && config.android.ndkPath,
					description: __('Path to the Android NDK:').bold + ' ' + __('(this is needed for building native Titainum Modules for Android)').grey,
					conform: function (value) {
						if (value && !afs.exists(afs.resolvePath(value))) {
							throw new appc.exception(__('Invalid Android NDK path'));
						}
						return true;
					}
				},
				'ios.developerName': {
					advanced: true,
					default: config.ios && config.ios.developerName,
					description: __('What is the name of the iOS developer certificate you want to use by default?').bold
						+ ' ' + __('(this is used if you want to test on device)').grey,
					conform: function (devname) {
						var devNames;

						if (env && devname) {
							var lowerCasedDevname = devname.trim().toLowerCase();

							if (/\([0-9A-Za-z]*\)$/.test(lowerCasedDevname)) {
								devNames = env.certs.devNames.map(function (name) {
									return name.trim().toLowerCase();
								});
							} else {
								devNames = env.certs.devNames.map(function (name) {
									var m = name.match(/^([^(]+?)*/);
									return (m ? m[0] : name).trim().toLowerCase();
								});
							}

							if (devNames.indexOf(lowerCasedDevname) == -1) {
								var width = 0,
									i = 0,
									l = env.certs.devNames.length,
									h = Math.ceil(l / 2),
									output = [__('Available names:')];

								for (; i < h; i++) {
									if (env.certs.devNames[i].length > width) {
										width = env.certs.devNames[i].length;
									}
									output.push('    ' + env.certs.devNames[i]);
								}

								width += 12; // 4 spaces left padding, 8 spaces between columns
								for (h = 1; i < l; h++, i++) {
									output[h] = appc.string.rpad(output[h], width) + env.certs.devNames[i];
								}

								throw new appc.exception(
									__('Unable to find an iOS Developer Certificate for "%s"', devname),
									output.map(function (s, i) { return i ? s.cyan : s; })
								);
							}
						}
						return true;
					}
				},
				'ios.distributionName': {
					advanced: true,
					default: config.ios && config.ios.distributionName,
					description: __('What is the name of the iOS distribution certificate you want to use by default?').bold
						+ ' ' + __('(this is used if you want to distribute the app either through the App Store or Ad Hoc)').grey,
					conform: function (name) {
						if (distNames.indexOf(name) == -1) {
							throw new appc.exception(__('Unable to find an iOS Distribution Certificate for "%s"', name), [
								__('Available names:')
							].concat(distNames.map(function (d) { return '    ' + d.cyan; })));
						}
						return true;
					}
				}
			};

		// if we're not doing an advanced setup, then let's remove the advanced props now
		if (!cli.argv.advanced) {
			Object.keys(props).forEach(function (name) {
				if (props[name].advanced) {
					delete props[name];
				}
			});
		}

		// remove ios props if we're not on mac os x
		if (process.platform != 'darwin' || !env || !env.certs.devNames.length) {
			delete props['ios.developerName'];
		}
		if (process.platform != 'darwin' || !env || !env.certs.distNames.length) {
			delete props['ios.distributionName'];
		}

		// overwrite prompt settings and render function
		prompt.colors = false;
		prompt.delimiter = prompt.message = '';
		prompt._performValidation = function (name, prop, against, schema, line, callback) {
			var result = { valid: false },
				msg,
				errorMsg = prop.schema.errorMsg;

			try {
				result = validate(against, schema);
			} catch (err) {
				if (err.type == 'AppcException') {
					logger.error(err.message);
					err.details.forEach(function (line) {
						logger.log(line);
					});
					return false;
				} else {
					return (line !== -1) ? callback(err) : false;
				}
			}

			if (!result.valid) {
				if (errorMsg) {
					logger.error(errorMsg);
				} else {
					msg = line !== -1 ? 'Invalid input for ' : 'Invalid command-line input for ';
					logger.error(msg + name.stripColors);
					prop.schema.message && logger.error(prop.schema.message);
				}

				prompt.emit('invalid', prop, line);
			}

			return result.valid;
		};

		prompt.start();
		prompt.get({
			properties: props
		}, function (err, results) {
			if (err) {
				logger.log('\n');
				process.exit(1);
			}

			Object.keys(results).forEach(function (key) {
				config.set(key, (results[key] || '').trim());
			});

			config.save();
			logger.log('\n' + __('Configuration saved') + '\n');
		});
	});
};
<commit_msg>[TIMOB-12268] Fixed bug with setup command where an error occurs when a previously saved active SDK version is invalid.<commit_after>/*
 * setup.js: Titanium CLI setup command
 *
 * Copyright (c) 2012, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	afs = appc.fs,
	prompt = require('prompt'),
	async = require('async'),
	exec = require('child_process').exec,
	i18n = appc.i18n(__dirname),
	__ = i18n.__,
	__n = i18n.__n;

exports.desc = __('run the setup wizard');

exports.config = function (logger, config, cli) {
	return {
		noAuth: true,
		flags: {
			advanced: {
				abbr: 'a',
				desc: __('prompts for all configuration options')
			}
		}
	};
};

exports.run = function (logger, config, cli) {
	logger.log(__('Enter %s at any time to quit', 'ctrl-c'.cyan) + '\n');

	appc.ios.detect(function (env) {
		var validate = require('revalidator').validate,
			distNames = env && env.certs.distNames.map(function (name) {
				var m = name.match(/^([^(]+?)*/);
				return m && m[0].trim();
			}),
			sdk = cli.env.getSDK(config.user.sdk),
			props = {
				'user.name': {
					default: config.user.name,
					description: __('What is your name?').bold + ' ' + __('(this is used as the default for the "author" field in the tiapp.xml or module manifest file when creating new projects)').grey,
					errorMsg: __('Invalid name'),
					conform: function (value) {
						return !!value.trim()
					}
				},
				'user.email': {
					default: config.user.email,
					description: __('What is your email address used for logging into the Appcelerator Network?').bold,
					errorMsg: __('Invalid e-mail address'),
					conform: function (value) {
						return !!value.trim()
					}
				},
				'user.locale': {
					default: config.user.locale,
					description: __('What would you like as your default locale?').bold + ' ' + __('(examples: "en", "de", "fr")').grey,
					errorMsg: __('Invalid locale'),
					conform: function (value) {
						return !!value.trim()
					}

				},
				'app.idprefix': {
					advanced: true,
					default: config.app.idprefix,
					description: __('What is your prefix for application IDs?').bold + ' ' + __('(example: com.mycompany)').grey
				},
				'app.publisher': {
					advanced: true,
					default: config.app.publisher,
					description: __('Used for populating the "publisher" field in new projects:').bold
				},
				'app.url': {
					advanced: true,
					default: config.app.url,
					description: __('Used for populating the "url" field in new projects:').bold
				},
				'app.sdk': {
					default: sdk && sdk.name,
					description: __('What Titanium SDK would you like to use by default?').bold,
					conform: function (value) {
						if (!cli.env.sdks[value]) {
							throw new appc.exception(__('Invalid Titanium SDK'));
						}
						return true;
					}
				},
				'app.workspace': {
					default: config.app.workspace,
					description: __('Path to your workspace where your projects should be created:').bold,
					conform: function (value) {
						if (!afs.exists(afs.resolvePath(value))) {
							throw new appc.exception(__('Invalid workspace directory'));
						}
						return true;
					}
				},
				'cli.colors': {
					advanced: true,
					default: !!config.cli.colors,
					description: __('Enable colors in the CLI?').bold,
					before: function (value) {
						return value === 'true';
					},
					conform: function (value) {
						if (!/^true|false$/.test(value)) {
							throw new appc.exception(__('Please specify %s or %s', 'true', 'false'));
						}
						return true;
					}
				},
				'cli.logLevel': {
					advanced: true,
					default: config.cli.logLevel || 'info',
					description: __('Default logging output level').bold,
					conform: function (value) {
						if (logger.getLevels().indexOf(value.toLowerCase()) == -1) {
							throw new appc.exception(
								__('Invalid log level'),
								[__('Available log levels:')].concat(logger.getLevels().map(function (level) {
									return '    ' + level.cyan;
								}))
							);
						}
						return true;
					}
				},
				'cli.prompt': {
					advanced: true,
					default: config.cli.hasOwnProperty('prompt') ? !!config.cli.prompt : true,
					description: __('Would you like to be prompted for missing options and arguments?').bold,
					before: function (value) {
						return value === 'true';
					},
					conform: function (value) {
						if (!/^true|false$/.test(value)) {
							throw new appc.exception(__('Please specify %s or %s', 'true', 'false'));
						}
						return true;
					}
				},
				'cli.failOnWrongSDK': {
					advanced: true,
					default: !!config.cli.failOnWrongSDK || false,
					description: __('Fail if trying to compile an app on different version in the tiapp.xml?').bold,
					before: function (value) {
						return value === 'true';
					},
					conform: function (value) {
						if (!/^true|false$/.test(value)) {
							throw new appc.exception(__('Please specify %s or %s', 'true', 'false'));
						}
						return true;
					}
				},
				'android.sdkPath': {
					default: config.android && config.android.sdkPath,
					description: __('Path to the Android SDK:').bold + ' ' + __('(this is needed for building Android apps)').grey,
					conform: function (value) {
						if (value && !afs.exists(afs.resolvePath(value))) {
							throw new appc.exception(__('Invalid Android SDK path'));
						}
						return true;
					}
				},
				'android.ndkPath': {
					advanced: true,
					default: config.android && config.android.ndkPath,
					description: __('Path to the Android NDK:').bold + ' ' + __('(this is needed for building native Titainum Modules for Android)').grey,
					conform: function (value) {
						if (value && !afs.exists(afs.resolvePath(value))) {
							throw new appc.exception(__('Invalid Android NDK path'));
						}
						return true;
					}
				},
				'ios.developerName': {
					advanced: true,
					default: config.ios && config.ios.developerName,
					description: __('What is the name of the iOS developer certificate you want to use by default?').bold
						+ ' ' + __('(this is used if you want to test on device)').grey,
					conform: function (devname) {
						var devNames;

						if (env && devname) {
							var lowerCasedDevname = devname.trim().toLowerCase();

							if (/\([0-9A-Za-z]*\)$/.test(lowerCasedDevname)) {
								devNames = env.certs.devNames.map(function (name) {
									return name.trim().toLowerCase();
								});
							} else {
								devNames = env.certs.devNames.map(function (name) {
									var m = name.match(/^([^(]+?)*/);
									return (m ? m[0] : name).trim().toLowerCase();
								});
							}

							if (devNames.indexOf(lowerCasedDevname) == -1) {
								var width = 0,
									i = 0,
									l = env.certs.devNames.length,
									h = Math.ceil(l / 2),
									output = [__('Available names:')];

								for (; i < h; i++) {
									if (env.certs.devNames[i].length > width) {
										width = env.certs.devNames[i].length;
									}
									output.push('    ' + env.certs.devNames[i]);
								}

								width += 12; // 4 spaces left padding, 8 spaces between columns
								for (h = 1; i < l; h++, i++) {
									output[h] = appc.string.rpad(output[h], width) + env.certs.devNames[i];
								}

								throw new appc.exception(
									__('Unable to find an iOS Developer Certificate for "%s"', devname),
									output.map(function (s, i) { return i ? s.cyan : s; })
								);
							}
						}
						return true;
					}
				},
				'ios.distributionName': {
					advanced: true,
					default: config.ios && config.ios.distributionName,
					description: __('What is the name of the iOS distribution certificate you want to use by default?').bold
						+ ' ' + __('(this is used if you want to distribute the app either through the App Store or Ad Hoc)').grey,
					conform: function (name) {
						if (distNames.indexOf(name) == -1) {
							throw new appc.exception(__('Unable to find an iOS Distribution Certificate for "%s"', name), [
								__('Available names:')
							].concat(distNames.map(function (d) { return '    ' + d.cyan; })));
						}
						return true;
					}
				}
			};

		// if we're not doing an advanced setup, then let's remove the advanced props now
		if (!cli.argv.advanced) {
			Object.keys(props).forEach(function (name) {
				if (props[name].advanced) {
					delete props[name];
				}
			});
		}

		// remove ios props if we're not on mac os x
		if (process.platform != 'darwin' || !env || !env.certs.devNames.length) {
			delete props['ios.developerName'];
		}
		if (process.platform != 'darwin' || !env || !env.certs.distNames.length) {
			delete props['ios.distributionName'];
		}

		// overwrite prompt settings and render function
		prompt.colors = false;
		prompt.delimiter = prompt.message = '';
		prompt._performValidation = function (name, prop, against, schema, line, callback) {
			var result = { valid: false },
				msg,
				errorMsg = prop.schema.errorMsg;

			try {
				result = validate(against, schema);
			} catch (err) {
				if (err.type == 'AppcException') {
					logger.error(err.message);
					err.details.forEach(function (line) {
						logger.log(line);
					});
					return false;
				} else {
					return (line !== -1) ? callback(err) : false;
				}
			}

			if (!result.valid) {
				if (errorMsg) {
					logger.error(errorMsg);
				} else {
					msg = line !== -1 ? 'Invalid input for ' : 'Invalid command-line input for ';
					logger.error(msg + name.stripColors);
					prop.schema.message && logger.error(prop.schema.message);
				}

				prompt.emit('invalid', prop, line);
			}

			return result.valid;
		};

		prompt.start();
		prompt.get({
			properties: props
		}, function (err, results) {
			if (err) {
				logger.log('\n');
				process.exit(1);
			}

			Object.keys(results).forEach(function (key) {
				config.set(key, (results[key] || '').trim());
			});

			config.save();
			logger.log('\n' + __('Configuration saved') + '\n');
		});
	});
};
<|endoftext|>


<commit_before>/**

 *
 * User: Jhonny Ventiades<jhonny.ventiadesg@gmail.com>
 * Date: 2014-07-09
 */

'use strict';

var express = require('express'),
    favicon = require('static-favicon'),
    morgan = require('morgan'),
    errorHandler = require('errorhandler'),
    path = require('path'),
    config = require('./config');

/**
 * Express configuration
 */
module.exports = function(app) {
  var env = app.get('env');

  if ('development' === env) {

    // Disable caching of scripts for easier testing
    app.use(function noCache(req, res, next) {
      if (req.url.indexOf('/scripts/') === 0) {
        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.header('Pragma', 'no-cache');
        res.header('Expires', 0);
      }
      next();
    });

    app.use(express.static(path.join(config.root, '.tmp')));
    //app.use(express.static('rootPath', '.tmp'));
    app.use(express.static(path.join(config.root, 'app')));
      //app.use(express.static('rootPath', 'app'));
    app.set('views', config.root + '/app/views');

      app.use('/',express.static(path.join(config.root, '/app/views')));
      app.use(express.static(path.join(config.root, '/app')));
  }

  /*if ('production' === env) {
    //app.use(compression());
    //app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('views', config.root + '/app/views');
  }*/

  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(morgan('dev'));

  // Error handler - has to be last
  /*if ('development' === app.get('env')) {
    app.use(errorHandler());
  }*/
};<commit_msg>Studya #comment fixing server #time 10m<commit_after>/**

 *
 * User: Jhonny Ventiades<jhonny.ventiadesg@gmail.com>
 * Date: 2014-07-09
 */

'use strict';

var express = require('express'),
    favicon = require('static-favicon'),
    morgan = require('morgan'),
    errorHandler = require('errorhandler'),
    path = require('path'),
    config = require('./config');

/**
 * Express configuration
 */
module.exports = function(app) {
  var env = app.get('env');
    console.log(env);
  //if ('development' === env) {

    // Disable caching of scripts for easier testing
    app.use(function noCache(req, res, next) {
      if (req.url.indexOf('/scripts/') === 0) {
        res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.header('Pragma', 'no-cache');
        res.header('Expires', 0);
      }
      next();
    });

    app.use(express.static(path.join(config.root, '.tmp')));
    //app.use(express.static('rootPath', '.tmp'));
    app.use(express.static(path.join(config.root, 'app')));
      //app.use(express.static('rootPath', 'app'));
    app.set('views', config.root + '/app/views');

      app.use('/',express.static(path.join(config.root, '/app/views')));
      app.use(express.static(path.join(config.root, '/app')));
//  }

  //if ('production' === env) {
    //app.use(compression());
    //app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('views', config.root + '/app/views');
  //}

  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(morgan('dev'));

  // Error handler - has to be last
  //if ('development' === app.get('env')) {
    app.use(errorHandler());
  //}
};<|endoftext|>


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

var config = require('../config');
var PackageName = require('./package-name');
var path = require('path');
var extend = require('../common').extend;
var hasProperties = require('../common').hasProperties;
var registryCache = require('../package').registryCache;
var Promise = require('rsvp').Promise;
var ui = require('../ui');
var fs = require('graceful-fs');
var asp = require('rsvp').denodeify;
var readJSON = require('../common').readJSON;

/*
 * Package.json Configuration Class
 *
 * name
 * main
 * registry
 * dependencies
 * configFile
 * baseURL
 * lib
 * dist
 * packages
 * format
 * map
 * buildConfig
 *
 */
function PackageJSON(fileName) {
  this.fileName = fileName;
}

PackageJSON.prototype.read = function() {
  if (this.read_)
    throw "Package.json file already read";

  this.read_ = true;
  var self = this;

  return readJSON(this.fileName)
  .then(function(pjson) {
    return checkCreatePackageJSON(pjson);
  })
  .then(function(pjson) {
    self.originalPjson = pjson;

    // derive the jspm config from the 'jspm' property in the package.json
    // sets the registry property if dependencies are jspm-prefixed
    self.jspmPrefix = !!pjson.jspm;
    pjson = config.derivePackageConfig(pjson);

    self.dir = path.dirname(self.fileName);

    // populate defaults as we go
    var defaults = self.defaults = {};

    // create structured configuration with defaults
    defaults.name = 'app';
    self.name = pjson.name || defaults.name;

    defaults.main = self.name;
    self.main = pjson.main || defaults.main;

    self.registry = pjson.registry;
    self.dependencies = {};
    // only read dependencies when combined with a registry property
    if (pjson.dependencies && pjson.registry) {
      for (var d in pjson.dependencies) {
        var dep = pjson.dependencies[d];

        // version only
        if (dep.indexOf(':') == -1 && dep.indexOf('@') == -1)
          dep = d + '@' + dep;

        // convert into package objects
        self.dependencies[d] = new PackageName(dep);
      }
    }

    defaults.baseURL = self.dir;
    self.baseURL = pjson.directories && pjson.directories.baseURL && path.resolve(self.dir, pjson.directories.baseURL) || defaults.baseURL;

    defaults.lib = path.resolve(self.baseURL, 'lib');
    defaults.dist = path.resolve(self.baseURL, 'dist');
    defaults.packages = path.resolve(self.baseURL, 'jspm_packages');

    self.lib = pjson.directories && pjson.directories.lib && path.resolve(self.dir, pjson.directories.lib) || defaults.lib;
    self.dist = pjson.directories && pjson.directories.dist && path.resolve(self.dir, pjson.directories.dist) || defaults.dist;
    // NB can remove jspmPackages suport in time
    self.packages = pjson.directories && pjson.directories.packages && path.resolve(self.dir, pjson.directories.packages)
      || pjson.directories && pjson.directories.jspmPackages && path.resolve(self.dir, pjson.directories.jspmPackages) || defaults.packages;

    defaults.configFile = path.resolve(self.baseURL, 'config.js');
    self.configFile = pjson.configFile && path.resolve(self.dir, pjson.configFile) || defaults.configFile;

    self.format = pjson.format;
    self.map = extend({}, pjson.map || {});

    self.buildConfig = extend({}, pjson.buildConfig || {});
  });
}

PackageJSON.prototype.write = function() {
  var pjson = this.jspmPrefix ? {} : this.originalPjson;
  if (this.jspmPrefix)
    this.originalPjson.jspm = pjson;

  var defaults = this.defaults;

  // only set properties that differ from the defaults
  if (this.name != defaults.name)
    pjson.name = this.name;
  if (this.main != defaults.main)
    pjson.main = this.main;

  if (this.format)
    pjson.format = this.format;

  var directories = {};
  if (this.baseURL != defaults.baseURL)
    directories.baseURL = this.baseURL;
  if (this.lib != defaults.lib)
    directories.lib = this.lib;
  if (this.dist != defaults.dist)
    directories.dist = this.dist;
  if (this.packages != defaults.packages)
    directories.packages = this.packages;

  if (hasProperties(directories)) {
    for (var d in directories)
      directories[d] = path.relative(this.dir, directories[d]);
    pjson.directories = extend(pjson.directories || {}, directories);
  }

  if (this.configFile != defaults.configFile)
    pjson.configFile = path.relative(this.dir, this.configFile);

  pjson.map = this.map;
  if (!hasProperties(pjson.map))
    delete pjson.map;

  pjson.dependencies = {};
  var depValue;
  for (var d in this.dependencies) {
    var dep = this.dependencies[d];
    if (!dep)
      continue;
    var regName;
    // github:some/thing: x.y.z
    if (d == dep.name)
      depValue = dep.version;
    // name is exactly as in registry
    // jquery: github:components/jquery@^x.y.z -> jquery: ^x.y.z
    else if (registryCache[d + '@' + dep.version] == dep.exactName || registryCache[d] == dep.name)
        depValue = dep.version;
    else
      depValue = this.dependencies[d].exactName;

    pjson.dependencies[d] = depValue;
  }
  if (!hasProperties(pjson.dependencies))
    delete pjson.dependencies;

  pjson.buildConfig = this.buildConfig;
  if (!hasProperties(pjson.buildConfig))
    delete pjson.buildConfig;

  // NB check that the file hasn't changed since we opened it and if so, prompt
  return asp(fs.writeFile)(this.fileName, JSON.stringify(this.originalPjson, null, 2) + '\n');
}

// can take an existing non-jspm package.json
function checkCreatePackageJSON(initialPjson) {
  initialPjson = initialPjson || {};

  // already jspm-optimized
  if (initialPjson.jspm || initialPjson.registry)
    return initialPjson;

  var pjson = initialPjson;
  var base;

  return Promise.resolve()
  .then(function() {
    return ui.confirm('Would you like jspm to prefix the jspm package.json properties under %jspm%?', true);
  })
  .then(function(prefix) {
    if (prefix)
      initialPjson.jspm = pjson = {};
    return ui.input('Enter a name for the project (optional)', initialPjson.name);
  })
  .then(function(name) {
    pjson.name = name;
    return ui.input('Enter baseURL path', '.');
  })
  .then(function(baseURL) {
    base = baseURL + path.sep;
    pjson.baseURL = baseURL;
    return ui.input('Enter project source folder', base + 'lib');
  })
  .then(function(lib) {
    pjson.directories = pjson.directories || {};
    pjson.directories.lib = lib;
    return ui.input('Enter project built folder (optional)');
  })
  .then(function(dist) {
    pjson.directories.dist = dist;
    return ui.input('Enter packages folder', base + 'jspm_packages');
  })
  .then(function(packages) {
    pjson.directories.packages = packages;
    return ui.input('Enter config file path', base + 'config.js');
  })
  .then(function(configFile) {
    pjson.configFile = configFile;
    return initialPjson;
  });
}

module.exports = PackageJSON;
<commit_msg>set baseURL correctly during init<commit_after>/*
 *   Copyright 2014 Guy Bedford (http://guybedford.com)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

var config = require('../config');
var PackageName = require('./package-name');
var path = require('path');
var extend = require('../common').extend;
var hasProperties = require('../common').hasProperties;
var registryCache = require('../package').registryCache;
var Promise = require('rsvp').Promise;
var ui = require('../ui');
var fs = require('graceful-fs');
var asp = require('rsvp').denodeify;
var readJSON = require('../common').readJSON;

/*
 * Package.json Configuration Class
 *
 * name
 * main
 * registry
 * dependencies
 * configFile
 * baseURL
 * lib
 * dist
 * packages
 * format
 * map
 * buildConfig
 *
 */
function PackageJSON(fileName) {
  this.fileName = fileName;
}

PackageJSON.prototype.read = function() {
  if (this.read_)
    throw "Package.json file already read";

  this.read_ = true;
  var self = this;

  return readJSON(this.fileName)
  .then(function(pjson) {
    return checkCreatePackageJSON(pjson);
  })
  .then(function(pjson) {
    self.originalPjson = pjson;

    // derive the jspm config from the 'jspm' property in the package.json
    // sets the registry property if dependencies are jspm-prefixed
    self.jspmPrefix = !!pjson.jspm;
    pjson = config.derivePackageConfig(pjson);

    self.dir = path.dirname(self.fileName);

    // populate defaults as we go
    var defaults = self.defaults = {};

    // create structured configuration with defaults
    defaults.name = 'app';
    self.name = pjson.name || defaults.name;

    defaults.main = self.name;
    self.main = pjson.main || defaults.main;

    self.registry = pjson.registry;
    self.dependencies = {};
    // only read dependencies when combined with a registry property
    if (pjson.dependencies && pjson.registry) {
      for (var d in pjson.dependencies) {
        var dep = pjson.dependencies[d];

        // version only
        if (dep.indexOf(':') == -1 && dep.indexOf('@') == -1)
          dep = d + '@' + dep;

        // convert into package objects
        self.dependencies[d] = new PackageName(dep);
      }
    }

    defaults.baseURL = self.dir;
    self.baseURL = pjson.directories && pjson.directories.baseURL && path.resolve(self.dir, pjson.directories.baseURL) || defaults.baseURL;

    defaults.lib = path.resolve(self.baseURL, 'lib');
    defaults.dist = path.resolve(self.baseURL, 'dist');
    defaults.packages = path.resolve(self.baseURL, 'jspm_packages');

    self.lib = pjson.directories && pjson.directories.lib && path.resolve(self.dir, pjson.directories.lib) || defaults.lib;
    self.dist = pjson.directories && pjson.directories.dist && path.resolve(self.dir, pjson.directories.dist) || defaults.dist;
    // NB can remove jspmPackages suport in time
    self.packages = pjson.directories && pjson.directories.packages && path.resolve(self.dir, pjson.directories.packages)
      || pjson.directories && pjson.directories.jspmPackages && path.resolve(self.dir, pjson.directories.jspmPackages) || defaults.packages;

    defaults.configFile = path.resolve(self.baseURL, 'config.js');
    self.configFile = pjson.configFile && path.resolve(self.dir, pjson.configFile) || defaults.configFile;

    self.format = pjson.format;
    self.map = extend({}, pjson.map || {});

    self.buildConfig = extend({}, pjson.buildConfig || {});
  });
}

PackageJSON.prototype.write = function() {
  var pjson = this.jspmPrefix ? {} : this.originalPjson;
  if (this.jspmPrefix)
    this.originalPjson.jspm = pjson;

  var defaults = this.defaults;

  // only set properties that differ from the defaults
  if (this.name != defaults.name)
    pjson.name = this.name;
  if (this.main != defaults.main)
    pjson.main = this.main;

  if (this.format)
    pjson.format = this.format;

  var directories = {};
  if (this.baseURL != defaults.baseURL)
    directories.baseURL = this.baseURL;
  if (this.lib != defaults.lib)
    directories.lib = this.lib;
  if (this.dist != defaults.dist)
    directories.dist = this.dist;
  if (this.packages != defaults.packages)
    directories.packages = this.packages;

  if (hasProperties(directories)) {
    for (var d in directories)
      directories[d] = path.relative(this.dir, directories[d]);
    pjson.directories = extend(pjson.directories || {}, directories);
  }

  if (this.configFile != defaults.configFile)
    pjson.configFile = path.relative(this.dir, this.configFile);

  pjson.map = this.map;
  if (!hasProperties(pjson.map))
    delete pjson.map;

  pjson.dependencies = {};
  var depValue;
  for (var d in this.dependencies) {
    var dep = this.dependencies[d];
    if (!dep)
      continue;
    var regName;
    // github:some/thing: x.y.z
    if (d == dep.name)
      depValue = dep.version;
    // name is exactly as in registry
    // jquery: github:components/jquery@^x.y.z -> jquery: ^x.y.z
    else if (registryCache[d + '@' + dep.version] == dep.exactName || registryCache[d] == dep.name)
        depValue = dep.version;
    else
      depValue = this.dependencies[d].exactName;

    pjson.dependencies[d] = depValue;
  }
  if (!hasProperties(pjson.dependencies))
    delete pjson.dependencies;

  pjson.buildConfig = this.buildConfig;
  if (!hasProperties(pjson.buildConfig))
    delete pjson.buildConfig;

  // NB check that the file hasn't changed since we opened it and if so, prompt
  return asp(fs.writeFile)(this.fileName, JSON.stringify(this.originalPjson, null, 2) + '\n');
}

// can take an existing non-jspm package.json
function checkCreatePackageJSON(initialPjson) {
  initialPjson = initialPjson || {};

  // already jspm-optimized
  if (initialPjson.jspm || initialPjson.registry)
    return initialPjson;

  var pjson = initialPjson;
  var base;

  return Promise.resolve()
  .then(function() {
    return ui.confirm('Would you like jspm to prefix the jspm package.json properties under %jspm%?', true);
  })
  .then(function(prefix) {
    if (prefix)
      initialPjson.jspm = pjson = {};
    return ui.input('Enter a name for the project (optional)', initialPjson.name);
  })
  .then(function(name) {
    pjson.name = name;
    return ui.input('Enter baseURL path', '.');
  })
  .then(function(baseURL) {
    base = baseURL + path.sep;
    pjson.directories = pjson.directories || {};
    pjson.directories.baseURL = baseURL;
    return ui.input('Enter project source folder', base + 'lib');
  })
  .then(function(lib) {
    pjson.directories = pjson.directories || {};
    pjson.directories.lib = lib;
    return ui.input('Enter project built folder (optional)');
  })
  .then(function(dist) {
    pjson.directories.dist = dist;
    return ui.input('Enter packages folder', base + 'jspm_packages');
  })
  .then(function(packages) {
    pjson.directories.packages = packages;
    return ui.input('Enter config file path', base + 'config.js');
  })
  .then(function(configFile) {
    pjson.configFile = configFile;
    return initialPjson;
  });
}

module.exports = PackageJSON;
<|endoftext|>


<commit_before>var m_rad = 5;
var marker_icon_path = 'M 0, 0 m -' + m_rad + ', 0 a ' + m_rad + ',' + m_rad + ' 0 1,0 ' + 2 * m_rad + ',0 a ' + m_rad + ',' + m_rad + ' 0 1,0 -' + 2 * m_rad + ',0';
var startTime = 0;
var DRONES = [];
var polylines = [];
var map;
var beacon_filter = [];

var cluster_styles =
    [
        [{
            url: 'http://localhost:8000/static/m1.png',
            width: 40,
            height: 40,
            textColor: '#ffffff',
            textSize: 11
        }],
        [{
            url: 'http://localhost:8000/static/m2.png',
            height: 40,
            width: 40,
            textColor: '#ffffff',
            textSize: 11
        }],
        [{
            url: 'http://localhost:8000/static/m3.png',
            height: 40,
            width: 40,
            textColor: '#525252',
            textSize: 11
        }],
        [{
            url: 'http://localhost:8000/static/m4.png',
            height: 40,
            width: 40,
            textColor: '#ffffff',
            textSize: 11
        }]
    ];

clearMarkers();

setInterval(
    function getPoint() {
        $.ajax({
            type: "GET",
            url: "http://localhost:8000/map/getData/?StartTime=" + startTime,
            dataType: "json",
            success: parseSuccess,
            error: errorHandler
        });
    }, 500);

function errorHandler(response, options, error) {
    console.error("Error while trying to retrieve beacon and drone data from server.");
    console.error(response);
    console.error(response.responseText);
    console.log(error);
}

function parseSuccess(response) {
    startTime = response.current_time;
    updateDrones(response.drones);
    addDronesPolyline(response.drones_positions);
    addBeaconPoints(response.beacons_positions);
    createClusters();
}

function median(values) {
    values.sort(function (a, b) {
        return a - b;
    });
    var half = Math.floor(values.length / 2);
    if (values.length % 2)
        return values[half];
    else
        return (values[half - 1] + values[half]) / 2.0;
}

function createClusters() {
    markers.map(function (beacon_markers, i) {
        if (!beacon_filter[i]) {
            var cluster = new MarkerClusterer(
                map,
                beacon_markers,
                {
                    gridSize: 40,
                    averageCenter: true,
                    styles: cluster_styles[i === 0 ? 0 : i < 3 ? 1 : i < 6 ? 2 : 3]
                });
            cluster.setCalculator(function (markers, numStyles) {
                var rssiSum = 0;
                var min = 255;
                var max = 0;
                var rssiArr = [];
                for (var i = 0; i < markers.length; i++) {
                    var rssi = parseInt(markers[i].label.split(" ")[0]);
                    if (rssi > max) max = rssi;
                    if (rssi < min) min = rssi;
                    rssiArr.push(rssi);
                    rssiSum += rssi;
                }
                var med = median(rssiArr);
                var minor = markers[0].label.split(" ")[1];
                var major = markers[0].label.split(" ")[2];
                return {
                    text: minor + " " + major + " " + markers.length + "
" + max + " " + min + "
" + Math.round(rssiSum / markers.length) + " " + Math.round(med),
                    index: 0
                };
            });
        }
    });
}

function updateDrones(drones) {
    var found = false;
    for (var i = 0; i < drones.length; i++) {
        for (var j = 0; j < DRONES.length; j++) {
            if (DRONES[j].pk === drones[i].pk) {
                found = true;
            }
        }
        if (!found) {
            DRONES.push(drones[i]);
        }
        found = false;
    }
    updateLegend();
}

function findDrone(id) {
    for (var i = 0; i < DRONES.length; i++) {
        if (DRONES[i].pk === id) return DRONES[i];
    }
    console.error("Any drone with id " + id + " found.");
}

function addDronesPolyline(points) {
    for (var i = 0; i < points.length; i++) {
        var latitude = parseFloat(points[i].fields.latitude);
        var longitude = parseFloat(points[i].fields.longitude);
        var drone = findDrone(points[i].fields.drone);
        var lastPoint = drone.fields.last_position;
        drone.fields.last_position = {
            lat: latitude,
            lng: longitude
        };
        if (typeof lastPoint !== "undefined") {
            addPolyline(lastPoint, drone.fields.last_position, drone.fields.color);
        } else {
            addPoint(latitude, longitude, drone.fields.color, "", drone.fields.name, 1); //add point if just one point (start point)
        }
    }
}

function addBeaconPoints(beacons) {
    for (var i = 0; i < beacons.length; i++) {
        var latitude = beacons[i].fields.latitude;
        var longitude = beacons[i].fields.longitude;
        var altitude = beacons[i].fields.altitude;
        var scale = (100 - beacons[i].fields.altitude) / 30;
        var color = beacons[i].fields.major === 4 ? "red" :
            beacons[i].fields.major === 3 ? "yellow" :
                beacons[i].fields.major === 2 ? "green" :
                    beacons[i].fields.major === 1 ? "#696969" : "white";
        var label = beacons[i].fields.rssi + " " + beacons[i].fields.minor + " " + beacons[i].fields.major;
        var title = Math.round(altitude * 100) / 100 + " m";
        var marker = addPoint(latitude, longitude, color, label, title, 3.0);
        addMarkerToInternalCollection(marker, beacons[i].fields.major, beacons[i].fields.minor);
    }
}

function addMarkerToInternalCollection(marker, major, minor) {
    markers[indexInMarkersCollection(major,minor)].push(marker);
}

function indexInMarkersCollection(major, minor){
    switch (major) {
        case 1:
            return 0;
        case 2:
            return 0 + minor;
        case 3:
            return 2 + minor;
        case 4:
            return 5 + minor;
    }
}

function addPoint(latitude, longitude, color, label, title, scale) {
    return new google.maps.Marker({
        position: {lat: latitude, lng: longitude},
        map: map,
        icon: {
            path: marker_icon_path,
            fillColor: color,
            fillOpacity: 1.0,
            strokeOpacity: 0.0,
            scale: scale
        },
        label: label,
        title: title
    });
}

function addPolyline(p1, p2, color) {
    var polyline = new google.maps.Polyline({
        path: [
            p1,
            p2
        ],
        map: map,
        geodesic: true,
        strokeColor: color,
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    polylines.push(polyline);
}

function initMap() {
    var center_pos = {lat: 50.089684, lng: 20.202649};
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: center_pos,
        scrollwheel: true,
        draggable: true,
        mapTypeId: 'satellite'
    });

    /* north-west corner, clockwise direction */
    var areaCoords = [
        {lat: 50.0931667, lng: 20.1916000},
        {lat: 50.0931667, lng: 20.2000000},
        {lat: 50.0931667, lng: 20.2066167},
        {lat: 50.0903500, lng: 20.2090667},
        {lat: 50.0883333, lng: 20.2090667},
        {lat: 50.0883333, lng: 20.2029000},
        {lat: 50.0883333, lng: 20.2000000},
        {lat: 50.0883333, lng: 20.1970000},
        {lat: 50.0883333, lng: 20.1926833},
        {lat: 50.0906167, lng: 20.1919500},
        {lat: 50.0916333, lng: 20.1916000}
    ];

    var area = new google.maps.Polygon({
        paths: areaCoords,
        strokeColor: '#FFA500',
        strokeOpacity: 1,
        strokeWeight: 5,
        fillColor: 'green',
        fillOpacity: 0.2
    });

    var infoWindow = new google.maps.InfoWindow({
        pixelOffset: new google.maps.Size(0,0)
    });

    function popup(event) {
        var latitude = event.latLng.lat();
        var longitude = event.latLng.lng();
        var latLng = event.latLng;

        infoWindowHtml ='
' +
                            '' +
                                latitude +
                            '' + ', ' +
                            '' +
                                longitude +
                            '' +
                         '
';
        infoWindow.setContent(infoWindowHtml);
        infoWindow.setPosition(latLng) ;

        infoWindow.open(map);
        selectText('iw-text');
        document.execCommand('copy');
        clearSelection('iw-text');
        $('#lat').click( { elementId: 'lat'}, copyElementText );
        $('#lng').click( { elementId: 'lng'}, copyElementText );

    }
    //Add listener
    google.maps.event.addListener(map, "click", popup); //end addListener

    //Add listener
    google.maps.event.addListener(area, "click", popup); //end addListener

    var legend = document.getElementById('legend');
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);

    var beacons = document.getElementById('beacons');
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(beacons);

    for (var i = 0; i < 10; i++) {
        var div = document.createElement('div');
        var color = i === 0 ? "#525252" : i < 3 ? "#2bb128" : i < 6 ? "#fff600" : "#ff0612";
        var major = i === 0 ? 1 : i < 3 ? 2 : i < 6 ? 3 : 4;
        var minor = i === 9 ? 4 : ( i === 8 || i === 5 ) ? 3 : ( i === 2 || i === 4 || i === 7) ? 2 : 1;
        div.innerHTML = '╼  ' + major + "." + minor + '<input class="custom-checkbox" type="checkbox" checked="true" onchange="checkboxChanged(event,' + major + ',' + minor+ ');"/>';
        beacons.appendChild(div);
    }

    area.setMap(map);
}

function checkboxChanged(event, major, minor){
    if (event.target.checked) {
        check(major, minor);
    } else {
        uncheck(major, minor);
    }
}

function check(major, minor){
    var indx = indexInMarkersCollection(major, minor);
    beacon_filter[indx] = false;
    setMarkersMap(indx , map);
}

function uncheck(major, minor){
    var indx = indexInMarkersCollection(major, minor);
    beacon_filter[indx] = true;
    setMarkersMap(indx , null);
}

$(function () {
    var d = new Date();
    var month = d.getMonth();
    var day = d.getDate();
    var year = d.getFullYear();
    var hour = d.getHours();
    var minute = d.getMinutes();

    $('#datetimepicker1')
        .datetimepicker({
            locale: 'pl',
            defaultDate: new Date()
        });

    startTime = d.getTime();
});

function buttonEvent() {
    for (var i = 0; i < markers.length; i++) {
        setMarkersMap(i, null);
    }
    clearMarkers();
    for (var i = 0; i < polylines.length; i++) {
        polylines[i].setMap(null);
    }
    polylines = [];
    var date = $("#datetimepicker1").find("input").val();
    var parts = date.split(".");
    var tail = parts[2].split(" ");
    var hours = tail[1].split(":");
    var dateP = new Date(tail[0], parts[1] - 1, parts[0], hours[0], hours[1]);
    startTime = dateP.getTime();
}

function setMarkersMap(i, map){
    for (var j = 0; j < markers[i].length; j++) {
        markers[i][j].setMap(map);
    }
}

function clearMarkers() {
    markers = [];
    var beacons = document.getElementById('beacons');
    for (var i = 0; i < 10; i++) {
        markers[i] = [];
        beacon_filter[i] = false;
        if(beacons !== null) beacons.childNodes[i].childNodes[3].checked = true;
    }
}

function copyElementText(event){
    selectText(event.data.elementId);
    document.execCommand('copy');
    clearSelection(event.data.elementId);
}

function selectText(element) {
    var text = document.getElementById(element);
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
}

function clearSelection(element) {
    var text = document.getElementById(element);
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
}

function updateLegend(){
    var legend = document.getElementById('legend');
    while (legend.firstChild) {
        legend.removeChild(legend.firstChild);
    }
    for(var i = 0; i < DRONES.length; i++){
        var div = document.createElement('div');
        var color = DRONES[i].fields.color;
        var name = DRONES[i].fields.name;
        div.innerHTML = '╼  ' + name + '';
        legend.appendChild(div);
    }
}
<commit_msg>clusters hidding test<commit_after>var m_rad = 5;
var marker_icon_path = 'M 0, 0 m -' + m_rad + ', 0 a ' + m_rad + ',' + m_rad + ' 0 1,0 ' + 2 * m_rad + ',0 a ' + m_rad + ',' + m_rad + ' 0 1,0 -' + 2 * m_rad + ',0';
var startTime = 0;
var DRONES = [];
var polylines = [];
var map;
var beacon_filter = [];
var clusters = [];

var cluster_styles =
    [
        [{
            url: 'http://localhost:8000/static/m1.png',
            width: 40,
            height: 40,
            textColor: '#ffffff',
            textSize: 11
        }],
        [{
            url: 'http://localhost:8000/static/m2.png',
            height: 40,
            width: 40,
            textColor: '#ffffff',
            textSize: 11
        }],
        [{
            url: 'http://localhost:8000/static/m3.png',
            height: 40,
            width: 40,
            textColor: '#525252',
            textSize: 11
        }],
        [{
            url: 'http://localhost:8000/static/m4.png',
            height: 40,
            width: 40,
            textColor: '#ffffff',
            textSize: 11
        }]
    ];

clearMarkers();

setInterval(
    function getPoint() {
        $.ajax({
            type: "GET",
            url: "http://localhost:8000/map/getData/?StartTime=" + startTime,
            dataType: "json",
            success: parseSuccess,
            error: errorHandler
        });
    }, 500);

function errorHandler(response, options, error) {
    console.error("Error while trying to retrieve beacon and drone data from server.");
    console.error(response);
    console.error(response.responseText);
    console.log(error);
}

function parseSuccess(response) {
    startTime = response.current_time;
    updateDrones(response.drones);
    addDronesPolyline(response.drones_positions);
    addBeaconPoints(response.beacons_positions);
    createClusters();
}

function median(values) {
    values.sort(function (a, b) {
        return a - b;
    });
    var half = Math.floor(values.length / 2);
    if (values.length % 2)
        return values[half];
    else
        return (values[half - 1] + values[half]) / 2.0;
}

function createClusters() {
    markers.map(function (beacon_markers, i) {
        if (beacon_filter[i] === true) {
            var cluster = new MarkerClusterer(
                map,
                beacon_markers,
                {
                    gridSize: 40,
                    averageCenter: true,
                    ignoreHidden: true,
                    styles: cluster_styles[i === 0 ? 0 : i < 3 ? 1 : i < 6 ? 2 : 3],
                    visible: false
                });
            cluster.setCalculator(function (markers, numStyles) {
                var rssiSum = 0;
                var min = 255;
                var max = 0;
                var rssiArr = [];
                for (var i = 0; i < markers.length; i++) {
                    var rssi = parseInt(markers[i].label.split(" ")[0]);
                    if (rssi > max) max = rssi;
                    if (rssi < min) min = rssi;
                    rssiArr.push(rssi);
                    rssiSum += rssi;
                }
                var med = median(rssiArr);
                var minor = markers[0].label.split(" ")[1];
                var major = markers[0].label.split(" ")[2];
                return {
                    text: minor + " " + major + " " + markers.length + "
" + max + " " + min + "
" + Math.round(rssiSum / markers.length) + " " + Math.round(med),
                    index: 0
                };
            });
            clusters[i] = cluster;
        }
    });
}

function updateDrones(drones) {
    var found = false;
    for (var i = 0; i < drones.length; i++) {
        for (var j = 0; j < DRONES.length; j++) {
            if (DRONES[j].pk === drones[i].pk) {
                found = true;
            }
        }
        if (!found) {
            DRONES.push(drones[i]);
        }
        found = false;
    }
    updateLegend();
}

function findDrone(id) {
    for (var i = 0; i < DRONES.length; i++) {
        if (DRONES[i].pk === id) return DRONES[i];
    }
    console.error("Any drone with id " + id + " found.");
}

function addDronesPolyline(points) {
    for (var i = 0; i < points.length; i++) {
        var latitude = parseFloat(points[i].fields.latitude);
        var longitude = parseFloat(points[i].fields.longitude);
        var drone = findDrone(points[i].fields.drone);
        var lastPoint = drone.fields.last_position;
        drone.fields.last_position = {
            lat: latitude,
            lng: longitude
        };
        if (typeof lastPoint !== "undefined") {
            addPolyline(lastPoint, drone.fields.last_position, drone.fields.color);
        } else {
            addPoint(latitude, longitude, drone.fields.color, "", drone.fields.name, 1); //add point if just one point (start point)
        }
    }
}

function addBeaconPoints(beacons) {
    for (var i = 0; i < beacons.length; i++) {
        var latitude = beacons[i].fields.latitude;
        var longitude = beacons[i].fields.longitude;
        var altitude = beacons[i].fields.altitude;
        var scale = (100 - beacons[i].fields.altitude) / 30;
        var color = beacons[i].fields.major === 4 ? "red" :
            beacons[i].fields.major === 3 ? "yellow" :
                beacons[i].fields.major === 2 ? "green" :
                    beacons[i].fields.major === 1 ? "#696969" : "white";
        var label = beacons[i].fields.rssi + " " + beacons[i].fields.minor + " " + beacons[i].fields.major;
        var title = Math.round(altitude * 100) / 100 + " m";
        var marker = addPoint(latitude, longitude, color, label, title, 3.0);
        addMarkerToInternalCollection(marker, beacons[i].fields.major, beacons[i].fields.minor);
    }
}

function addMarkerToInternalCollection(marker, major, minor) {
    markers[indexInMarkersCollection(major, minor)].push(marker);
}

function indexInMarkersCollection(major, minor) {
    switch (major) {
        case 1:
            return 0;
        case 2:
            return 0 + minor;
        case 3:
            return 2 + minor;
        case 4:
            return 5 + minor;
    }
}

function addPoint(latitude, longitude, color, label, title, scale) {
    return new google.maps.Marker({
        position: {lat: latitude, lng: longitude},
        map: map,
        icon: {
            path: marker_icon_path,
            fillColor: color,
            fillOpacity: 1.0,
            strokeOpacity: 0.0,
            scale: scale
        },
        label: label,
        title: title
    });
}

function addPolyline(p1, p2, color) {
    var polyline = new google.maps.Polyline({
        path: [
            p1,
            p2
        ],
        map: map,
        geodesic: true,
        strokeColor: color,
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    polylines.push(polyline);
}

function initMap() {
    var center_pos = {lat: 50.089684, lng: 20.202649};
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: center_pos,
        scrollwheel: true,
        draggable: true,
        mapTypeId: 'satellite'
    });

    /* north-west corner, clockwise direction */
    var areaCoords = [
        {lat: 50.0931667, lng: 20.1916000},
        {lat: 50.0931667, lng: 20.2000000},
        {lat: 50.0931667, lng: 20.2066167},
        {lat: 50.0903500, lng: 20.2090667},
        {lat: 50.0883333, lng: 20.2090667},
        {lat: 50.0883333, lng: 20.2029000},
        {lat: 50.0883333, lng: 20.2000000},
        {lat: 50.0883333, lng: 20.1970000},
        {lat: 50.0883333, lng: 20.1926833},
        {lat: 50.0906167, lng: 20.1919500},
        {lat: 50.0916333, lng: 20.1916000}
    ];

    var area = new google.maps.Polygon({
        paths: areaCoords,
        strokeColor: '#FFA500',
        strokeOpacity: 1,
        strokeWeight: 5,
        fillColor: 'green',
        fillOpacity: 0.2
    });

    var infoWindow = new google.maps.InfoWindow({
        pixelOffset: new google.maps.Size(0, 0)
    });

    function popup(event) {
        var latitude = event.latLng.lat();
        var longitude = event.latLng.lng();
        var latLng = event.latLng;

        infoWindowHtml = '
' +
            '' +
            latitude +
            '' + ', ' +
            '' +
            longitude +
            '' +
            '
';
        infoWindow.setContent(infoWindowHtml);
        infoWindow.setPosition(latLng);

        infoWindow.open(map);
        selectText('iw-text');
        document.execCommand('copy');
        clearSelection('iw-text');
        $('#lat').click({elementId: 'lat'}, copyElementText);
        $('#lng').click({elementId: 'lng'}, copyElementText);

    }

    //Add listener
    google.maps.event.addListener(map, "click", popup); //end addListener

    //Add listener
    google.maps.event.addListener(area, "click", popup); //end addListener

    var legend = document.getElementById('legend');
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);

    var beacons = document.getElementById('beacons');
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(beacons);

    for (var i = 0; i < 10; i++) {
        var div = document.createElement('div');
        var color = i === 0 ? "#525252" : i < 3 ? "#2bb128" : i < 6 ? "#fff600" : "#ff0612";
        var major = i === 0 ? 1 : i < 3 ? 2 : i < 6 ? 3 : 4;
        var minor = i === 9 ? 4 : ( i === 8 || i === 5 ) ? 3 : ( i === 2 || i === 4 || i === 7) ? 2 : 1;
        div.innerHTML = '╼  ' + major + "." + minor + '<input class="custom-checkbox" type="checkbox" checked="true" onchange="checkboxChanged(event,' + major + ',' + minor + ');"/>';
        beacons.appendChild(div);
    }

    area.setMap(map);
}

function checkboxChanged(event, major, minor) {
    if (event.target.checked) {
        check(major, minor);
    } else {
        uncheck(major, minor);
    }
}

function check(major, minor) {
    var indx = indexInMarkersCollection(major, minor);
    beacon_filter[indx] = false;
    //clusters[indx].visible = true;
    setMarkersMap(indx, map);
}

function uncheck(major, minor) {
    var indx = indexInMarkersCollection(major, minor);
    beacon_filter[indx] = true;
    //clusters[indx].visible = false;
    setMarkersMap(indx, null);
}

$(function () {
    var d = new Date();
    var month = d.getMonth();
    var day = d.getDate();
    var year = d.getFullYear();
    var hour = d.getHours();
    var minute = d.getMinutes();

    $('#datetimepicker1')
        .datetimepicker({
            locale: 'pl',
            defaultDate: new Date()
        });

    startTime = d.getTime();
});

function buttonEvent() {
    for (var i = 0; i < markers.length; i++) {
        setMarkersMap(i, null);
    }
    clearMarkers();
    for (var i = 0; i < polylines.length; i++) {
        polylines[i].setMap(null);
    }
    polylines = [];
    var date = $("#datetimepicker1").find("input").val();
    var parts = date.split(".");
    var tail = parts[2].split(" ");
    var hours = tail[1].split(":");
    var dateP = new Date(tail[0], parts[1] - 1, parts[0], hours[0], hours[1]);
    startTime = dateP.getTime();
}

function setMarkersMap(i, map) {
    for (var j = 0; j < markers[i].length; j++) {
        markers[i][j].setMap(map);
        markers[i][j].visible = (map !== null);
    }
}

function clearMarkers() {
    markers = [];
    var beacons = document.getElementById('beacons');
    for (var i = 0; i < 10; i++) {
        markers[i] = [];
        beacon_filter[i] = false;
        if (beacons !== null) beacons.childNodes[i].childNodes[3].checked = true;
    }
}

function copyElementText(event) {
    selectText(event.data.elementId);
    document.execCommand('copy');
    clearSelection(event.data.elementId);
}

function selectText(element) {
    var text = document.getElementById(element);
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
}

function clearSelection(element) {
    var text = document.getElementById(element);
    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
}

function updateLegend() {
    var legend = document.getElementById('legend');
    while (legend.firstChild) {
        legend.removeChild(legend.firstChild);
    }
    for (var i = 0; i < DRONES.length; i++) {
        var div = document.createElement('div');
        var color = DRONES[i].fields.color;
        var name = DRONES[i].fields.name;
        div.innerHTML = '╼  ' + name + '';
        legend.appendChild(div);
    }
}
<|endoftext|>


<commit_before>/**
 * bootbox.js v2.3.2
 *
 * The MIT License
 *
 * Copyright (C) 2011-2012 by Nick Payne <nick@kurai.co.uk>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE
 */
var bootbox=window.bootbox||function(k){function j(b,a){null==a&&(a=l);return"string"==typeof h[a][b]?h[a][b]:a!=m?j(b,m):b}var l="en",m="en",p=!0,g={},f={},h={en:{OK:"OK",CANCEL:"Cancel",CONFIRM:"OK"},fr:{OK:"OK",CANCEL:"Annuler",CONFIRM:"D'accord"},de:{OK:"OK",CANCEL:"Abbrechen",CONFIRM:"Akzeptieren"},es:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Aceptar"},br:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Sim"},nl:{OK:"OK",CANCEL:"Annuleren",CONFIRM:"Accepteren"},ru:{OK:"OK",CANCEL:"\u041e\u0442\u043c\u0435\u043d\u0430",
CONFIRM:"\u041f\u0440\u0438\u043c\u0435\u043d\u0438\u0442\u044c"},it:{OK:"OK",CANCEL:"Annulla",CONFIRM:"Conferma"}};f.setLocale=function(b){for(var a in h)if(a==b){l=b;return}throw Error("Invalid locale: "+b);};f.addLocale=function(b,a){"undefined"==typeof h[b]&&(h[b]={});for(var c in a)h[b][c]=a[c]};f.setIcons=function(b){g=b;if("object"!==typeof g||null==g)g={}};f.alert=function(){var b="",a=j("OK"),c=null;switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"function"==typeof arguments[1]?
c=arguments[1]:a=arguments[1];break;case 3:b=arguments[0];a=arguments[1];c=arguments[2];break;default:throw Error("Incorrect number of arguments: expected 1-3");}return f.dialog(b,{label:a,icon:g.OK,callback:c},{onEscape:c})};f.confirm=function(){var b="",a=j("CANCEL"),c=j("CONFIRM"),e=null;switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"function"==typeof arguments[1]?e=arguments[1]:a=arguments[1];break;case 3:b=arguments[0];a=arguments[1];"function"==typeof arguments[2]?
e=arguments[2]:c=arguments[2];break;case 4:b=arguments[0];a=arguments[1];c=arguments[2];e=arguments[3];break;default:throw Error("Incorrect number of arguments: expected 1-4");}return f.dialog(b,[{label:a,icon:g.CANCEL,callback:function(){"function"==typeof e&&e(!1)}},{label:c,icon:g.CONFIRM,callback:function(){"function"==typeof e&&e(!0)}}])};f.prompt=function(){var b="",a=j("CANCEL"),c=j("CONFIRM"),e=null;switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"function"==typeof arguments[1]?
e=arguments[1]:a=arguments[1];break;case 3:b=arguments[0];a=arguments[1];"function"==typeof arguments[2]?e=arguments[2]:c=arguments[2];break;case 4:b=arguments[0];a=arguments[1];c=arguments[2];e=arguments[3];break;default:throw Error("Incorrect number of arguments: expected 1-4");}var n=k("<form></form>");n.append("<input autocomplete=off type=text />");var h=f.dialog(n,[{label:a,icon:g.CANCEL,callback:function(){"function"==typeof e&&e(null)}},{label:c,icon:g.CONFIRM,callback:function(){"function"==
typeof e&&e(n.find("input[type=text]").val())}}],{header:b});h.on("shown",function(){n.find("input[type=text]").focus();n.on("submit",function(a){a.preventDefault();h.find(".btn-primary").click()})});return h};f.modal=function(){var b,a,c,e={onEscape:null,keyboard:!0,backdrop:!0};switch(arguments.length){case 1:b=arguments[0];break;case 2:b=arguments[0];"object"==typeof arguments[1]?c=arguments[1]:a=arguments[1];break;case 3:b=arguments[0];a=arguments[1];c=arguments[2];break;default:throw Error("Incorrect number of arguments: expected 1-3");
}e.header=a;c="object"==typeof c?k.extend(e,c):e;return f.dialog(b,[],c)};f.dialog=function(b,a,c){var e=null,f="",h=[],c=c||{};null==a?a=[]:"undefined"==typeof a.length&&(a=[a]);for(var d=a.length;d--;){var g=null,j=null,l="",m=null;if("undefined"==typeof a[d].label&&"undefined"==typeof a[d]["class"]&&"undefined"==typeof a[d].callback){var g=0,q=null,o;for(o in a[d])if(q=o,1<++g)break;1==g&&"function"==typeof a[d][o]&&(a[d].label=q,a[d].callback=a[d][o])}"function"==typeof a[d].callback&&(m=a[d].callback);
a[d]["class"]?j=a[d]["class"]:d==a.length-1&&2>=a.length&&(j="btn-primary");g=a[d].label?a[d].label:"Option "+(d+1);a[d].icon&&(l=" ");f+=""+l+""+g+"";h[d]=m}a=["
"];if(c.header){d="";if("undefined"==typeof c.headerCloseButton||c.headerCloseButton)d="×";a.push("
"+d+"
"+c.header+"

")}a.push("

");
f&&a.push("
"+f+"
");a.push("
");var i=k(a.join("\n"));("undefined"===typeof c.animate?p:c.animate)&&i.addClass("fade");k(".modal-body",i).html(b);i.bind("hidden",function(){i.remove()});i.bind("hide",function(){if("escape"==e&&"function"==typeof c.onEscape)c.onEscape()});k(document).bind("keyup.modal",function(a){27==a.which&&(e="escape")});i.bind("shown",function(){k("a.btn-primary:last",i).focus()});i.on("click",".modal-footer a, a.close",function(a){var b=k(this).data("handler"),
b=h[b],c=null;"function"==typeof b&&(c=b());!1!==c&&(a.preventDefault(),e="button",i.modal("hide"))});null==c.keyboard&&(c.keyboard="function"==typeof c.onEscape);k("body").append(i);i.modal({backdrop:c.backdrop||!0,keyboard:c.keyboard});return i};f.hideAll=function(){k(".bootbox").modal("hide")};f.animate=function(b){p=b};return f}(window.jQuery);
<commit_msg>update bootbox plugin to latest version<commit_after>/**
 * bootbox.js v3.3.0
 *
 * http://bootboxjs.com/license.txt
 */
var bootbox=window.bootbox||function(a,b){function c(a,b){return"undefined"==typeof b&&(b=d),"string"==typeof m[b][a]?m[b][a]:b!=e?c(a,e):a}var d="en",e="en",f=!0,g="static",h="javascript:;",i="",j={},k={},l={};l.setLocale=function(a){for(var b in m)if(b==a)return d=a,void 0;throw new Error("Invalid locale: "+a)},l.addLocale=function(a,b){"undefined"==typeof m[a]&&(m[a]={});for(var c in b)m[a][c]=b[c]},l.setIcons=function(a){k=a,("object"!=typeof k||null===k)&&(k={})},l.setBtnClasses=function(a){j=a,("object"!=typeof j||null===j)&&(j={})},l.alert=function(){var a="",b=c("OK"),d=null;switch(arguments.length){case 1:a=arguments[0];break;case 2:a=arguments[0],"function"==typeof arguments[1]?d=arguments[1]:b=arguments[1];break;case 3:a=arguments[0],b=arguments[1],d=arguments[2];break;default:throw new Error("Incorrect number of arguments: expected 1-3")}return l.dialog(a,{label:b,icon:k.OK,"class":j.OK,callback:d},{onEscape:d||!0})},l.confirm=function(){var a="",b=c("CANCEL"),d=c("CONFIRM"),e=null;switch(arguments.length){case 1:a=arguments[0];break;case 2:a=arguments[0],"function"==typeof arguments[1]?e=arguments[1]:b=arguments[1];break;case 3:a=arguments[0],b=arguments[1],"function"==typeof arguments[2]?e=arguments[2]:d=arguments[2];break;case 4:a=arguments[0],b=arguments[1],d=arguments[2],e=arguments[3];break;default:throw new Error("Incorrect number of arguments: expected 1-4")}var f=function(){return"function"==typeof e?e(!1):void 0},g=function(){return"function"==typeof e?e(!0):void 0};return l.dialog(a,[{label:b,icon:k.CANCEL,"class":j.CANCEL,callback:f},{label:d,icon:k.CONFIRM,"class":j.CONFIRM,callback:g}],{onEscape:f})},l.prompt=function(){var a="",d=c("CANCEL"),e=c("CONFIRM"),f=null,g="";switch(arguments.length){case 1:a=arguments[0];break;case 2:a=arguments[0],"function"==typeof arguments[1]?f=arguments[1]:d=arguments[1];break;case 3:a=arguments[0],d=arguments[1],"function"==typeof arguments[2]?f=arguments[2]:e=arguments[2];break;case 4:a=arguments[0],d=arguments[1],e=arguments[2],f=arguments[3];break;case 5:a=arguments[0],d=arguments[1],e=arguments[2],f=arguments[3],g=arguments[4];break;default:throw new Error("Incorrect number of arguments: expected 1-5")}var h=a,i=b("<form></form>");i.append("<input class='input-block-level' autocomplete=off type=text value='"+g+"' />");var m=function(){return"function"==typeof f?f(null):void 0},n=function(){return"function"==typeof f?f(i.find("input[type=text]").val()):void 0},o=l.dialog(i,[{label:d,icon:k.CANCEL,"class":j.CANCEL,callback:m},{label:e,icon:k.CONFIRM,"class":j.CONFIRM,callback:n}],{header:h,show:!1,onEscape:m});return o.on("shown",function(){i.find("input[type=text]").focus(),i.on("submit",function(a){a.preventDefault(),o.find(".btn-primary").click()})}),o.modal("show"),o},l.dialog=function(c,d,e){function j(){var a=null;"function"==typeof e.onEscape&&(a=e.onEscape()),a!==!1&&x.modal("hide")}var k="",l=[];e||(e={}),"undefined"==typeof d?d=[]:"undefined"==typeof d.length&&(d=[d]);for(var m=d.length;m--;){var n=null,o=null,p=null,q="",r=null;if("undefined"==typeof d[m].label&&"undefined"==typeof d[m]["class"]&&"undefined"==typeof d[m].callback){var s=0,t=null;for(var u in d[m])if(t=u,++s>1)break;1==s&&"function"==typeof d[m][u]&&(d[m].label=t,d[m].callback=d[m][u])}"function"==typeof d[m].callback&&(r=d[m].callback),d[m]["class"]?p=d[m]["class"]:m==d.length-1&&d.length<=2&&(p="btn-primary"),d[m].link!==!0&&(p="btn "+p),n=d[m].label?d[m].label:"Option "+(m+1),d[m].icon&&(q=" "),o=d[m].href?d[m].href:h,k=""+q+n+""+k,l[m]=r}var v=["
"];if(e.header){var w="";("undefined"==typeof e.headerCloseButton||e.headerCloseButton)&&(w="×"),v.push("
"+w+"
"+e.header+"

")}v.push("

"),k&&v.push("
"+k+"
"),v.push("
");var x=b(v.join("\n")),y="undefined"==typeof e.animate?f:e.animate;y&&x.addClass("fade");var z="undefined"==typeof e.classes?i:e.classes;return z&&x.addClass(z),x.find(".modal-body").html(c),x.on("keyup.dismiss.modal",function(a){27===a.which&&e.onEscape&&j("escape")}),x.on("click","a.close",function(a){a.preventDefault(),j("close")}),x.on("shown",function(){x.find("a.btn-primary:first").focus()}),x.on("hidden",function(a){a.target===this&&x.remove()}),x.on("click",".modal-footer a",function(a){var c=b(this).data("handler"),e=l[c],f=null;("undefined"==typeof c||"undefined"==typeof d[c].href)&&(a.preventDefault(),"function"==typeof e&&(f=e(a)),f!==!1&&x.modal("hide"))}),b("body").append(x),x.modal({backdrop:"undefined"==typeof e.backdrop?g:e.backdrop,keyboard:!1,show:!1}),x.on("show",function(){b(a).off("focusin.modal")}),("undefined"==typeof e.show||e.show===!0)&&x.modal("show"),x},l.modal=function(){var a,c,d,e={onEscape:null,keyboard:!0,backdrop:g};switch(arguments.length){case 1:a=arguments[0];break;case 2:a=arguments[0],"object"==typeof arguments[1]?d=arguments[1]:c=arguments[1];break;case 3:a=arguments[0],c=arguments[1],d=arguments[2];break;default:throw new Error("Incorrect number of arguments: expected 1-3")}return e.header=c,d="object"==typeof d?b.extend(e,d):e,l.dialog(a,[],d)},l.hideAll=function(){b(".bootbox").modal("hide")},l.animate=function(a){f=a},l.backdrop=function(a){g=a},l.classes=function(a){i=a};var m={br:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Sim"},da:{OK:"OK",CANCEL:"Annuller",CONFIRM:"Accepter"},de:{OK:"OK",CANCEL:"Abbrechen",CONFIRM:"Akzeptieren"},en:{OK:"OK",CANCEL:"Cancel",CONFIRM:"OK"},es:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Aceptar"},fr:{OK:"OK",CANCEL:"Annuler",CONFIRM:"D'accord"},it:{OK:"OK",CANCEL:"Annulla",CONFIRM:"Conferma"},nl:{OK:"OK",CANCEL:"Annuleren",CONFIRM:"Accepteren"},pl:{OK:"OK",CANCEL:"Anuluj",CONFIRM:"Potwierdź"},ru:{OK:"OK",CANCEL:"Отмена",CONFIRM:"Применить"},zh_CN:{OK:"OK",CANCEL:"取消",CONFIRM:"确认"},zh_TW:{OK:"OK",CANCEL:"取消",CONFIRM:"確認"}};return l}(document,window.jQuery);window.bootbox=bootbox;<|endoftext|>


<commit_before>var request = require('request');
var config  = require('../config');

var fs   = require('fs');
var path = require('path');
var fut  = require('futures').sequence;

var demoMode = false;
var assetDir = path.join(__dirname, '/assets/images/');

// 'node index.js demo'
// should use demo mode ?
if(process.argv.length === 3 && process.argv[2] === 'demo') {
    demoMode = true;
}

fs.exists(config.uploadDir, function (exists) {
    if(!exists) fs.mkdir(config.uploadDir);
});

var assetsSeq = new fut();

fs.readdir(assetDir, function (err, files) {
    if(err) throw err;

    files.forEach(function (file, index) {

        if(demoMode && index === 4) return;

        assetsSeq.then(function (next) {

            var req  = request.post(config.url + '/meals/');
            var form = req.form();

            form.append('title', path.basename(file, '.jpg'));
            form.append('amount', 1);
            form.append('image', fs.createReadStream(assetDir + path.basename(file)));

            req.on('response', function (response) {
                console.log(file + ' added.');
                next();
            });

        });
    });
});

var mealtimesMigration = [
    { id: 'mealtime_1', title: 'A - 12:30'},
    { id: 'mealtime_2', title: 'B - 13:15'},
    { id: 'mealtime_3', title: 'C - 14:00'}
];

var mealtimeSeq = new fut();

mealtimeSeq

    .then(function (next) {

        request({
            uri     :  config.url + '/mealtimes/',
            method  : 'GET',
            json: true
        }, function (error, response, mealtimes) {
            if(mealtimes.length < mealtimesMigration.length) {
                next();
            } else {
                console.log('mealtimes already exists.');
            }
        });

    })

    .then(function () {

        mealtimesMigration.forEach(function (item) {
            request({
                uri     :  config.url + '/mealtimes/',
                method  : 'POST',
                body    : {
                    id   : item.id,
                    title: item.title
                },
                json: true
            }, function () {
                console.log('Added mealtime: ' + item.id + ' ' + item.title);
            });
        });
    });

<commit_msg>fixed config load bug<commit_after>var request = require('request');
var config  = require('../../config');

var fs   = require('fs');
var path = require('path');
var fut  = require('futures').sequence;

var demoMode = false;
var assetDir = path.join(__dirname, '/assets/images/');

// 'node index.js demo'
// should use demo mode ?
if(process.argv.length === 3 && process.argv[2] === 'demo') {
    demoMode = true;
}

fs.exists(config.uploadDir, function (exists) {
    if(!exists) fs.mkdir(config.uploadDir);
});

var assetsSeq = new fut();

fs.readdir(assetDir, function (err, files) {
    if(err) throw err;

    files.forEach(function (file, index) {

        if(demoMode && index === 4) return;

        assetsSeq.then(function (next) {

            var req  = request.post(config.url + '/meals/');
            var form = req.form();

            form.append('title', path.basename(file, '.jpg'));
            form.append('amount', 1);
            form.append('image', fs.createReadStream(assetDir + path.basename(file)));

            req.on('response', function (response) {
                console.log(file + ' added.');
                next();
            });

        });
    });
});

var mealtimesMigration = [
    { id: 'mealtime_1', title: 'A - 12:30'},
    { id: 'mealtime_2', title: 'B - 13:15'},
    { id: 'mealtime_3', title: 'C - 14:00'}
];

var mealtimeSeq = new fut();

mealtimeSeq

    .then(function (next) {

        request({
            uri     :  config.url + '/mealtimes/',
            method  : 'GET',
            json: true
        }, function (error, response, mealtimes) {
            if(mealtimes.length < mealtimesMigration.length) {
                next();
            } else {
                console.log('mealtimes already exists.');
            }
        });

    })

    .then(function () {

        mealtimesMigration.forEach(function (item) {
            request({
                uri     :  config.url + '/mealtimes/',
                method  : 'POST',
                body    : {
                    id   : item.id,
                    title: item.title
                },
                json: true
            }, function () {
                console.log('Added mealtime: ' + item.id + ' ' + item.title);
            });
        });
    });

<|endoftext|>


<commit_before>chrome.storage.local.get(function (model) {
  if (model.enabled) {
    var spineScript = document.createElement('script');
    spineScript.setAttribute('src', chrome.extension.getURL('spine.js'));

    var sinonScript = document.createElement('script');
    sinonScript.setAttribute('src', chrome.extension.getURL('sinon.js'));

    var initScript = document.createElement('script');
    initScript.textContent =
      (model.verbose ? 'console.log("Spline Model: ", ' + JSON.stringify(model) + '); ' : '') +
      'window.spine = window.spine || {};' +
      'spine.verbose = ' + (model.verbose ? 'true; ' : 'false; ') +
      'spine.init = function () {' +
      '  spine.traceActions(' + (model.traceActions ? "" : "false") + ');' +
      (model.ajaxTraces.length > 0
        ? '  spine.traceAjax.apply(spine, ' + JSON.stringify(model.ajaxTraces) + ')'
        : '') +
      (model.backboneTraces.length > 0
        ? '  spine.traceEvents.apply(spine, ' + JSON.stringify(model.backboneTraces) + ')'
        : '') +
      '};';

    var scriptParent = (document.head||document.documentElement);
    scriptParent.appendChild(sinonScript);
    scriptParent.appendChild(spineScript);
    scriptParent.appendChild(initScript);
  }
});

chrome.runtime.sendMessage('page:load');

window.addEventListener('message', function (msg) {
  if (msg.data.match(/^spine:/)) chrome.runtime.sendMessage(msg.data)
});
<commit_msg>Try not to crash google docs when the extension is left on<commit_after>chrome.storage.local.get(function (model) {
  if (model.enabled) {
    var spineScript = document.createElement('script');
    spineScript.setAttribute('src', chrome.extension.getURL('spine.js'));

    var sinonScript = document.createElement('script');
    sinonScript.setAttribute('src', chrome.extension.getURL('sinon.js'));

    var initScript = document.createElement('script');
    initScript.textContent =
      (model.verbose ? 'console.log("Spline Model: ", ' + JSON.stringify(model) + '); ' : '') +
      'window.spine = window.spine || {};' +
      'spine.verbose = ' + (model.verbose ? 'true; ' : 'false; ') +
      'spine.init = function () {' +
      '  spine.traceActions(' + (model.traceActions ? "" : "false") + ');' +
      (model.ajaxTraces.length > 0
        ? '  spine.traceAjax.apply(spine, ' + JSON.stringify(model.ajaxTraces) + ')'
        : '') +
      (model.backboneTraces.length > 0
        ? '  spine.traceEvents.apply(spine, ' + JSON.stringify(model.backboneTraces) + ')'
        : '') +
      '};';

    var scriptParent = (document.head||document.documentElement);
    scriptParent.appendChild(sinonScript);
    scriptParent.appendChild(spineScript);
    scriptParent.appendChild(initScript);
  }
});

chrome.runtime.sendMessage('page:load');

window.addEventListener('message', function (msg) {
  if (msg.data
      && typeof(msg.data.match) == 'function'
      && msg.data.match(/^spine:/)
    ) chrome.runtime.sendMessage(msg.data);
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name Flight Management Computer for GeoFS
// @description This extension adds an FMC which controls features such as VNAV, LNAV, route, progress information, etc.
// @namespace GeoFS-Plugins
// @match http://*/geofs.php*
// @run-at document-end
// @version 0.5.1-beta
// @grant none
// ==/UserScript==
<commit_msg>Update to v0.5.2 for release<commit_after>// ==UserScript==
// @name Flight Management Computer for GeoFS
// @description This extension adds an FMC which controls features such as VNAV, LNAV, route, progress information, etc.
// @author Harry Xue
// @namespace GeoFS-Plugins
// @match http://*/geofs.php*
// @run-at document-end
// @version 0.5.2
// @grant none
// ==/UserScript==
<|endoftext|>