<commit_before>'use strict';

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

var _ = require('underscore');

function objectIntersect(arr1, arr2){
    return _.filter(arr1, function(item){
        return !(_.any(arr2, function(otherItem){
            return _.isEqual(item, otherItem);
        }));
    });
}

function LegacySelleckt(options){
    if(!window.MutationObserver || !window.MutationObserver._period){
        throw new Error('LegacySelleckt requires the MutationObserver shim');
    }

    SingleSelleckt.call(this, options);
}

LegacySelleckt.prototype.DELAY_TIMEOUT = window.MutationObserver._period;

LegacySelleckt.prototype._mutationHandler = function(mutations){
    var createSellecktItem = _.bind(this._createSellecktItem, this),
        $items = this.$sellecktEl.find('.' + this.itemslistClass),
        itemsFromNodes = _.bind(this._getItemsFromNodes, this),
        findItemInList = _.bind(this.findItemInList, this),
        newItems = [],
        removedItems = [];

    _.each(mutations, function(mutation) {
        newItems = newItems.concat(itemsFromNodes(mutation.addedNodes));
        removedItems = removedItems.concat(itemsFromNodes(mutation.removedNodes));
    });

    //the Mutation Observer shim sometimes gets confused when removing nodes
    //let's double check that the nodes are indeed removed (otherwise they
    //appear in the newItems array too)
    var trulyRemoved = objectIntersect(removedItems, newItems);
    var trulyNew = objectIntersect(newItems, removedItems);

    removedItems = trulyRemoved;
    newItems = trulyNew;

    $items.append(_.map(newItems, createSellecktItem));

    _.each(removedItems, function(item){
        findItemInList(item).remove();
    });
};

module.exports = LegacySelleckt;
<commit_msg>Legacy Selleckt now directly monkey patchs SingleSelleckt<commit_after>'use strict';

/*
 * This module monkey patches Selleckt for browsers that do not
 * support the MutationObserver.
 * A shim should also be included: https://github.com/megawac/MutationObserver.js
*/

var SingleSelleckt = require('./selleckt').SingleSelleckt;
var _ = require('underscore');

function objectIntersect(arr1, arr2){
    return _.filter(arr1, function(item){
        return !(_.any(arr2, function(otherItem){
            return _.isEqual(item, otherItem);
        }));
    });
}

if(!window.MutationObserver || !window.MutationObserver._period){
    throw new Error('Legacy Selleckt compatability requires the MutationObserver shim');
}

SingleSelleckt.prototype.DELAY_TIMEOUT = window.MutationObserver._period * 2;

SingleSelleckt.prototype._mutationHandler = function(mutations){
    var createSellecktItem = _.bind(this._createSellecktItem, this),
        $items = this.$sellecktEl.find('.' + this.itemslistClass),
        itemsFromNodes = _.bind(this._getItemsFromNodes, this),
        findItemInList = _.bind(this.findItemInList, this),
        newItems = [],
        removedItems = [];

    _.each(mutations, function(mutation) {
        newItems = newItems.concat(itemsFromNodes(mutation.addedNodes));
        removedItems = removedItems.concat(itemsFromNodes(mutation.removedNodes));
    });

    //the Mutation Observer shim sometimes gets confused when removing nodes
    //let's double check that the nodes are indeed removed (otherwise they
    //appear in the newItems array too)
    var trulyRemoved = objectIntersect(removedItems, newItems);
    var trulyNew = objectIntersect(newItems, removedItems);

    removedItems = trulyRemoved;
    newItems = trulyNew;

    $items.append(_.map(newItems, createSellecktItem));

    _.each(removedItems, function(item){
        findItemInList(item).remove();
    });
};

module.exports = SingleSelleckt;
<|endoftext|>


<commit_before>'use strict'
/**
 * Created by tungtouch on 2/9/15.
 */

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

var dgram = require('dgram');
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:");
var client = dgram.createSocket("udp4");
var async = require('async');

var max = 10000;
var numCluster = 100;
var arr = [];
var indexCache = 0;
for (var i = 0; i < max; i++) {
    arr.push(i);
}

var q = async.queue(function(index, cb){
    setTimeout(function () {
        client.send(message, 0, message.length, 4444, "128.199.126.250", function (err) {
            //console.log("Request : ", index);
            indexCache++;

            if(err){
                console.log('ERROR :', err);
                console.log("Total Request", index * numCluster);
            }
            if(indexCache == max ){
                console.log("Total Request", index * numCluster);
            }

            cb(err);
        });

    }, 20);
});

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCluster; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    // Workers can share any TCP connection
    // In this case its a HTTP server
    q.push(arr);
}
console.log("Starting Benchmark!");
<commit_msg>Update UDPefef<commit_after>'use strict'
/**
 * Created by tungtouch on 2/9/15.
 */

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

var dgram = require('dgram');
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:");
var client = dgram.createSocket("udp4");
var async = require('async');

var max = 10000;
var numCluster = 100;
var arr = [];
var indexCache = 0;
for (var i = 0; i < max; i++) {
    arr.push(i);
}

var q = async.queue(function(index, cb){
    setTimeout(function () {
        client.send(message, 0, message.length, 4444, "128.199.126.250", function (err) {
            //console.log("Request : ", index);

            console.log("Total Request", index*numCluster);
            if(err){
                console.log('ERROR :', err);
                console.log("Total Request", index * numCluster);
            }

            cb(err);
        });

    }, 20);
});

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCluster; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    // Workers can share any TCP connection
    // In this case its a HTTP server
    q.push(arr);
}
console.log("Starting Benchmark!");
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var fs = require('fs'),
    path = require('path'),
    exec = require('child_process').exec,
    chalk = require('chalk'),
    Table = require('cli-table'),

    Minimize = require('minimize'),
    minimize = new Minimize();

var fileNames = [
  'abc',
  'amazon',
  'eloquentjavascript',
  //'es6-draft',
  'es6-table',
  'google',
  'html-minifier',
  'msn',
  'newyorktimes',
  'stackoverflow',
  'wikipedia',
  'es6'
];

fileNames = fileNames.sort().reverse();

var table = new Table({
  head: ['File', 'Before', 'After', 'Savings', 'Time'],
  colWidths: [20, 25, 25, 20, 20]
});

function toKb(size) {
  return (size / 1024).toFixed(2);
}

function redSize(size) {
  return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}

function greenSize(size) {
  return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}

function blueSavings(oldSize, newSize) {
  var savingsPercent = (1 - newSize / oldSize) * 100;
  var savings = (oldSize - newSize) / 1024;
  return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)');
}

function blueTime(time) {
  return chalk.cyan.bold(time) + chalk.white(' ms');
}

function test(fileName, done) {

  if (!fileName) {
    console.log('\n' + table.toString());
    return;
  }

  console.log('Processing...', fileName);

  var filePath = path.join('benchmarks/', fileName + '.html');
  var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html');
  var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz');
  var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz');
  var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath;

  // Open and read the size of the original input
  fs.stat(filePath, function (err, stats) {
    if (err) {
      throw new Error('There was an error reading ' + filePath);
    }
    var originalSize = stats.size;

    exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () {
      // Open and read the size of the gzipped original
      fs.stat(gzFilePath, function (err, stats) {
        if (err) {
          throw new Error('There was an error reading ' + gzFilePath);
        }

        var gzOriginalSize = stats.size;

        // Begin timing after gzipped fixtures have been created
        var startTime = new Date();
        exec('node ' + command, function () {

          // Open and read the size of the minified output
          fs.stat(minifiedFilePath, function (err, stats) {
            if (err) {
              throw new Error('There was an error reading ' + minifiedFilePath);
            }

            var minifiedSize = stats.size;
            var minifiedTime = new Date() - startTime;

            minimize.parse(
              fs.readFileSync(filePath),
              function (error, data) {
                console.log('minimize',
                  filePath,
                  toKb(data.length),
                  toKb(minifiedSize));
              }
            );

            // Gzip the minified output
            exec('gzip --keep --force --best --stdout ' + minifiedFilePath + ' > ' + gzMinifiedFilePath, function () {
              // Open and read the size of the minified+gzipped output
              fs.stat(gzMinifiedFilePath, function (err, stats) {
                if (err) {
                  throw new Error('There was an error reading ' + gzMinifiedFilePath);
                }

                var gzMinifiedSize = stats.size;
                var gzMinifiedTime = new Date() - startTime;

                table.push([
                  [fileName, '+ gzipped'].join('\n'),
                  [redSize(originalSize), redSize(gzOriginalSize)].join('\n'),
                  [greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'),
                  [blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'),
                  [blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n')
                ]);

                done();
              });
            });
          });
        });
      });
    });
  });
}

(function run() {
  test(fileNames.pop(), run);
})();
<commit_msg>improve benchmark.js - use internal zlib instead of external gzip command - perform gzip on Minimized output - incorporate Minimize results into table<commit_after>#!/usr/bin/env node

'use strict';

var fs = require('fs'),
    path = require('path'),
    zlib = require('zlib'),
    exec = require('child_process').exec,
    chalk = require('chalk'),
    Table = require('cli-table'),

    Minimize = require('minimize'),
    minimize = new Minimize();

var fileNames = [
  'abc',
  'amazon',
  'eloquentjavascript',
  'es6-draft',
  'es6-table',
  'google',
  'html-minifier',
  'msn',
  'newyorktimes',
  'stackoverflow',
  'wikipedia',
  'es6'
].sort();

var table = new Table({
  head: ['File', 'Before', 'After', 'Savings', 'Time', 'Minimize'],
  colWidths: [20, 25, 25, 20, 10, 25]
});

function toKb(size) {
  return (size / 1024).toFixed(2);
}

function redSize(size) {
  return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}

function greenSize(size) {
  return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)');
}

function blueSavings(oldSize, newSize) {
  var savingsPercent = (1 - newSize / oldSize) * 100;
  var savings = (oldSize - newSize) / 1024;
  return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)');
}

function blueTime(time) {
  return chalk.cyan.bold(time) + chalk.white(' ms');
}

function gzip(inPath, outPath, callback) {
  fs.createReadStream(inPath).pipe(zlib.createGzip({
    level: zlib.Z_BEST_COMPRESSION
  })).pipe(fs.createWriteStream(outPath)).on('finish', callback);
}

function run(tasks, done) {
  var remaining = tasks.length;

  function callback() {
    if (!--remaining) {
      done();
    }
  }

  tasks.forEach(function (task) {
    task(callback);
  });
}

var rows = {};
run(fileNames.map(function (fileName) {
  return function (done) {
    console.log('Processing...', fileName);

    var filePath = path.join('benchmarks/', fileName + '.html');
    var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html');
    var minimizedFilePath = path.join('benchmarks/generated/', fileName + '.mz.html');
    var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz');
    var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz');
    var gzMinimizedFilePath = path.join('benchmarks/generated/', fileName + '.mz.html.gz');
    var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath;
    var originalSize, gzOriginalSize,
        minifiedSize, gzMinifiedSize,
        minimizedSize, gzMinimizedSize,
        minifiedTime, gzMinifiedTime;

    run([
      // Open and read the size of the original input
      function (done) {
        fs.stat(filePath, function (err, stats) {
          if (err) {
            throw new Error('There was an error reading ' + filePath);
          }
          originalSize = stats.size;
          done();
        });
      },
      // Open and read the size of the gzipped original
      function (done) {
        gzip(filePath, gzFilePath, function () {
          fs.stat(gzFilePath, function (err, stats) {
            if (err) {
              throw new Error('There was an error reading ' + gzFilePath);
            }
            gzOriginalSize = stats.size;
            done();
          });
        });
      },
      // Minified test
      function (done) {
        // Begin timing after gzipped fixtures have been created
        var startTime = Date.now();
        exec('node ' + command, function () {

          // Open and read the size of the minified output
          fs.stat(minifiedFilePath, function (err, stats) {
            if (err) {
              throw new Error('There was an error reading ' + minifiedFilePath);
            }

            minifiedSize = stats.size;
            minifiedTime = Date.now() - startTime;

            // Gzip the minified output
            gzip(minifiedFilePath, gzMinifiedFilePath, function () {
              // Open and read the size of the minified+gzipped output
              fs.stat(gzMinifiedFilePath, function (err, stats) {
                if (err) {
                  throw new Error('There was an error reading ' + gzMinifiedFilePath);
                }

                gzMinifiedSize = stats.size;
                gzMinifiedTime = Date.now() - startTime;
                done();
              });
            });
          });
        });
      },
      // Minimize test
      function (done) {
        fs.readFile(filePath, function (err, data) {
          if (err) {
            throw new Error('There was an error reading ' + filePath);
          }
          minimize.parse(data, function (error, data) {
            minimizedSize = data.length;
            fs.writeFile(minimizedFilePath, data, function (err) {
              if (err) {
                throw new Error('There was an error writing ' + minimizedFilePath);
              }
              gzip(minimizedFilePath, gzMinimizedFilePath, function () {
                fs.stat(gzMinimizedFilePath, function (err, stats) {
                  if (err) {
                    throw new Error('There was an error reading ' + gzMinimizedFilePath);
                  }
                  gzMinimizedSize = stats.size;
                  done();
                });
              });
            });
          });
        });
      }
    ], function () {
      rows[fileName] = [
        [fileName, '+ gzipped'].join('\n'),
        [redSize(originalSize), redSize(gzOriginalSize)].join('\n'),
        [greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'),
        [blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'),
        [blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n'),
        [greenSize(minimizedSize), greenSize(gzMinimizedSize)].join('\n')
      ];
      done();
    });
  };
}), function () {
  fileNames.forEach(function (fileName) {
    table.push(rows[fileName]);
  });
  console.log('\n' + table.toString());
});
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const util = require("util");
const memorize = require("./util/memorize");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./util/Hash")} Hash */

const getJavascriptModulesPlugin = memorize(() =>
	require("./JavascriptModulesPlugin")
);

/**
 * @typedef {Object} RenderContext
 * @property {Chunk} chunk the chunk
 * @property {DependencyTemplates} dependencyTemplates the dependency templates
 * @property {RuntimeTemplate} runtimeTemplate the runtime template
 * @property {ModuleGraph} moduleGraph the module graph
 * @property {ChunkGraph} chunkGraph the chunk graph
 */

// TODO webpack 6: remove this class
module.exports = class ModuleTemplate {
	/**
	 * @param {RuntimeTemplate} runtimeTemplate the runtime template
	 * @param {Compilation} compilation the compilation
	 */
	constructor(runtimeTemplate, compilation) {
		this.runtimeTemplate = runtimeTemplate;
		this.type = "javascript";
		this.hooks = Object.freeze({
			content: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModuleContent.tap(options, fn);
					},
					"ModuleTemplate.hooks.content is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
					"DEP_MODULE_TEMPLATE_CONTENT"
				)
			},
			module: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModuleContent.tap(options, fn);
					},
					"ModuleTemplate.hooks.module is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
					"DEP_MODULE_TEMPLATE_MODULE"
				)
			},
			render: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModuleContainer.tap(options, fn);
					},
					"ModuleTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer instead)",
					"DEP_MODULE_TEMPLATE_RENDER"
				)
			},
			package: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModulePackage.tap(options, fn);
					},
					"ModuleTemplate.hooks.package is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModulePackage instead)",
					"DEP_MODULE_TEMPLATE_PACKAGE"
				)
			},
			hash: {
				tap: util.deprecate(
					(options, fn) => {
						compilation.hooks.fullHash.tap(options, fn);
					},
					"ModuleTemplate.hooks.package is deprecated (use Compilation.hooks.fullHash instead)",
					"DEP_MODULE_TEMPLATE_HASH"
				)
			}
		});
	}
};
<commit_msg>fix compat hooks in ModuleTemplate, deprecate ModuleTemplate.runtimeTemplate<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const util = require("util");
const memorize = require("./util/memorize");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./util/Hash")} Hash */

const getJavascriptModulesPlugin = memorize(() =>
	require("./JavascriptModulesPlugin")
);

/**
 * @typedef {Object} RenderContext
 * @property {Chunk} chunk the chunk
 * @property {DependencyTemplates} dependencyTemplates the dependency templates
 * @property {RuntimeTemplate} runtimeTemplate the runtime template
 * @property {ModuleGraph} moduleGraph the module graph
 * @property {ChunkGraph} chunkGraph the chunk graph
 */

// TODO webpack 6: remove this class
class ModuleTemplate {
	/**
	 * @param {RuntimeTemplate} runtimeTemplate the runtime template
	 * @param {Compilation} compilation the compilation
	 */
	constructor(runtimeTemplate, compilation) {
		this._runtimeTemplate = runtimeTemplate;
		this.type = "javascript";
		this.hooks = Object.freeze({
			content: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModuleContent.tap(
								options,
								(source, module, renderContext) =>
									fn(
										source,
										module,
										renderContext,
										renderContext.dependencyTemplates
									)
							);
					},
					"ModuleTemplate.hooks.content is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
					"DEP_MODULE_TEMPLATE_CONTENT"
				)
			},
			module: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModuleContent.tap(
								options,
								(source, module, renderContext) =>
									fn(
										source,
										module,
										renderContext,
										renderContext.dependencyTemplates
									)
							);
					},
					"ModuleTemplate.hooks.module is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
					"DEP_MODULE_TEMPLATE_MODULE"
				)
			},
			render: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModuleContainer.tap(
								options,
								(source, module, renderContext) =>
									fn(
										source,
										module,
										renderContext,
										renderContext.dependencyTemplates
									)
							);
					},
					"ModuleTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer instead)",
					"DEP_MODULE_TEMPLATE_RENDER"
				)
			},
			package: {
				tap: util.deprecate(
					(options, fn) => {
						getJavascriptModulesPlugin()
							.getCompilationHooks(compilation)
							.renderModulePackage.tap(
								options,
								(source, module, renderContext) =>
									fn(
										source,
										module,
										renderContext,
										renderContext.dependencyTemplates
									)
							);
					},
					"ModuleTemplate.hooks.package is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModulePackage instead)",
					"DEP_MODULE_TEMPLATE_PACKAGE"
				)
			},
			hash: {
				tap: util.deprecate(
					(options, fn) => {
						compilation.hooks.fullHash.tap(options, fn);
					},
					"ModuleTemplate.hooks.package is deprecated (use Compilation.hooks.fullHash instead)",
					"DEP_MODULE_TEMPLATE_HASH"
				)
			}
		});
	}
}

Object.defineProperty(ModuleTemplate.prototype, "runtimeTemplate", {
	get: util.deprecate(
		/**
		 * @this {ModuleTemplate}
		 * @returns {TODO} output options
		 */
		function() {
			return this._runtimeTemplate;
		},
		"ModuleTemplate.runtimeTemplate is deprecated (use Compilation.runtimeTemplate instead)",
		"DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS"
	)
});

module.exports = ModuleTemplate;
<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global setTimeout, clearTimeout */

(function (global) {

  function EventTarget() {
    var listeners = [];

    function lastIndexOf(type, callback) {
      var i = listeners.length - 1;
      while (i >= 0 && !(listeners[i].type === type && listeners[i].callback === callback)) {
        i -= 1;
      }
      return i;
    }

    this.dispatchEvent = function (event) {
      function a(e) {
        return function () {
          throw e;
        };
      }

      var type = event.type,
        candidates = listeners.slice(0),
        i;
      for (i = 0; i < candidates.length; i += 1) {
        if (candidates[i].type === type) {
          try {
            candidates[i].callback.call(this, event);
          } catch (e) {
            // This identifier is local to the catch clause. But it's not true for IE < 9 ? (so "a" used)
            setTimeout(a(e), 0);
          }
        }
      }
    };

    this.addEventListener = function (type, callback) {
      if (lastIndexOf(type, callback) === -1) {
        listeners.push({type: type, callback: callback});
      }
    };

    this.removeEventListener = function (type, callback) {
      var i = lastIndexOf(type, callback);
      if (i !== -1) {
        listeners.splice(i, 1);
      }
    };

    return this;
  }

  function empty() {}

  var Transport = null,
    isOpera = Object.prototype.toString.call(global.opera) === '[object Opera]',
    supportCORS = true, // anonymous mode at least
    tmp = global.XMLHttpRequest && (new global.XMLHttpRequest()),
    nativeProgress = (tmp && ('onprogress' in tmp)),
    progress = isOpera || nativeProgress,
    withCredentials = tmp && ('withCredentials' in tmp);
  tmp = null;

  function EventSource(url, options) {
    function F() {}
    F.prototype = EventSource.prototype;

    url = String(url);

    var that = new F(),
      retry = 1000,
      lastEventId = '',
      xhr = null,
      reconnectTimeout = null,
      checkTimeout = null,
      stop;

    that.url = url;
    that.withCredentials = !!(options && options.withCredentials && withCredentials);

    that.CONNECTING = 0;
    that.OPEN = 1;
    that.CLOSED = 2;
    that.readyState = that.CONNECTING;

    // Queue a task which, if the readyState is set to a value other than CLOSED,
    // sets the readyState to ... and fires event
    function queue(event, readyState) {
      setTimeout(function () {
        if (that.readyState !== that.CLOSED) { // http://www.w3.org/Bugs/Public/show_bug.cgi?id=14331
          if (readyState !== null) {
            that.readyState = readyState;
          }

          event.target = that;
          that.dispatchEvent(event);
          if (/^(message|error|open)$/.test(event.type) && typeof that['on' + event.type] === 'function') {
            // as IE doesn't support getters/setters, we can't implement 'onmessage' via addEventListener/removeEventListener
            that['on' + event.type](event);
          }
        }
      }, 0);
    }

    function close() {
      // http://dev.w3.org/html5/eventsource/ The close() method must close the connection, if any; must abort any instances of the fetch algorithm started for this EventSource object; and must set the readyState attribute to CLOSED.
      if (xhr !== null) {
        stop();
        xhr.abort();
        xhr = null;
      }
      if (reconnectTimeout !== null) {
        clearTimeout(reconnectTimeout);
        reconnectTimeout = null;
      }
      that.readyState = that.CLOSED;
    }

    stop = function () {
      if (checkTimeout !== null) {
        clearTimeout(checkTimeout);
        checkTimeout = null;
      }
      if ('\v' === 'v' && global.detachEvent) {
        global.detachEvent('onunload', close);
      }
      xhr.onload = xhr.onerror = xhr.onprogress = xhr.onreadystatechange = empty;
    };

    that.close = close;

    EventTarget.call(that);

    function openConnection() {
      reconnectTimeout = null;
      if ('\v' === 'v' && global.attachEvent) {
        global.attachEvent('onunload', close);
      }

      var offset = 0,
        charOffset = 0,
        opened = false,
        buffer = {
          data: '',
          lastEventId: lastEventId,
          name: ''
        };

      xhr = new Transport();

      // with GET method in FF xhr.onreadystatechange with readyState === 3 doesn't work + POST = no-cache
      xhr.open('POST', url, true);

      function onReadyStateChange(readyState) {
        if (!xhr) {//? strange Opera error
          return;
        }

        var responseText = '',
          contentType = '',
          i,
          j,
          part,
          stream,
          field,
          value;

        // Opera doesn't fire several readystatechange events while chunked data is coming in
        // see http://stackoverflow.com/questions/2657450/how-does-gmail-do-comet-on-opera
        if (checkTimeout === null && !nativeProgress && readyState === 3) {
          (function loop() {
            checkTimeout = setTimeout(function () {
              onReadyStateChange(+xhr.readyState);
              loop();
            }, 250);
          }());
        }

        try {
          contentType = readyState > 1 ? ((xhr.getResponseHeader ? xhr.getResponseHeader('Content-Type') : xhr.contentType) || '') : '';
          responseText = readyState > 2 ? xhr.responseText || '' : '';
        } catch (e) {}

        if (!opened && (/^text\/event\-stream/i).test(contentType)) {
          queue({type: 'open'}, that.OPEN);
          opened = true;
        }

        if (opened && (/\r|\n/).test(responseText.slice(charOffset))) {
          part = responseText.slice(offset);
          stream = (offset ? part : part.replace(/^\uFEFF/, '')).replace(/\r\n?/g, '\n').split('\n');

          offset += part.length - stream[stream.length - 1].length;
          for (i = 0; i < stream.length - 1; i += 1) {
            field = stream[i];
            value = '';
            j = field.indexOf(':');
            if (j !== -1) {
              value = field.slice(j + (field.charAt(j + 1) === ' ' ? 2 : 1));
              field = field.slice(0, j);
            }

            if (!stream[i]) {
              // dispatch the event
              if (buffer.data) {
                lastEventId = buffer.lastEventId;
                queue({
                  type: buffer.name || 'message',
                  lastEventId: lastEventId,
                  data: buffer.data.replace(/\n$/, '')
                }, null);
              }
              // Set the data buffer and the event name buffer to the empty string.
              buffer.data = '';
              buffer.name = '';
            }

            if (field === 'event') {
              buffer.name = value;
            }

            if (field === 'id') {
              buffer.lastEventId = value; // see http://www.w3.org/Bugs/Public/show_bug.cgi?id=13761
            }

            if (field === 'retry') {
              if (/^\d+$/.test(value)) {
                retry = +value;
              }
            }

            if (field === 'data') {
              buffer.data += value + '\n';
            }
          }
        }
        charOffset = responseText.length;

        if (readyState === 4) {
          stop();
          xhr = null;
          if (opened) {
            // reestablishes the connection
            queue({type: 'error'}, that.CONNECTING);
            // setTimeout will wait before previous setTimeout(0) have completed
            reconnectTimeout = setTimeout(openConnection, retry);
          } else {
            // fail the connection
            queue({type: 'error'}, that.CLOSED);
          }
        }
      }

      if (xhr.setRequestHeader) { // XDomainRequest doesn't have this method
        // Chrome bug:
        // Request header field Cache-Control is not allowed by Access-Control-Allow-Headers.
        //xhr.setRequestHeader('Cache-Control', 'no-cache');

        // Chrome bug:
        // http://code.google.com/p/chromium/issues/detail?id=71694
        // If you force Chrome to have a whitelisted content-type, either explicitly with setRequestHeader(), or implicitly by sending a FormData, then no preflight is done.
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        if (!progress) {
          //! X-Requested-With header should be allowed for CORS requests
          xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');// long-polling
        }

        //  Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
        //if (lastEventId !== '') {
        //  xhr.setRequestHeader('Last-Event-ID', lastEventId);
        //}
        xhr.onreadystatechange = function () {
          onReadyStateChange(+xhr.readyState);
        };

        xhr.withCredentials = that.withCredentials;
      }
      xhr.onload = xhr.onerror = function () {
        onReadyStateChange(4);
      };
      // onprogress fires multiple times while readyState === 3
      xhr.onprogress = function () {
        onReadyStateChange(3);
      };

      xhr.send(lastEventId !== '' ? 'Last-Event-ID=' + encodeURIComponent(lastEventId) : '');
    }
    openConnection();

    return that;
  }

  EventSource.CONNECTING = 0;
  EventSource.OPEN = 1;
  EventSource.CLOSED = 2;

  if (!(global.EventSource && global.EventSource.constructor && global.EventSource.constructor.length > 1)) {
    if (progress && withCredentials) {
      Transport = global.XMLHttpRequest;
    } else {
      if (global.XDomainRequest) {
        // http://blogs.msdn.com/b/ieinternals/archive/2010/04/06/comet-streaming-in-internet-explorer-with-xmlhttprequest-and-xdomainrequest.aspx?PageIndex=1#comments
        // XDomainRequest does not have a binary interface. To use with non-text, first base64 to string.
        // http://cometdaily.com/2008/page/3/
        Transport = global.XDomainRequest;
        nativeProgress = true;
      } else {
        if (!isOpera && global.EventSource) {
          supportCORS = false;
        } else {
          supportCORS = withCredentials;
          Transport = global.XMLHttpRequest || function () {
            return (new global.ActiveXObject('Microsoft.XMLHTTP'));
          };
        }
      }
    }
  }

  if (Transport) {
    global.EventSource = EventSource;
  }

  global.EventSource.supportCORS = supportCORS;

}(this));
<commit_msg>Update the EventSource polyfill lib<commit_after>/*jslint indent: 2 */
/*global setTimeout, clearTimeout */

(function (global) {

  function EventTarget() {
    this.listeners = [];
    return this;
  }

  EventTarget.prototype = {
    dispatchEvent: function (event) {
      function a(x, type, event) {
        if (x.type === type) {
          event.currentTarget = this;
          event.eventPhase = 2;
          try {
            x.callback.call(this, event);
          } catch (e) {
            setTimeout(function () {
              throw e;
            }, 0);
          }
          event.currentTarget = null;
          event.eventPhase = 2;
        }
      }
      var type = event.type,
        candidates = this.listeners.slice(0),
        i;
      for (i = 0; i < candidates.length; i += 1) {
        a.call(this, candidates[i], type, event);
      }
    },
    addEventListener: function (type, callback, capture) {
      capture = Boolean(capture);
      var listeners = this.listeners,
        i = listeners.length - 1;
      while (i >= 0 && !(listeners[i].type === type && listeners[i].callback === callback && listeners[i].capture === capture)) {
        i -= 1;
      }
      if (i === -1) {
        listeners.push({type: type, callback: callback, capture: capture});
      }
    },
    removeEventListener: function (type, callback, capture) {
      capture = Boolean(capture);
      var listeners = this.listeners,
        i = listeners.length - 1;
      while (i >= 0 && !(listeners[i].type === type && listeners[i].callback === callback && listeners[i].capture === capture)) {
        i -= 1;
      }
      if (i !== -1) {
        listeners.splice(i, 1);
      }
    }
  };

  // http://blogs.msdn.com/b/ieinternals/archive/2010/04/06/comet-streaming-in-internet-explorer-with-xmlhttprequest-and-xdomainrequest.aspx?PageIndex=1#comments
  // XDomainRequest does not have a binary interface. To use with non-text, first base64 to string.
  // http://cometdaily.com/2008/page/3/

  var xhr2 = global.XMLHttpRequest && ('withCredentials' in (new global.XMLHttpRequest())) && !!global.ProgressEvent;

  function EventSource(url, options) {
    url = String(url);

    var that = this,
      retry = 1000,
      lastEventId = '',
      xhr = null,
      reconnectTimeout = null,
      checkTimeout = null,
      withCredentials = Boolean(xhr2 && options && options.withCredentials);

    options = null;
    that.url = url;

    that.readyState = that.CONNECTING;
    that.withCredentials = withCredentials;

    // Queue a task which, if the readyState is set to a value other than CLOSED,
    // sets the readyState to ... and fires event
    function queue(event, readyState) {
      setTimeout(function () {
        if (that.readyState !== that.CLOSED) { // http://www.w3.org/Bugs/Public/show_bug.cgi?id=14331
          if (readyState !== null) {
            that.readyState = readyState;
          }

          event.target = that;
          that.dispatchEvent(event);
          if (/^(message|error|open)$/.test(event.type) && typeof that['on' + event.type] === 'function') {
            // as IE 8 doesn't support getters/setters, we can't implement 'onmessage' via addEventListener/removeEventListener
            that['on' + event.type](event);
          }
        }
      }, 0);
    }

    function stop() {
      if (checkTimeout !== null) {
        clearTimeout(checkTimeout);
        checkTimeout = null;
      }
      xhr.onload = xhr.onerror = xhr.onprogress = xhr.onreadystatechange = function () {};
    }

    function close() {
      // http://dev.w3.org/html5/eventsource/ The close() method must close the connection, if any; must abort any instances of the fetch algorithm started for this EventSource object; and must set the readyState attribute to CLOSED.
      if (xhr !== null) {
        stop();
        xhr.abort();
        xhr = null;
      }
      if (reconnectTimeout !== null) {
        clearTimeout(reconnectTimeout);
        reconnectTimeout = null;
      }
      that.readyState = that.CLOSED;
    }

    that.close = close;

    EventTarget.call(that);

    function openConnection() {
      reconnectTimeout = null;

      var offset = 0,
        charOffset = 0,
        opened = false,
        closed = false,
        buffer = {
          data: '',
          lastEventId: lastEventId,
          name: ''
        };

      xhr = !xhr2 && global.XDomainRequest ? new global.XDomainRequest() : new global.XMLHttpRequest();

      // with GET method in FF xhr.onreadystatechange with readyState === 3 doesn't work + POST = no-cache
      xhr.open('POST', url, true);

      function onReadyStateChange(readyState) {
        var responseText = '',
          contentType = '',
          i,
          j,
          part,
          stream,
          field,
          value;

        // (onreadystatechange can't prevent onload/onerror)
        if (closed) {
          return;
        }

        try {
          contentType = readyState > 1 ? ((xhr.getResponseHeader ? xhr.getResponseHeader('Content-Type') : xhr.contentType) || '') : '';
          responseText = readyState > 2 ? xhr.responseText || '' : '';
        } catch (e) {}

        if (!opened && (/^text\/event\-stream/i).test(contentType)) {
          queue({type: 'open'}, that.OPEN);
          opened = true;
        }

        if (opened && (/\r|\n/).test(responseText.slice(charOffset))) {
          part = responseText.slice(offset);
          stream = (offset ? part : part.replace(/^\uFEFF/, '')).replace(/\r\n?/g, '\n').split('\n');

          offset += part.length - stream[stream.length - 1].length;
          for (i = 0; i < stream.length - 1; i += 1) {
            field = stream[i];
            value = '';
            j = field.indexOf(':');
            if (j !== -1) {
              value = field.slice(j + (field.charAt(j + 1) === ' ' ? 2 : 1));
              field = field.slice(0, j);
            }

            if (!stream[i]) {
              // dispatch the event
              if (buffer.data) {
                lastEventId = buffer.lastEventId;
                queue({
                  type: buffer.name || 'message',
                  lastEventId: lastEventId,
                  data: buffer.data.replace(/\n$/, '')
                }, null);
              }
              // Set the data buffer and the event name buffer to the empty string.
              buffer.data = '';
              buffer.name = '';
            }

            if (field === 'event') {
              buffer.name = value;
            }

            if (field === 'id') {
              buffer.lastEventId = value; // see http://www.w3.org/Bugs/Public/show_bug.cgi?id=13761
            }

            if (field === 'retry') {
              if (/^\d+$/.test(value)) {
                retry = +value;
              }
            }

            if (field === 'data') {
              buffer.data += value + '\n';
            }
          }
        }
        charOffset = responseText.length;

        if (!global.XDomainRequest && !xhr2) { // Opera < 12
          // Opera doesn't fire several readystatechange events while chunked data is coming in
          // see http://stackoverflow.com/questions/2657450/how-does-gmail-do-comet-on-opera
          if (opened && checkTimeout === null && readyState === 3) {
            checkTimeout = setTimeout(function () {
              checkTimeout = null;
              if (+xhr.readyState === 3) { // xhr.readyState may be changed to 4 in Opera 11.50
                onReadyStateChange(3); // will setTimeout - setInterval
              }
            }, 250);
          }
        }

        if (readyState === 4) {
          stop();
          xhr = null;
          closed = true;
          if (opened) {
            // reestablishes the connection
            queue({type: 'error'}, that.CONNECTING);
            // setTimeout will wait before previous setTimeout(0) have completed
            reconnectTimeout = setTimeout(openConnection, retry);
          } else {
            // fail the connection
            queue({type: 'error'}, that.CLOSED);
          }
        }
      }

      if (xhr.setRequestHeader) { // !XDomainRequest
        // http://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html
        // Cache-Control is not a simple header
        // Request header field Cache-Control is not allowed by Access-Control-Allow-Headers.
        //xhr.setRequestHeader('Cache-Control', 'no-cache');

        // Chrome bug:
        // http://code.google.com/p/chromium/issues/detail?id=71694
        // If you force Chrome to have a whitelisted content-type, either explicitly with setRequestHeader(), or implicitly by sending a FormData, then no preflight is done.
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('Accept', 'text/event-stream');

        // Request header field Last-Event-ID is not allowed by Access-Control-Allow-Headers.
        // +setRequestHeader shouldn't be used to avoid preflight requests
        //if (lastEventId !== '') {
        //  xhr.setRequestHeader('Last-Event-ID', lastEventId);
        //}
      }

      xhr.onreadystatechange = function () {
        onReadyStateChange(+this.readyState);
      };

      xhr.withCredentials = withCredentials;

      xhr.onload = xhr.onerror = function () {
        onReadyStateChange(4);
      };

      // onprogress fires multiple times while readyState === 3
      xhr.onprogress = function () {
        onReadyStateChange(3);
      };

      xhr.send(lastEventId !== '' ? 'Last-Event-ID=' + encodeURIComponent(lastEventId) : '');
    }
    openConnection();

    return that;
  }

  EventSource.CONNECTING = 0;
  EventSource.OPEN = 1;
  EventSource.CLOSED = 2;

  EventSource.prototype = new EventTarget();
  EventSource.prototype.CONNECTING = EventSource.CONNECTING;
  EventSource.prototype.OPEN = EventSource.OPEN;
  EventSource.prototype.CLOSED = EventSource.CLOSED;

  //if (!('withCredentials' in global.EventSource.prototype)) { // to detect CORS in FF 11
  global.EventSource = EventSource;
  //}

}(this));
<|endoftext|>


<commit_before>/**
 ** Input: generated poem text as a string, with pid number of appropriate parent specified in the request
 ** Input will be inside post data : req.body
 ** Input will structured as a JSON with pid(parentId, generatedText, metadata)
 ** Output: http status code 200 if successful, if input is wrong send 400, if server messes up, send 500
 ** Used to send a newly read poem to the backend to be added to the tree, processed in realtime locally and later processed offline globally
 **/
exports.onNewPoemGenerated = function(req,res) {}<commit_msg>API added to process a POST new_poem<commit_after>/**
 ** Input: generated poem text as a string, with pid number of appropriate parent specified in the request
 ** Input will be inside post data : req.body
 ** Input will structured as a JSON with pid(parentId, generatedText, metadata)
 ** Output: http status code 200 if successful, if input is wrong send 400, if server messes up, send 500
 ** Used to send a newly read poem to the backend to be added to the tree, processed in realtime locally and later processed offline globally
 **/
exports.onNewPoemGenerated = function(req,res) {

	var express = require("express");
	var bodyParser = require("body-parser");
	var app = express();

	//Here we are configuring express to use body-parser as middle-ware.
	app.use(bodyParser.urlencoded({ extended: false }));

	/*
	 	** RETRIEVE POST REQUEST PARAMS
			* MAKE SURE THAT THE REQUEST CONTAINS THE POEM TEXT WITH THE '\n' TAGS
	*/
	var parentPID = req.body.pid;
	var newPoem = req.body.poem;

	var levenshtein = require('fast-levenshtein');
	var fs = require('fs');
	var poemsDir = __dirname + '/Poems/';

	// GET THE LIST OF POEM JSON FILES IN THE DIRECTORY
	var files = fs.readdirSync(poemsDir);

	var links = [];

	// CONSTRUCT THE NEW POEM JSON OBJECT TO BE WRITTEN OUT TO <PnewPoemObj.pid>.JSON FILE
	var newPoemObj = {};
	newPoemObj.pid = "123456qwerty";
 	newPoemObj.title = "123456qwerty New text";
 	newPoemObj.poem = newPoem;
 	newPoemObj.children = "";
 	newPoemObj.orig_src = parentPID;
 	newPoemObj.poem_num = "";
 	newPoemObj.userdata = "";
 	newPoemObj.links = links;

    var startTime = new Date().valueOf();
    var parsedPoem, poem, distance;
    var jsonString, jsonParsedPoem;

    /*
    	* ITERATE OVER ALL THE POEM JSON FILES PRESENT IN THE DIRECTORY
    	* RETRIEVE THE POEM TEXT
    	* COMPUTER THE LEVENSHTEIN'S DISTANCE BETWEEN THIS POEM TEXT AND THE NEW
    		POEM TEXT
    	* WRITE IT TO THE links FIELD IN THE NEW POEM JSON OBJECT
    	* ONCE WE ARE DONE WITH THIS FOR ALL THE POEMS JSON FILES PRESENT IN THE DIRECTORY,
    		WRITE THE NEW POEM TO THE SAME DIRECTORY AS <PnewPoemObj.pid>.JSON
    */
    for (var i in files) {

    	parsedPoem = require(poemsDir + files[i]);
    	poem = parsedPoem.poem;

    	distance = levenshtein.get(newPoem, poem);

		newPoemObj.links.push({pid: parsedPoem.pid, dist: distance});
      	jsonString = JSON.stringify(newPoemObj);

      	/* 	UPDATE THE links FIELD OF THE ALREADY PRESENT POEM WITH THE
      		PID OF THE NEW POEM AND THE LEVENSHTEIN'S DISTANCE BETWEEN
      		THESE TWO POEMS
      	*/
      	parsedPoem.links.push({pid: newPoemObj.pid, dist: distance});
      	jsonParsedPoem = JSON.stringify(parsedPoem);
      	fs.writeFileSync(poemsDir + files[i], jsonParsedPoem);
    }

    // WRITE THE NEW POEM TO THE SAME DIRECTORY AS <PnewPoemObj.pid>.JSON
    fs.writeFileSync(poemsDir + newPoemObj.pid + '.json', jsonString);

    //console.log('Time taken: ' + (new Date().valueOf() - startTime));

    // SEND THE TIME TAKEN (TO WRITE THIS NEW POEM JSON FILE + UPDATE THE ALREADY PRESENT
    // POEM FILES) BACK IN THE RESPONSE
    res.send('Time taken: ' + (new Date().valueOf() - startTime));
}<|endoftext|>


<commit_before>/********************************************************
 * Copyright (c) 2013 Azavea, Inc.
 * See LICENSE in the project root for copying permission
 ********************************************************/

var ecepAdmin = ((typeof ecepAdmin === 'undefined') ? {} : ecepAdmin);

ecepAdmin.marker_array = [];
ecepAdmin.map;

ecepAdmin.clearMarkers = function() {
    for (var i = 0; i < ecepAdmin.marker_array.length; i++){
        ecepAdmin.marker_array[i].setMap(null);
    }
    ecepAdmin.marker_array = [];
}

ecepAdmin.addMarker = function(location) {
    var marker = new google.maps.Marker({
        map: ecepAdmin.map,
        position: location
    });
    google.maps.event.addListener(marker, 'click', function() {
        ecepAdmin.addGeocodedPoint(marker.getPosition());
    });

    ecepAdmin.marker_array.push(marker);
};

ecepAdmin.loadMap = function(){
    var latlng = new google.maps.LatLng(latSettings, lngSettings);
    var mapOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    ecepAdmin.map = new google.maps.Map($('#map')[0], mapOptions);

    google.maps.event.addListener(ecepAdmin.map, "rightclick", function(event) {
        ecepAdmin.clearMarkers();
        ecepAdmin.addMarker(event.latLng);
        ecepAdmin.addGeocodedPoint(event.latLng);
    });

    if ($('#id_geom').val() && $('#id_geom').val() !== 'None') {
        // If point already found, center and add marker there
        var regexPoints = /([-.\d]+) ([-.\d]+)/;
        var results = regexPoints.exec($('#id_geom').val());
        var latlng = new google.maps.LatLng(results[2], results[1]);
        ecepAdmin.map.setZoom(15);
        ecepAdmin.map.setCenter(latlng);
        ecepAdmin.addMarker(latlng);
    }

};

// Function to add geocoded location to admin form
ecepAdmin.addGeocodedPoint = function(location) {
    $('#id_geom').val("POINT (" + location.lng() + " " + location.lat() + ")");
};

// Function to filter results that are not rooftop results
ecepAdmin.rooftopResults = function(geocode_results) {
    for (var i = 0; i < geocode_results.length; i++) {
        if (geocode_results[i].geometry.location_type !== 'ROOFTOP') {
            geocode_results.splice(i, 1);
        }
    }
};

/** Function to geocode address and insert value into the location
 *  input of the admin form.
 *
 *  Provides user feedback if geocoding is unsuccessful and describes
 *  how to manually set the geolocation by right-clicking
 */
ecepAdmin.geocodeAddress = function() {
    var geocoder = new google.maps.Geocoder();
    var $mapHelp = $('#map-help');
    var streetnum = $("#id_address").val(),
        city = $("#id_city").val(),
        state = $("#id_state").val(),
        zip = $("#id_zip").val();
    var address = [streetnum, city, state, zip].join(', ');
    ecepAdmin.clearMarkers();

    geocoder.geocode( {'address': address}, function(results, status) {
        // Filter results (only rooftop)
        ecepAdmin.rooftopResults(results);

        for (var i = 0; i < results.length; i++) {
            // Add markers for all results
            ecepAdmin.addMarker(results[i].geometry.location);
        }

        if (results.length === 1) {
        // If only one marker, set the form value to that location
        // and zoom into that location
            $mapHelp.hide();
            ecepAdmin.addGeocodedPoint(results[0].geometry.location);
            ecepAdmin.map.setZoom(15);
            ecepAdmin.map.setCenter(results[0].geometry.location);
        }

        else if (results.length > 1) {
        // If more than 2 results, let user know they can choose one
        // by clicking on the correct marker or they can set their
        // own marker with a right-click
            $mapHelp.text("There are multiple locations that match that address, please select the correct location by clicking on a marker. You can also set the location manually by right-clicking on a position.");
            $mapHelp.show();
        }
        else if (results.length === 0 || status !== google.maps.GeocoderStatus.OK) {
            // If there aren't any results, let user know they can manually set
            // the location by right clicking on the map
            $mapHelp.text("We could not match that address to a location. You can manually set the location by right-clicking on any location on the map.");
            $mapHelp.show();
        }

    });
};

ecepAdmin.mapHelp = function() {
    $('#map-help').text("Please fill in the address of the location then click the 'Geocode Address' button to find its latitude and longitude. You can also select a location manually by right-clicking anywhere on the map.");
    $('#map-help').show();
};

google.maps.event.addDomListener(window, 'load', ecepAdmin.loadMap);
<commit_msg>Add list of dependencies to header<commit_after>/********************************************************
 * Copyright (c) 2013 Azavea, Inc.
 * See LICENSE in the project root for copying permission
 * Requires: google-maps-api-v3; jquery-1.7.2
 ********************************************************/

var ecepAdmin = ((typeof ecepAdmin === 'undefined') ? {} : ecepAdmin);

ecepAdmin.marker_array = [];
ecepAdmin.map;

ecepAdmin.clearMarkers = function() {
    for (var i = 0; i < ecepAdmin.marker_array.length; i++){
        ecepAdmin.marker_array[i].setMap(null);
    }
    ecepAdmin.marker_array = [];
}

ecepAdmin.addMarker = function(location) {
    var marker = new google.maps.Marker({
        map: ecepAdmin.map,
        position: location
    });
    google.maps.event.addListener(marker, 'click', function() {
        ecepAdmin.addGeocodedPoint(marker.getPosition());
    });

    ecepAdmin.marker_array.push(marker);
};

ecepAdmin.loadMap = function(){
    var latlng = new google.maps.LatLng(latSettings, lngSettings);
    var mapOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    ecepAdmin.map = new google.maps.Map($('#map')[0], mapOptions);

    google.maps.event.addListener(ecepAdmin.map, "rightclick", function(event) {
        ecepAdmin.clearMarkers();
        ecepAdmin.addMarker(event.latLng);
        ecepAdmin.addGeocodedPoint(event.latLng);
    });

    if ($('#id_geom').val() && $('#id_geom').val() !== 'None') {
        // If point already found, center and add marker there
        var regexPoints = /([-.\d]+) ([-.\d]+)/;
        var results = regexPoints.exec($('#id_geom').val());
        var latlng = new google.maps.LatLng(results[2], results[1]);
        ecepAdmin.map.setZoom(15);
        ecepAdmin.map.setCenter(latlng);
        ecepAdmin.addMarker(latlng);
    }

};

// Function to add geocoded location to admin form
ecepAdmin.addGeocodedPoint = function(location) {
    $('#id_geom').val("POINT (" + location.lng() + " " + location.lat() + ")");
};

// Function to filter results that are not rooftop results
ecepAdmin.rooftopResults = function(geocode_results) {
    for (var i = 0; i < geocode_results.length; i++) {
        if (geocode_results[i].geometry.location_type !== 'ROOFTOP') {
            geocode_results.splice(i, 1);
        }
    }
};

/** Function to geocode address and insert value into the location
 *  input of the admin form.
 *
 *  Provides user feedback if geocoding is unsuccessful and describes
 *  how to manually set the geolocation by right-clicking
 */
ecepAdmin.geocodeAddress = function() {
    var geocoder = new google.maps.Geocoder();
    var $mapHelp = $('#map-help');
    var streetnum = $("#id_address").val(),
        city = $("#id_city").val(),
        state = $("#id_state").val(),
        zip = $("#id_zip").val();
    var address = [streetnum, city, state, zip].join(', ');
    ecepAdmin.clearMarkers();

    geocoder.geocode( {'address': address}, function(results, status) {
        // Filter results (only rooftop)
        ecepAdmin.rooftopResults(results);

        for (var i = 0; i < results.length; i++) {
            // Add markers for all results
            ecepAdmin.addMarker(results[i].geometry.location);
        }

        if (results.length === 1) {
        // If only one marker, set the form value to that location
        // and zoom into that location
            $mapHelp.hide();
            ecepAdmin.addGeocodedPoint(results[0].geometry.location);
            ecepAdmin.map.setZoom(15);
            ecepAdmin.map.setCenter(results[0].geometry.location);
        }

        else if (results.length > 1) {
        // If more than 2 results, let user know they can choose one
        // by clicking on the correct marker or they can set their
        // own marker with a right-click
            $mapHelp.text("There are multiple locations that match that address, please select the correct location by clicking on a marker. You can also set the location manually by right-clicking on a position.");
            $mapHelp.show();
        }
        else if (results.length === 0 || status !== google.maps.GeocoderStatus.OK) {
            // If there aren't any results, let user know they can manually set
            // the location by right clicking on the map
            $mapHelp.text("We could not match that address to a location. You can manually set the location by right-clicking on any location on the map.");
            $mapHelp.show();
        }

    });
};

ecepAdmin.mapHelp = function() {
    $('#map-help').text("Please fill in the address of the location then click the 'Geocode Address' button to find its latitude and longitude. You can also select a location manually by right-clicking anywhere on the map.");
    $('#map-help').show();
};

google.maps.event.addDomListener(window, 'load', ecepAdmin.loadMap);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var optimist = require('optimist')
  .usage(
    'Get latest dependency version information.\n' +
    'Usage: $0 [command] [options...]\n\n' +
    'Command:\n' +
    '  update, u  Update dependencies to latest STABLE versions and save to package.json'
  )
  .alias('g', 'global')
  .describe('g', 'Consider global dependencies');

var david = require('../');
var argv = optimist.argv;
var fs = require('fs');
var npm = require('npm');
var cwd = process.cwd();
var packageFile = cwd + '/package.json';

var blue  = '\033[34m';
var reset = '\033[0m';
var green = '\033[32m';
var gray = '\033[90m';
var yellow = '\033[33m';

if (argv.usage || argv.help) {
  return optimist.showHelp();
}

if (argv.v || argv.version) {
  return console.log('v' + require('../package.json').version);
}

argv.update = argv._.indexOf('update') > -1 || argv._.indexOf('u') > -1;

function printDeps (deps, type) {
  if (!Object.keys(deps).length) {
    return;
  }

  type = type ? type + ' ' : '';

  var oneline = ['npm install'];

  if (type == 'Dev ') {
    oneline.push('--save-dev');
  } else if (type == 'Global ') {
    oneline.push('--global');
  } else {
    oneline.push('--save');
  }

  console.log('');
  console.log('%sOutdated %sDependencies%s', yellow, type, reset);
  console.log('');

  for (var name in deps) {
    var dep = deps[name];
    oneline.push(name+'@'+dep.stable);
    console.log('%s%s%s %s(package:%s %s, %slatest: %s%s%s)%s',
                green,
                name,
                reset,

                gray,
                blue,
                dep.required,

                gray,
                blue,
                dep.stable,
                gray,
                reset
               );
  }
  console.log('');
  console.log('%s%s%s', gray, oneline.join(' '), reset);
  console.log('');
}

// Get updated deps and devDeps
function getDeps (pkg, cb) {

  david.getUpdatedDependencies(pkg, { stable: true }, function (er, deps) {
    if (er) return cb(er);

    david.getUpdatedDependencies(pkg, { dev: true, stable: true }, function (er, devDeps) {
      cb(er, deps, devDeps);
    });
  });
}

/**
 * Install the passed dependencies
 *
 * @param {Object} deps Dependencies to install (result from david)
 * @param {Object} opts Install options
 * @param {Boolean} [opts.global] Install globally
 * @param {Boolean} [opts.save] Save installed dependencies to dependencies/devDependencies
 * @param {Boolean} [opts.dev] Provided dependencies are dev dependencies
 * @param {Function} cb Callback
 */
function installDeps (deps, opts, cb) {

  opts = opts || {};

  npm.load({global: opts.global}, function (er) {
    if (er) return cb(er);

    if (opts.save) {
      npm.config.set('save' + (opts.dev ? '-dev' : ''), true);
    }

    var installArgs = Object.keys(deps).map(function (depName) {
      return depName + '@' + deps[depName].stable;
    });

    npm.commands.install(installArgs, function (er) {
      npm.config.set('save' + (opts.dev ? '-dev' : ''), false);
      cb(er);
    });
  });
}

if (argv.g || argv.global) {

  npm.load({ global: true }, function(err) {
    if (err) throw err;

    npm.commands.ls([], true, function(err, data) {
      if (err) throw err;

      var pkg = {
        name: 'Global Dependencies',
        dependencies: {}
      };

      for (var key in data.dependencies) {
        pkg.dependencies[key] = data.dependencies[key].version;
      }

      getDeps(pkg, function (er, deps) {
        if (er) return console.error('Failed to get updated dependencies/devDependencies', er);

        if (argv.update) {

          installDeps(deps, {global: true}, function (er) {
            if (er) return console.error('Failed to update global dependencies', er);
          });

        } else {
          printDeps(deps, 'Global');
        }
      });
    });
  });

} else {

  if (!fs.existsSync(packageFile)) {
    return console.error('package.json does not exist');
  }

  var pkg = require(cwd + '/package.json');

  getDeps(pkg, function (er, deps, devDeps) {
    if (er) return console.error('Failed to get updated dependencies/devDependencies', er);

    if (argv.update) {

      installDeps(deps, {save: true}, function (er) {
        if (er) return console.error('Failed to update/save dependencies', er);

        installDeps(devDeps, {save: true, dev: true}, function (er) {
          if (er) return console.error('Failed to update/save devDependencies', er);
        });
      });

    } else {
      printDeps(deps);
      printDeps(devDeps, 'Dev');
    }
  });
}

<commit_msg>CLI update to unstable<commit_after>#!/usr/bin/env node

var optimist = require('optimist')
  .usage(
    'Get latest dependency version information.\n' +
    'Usage: $0 [command] [options...]\n\n' +
    'Command:\n' +
    '  update, u  Update dependencies to latest STABLE versions and save to package.json'
  )
  .alias('g', 'global')
  .describe('g', 'Consider global dependencies')
  .alias('u', 'unstable')
  .describe('u', 'Use UNSTABLE dependencies')
  .alias('v', 'version')
  .describe('v', 'Print version number and exit');

var david = require('../');
var argv = optimist.argv;
var fs = require('fs');
var npm = require('npm');
var cwd = process.cwd();
var packageFile = cwd + '/package.json';

var blue  = '\033[34m';
var reset = '\033[0m';
var green = '\033[32m';
var gray = '\033[90m';
var yellow = '\033[33m';

if (argv.usage || argv.help) {
  return optimist.showHelp();
}

if (argv.version) {
  return console.log('v' + require('../package.json').version);
}

argv.update = argv._.indexOf('update') > -1 || argv._.indexOf('u') > -1;

function printDeps (deps, type) {
  if (!Object.keys(deps).length) {
    return;
  }

  type = type ? type + ' ' : '';

  var oneline = ['npm install'];

  if (type == 'Dev ') {
    oneline.push('--save-dev');
  } else if (type == 'Global ') {
    oneline.push('--global');
  } else {
    oneline.push('--save');
  }

  console.log('');
  console.log('%sOutdated %sDependencies%s', yellow, type, reset);
  console.log('');

  for (var name in deps) {
    var dep = deps[name];
    oneline.push(name+'@'+dep[argv.unstable ? 'latest' : 'stable']);
    console.log('%s%s%s %s(package:%s %s, %slatest: %s%s%s)%s',
                green,
                name,
                reset,

                gray,
                blue,
                dep.required,

                gray,
                blue,
                dep[argv.unstable ? 'latest' : 'stable'],
                gray,
                reset
               );
  }
  console.log('');
  console.log('%s%s%s', gray, oneline.join(' '), reset);
  console.log('');
}

// Get updated deps and devDeps
function getDeps (pkg, cb) {

  david.getUpdatedDependencies(pkg, { stable: !argv.unstable }, function (er, deps) {
    if (er) return cb(er);

    david.getUpdatedDependencies(pkg, { dev: true, stable: !argv.unstable }, function (er, devDeps) {
      cb(er, deps, devDeps);
    });
  });
}

/**
 * Install the passed dependencies
 *
 * @param {Object} deps Dependencies to install (result from david)
 * @param {Object} opts Install options
 * @param {Boolean} [opts.global] Install globally
 * @param {Boolean} [opts.save] Save installed dependencies to dependencies/devDependencies
 * @param {Boolean} [opts.dev] Provided dependencies are dev dependencies
 * @param {Function} cb Callback
 */
function installDeps (deps, opts, cb) {

  opts = opts || {};

  npm.load({global: opts.global}, function (er) {
    if (er) return cb(er);

    if (opts.save) {
      npm.config.set('save' + (opts.dev ? '-dev' : ''), true);
    }

    var installArgs = Object.keys(deps).map(function (depName) {
      return depName + '@' + deps[depName][argv.unstable ? 'latest' : 'stable'];
    });

    npm.commands.install(installArgs, function (er) {
      npm.config.set('save' + (opts.dev ? '-dev' : ''), false);
      cb(er);
    });
  });
}

if (argv.global) {

  npm.load({ global: true }, function(err) {
    if (err) throw err;

    npm.commands.ls([], true, function(err, data) {
      if (err) throw err;

      var pkg = {
        name: 'Global Dependencies',
        dependencies: {}
      };

      for (var key in data.dependencies) {
        pkg.dependencies[key] = data.dependencies[key].version;
      }

      getDeps(pkg, function (er, deps) {
        if (er) return console.error('Failed to get updated dependencies/devDependencies', er);

        if (argv.update) {

          installDeps(deps, {global: true}, function (er) {
            if (er) return console.error('Failed to update global dependencies', er);
          });

        } else {
          printDeps(deps, 'Global');
        }
      });
    });
  });

} else {

  if (!fs.existsSync(packageFile)) {
    return console.error('package.json does not exist');
  }

  var pkg = require(cwd + '/package.json');

  getDeps(pkg, function (er, deps, devDeps) {
    if (er) return console.error('Failed to get updated dependencies/devDependencies', er);

    if (argv.update) {

      installDeps(deps, {save: true}, function (er) {
        if (er) return console.error('Failed to update/save dependencies', er);

        installDeps(devDeps, {save: true, dev: true}, function (er) {
          if (er) return console.error('Failed to update/save devDependencies', er);
        });
      });

    } else {
      printDeps(deps);
      printDeps(devDeps, 'Dev');
    }
  });
}

<|endoftext|>


<commit_before>#!/usr/bin/env node

var david = require('../')
var clc = require('cli-color-tty')()
var Table = require('cli-table')
var fs = require('fs')
var path = require('path')
var npm = require('npm')
var argv = require('minimist')(process.argv.slice(2))
var xtend = require('xtend')
var exit = require('exit')

if (argv.usage || argv.help || argv.h) {
  console.log(fs.readFileSync(path.join(__dirname, 'usage.txt'), 'utf8'))
  exit()
}

if (argv.version || argv.v) {
  console.log('v' + require('../package.json').version)
  exit()
}

argv.update = argv._.indexOf('update') > -1 || argv._.indexOf('u') > -1

function getNonWarnDepNames (deps) {
  return Object.keys(deps).reduce(function (names, name) {
    if (!deps[name].warn) {
      names.push(name)
    }
    return names
  }, [])
}

/**
 * Like printDeps, walk the list, but only print dependencies
 * with warnings.
 * @param {Object} deps
 * @param {String} type
 */
function printWarnings (deps, type) {
  if (!Object.keys(deps).length) return

  var warnings = {
    E404: {title: 'Unregistered', list: []},
    ESCM: {title: 'SCM', list: []},
    EDEPTYPE: {title: 'Non-string dependency', list: []}
  }

  for (var name in deps) {
    var dep = deps[name]

    if (dep.warn) {
      warnings[dep.warn.code].list.push([clc.magenta(name), clc.red(dep.warn.toString())])
    }
  }

  Object.keys(warnings).forEach(function (warnType) {
    var warnList = warnings[warnType].list

    if (!warnList.length) return

    var table = new Table({head: ['Name', 'Message'], style: {head: ['reset']}})

    console.log(clc.underline(warnings[warnType].title + ' ' + (type ? type + 'D' : 'd') + 'ependencies') + '\n')
    warnList.forEach(function (row) { table.push(row) })
    console.log(table.toString() + '\n')
  })
}

function printDeps (deps, type) {
  if (!Object.keys(deps).length) return

  var oneLine = ['npm install']

  if (type === 'dev') {
    oneLine.push('--save-dev')
  } else if (type === 'optional') {
    oneLine.push('--save-optional')
  } else if (type === 'global') {
    oneLine.push('--global')
  } else {
    oneLine.push('--save')
  }

  var nonWarnDepNames = getNonWarnDepNames(deps)

  if (nonWarnDepNames.length) {
    if (type) {
      console.log(clc.underline('%sDependencies'), type)
    } else {
      console.log(clc.underline('dependencies'))
    }

    var table = new Table({head: ['Name', 'Package', 'Latest'], style: {head: ['reset']}})

    nonWarnDepNames.forEach(function (name) {
      var dep = deps[name]

      oneLine.push(name + '@' + dep[argv.unstable ? 'latest' : 'stable'])

      table.push([
        clc.magenta(name),
        clc.red(dep.required),
        clc.green(dep[argv.unstable ? 'latest' : 'stable'])
      ])
    })

    console.log('\n' + table.toString() + '\n\n' + oneLine.join(' ') + '\n')
  }

  printWarnings(deps, type)
}

// Get a list of dependency filters
var filterList = argv._.filter(function (v) {
  return !(v === 'update' || v === 'u')
})

// Filter the passed deps (result from david) by the dependency names passed on the command line
function filterDeps (deps) {
  if (!filterList.length) return deps

  return Object.keys(deps).reduce(function (filteredDeps, name) {
    if (filterList.indexOf(name) !== -1) {
      filteredDeps[name] = deps[name]
    }
    return filteredDeps
  }, {})
}

// Get updated deps, devDeps and optionalDeps
function getUpdatedDeps (pkg, cb) {
  var opts = {
    stable: !argv.unstable,
    loose: true,
    error: {
      E404: argv.error404,
      ESCM: argv.errorSCM,
      EDEPTYPE: argv.errorDepType
    },
    ignore: argv.ignore || argv.i
  }

  if (argv.registry) {
    opts.npm = {registry: argv.registry}
  }

  david.getUpdatedDependencies(pkg, opts, function (err, deps) {
    if (err) return cb(err)

    david.getUpdatedDependencies(pkg, xtend(opts, {dev: true}), function (err, devDeps) {
      if (err) return cb(err)

      david.getUpdatedDependencies(pkg, xtend(opts, {optional: true}), function (err, optionalDeps) {
        cb(err, filterDeps(deps), filterDeps(devDeps), filterDeps(optionalDeps))
      })
    })
  })
}

/**
 * Install the passed dependencies
 *
 * @param {Object} deps Dependencies to install (result from david)
 * @param {Object} opts Install options
 * @param {Boolean} [opts.global] Install globally
 * @param {Boolean} [opts.save] Save installed dependencies to dependencies/devDependencies/optionalDependencies
 * @param {Boolean} [opts.dev] Provided dependencies are dev dependencies
 * @param {Boolean} [opts.optional] Provided dependencies are optional dependencies
 * @param {String} [opts.registry] The npm registry URL to use
 * @param {Function} cb Callback
 */
function installDeps (deps, opts, cb) {
  opts = opts || {}

  var depNames = Object.keys(deps)

  // Nothing to install!
  if (!depNames.length) {
    return cb(null)
  }

  depNames = depNames.filter(function (depName) {
    return !deps[depName].warn
  })

  var npmOpts = {global: opts.global}

  // Avoid warning message from npm for invalid registry url
  if (opts.registry) {
    npmOpts.registry = opts.registry
  }

  npm.load(npmOpts, function (err) {
    if (err) return cb(err)

    if (opts.save) {
      npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), true)
    }

    var installArgs = [depNames.map(function (depName) {
      return depName + '@' + deps[depName][argv.unstable ? 'latest' : 'stable']
    }), function (err) {
      npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), false)
      cb(err)
    }]

    if (opts.path) { installArgs.unshift(opts.path) }

    npm.commands.install.apply(npm.commands, installArgs)
  })
}

if (argv.global || argv.g) {
  var opts = {global: true}

  // Avoid warning message from npm for invalid registry url
  if (argv.registry) {
    opts.registry = argv.registry
  }

  npm.load(opts, function (err) {
    if (err) {
      console.error('Failed to load npm', err)
      exit(1)
    }

    npm.commands.ls([], true, function (err, data) {
      if (err) {
        console.error('Failed to list global dependencies', err)
        exit(1)
      }

      var pkg = {
        name: 'Global Dependencies',
        dependencies: {}
      }

      for (var key in data.dependencies) {
        pkg.dependencies[key] = data.dependencies[key].version
      }

      getUpdatedDeps(pkg, function (err, deps) {
        if (err) {
          console.error('Failed to get updated dependencies/devDependencies', err)
          exit(1)
        }

        if (argv.update) {
          installDeps(deps, opts, function (err) {
            if (err) {
              console.error('Failed to update global dependencies', err)
              exit(1)
            }

            printWarnings(deps, 'global')
          })
        } else {
          printDeps(deps, 'global')
        }
      })
    })
  })
} else {
  var pkg, pkgDir

  if (argv.package || argv.p) {
    pkg = argv.package || argv.p
    pkgDir = path.dirname(pkg)
  } else {
    pkgDir = process.cwd()
    pkg = pkgDir + '/package.json'
  }

  try {
    pkg = fs.readFileSync(pkg)
    try {
      pkg = JSON.parse(pkg)
    } catch (err) {
      console.error('Failed to parse package.json', err)
      exit(1)
    }
  } catch (err) {
    console.error('Failed to read package.json', err)
    exit(1)
  }

  getUpdatedDeps(pkg, function (err, deps, devDeps, optionalDeps) {
    if (err) {
      console.error('Failed to get updated dependencies/devDependencies', err)
      exit(1)
    }

    if (argv.update) {
      var opts = {save: true, registry: argv.registry, path: pkgDir}

      installDeps(deps, opts, function (err) {
        if (err) {
          console.error('Failed to update/save dependencies', err)
          exit(1)
        }

        installDeps(devDeps, xtend(opts, {dev: true}), function (err) {
          if (err) {
            console.error('Failed to update/save devDependencies', err)
            exit(1)
          }

          installDeps(optionalDeps, xtend(opts, {optional: true}), function (err) {
            if (err) {
              console.error('Failed to update/save optionalDependencies', err)
              exit(1)
            }

            printWarnings(deps)
            printWarnings(devDeps, 'dev')
            printWarnings(optionalDeps, 'optional')
          })
        })
      })
    } else {
      printDeps(deps)
      printDeps(devDeps, 'dev')
      printDeps(optionalDeps, 'optional')

      if (getNonWarnDepNames(deps).length ||
          getNonWarnDepNames(devDeps).length ||
          getNonWarnDepNames(optionalDeps).length) {
        exit(1)
      } else {
        // Log feedback if all dependencies are up to date
        console.log(clc.green('All dependencies up to date'))
      }
    }
  })
}
<commit_msg>Fixes #105 - now gives a message if all global deps are up-to-date<commit_after>#!/usr/bin/env node

var david = require('../')
var clc = require('cli-color-tty')()
var Table = require('cli-table')
var fs = require('fs')
var path = require('path')
var npm = require('npm')
var argv = require('minimist')(process.argv.slice(2))
var xtend = require('xtend')
var exit = require('exit')

if (argv.usage || argv.help || argv.h) {
  console.log(fs.readFileSync(path.join(__dirname, 'usage.txt'), 'utf8'))
  exit()
}

if (argv.version || argv.v) {
  console.log('v' + require('../package.json').version)
  exit()
}

argv.update = argv._.indexOf('update') > -1 || argv._.indexOf('u') > -1

function getNonWarnDepNames (deps) {
  return Object.keys(deps).reduce(function (names, name) {
    if (!deps[name].warn) {
      names.push(name)
    }
    return names
  }, [])
}

/**
 * Like printDeps, walk the list, but only print dependencies
 * with warnings.
 * @param {Object} deps
 * @param {String} type
 */
function printWarnings (deps, type) {
  if (!Object.keys(deps).length) return

  var warnings = {
    E404: {title: 'Unregistered', list: []},
    ESCM: {title: 'SCM', list: []},
    EDEPTYPE: {title: 'Non-string dependency', list: []}
  }

  for (var name in deps) {
    var dep = deps[name]

    if (dep.warn) {
      warnings[dep.warn.code].list.push([clc.magenta(name), clc.red(dep.warn.toString())])
    }
  }

  Object.keys(warnings).forEach(function (warnType) {
    var warnList = warnings[warnType].list

    if (!warnList.length) return

    var table = new Table({head: ['Name', 'Message'], style: {head: ['reset']}})

    console.log(clc.underline(warnings[warnType].title + ' ' + (type ? type + 'D' : 'd') + 'ependencies') + '\n')
    warnList.forEach(function (row) { table.push(row) })
    console.log(table.toString() + '\n')
  })
}

function printDeps (deps, type) {
  if (!Object.keys(deps).length) return

  var oneLine = ['npm install']

  if (type === 'dev') {
    oneLine.push('--save-dev')
  } else if (type === 'optional') {
    oneLine.push('--save-optional')
  } else if (type === 'global') {
    oneLine.push('--global')
  } else {
    oneLine.push('--save')
  }

  var nonWarnDepNames = getNonWarnDepNames(deps)

  if (nonWarnDepNames.length) {
    if (type) {
      console.log(clc.underline('%sDependencies'), type)
    } else {
      console.log(clc.underline('dependencies'))
    }

    var table = new Table({head: ['Name', 'Package', 'Latest'], style: {head: ['reset']}})

    nonWarnDepNames.forEach(function (name) {
      var dep = deps[name]

      oneLine.push(name + '@' + dep[argv.unstable ? 'latest' : 'stable'])

      table.push([
        clc.magenta(name),
        clc.red(dep.required),
        clc.green(dep[argv.unstable ? 'latest' : 'stable'])
      ])
    })

    console.log('\n' + table.toString() + '\n\n' + oneLine.join(' ') + '\n')
  }

  printWarnings(deps, type)
}

// Get a list of dependency filters
var filterList = argv._.filter(function (v) {
  return !(v === 'update' || v === 'u')
})

// Filter the passed deps (result from david) by the dependency names passed on the command line
function filterDeps (deps) {
  if (!filterList.length) return deps

  return Object.keys(deps).reduce(function (filteredDeps, name) {
    if (filterList.indexOf(name) !== -1) {
      filteredDeps[name] = deps[name]
    }
    return filteredDeps
  }, {})
}

// Get updated deps, devDeps and optionalDeps
function getUpdatedDeps (pkg, cb) {
  var opts = {
    stable: !argv.unstable,
    loose: true,
    error: {
      E404: argv.error404,
      ESCM: argv.errorSCM,
      EDEPTYPE: argv.errorDepType
    },
    ignore: argv.ignore || argv.i
  }

  if (argv.registry) {
    opts.npm = {registry: argv.registry}
  }

  david.getUpdatedDependencies(pkg, opts, function (err, deps) {
    if (err) return cb(err)

    david.getUpdatedDependencies(pkg, xtend(opts, {dev: true}), function (err, devDeps) {
      if (err) return cb(err)

      david.getUpdatedDependencies(pkg, xtend(opts, {optional: true}), function (err, optionalDeps) {
        cb(err, filterDeps(deps), filterDeps(devDeps), filterDeps(optionalDeps))
      })
    })
  })
}

/**
 * Install the passed dependencies
 *
 * @param {Object} deps Dependencies to install (result from david)
 * @param {Object} opts Install options
 * @param {Boolean} [opts.global] Install globally
 * @param {Boolean} [opts.save] Save installed dependencies to dependencies/devDependencies/optionalDependencies
 * @param {Boolean} [opts.dev] Provided dependencies are dev dependencies
 * @param {Boolean} [opts.optional] Provided dependencies are optional dependencies
 * @param {String} [opts.registry] The npm registry URL to use
 * @param {Function} cb Callback
 */
function installDeps (deps, opts, cb) {
  opts = opts || {}

  var depNames = Object.keys(deps)

  // Nothing to install!
  if (!depNames.length) {
    return cb(null)
  }

  depNames = depNames.filter(function (depName) {
    return !deps[depName].warn
  })

  var npmOpts = {global: opts.global}

  // Avoid warning message from npm for invalid registry url
  if (opts.registry) {
    npmOpts.registry = opts.registry
  }

  npm.load(npmOpts, function (err) {
    if (err) return cb(err)

    if (opts.save) {
      npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), true)
    }

    var installArgs = [depNames.map(function (depName) {
      return depName + '@' + deps[depName][argv.unstable ? 'latest' : 'stable']
    }), function (err) {
      npm.config.set('save' + (opts.dev ? '-dev' : opts.optional ? '-optional' : ''), false)
      cb(err)
    }]

    if (opts.path) { installArgs.unshift(opts.path) }

    npm.commands.install.apply(npm.commands, installArgs)
  })
}

if (argv.global || argv.g) {
  var opts = {global: true}

  // Avoid warning message from npm for invalid registry url
  if (argv.registry) {
    opts.registry = argv.registry
  }

  npm.load(opts, function (err) {
    if (err) {
      console.error('Failed to load npm', err)
      exit(1)
    }

    npm.commands.ls([], true, function (err, data) {
      if (err) {
        console.error('Failed to list global dependencies', err)
        exit(1)
      }

      var pkg = {
        name: 'Global Dependencies',
        dependencies: {}
      }

      for (var key in data.dependencies) {
        pkg.dependencies[key] = data.dependencies[key].version
      }

      getUpdatedDeps(pkg, function (err, deps) {
        if (err) {
          console.error('Failed to get updated dependencies/devDependencies', err)
          exit(1)
        }

        if (argv.update) {
          installDeps(deps, opts, function (err) {
            if (err) {
              console.error('Failed to update global dependencies', err)
              exit(1)
            }
            printWarnings(deps, 'global')
          })
        } else {
          printDeps(deps, 'global')
          if (getNonWarnDepNames(deps).length) {
            exit(1)
          }
          // Log feedback if all global dependencies are up to date
          console.log(clc.green('All global dependencies up to date'))
        }
      })
    })
  })
} else {
  var pkg, pkgDir

  if (argv.package || argv.p) {
    pkg = argv.package || argv.p
    pkgDir = path.dirname(pkg)
  } else {
    pkgDir = process.cwd()
    pkg = pkgDir + '/package.json'
  }

  try {
    pkg = fs.readFileSync(pkg)
    try {
      pkg = JSON.parse(pkg)
    } catch (err) {
      console.error('Failed to parse package.json', err)
      exit(1)
    }
  } catch (err) {
    console.error('Failed to read package.json', err)
    exit(1)
  }

  getUpdatedDeps(pkg, function (err, deps, devDeps, optionalDeps) {
    if (err) {
      console.error('Failed to get updated dependencies/devDependencies', err)
      exit(1)
    }

    if (argv.update) {
      var opts = {save: true, registry: argv.registry, path: pkgDir}

      installDeps(deps, opts, function (err) {
        if (err) {
          console.error('Failed to update/save dependencies', err)
          exit(1)
        }

        installDeps(devDeps, xtend(opts, {dev: true}), function (err) {
          if (err) {
            console.error('Failed to update/save devDependencies', err)
            exit(1)
          }

          installDeps(optionalDeps, xtend(opts, {optional: true}), function (err) {
            if (err) {
              console.error('Failed to update/save optionalDependencies', err)
              exit(1)
            }

            printWarnings(deps)
            printWarnings(devDeps, 'dev')
            printWarnings(optionalDeps, 'optional')
          })
        })
      })
    } else {
      printDeps(deps)
      printDeps(devDeps, 'dev')
      printDeps(optionalDeps, 'optional')

      if (getNonWarnDepNames(deps).length ||
          getNonWarnDepNames(devDeps).length ||
          getNonWarnDepNames(optionalDeps).length) {
        exit(1)
      } else {
        // Log feedback if all dependencies are up to date
        console.log(clc.green('All dependencies up to date'))
      }
    }
  })
}
<|endoftext|>


<commit_before>#!/bin/sh
":" //# comment; exec /usr/bin/env node --harmony --harmony_arrow_functions "$0" "$@"

if (!require("yieldables")) throw new Error("Fly requires node >= 0.11")

require("co")(require("../dist")).catch(function (e) {
  if (e.code === "ENOENT") {
    console.error(
      "Your project is missing a Flyfile. For more info about\n" +
      "running Fly, see the Fly Start guide: git.io/fly-start")
  } else {
    require("../dist/util").trace(e)
  }
})
<commit_msg>got yield?<commit_after>#!/bin/sh
":" //# comment; exec /usr/bin/env node --harmony --harmony_arrow_functions "$0" "$@"

if (!require("yieldables")) throw new Error("Fly requires node >= 0.11")

require("co")(require("../dist")).catch(function (e) {
  if (e.code === "ENOENT") {
    console.error(
      "Got Flyfile? For more info about running Fly," +
      "see the Quickstart guide → git.io/fly-quick")
  } else {
    require("../dist/util").trace(e)
  }
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

var argv = require('minimist')(process.argv.slice(2))

if (argv.help) {
  console.log('--render /path/to/render/location/')
  console.log('--build /path/to/build/location/')
  console.log('--env')
  process.exit()
}

if (argv.render && typeof argv.render !== 'string') {
  console.log('Specify --render /path/to/render/location/')
  process.exit()
}

if (argv.build && typeof argv.build !== 'string') {
  console.log('Specify --build /path/to/build/location/')
  process.exit()
}

var env = process.env.NODE_ENV || argv.env || 'development'
var static = require('../config/static')[env]
var meta = require('../config/meta')
var base = require('../mithril/base')

var fs = require('fs')
var path = require('path')

if (argv.render) {
  base({meta, static})
    .then((html) => {
      fs.writeFileSync(path.resolve(process.cwd(), argv.render, 'index.html'), html, 'utf8')
    })
    .catch((err) => console.error(err))
}

else if (argv.build) {

  // varnalab.min.css

  var csso = require('csso')

  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'varnalab.min.css'),
    fs.readdirSync(path.resolve(__dirname, '../assets/css/'))
      .map((file) =>
        csso.minify(
          fs.readFileSync(path.resolve(__dirname, '../assets/css/' + file), 'utf8')
        ).css
      ).join('\n'),
    'utf8'
  )

  // varnalab.js

  var babel = require('babel-core')

  var options = {
    presets: ['es2015'],
    comments: false,
    compact: true,
    minified: true
  }

  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'varnalab.js'),

    babel.transformFileSync(
      path.resolve(__dirname, '../mithril/index.js'), options
    ).code + '\n' +

    babel.transformFileSync(
      path.resolve(__dirname, '../mithril/layout.js'), options
    ).code + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/components/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/components/', file), options
        ).code
      ).join('\n') + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/modules/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/modules/', file), options
        ).code
      ).join('\n') + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/routes/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/routes/', file), options
        ).code
      ).join('\n') + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/views/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/views/', file), options
        ).code
      ).join('\n'),

    'utf8'
  )

  // varnalab.min.js

  var minify = require('uglify-js').minify

  var options = {
    compress: {},
    mangle: true
  }

  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'varnalab.min.js'),
    minify(
      fs.readFileSync(
        path.resolve(process.cwd(), argv.build, 'varnalab.js'),
        'utf8'
      ),
      options
    ).code,
    'utf8'
  )

  // mdc.varnalab.css
  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'mdc.varnalab.min.css'),

    static.css
      .filter((file) => /@material/.test(file))
      .reduce((css, file) => (
        css += fs.readFileSync(path.resolve(__dirname, '../', file), 'utf8'),
        css
      ), ''),

    'utf8'
  )

  // mdc.varnalab.js
  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'mdc.varnalab.min.js'),

    static.js
      .filter((file) => /@material/.test(file))
      .reduce((js, file) => (
        js += fs.readFileSync(path.resolve(__dirname, '../', file), 'utf8'),
        js
      ), ''),

    'utf8'
  )
}
<commit_msg>Remove layout from build script<commit_after>#!/usr/bin/env node

var argv = require('minimist')(process.argv.slice(2))

if (argv.help) {
  console.log('--render /path/to/render/location/')
  console.log('--build /path/to/build/location/')
  console.log('--env')
  process.exit()
}

if (argv.render && typeof argv.render !== 'string') {
  console.log('Specify --render /path/to/render/location/')
  process.exit()
}

if (argv.build && typeof argv.build !== 'string') {
  console.log('Specify --build /path/to/build/location/')
  process.exit()
}

var env = process.env.NODE_ENV || argv.env || 'development'
var static = require('../config/static')[env]
var meta = require('../config/meta')
var base = require('../mithril/base')

var fs = require('fs')
var path = require('path')

if (argv.render) {
  base({meta, static})
    .then((html) => {
      fs.writeFileSync(path.resolve(process.cwd(), argv.render, 'index.html'), html, 'utf8')
    })
    .catch((err) => console.error(err))
}

else if (argv.build) {

  // varnalab.min.css

  var csso = require('csso')

  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'varnalab.min.css'),
    fs.readdirSync(path.resolve(__dirname, '../assets/css/'))
      .map((file) =>
        csso.minify(
          fs.readFileSync(path.resolve(__dirname, '../assets/css/' + file), 'utf8')
        ).css
      ).join('\n'),
    'utf8'
  )

  // varnalab.js

  var babel = require('babel-core')

  var options = {
    presets: ['es2015'],
    comments: false,
    compact: true,
    minified: true
  }

  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'varnalab.js'),

    babel.transformFileSync(
      path.resolve(__dirname, '../mithril/index.js'), options
    ).code + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/components/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/components/', file), options
        ).code
      ).join('\n') + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/modules/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/modules/', file), options
        ).code
      ).join('\n') + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/routes/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/routes/', file), options
        ).code
      ).join('\n') + '\n' +

    fs.readdirSync(path.resolve(__dirname, '../mithril/views/'))
      .map((file) =>
        babel.transformFileSync(
          path.resolve(__dirname, '../mithril/views/', file), options
        ).code
      ).join('\n'),

    'utf8'
  )

  // varnalab.min.js

  var minify = require('uglify-js').minify

  var options = {
    compress: {},
    mangle: true
  }

  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'varnalab.min.js'),
    minify(
      fs.readFileSync(
        path.resolve(process.cwd(), argv.build, 'varnalab.js'),
        'utf8'
      ),
      options
    ).code,
    'utf8'
  )

  // mdc.varnalab.css
  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'mdc.varnalab.min.css'),

    static.css
      .filter((file) => /@material/.test(file))
      .reduce((css, file) => (
        css += fs.readFileSync(path.resolve(__dirname, '../', file), 'utf8'),
        css
      ), ''),

    'utf8'
  )

  // mdc.varnalab.js
  fs.writeFileSync(
    path.resolve(process.cwd(), argv.build, 'mdc.varnalab.min.js'),

    static.js
      .filter((file) => /@material/.test(file))
      .reduce((js, file) => (
        js += fs.readFileSync(path.resolve(__dirname, '../', file), 'utf8'),
        js
      ), ''),

    'utf8'
  )
}
<|endoftext|>