<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  var OptionsPage = options.OptionsPage;

  /**
   * ImportDataOverlay class
   * Encapsulated handling of the 'Import Data' overlay page.
   * @class
   */
  function ImportDataOverlay() {
    OptionsPage.call(this,
                     'importData',
                     loadTimeData.getString('importDataOverlayTabTitle'),
                     'import-data-overlay');
  }

  cr.addSingletonGetter(ImportDataOverlay);

  ImportDataOverlay.prototype = {
    // Inherit from OptionsPage.
    __proto__: OptionsPage.prototype,

    /**
     * Initialize the page.
     */
    initializePage: function() {
      // Call base class implementation to start preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      var checkboxes =
          document.querySelectorAll('#import-checkboxes input[type=checkbox]');
      for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].onchange = function() {
          self.validateCommitButton_();
        };
      }

      $('import-browsers').onchange = function() {
        self.updateCheckboxes_();
        self.validateCommitButton_();
        self.updateBottomBar_();
      };

      $('import-data-commit').onclick = function() {
        chrome.send('importData', [
            String($('import-browsers').selectedIndex),
            String($('import-history').checked),
            String($('import-favorites').checked),
            String($('import-passwords').checked),
            String($('import-search').checked)]);
      };

      $('import-data-cancel').onclick = function() {
        ImportDataOverlay.dismiss();
      };

      $('import-choose-file').onclick = function() {
        chrome.send('chooseBookmarksFile');
      };

      $('import-data-show-bookmarks-bar').onchange = function() {
        // Note: The callback 'toggleShowBookmarksBar' is handled within the
        // browser options handler -- rather than the import data handler --
        // as the implementation is shared by several clients.
        chrome.send('toggleShowBookmarksBar');
      }

      $('import-data-confirm').onclick = function() {
        ImportDataOverlay.dismiss();
      };

      // Form controls are disabled until the profile list has been loaded.
      self.setAllControlsEnabled_(false);
    },

    /**
     * Sets the enabled and checked state of the commit button.
     * @private
     */
    validateCommitButton_: function() {
      var somethingToImport =
          $('import-history').checked || $('import-favorites').checked ||
          $('import-passwords').checked || $('import-search').checked;
      $('import-data-commit').disabled = !somethingToImport;
      $('import-choose-file').disabled = !$('import-favorites').checked;
    },

    /**
     * Sets the enabled state of all the checkboxes and the commit button.
     * @private
     */
    setAllControlsEnabled_: function(enabled) {
      var checkboxes =
          document.querySelectorAll('#import-checkboxes input[type=checkbox]');
      for (var i = 0; i < checkboxes.length; i++)
        this.setUpCheckboxState_(checkboxes[i], enabled);
      $('import-data-commit').disabled = !enabled;
      $('import-choose-file').hidden = !enabled;
      $('mac-password-keychain').hidden = !enabled;
    },

    /**
     * Sets the enabled state of a checkbox element.
     * @param {Object} checkbox A checkbox element.
     * @param {boolean} enabled The enabled state of the checkbox. If false,
     *     the checkbox is disabled. If true, the checkbox is enabled.
     * @private
     */
    setUpCheckboxState_: function(checkbox, enabled) {
      checkbox.setDisabled('noProfileData', !enabled);
    },

    /**
     * Update the enabled and visible states of all the checkboxes.
     * @private
     */
    updateCheckboxes_: function() {
      var index = $('import-browsers').selectedIndex;
      var bookmarksFileSelected = index == this.browserProfiles.length - 1;
      $('import-choose-file').hidden = !bookmarksFileSelected;
      $('import-data-commit').hidden = bookmarksFileSelected;

      var browserProfile;
      if (this.browserProfiles.length > index)
        browserProfile = this.browserProfiles[index];
      var importOptions = ['history', 'favorites', 'passwords', 'search'];
      for (var i = 0; i < importOptions.length; i++) {
        var checkbox = $('import-' + importOptions[i]);
        var enable = browserProfile && browserProfile[importOptions[i]];
        this.setUpCheckboxState_(checkbox, enable);
        var checkboxWithLabel = $('import-' + importOptions[i] + '-with-label');
        checkboxWithLabel.style.display = enable ? '' : 'none';
      }
    },

    /**
     * Show or hide gray message at the bottom.
     * @private
     */
    updateBottomBar_: function() {
      var index = $('import-browsers').selectedIndex;
      var browserProfile;
      if (this.browserProfiles.length > index)
        browserProfile = this.browserProfiles[index];
      var enable = browserProfile && browserProfile['show_bottom_bar'];
      $('mac-password-keychain').hidden = !enable;
    },

    /**
     * Update the supported browsers popup with given entries.
     * @param {array} browsers List of supported browsers name.
     * @private
     */
    updateSupportedBrowsers_: function(browsers) {
      this.browserProfiles = browsers;
      var browserSelect = $('import-browsers');
      browserSelect.remove(0);  // Remove the 'Loading...' option.
      browserSelect.textContent = '';
      var browserCount = browsers.length;

      if (browserCount == 0) {
        var option = new Option(loadTimeData.getString('noProfileFound'), 0);
        browserSelect.appendChild(option);

        this.setAllControlsEnabled_(false);
      } else {
        this.setAllControlsEnabled_(true);
        for (var i = 0; i < browserCount; i++) {
          var browser = browsers[i];
          var option = new Option(browser.name, browser.index);
          browserSelect.appendChild(option);
        }

        this.updateCheckboxes_();
        this.validateCommitButton_();
        this.updateBottomBar_();
      }
    },

    /**
     * Clear import prefs set when user checks/unchecks a checkbox so that each
     * checkbox goes back to the default "checked" state (or alternatively, to
     * the state set by a recommended policy).
     * @private
     */
    clearUserPrefs_: function() {
      var importPrefs = ['import_history',
                         'import_bookmarks',
                         'import_saved_passwords',
                         'import_search_engine'];
      for (var i = 0; i < importPrefs.length; i++)
        Preferences.clearPref(importPrefs[i], true);
    },

    /**
     * Update the dialog layout to reflect success state.
     * @param {boolean} success If true, show success dialog elements.
     * @private
     */
    updateSuccessState_: function(success) {
      var sections = document.querySelectorAll('.import-data-configure');
      for (var i = 0; i < sections.length; i++)
        sections[i].hidden = success;

      sections = document.querySelectorAll('.import-data-success');
      for (var i = 0; i < sections.length; i++)
        sections[i].hidden = !success;
    },
  };

  ImportDataOverlay.clearUserPrefs = function() {
    ImportDataOverlay.getInstance().clearUserPrefs_();
  };

  /**
   * Update the supported browsers popup with given entries.
   * @param {array} list of supported browsers name.
   */
  ImportDataOverlay.updateSupportedBrowsers = function(browsers) {
    ImportDataOverlay.getInstance().updateSupportedBrowsers_(browsers);
  };

  /**
   * Update the UI to reflect whether an import operation is in progress.
   * @param {boolean} importing True if an import operation is in progress.
   */
  ImportDataOverlay.setImportingState = function(importing) {
    var checkboxes =
        document.querySelectorAll('#import-checkboxes input[type=checkbox]');
    for (var i = 0; i < checkboxes.length; i++)
        checkboxes[i].setDisabled('Importing', state);
    if (!importing)
      ImportDataOverlay.getInstance().updateCheckboxes_();
    $('import-browsers').disabled = importing;
    $('import-throbber').style.visibility = importing ? 'visible' : 'hidden';
    ImportDataOverlay.getInstance().validateCommitButton_();
  };

  /**
   * Remove the import overlay from display.
   */
  ImportDataOverlay.dismiss = function() {
    ImportDataOverlay.clearUserPrefs();
    OptionsPage.closeOverlay();
  };

  /**
   * Show a message confirming the success of the import operation.
   */
  ImportDataOverlay.confirmSuccess = function() {
    var showBookmarksMessage = $('import-favorites').checked;
    ImportDataOverlay.setImportingState(false);
    $('import-find-your-bookmarks').hidden = !showBookmarksMessage;
    ImportDataOverlay.getInstance().updateSuccessState_(true);
  };

  /**
   * Show the import data overlay.
   */
  ImportDataOverlay.show = function() {
    // Make sure that any previous import success message is hidden, and
    // we're showing the UI to import further data.
    ImportDataOverlay.getInstance().updateSuccessState_(false);
    ImportDataOverlay.getInstance().validateCommitButton_();

    OptionsPage.navigateToPage('importData');
  };

  // Export
  return {
    ImportDataOverlay: ImportDataOverlay
  };
});
<commit_msg>Fix regression where all checkboxes are disabled on "Import Bookmarks ..." dialog.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  var OptionsPage = options.OptionsPage;

  /**
   * ImportDataOverlay class
   * Encapsulated handling of the 'Import Data' overlay page.
   * @class
   */
  function ImportDataOverlay() {
    OptionsPage.call(this,
                     'importData',
                     loadTimeData.getString('importDataOverlayTabTitle'),
                     'import-data-overlay');
  }

  cr.addSingletonGetter(ImportDataOverlay);

  ImportDataOverlay.prototype = {
    // Inherit from OptionsPage.
    __proto__: OptionsPage.prototype,

    /**
     * Initialize the page.
     */
    initializePage: function() {
      // Call base class implementation to start preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      var checkboxes =
          document.querySelectorAll('#import-checkboxes input[type=checkbox]');
      for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].onchange = function() {
          self.validateCommitButton_();
        };
      }

      $('import-browsers').onchange = function() {
        self.updateCheckboxes_();
        self.validateCommitButton_();
        self.updateBottomBar_();
      };

      $('import-data-commit').onclick = function() {
        chrome.send('importData', [
            String($('import-browsers').selectedIndex),
            String($('import-history').checked),
            String($('import-favorites').checked),
            String($('import-passwords').checked),
            String($('import-search').checked)]);
      };

      $('import-data-cancel').onclick = function() {
        ImportDataOverlay.dismiss();
      };

      $('import-choose-file').onclick = function() {
        chrome.send('chooseBookmarksFile');
      };

      $('import-data-show-bookmarks-bar').onchange = function() {
        // Note: The callback 'toggleShowBookmarksBar' is handled within the
        // browser options handler -- rather than the import data handler --
        // as the implementation is shared by several clients.
        chrome.send('toggleShowBookmarksBar');
      }

      $('import-data-confirm').onclick = function() {
        ImportDataOverlay.dismiss();
      };

      // Form controls are disabled until the profile list has been loaded.
      self.setAllControlsEnabled_(false);
    },

    /**
     * Sets the enabled and checked state of the commit button.
     * @private
     */
    validateCommitButton_: function() {
      var somethingToImport =
          $('import-history').checked || $('import-favorites').checked ||
          $('import-passwords').checked || $('import-search').checked;
      $('import-data-commit').disabled = !somethingToImport;
      $('import-choose-file').disabled = !$('import-favorites').checked;
    },

    /**
     * Sets the enabled state of all the checkboxes and the commit button.
     * @private
     */
    setAllControlsEnabled_: function(enabled) {
      var checkboxes =
          document.querySelectorAll('#import-checkboxes input[type=checkbox]');
      for (var i = 0; i < checkboxes.length; i++)
        this.setUpCheckboxState_(checkboxes[i], enabled);
      $('import-data-commit').disabled = !enabled;
      $('import-choose-file').hidden = !enabled;
      $('mac-password-keychain').hidden = !enabled;
    },

    /**
     * Sets the enabled state of a checkbox element.
     * @param {Object} checkbox A checkbox element.
     * @param {boolean} enabled The enabled state of the checkbox. If false,
     *     the checkbox is disabled. If true, the checkbox is enabled.
     * @private
     */
    setUpCheckboxState_: function(checkbox, enabled) {
      checkbox.setDisabled('noProfileData', !enabled);
    },

    /**
     * Update the enabled and visible states of all the checkboxes.
     * @private
     */
    updateCheckboxes_: function() {
      var index = $('import-browsers').selectedIndex;
      var bookmarksFileSelected = index == this.browserProfiles.length - 1;
      $('import-choose-file').hidden = !bookmarksFileSelected;
      $('import-data-commit').hidden = bookmarksFileSelected;

      var browserProfile;
      if (this.browserProfiles.length > index)
        browserProfile = this.browserProfiles[index];
      var importOptions = ['history', 'favorites', 'passwords', 'search'];
      for (var i = 0; i < importOptions.length; i++) {
        var checkbox = $('import-' + importOptions[i]);
        var enable = browserProfile && browserProfile[importOptions[i]];
        this.setUpCheckboxState_(checkbox, enable);
        var checkboxWithLabel = $('import-' + importOptions[i] + '-with-label');
        checkboxWithLabel.style.display = enable ? '' : 'none';
      }
    },

    /**
     * Show or hide gray message at the bottom.
     * @private
     */
    updateBottomBar_: function() {
      var index = $('import-browsers').selectedIndex;
      var browserProfile;
      if (this.browserProfiles.length > index)
        browserProfile = this.browserProfiles[index];
      var enable = browserProfile && browserProfile['show_bottom_bar'];
      $('mac-password-keychain').hidden = !enable;
    },

    /**
     * Update the supported browsers popup with given entries.
     * @param {array} browsers List of supported browsers name.
     * @private
     */
    updateSupportedBrowsers_: function(browsers) {
      this.browserProfiles = browsers;
      var browserSelect = $('import-browsers');
      browserSelect.remove(0);  // Remove the 'Loading...' option.
      browserSelect.textContent = '';
      var browserCount = browsers.length;

      if (browserCount == 0) {
        var option = new Option(loadTimeData.getString('noProfileFound'), 0);
        browserSelect.appendChild(option);

        this.setAllControlsEnabled_(false);
      } else {
        this.setAllControlsEnabled_(true);
        for (var i = 0; i < browserCount; i++) {
          var browser = browsers[i];
          var option = new Option(browser.name, browser.index);
          browserSelect.appendChild(option);
        }

        this.updateCheckboxes_();
        this.validateCommitButton_();
        this.updateBottomBar_();
      }
    },

    /**
     * Clear import prefs set when user checks/unchecks a checkbox so that each
     * checkbox goes back to the default "checked" state (or alternatively, to
     * the state set by a recommended policy).
     * @private
     */
    clearUserPrefs_: function() {
      var importPrefs = ['import_history',
                         'import_bookmarks',
                         'import_saved_passwords',
                         'import_search_engine'];
      for (var i = 0; i < importPrefs.length; i++)
        Preferences.clearPref(importPrefs[i], true);
    },

    /**
     * Update the dialog layout to reflect success state.
     * @param {boolean} success If true, show success dialog elements.
     * @private
     */
    updateSuccessState_: function(success) {
      var sections = document.querySelectorAll('.import-data-configure');
      for (var i = 0; i < sections.length; i++)
        sections[i].hidden = success;

      sections = document.querySelectorAll('.import-data-success');
      for (var i = 0; i < sections.length; i++)
        sections[i].hidden = !success;
    },
  };

  ImportDataOverlay.clearUserPrefs = function() {
    ImportDataOverlay.getInstance().clearUserPrefs_();
  };

  /**
   * Update the supported browsers popup with given entries.
   * @param {array} list of supported browsers name.
   */
  ImportDataOverlay.updateSupportedBrowsers = function(browsers) {
    ImportDataOverlay.getInstance().updateSupportedBrowsers_(browsers);
  };

  /**
   * Update the UI to reflect whether an import operation is in progress.
   * @param {boolean} importing True if an import operation is in progress.
   */
  ImportDataOverlay.setImportingState = function(importing) {
    var checkboxes =
        document.querySelectorAll('#import-checkboxes input[type=checkbox]');
    for (var i = 0; i < checkboxes.length; i++)
        checkboxes[i].setDisabled('Importing', importing);
    if (!importing)
      ImportDataOverlay.getInstance().updateCheckboxes_();
    $('import-browsers').disabled = importing;
    $('import-throbber').style.visibility = importing ? 'visible' : 'hidden';
    ImportDataOverlay.getInstance().validateCommitButton_();
  };

  /**
   * Remove the import overlay from display.
   */
  ImportDataOverlay.dismiss = function() {
    ImportDataOverlay.clearUserPrefs();
    OptionsPage.closeOverlay();
  };

  /**
   * Show a message confirming the success of the import operation.
   */
  ImportDataOverlay.confirmSuccess = function() {
    var showBookmarksMessage = $('import-favorites').checked;
    ImportDataOverlay.setImportingState(false);
    $('import-find-your-bookmarks').hidden = !showBookmarksMessage;
    ImportDataOverlay.getInstance().updateSuccessState_(true);
  };

  /**
   * Show the import data overlay.
   */
  ImportDataOverlay.show = function() {
    // Make sure that any previous import success message is hidden, and
    // we're showing the UI to import further data.
    ImportDataOverlay.getInstance().updateSuccessState_(false);
    ImportDataOverlay.getInstance().validateCommitButton_();

    OptionsPage.navigateToPage('importData');
  };

  // Export
  return {
    ImportDataOverlay: ImportDataOverlay
  };
});
<|endoftext|>


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

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");
// Local version replace global one
try {
	var localWebpack = require.resolve(path.join(process.cwd(), "node_modules", "webpack", "bin", "webpack.js"));
	if(__filename !== localWebpack) {
		return require(localWebpack);
	}
} catch(e) {}
var yargs = require("yargs")
	.usage("webpack " + require("../package.json").version + "\n" +
		"Usage: https://webpack.github.io/docs/cli.html\n" +
		"Usage without config file: webpack <entry> [<entry>] <output>\n" +
		"Usage with config file: webpack");

require("./config-yargs")(yargs);

var DISPLAY_GROUP = "Stats options:";
var BASIC_GROUP = "Basic options:";

yargs.options({
	"json": {
		type: "boolean",
		alias: "j",
		describe: "Prints the result as JSON."
	},
	"progress": {
		type: "boolean",
		describe: "Print compilation progress in percentage",
		group: BASIC_GROUP
	},
	"color": {
		type: "boolean",
		alias: "colors",
		default: function supportsColor() {
			return require("supports-color");
		},
		group: DISPLAY_GROUP,
		describe: "Enables/Disables colors on the console"
	},
	"sort-modules-by": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Sorts the modules list by property in module"
	},
	"sort-chunks-by": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Sorts the chunks list by property in chunk"
	},
	"sort-assets-by": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Sorts the assets list by property in asset"
	},
	"hide-modules": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Hides info about modules"
	},
	"display-exclude": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Exclude modules in the output"
	},
	"display-modules": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display even excluded modules in the output"
	},
	"display-chunks": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display chunks in the output"
	},
	"display-entrypoints": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display entry points in the output"
	},
	"display-origins": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display origins of chunks in the output"
	},
	"display-cached": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display also cached modules in the output"
	},
	"display-cached-assets": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display also cached assets in the output"
	},
	"display-reasons": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display reasons about module inclusion in the output"
	},
	"display-used-exports": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display information about used exports in modules (Tree Shaking)"
	},
	"display-provided-exports": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display information about exports provided from modules"
	},
	"display-error-details": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display details about errors"
	},
	"verbose": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Show more details"
	}
});

var argv = yargs.argv;

if(argv.verbose) {
	argv["display-reasons"] = true;
	argv["display-entrypoints"] = true;
	argv["display-used-exports"] = true;
	argv["display-provided-exports"] = true;
	argv["display-error-details"] = true;
	argv["display-modules"] = true;
	argv["display-cached"] = true;
	argv["display-cached-assets"] = true;
}

var options = require("./convert-argv")(yargs, argv);

function ifArg(name, fn, init) {
	if(Array.isArray(argv[name])) {
		if(init) init();
		argv[name].forEach(fn);
	} else if(typeof argv[name] !== "undefined") {
		if(init) init();
		fn(argv[name], -1);
	}
}

function hasPresetPredicate(options) {
	return typeof options.stats === "boolean" || typeof options.stats === "string";
}

function hasPreset(optionsArray) {
	options = Array.isArray(optionsArray) ? optionsArray : [optionsArray];
	return options.some(hasPresetPredicate);
}

function processOptions(options) {
	// process Promise
	if(typeof options.then === "function") {
		options.then(processOptions).catch(function(err) {
			console.error(err.stack || err);
			process.exit(); // eslint-disable-line
		});
		return;
	}

	// var firstOptions = Array.isArray(options) ? (options[0] || {}) : options;
	var firstOptions = Array.isArray(options) ? (options[0] || {}) : options;
	if(hasPreset(options)) {
		var statsPresetToOptions = require("../lib/Stats.js").presetToOptions;

		if(Array.isArray(options)) {

			options = options.map(function(singleOption) {
				singleOption.stats = statsPresetToOptions(singleOption.stats);
				return singleOption;
			})
		} else {
			options.stats = statsPresetToOptions(options.stats);
		}
	}

	var outputOptions = Object.create(options.stats || firstOptions.stats || {});
	if(typeof outputOptions.context === "undefined")
		outputOptions.context = firstOptions.context;

	ifArg("json", function(bool) {
		if(bool)
			outputOptions.json = bool;
	});

	if(typeof outputOptions.colors === "undefined")
		outputOptions.colors = require("supports-color");

	ifArg("sort-modules-by", function(value) {
		outputOptions.modulesSort = value;
	});

	ifArg("sort-chunks-by", function(value) {
		outputOptions.chunksSort = value;
	});

	ifArg("sort-assets-by", function(value) {
		outputOptions.assetsSort = value;
	});

	ifArg("display-exclude", function(value) {
		outputOptions.exclude = value;
	});

	if(!outputOptions.json) {
		if(typeof outputOptions.cached === "undefined")
			outputOptions.cached = false;
		if(typeof outputOptions.cachedAssets === "undefined")
			outputOptions.cachedAssets = false;

		ifArg("display-chunks", function(bool) {
			outputOptions.modules = !bool;
			outputOptions.chunks = bool;
		});

		ifArg("display-entrypoints", function(bool) {
			outputOptions.entrypoints = bool;
		});

		ifArg("display-reasons", function(bool) {
			outputOptions.reasons = bool;
		});

		ifArg("display-used-exports", function(bool) {
			outputOptions.usedExports = bool;
		});

		ifArg("display-provided-exports", function(bool) {
			outputOptions.providedExports = bool;
		});

		ifArg("display-error-details", function(bool) {
			outputOptions.errorDetails = bool;
		});

		ifArg("display-origins", function(bool) {
			outputOptions.chunkOrigins = bool;
		});

		ifArg("display-cached", function(bool) {
			if(bool)
				outputOptions.cached = true;
		});

		ifArg("display-cached-assets", function(bool) {
			if(bool)
				outputOptions.cachedAssets = true;
		});

		if(!outputOptions.exclude && !argv["display-modules"])
			outputOptions.exclude = ["node_modules", "bower_components", "jam", "components"];
	} else {
		if(typeof outputOptions.chunks === "undefined")
			outputOptions.chunks = true;
		if(typeof outputOptions.entrypoints === "undefined")
			outputOptions.entrypoints = true;
		if(typeof outputOptions.modules === "undefined")
			outputOptions.modules = true;
		if(typeof outputOptions.chunkModules === "undefined")
			outputOptions.chunkModules = true;
		if(typeof outputOptions.reasons === "undefined")
			outputOptions.reasons = true;
		if(typeof outputOptions.cached === "undefined")
			outputOptions.cached = true;
		if(typeof outputOptions.cachedAssets === "undefined")
			outputOptions.cachedAssets = true;
	}

	ifArg("hide-modules", function(bool) {
		if(bool) {
			outputOptions.modules = false;
			outputOptions.chunkModules = false;
		}
	});

	var webpack = require("../lib/webpack.js");

	Error.stackTraceLimit = 30;
	var lastHash = null;
	var compiler;
	try {
		compiler = webpack(options);
	} catch(e) {
		var WebpackOptionsValidationError = require("../lib/WebpackOptionsValidationError");
		if(e instanceof WebpackOptionsValidationError) {
			if(argv.color)
				console.error("\u001b[1m\u001b[31m" + e.message + "\u001b[39m\u001b[22m");
			else
				console.error(e.message);
			process.exit(1); // eslint-disable-line no-process-exit
		}
		throw e;
	}

	if(argv.progress) {
		var ProgressPlugin = require("../lib/ProgressPlugin");
		compiler.apply(new ProgressPlugin({
			profile: argv.profile
		}));
	}

	function compilerCallback(err, stats) {
		if(!options.watch || err) {
			// Do not keep cache anymore
			compiler.purgeInputFileSystem();
		}
		if(err) {
			lastHash = null;
			console.error(err.stack || err);
			if(err.details) console.error(err.details);
			process.exit(1); // eslint-disable-line
			return;
		}
		if(outputOptions.json) {
			process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + "\n");
		} else if(stats.hash !== lastHash) {
			lastHash = stats.hash;
			process.stdout.write(stats.toString(outputOptions) + "\n");
		}
		if(!options.watch && stats.hasErrors()) {
			process.on("exit", function() {
				process.exit(2); // eslint-disable-line
			});
		}
	}
	if(options.watch) {
		var primaryOptions = !Array.isArray(options) ? options : options[0];
		var watchOptions = primaryOptions.watchOptions || primaryOptions.watch || {};
		if(watchOptions.stdin) {
			process.stdin.on('end', function() {
				process.exit(0); // eslint-disable-line
			});
			process.stdin.resume();
		}
		compiler.watch(watchOptions, compilerCallback);
		console.log('\nWebpack is watching the files…\n');
	} else
		compiler.run(compilerCallback);

}

processOptions(options);
<commit_msg>chore(stats): remove comment, add semicolon, swap map with forEach<commit_after>#!/usr/bin/env node

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");
// Local version replace global one
try {
	var localWebpack = require.resolve(path.join(process.cwd(), "node_modules", "webpack", "bin", "webpack.js"));
	if(__filename !== localWebpack) {
		return require(localWebpack);
	}
} catch(e) {}
var yargs = require("yargs")
	.usage("webpack " + require("../package.json").version + "\n" +
		"Usage: https://webpack.github.io/docs/cli.html\n" +
		"Usage without config file: webpack <entry> [<entry>] <output>\n" +
		"Usage with config file: webpack");

require("./config-yargs")(yargs);

var DISPLAY_GROUP = "Stats options:";
var BASIC_GROUP = "Basic options:";

yargs.options({
	"json": {
		type: "boolean",
		alias: "j",
		describe: "Prints the result as JSON."
	},
	"progress": {
		type: "boolean",
		describe: "Print compilation progress in percentage",
		group: BASIC_GROUP
	},
	"color": {
		type: "boolean",
		alias: "colors",
		default: function supportsColor() {
			return require("supports-color");
		},
		group: DISPLAY_GROUP,
		describe: "Enables/Disables colors on the console"
	},
	"sort-modules-by": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Sorts the modules list by property in module"
	},
	"sort-chunks-by": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Sorts the chunks list by property in chunk"
	},
	"sort-assets-by": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Sorts the assets list by property in asset"
	},
	"hide-modules": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Hides info about modules"
	},
	"display-exclude": {
		type: "string",
		group: DISPLAY_GROUP,
		describe: "Exclude modules in the output"
	},
	"display-modules": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display even excluded modules in the output"
	},
	"display-chunks": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display chunks in the output"
	},
	"display-entrypoints": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display entry points in the output"
	},
	"display-origins": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display origins of chunks in the output"
	},
	"display-cached": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display also cached modules in the output"
	},
	"display-cached-assets": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display also cached assets in the output"
	},
	"display-reasons": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display reasons about module inclusion in the output"
	},
	"display-used-exports": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display information about used exports in modules (Tree Shaking)"
	},
	"display-provided-exports": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display information about exports provided from modules"
	},
	"display-error-details": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Display details about errors"
	},
	"verbose": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Show more details"
	}
});

var argv = yargs.argv;

if(argv.verbose) {
	argv["display-reasons"] = true;
	argv["display-entrypoints"] = true;
	argv["display-used-exports"] = true;
	argv["display-provided-exports"] = true;
	argv["display-error-details"] = true;
	argv["display-modules"] = true;
	argv["display-cached"] = true;
	argv["display-cached-assets"] = true;
}

var options = require("./convert-argv")(yargs, argv);

function ifArg(name, fn, init) {
	if(Array.isArray(argv[name])) {
		if(init) init();
		argv[name].forEach(fn);
	} else if(typeof argv[name] !== "undefined") {
		if(init) init();
		fn(argv[name], -1);
	}
}

function hasPresetPredicate(options) {
	return typeof options.stats === "boolean" || typeof options.stats === "string";
}

function hasPreset(optionsArray) {
	options = Array.isArray(optionsArray) ? optionsArray : [optionsArray];
	return options.some(hasPresetPredicate);
}

function processOptions(options) {
	// process Promise
	if(typeof options.then === "function") {
		options.then(processOptions).catch(function(err) {
			console.error(err.stack || err);
			process.exit(); // eslint-disable-line
		});
		return;
	}

	var firstOptions = Array.isArray(options) ? (options[0] || {}) : options;
	if(hasPreset(options)) {
		var statsPresetToOptions = require("../lib/Stats.js").presetToOptions;

		if(Array.isArray(options)) {
			options = options.forEach(function(singleOption) {
				singleOption.stats = statsPresetToOptions(singleOption.stats);
			});
		} else {
			options.stats = statsPresetToOptions(options.stats);
		}
	}

	var outputOptions = Object.create(options.stats || firstOptions.stats || {});
	if(typeof outputOptions.context === "undefined")
		outputOptions.context = firstOptions.context;

	ifArg("json", function(bool) {
		if(bool)
			outputOptions.json = bool;
	});

	if(typeof outputOptions.colors === "undefined")
		outputOptions.colors = require("supports-color");

	ifArg("sort-modules-by", function(value) {
		outputOptions.modulesSort = value;
	});

	ifArg("sort-chunks-by", function(value) {
		outputOptions.chunksSort = value;
	});

	ifArg("sort-assets-by", function(value) {
		outputOptions.assetsSort = value;
	});

	ifArg("display-exclude", function(value) {
		outputOptions.exclude = value;
	});

	if(!outputOptions.json) {
		if(typeof outputOptions.cached === "undefined")
			outputOptions.cached = false;
		if(typeof outputOptions.cachedAssets === "undefined")
			outputOptions.cachedAssets = false;

		ifArg("display-chunks", function(bool) {
			outputOptions.modules = !bool;
			outputOptions.chunks = bool;
		});

		ifArg("display-entrypoints", function(bool) {
			outputOptions.entrypoints = bool;
		});

		ifArg("display-reasons", function(bool) {
			outputOptions.reasons = bool;
		});

		ifArg("display-used-exports", function(bool) {
			outputOptions.usedExports = bool;
		});

		ifArg("display-provided-exports", function(bool) {
			outputOptions.providedExports = bool;
		});

		ifArg("display-error-details", function(bool) {
			outputOptions.errorDetails = bool;
		});

		ifArg("display-origins", function(bool) {
			outputOptions.chunkOrigins = bool;
		});

		ifArg("display-cached", function(bool) {
			if(bool)
				outputOptions.cached = true;
		});

		ifArg("display-cached-assets", function(bool) {
			if(bool)
				outputOptions.cachedAssets = true;
		});

		if(!outputOptions.exclude && !argv["display-modules"])
			outputOptions.exclude = ["node_modules", "bower_components", "jam", "components"];
	} else {
		if(typeof outputOptions.chunks === "undefined")
			outputOptions.chunks = true;
		if(typeof outputOptions.entrypoints === "undefined")
			outputOptions.entrypoints = true;
		if(typeof outputOptions.modules === "undefined")
			outputOptions.modules = true;
		if(typeof outputOptions.chunkModules === "undefined")
			outputOptions.chunkModules = true;
		if(typeof outputOptions.reasons === "undefined")
			outputOptions.reasons = true;
		if(typeof outputOptions.cached === "undefined")
			outputOptions.cached = true;
		if(typeof outputOptions.cachedAssets === "undefined")
			outputOptions.cachedAssets = true;
	}

	ifArg("hide-modules", function(bool) {
		if(bool) {
			outputOptions.modules = false;
			outputOptions.chunkModules = false;
		}
	});

	var webpack = require("../lib/webpack.js");

	Error.stackTraceLimit = 30;
	var lastHash = null;
	var compiler;
	try {
		compiler = webpack(options);
	} catch(e) {
		var WebpackOptionsValidationError = require("../lib/WebpackOptionsValidationError");
		if(e instanceof WebpackOptionsValidationError) {
			if(argv.color)
				console.error("\u001b[1m\u001b[31m" + e.message + "\u001b[39m\u001b[22m");
			else
				console.error(e.message);
			process.exit(1); // eslint-disable-line no-process-exit
		}
		throw e;
	}

	if(argv.progress) {
		var ProgressPlugin = require("../lib/ProgressPlugin");
		compiler.apply(new ProgressPlugin({
			profile: argv.profile
		}));
	}

	function compilerCallback(err, stats) {
		if(!options.watch || err) {
			// Do not keep cache anymore
			compiler.purgeInputFileSystem();
		}
		if(err) {
			lastHash = null;
			console.error(err.stack || err);
			if(err.details) console.error(err.details);
			process.exit(1); // eslint-disable-line
			return;
		}
		if(outputOptions.json) {
			process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + "\n");
		} else if(stats.hash !== lastHash) {
			lastHash = stats.hash;
			process.stdout.write(stats.toString(outputOptions) + "\n");
		}
		if(!options.watch && stats.hasErrors()) {
			process.on("exit", function() {
				process.exit(2); // eslint-disable-line
			});
		}
	}
	if(options.watch) {
		var primaryOptions = !Array.isArray(options) ? options : options[0];
		var watchOptions = primaryOptions.watchOptions || primaryOptions.watch || {};
		if(watchOptions.stdin) {
			process.stdin.on('end', function() {
				process.exit(0); // eslint-disable-line
			});
			process.stdin.resume();
		}
		compiler.watch(watchOptions, compilerCallback);
		console.log('\nWebpack is watching the files…\n');
	} else
		compiler.run(compilerCallback);

}

processOptions(options);
<|endoftext|>


<commit_before>"use strict";

module.exports = {
  "japan":"http://blog.openstreetmap.de/wp-uploads//2016/02/jp.svg",
  "france":"http://blog.openstreetmap.de/wp-uploads//2016/02/fr.svg",
  "spain":"http://blog.openstreetmap.de/wp-uploads//2015/01/es.svg",
  "czech republic":"http://blog.openstreetmap.de/wp-uploads//2015/01/cz.svg",
  "russia":"http://blog.openstreetmap.de/wp-uploads//2016/01/ru.svg",
  "romania":"http://blog.openstreetmap.de/wp-uploads//2015/10/ro.svg",
  "netherland":"http://blog.openstreetmap.de/wp-uploads//2015/07/nl.svg",
  "brasil":"http://blog.openstreetmap.de/wp-uploads//2015/01/pt-br.svg",
  "poland":"http://blog.openstreetmap.de/wp-uploads//2015/10/pl.svg",
  "taiwan":"http://blog.openstreetmap.de/wp-uploads//2016/01/tw.svg",
  "switzerland":"http://blog.openstreetmap.de/wp-uploads//2016/02/ch.svg",
  "schweiz":"http://blog.openstreetmap.de/wp-uploads//2016/01/ch.svg",
  "italy":"http://blog.openstreetmap.de/wp-uploads//2016/02/it.svg",
  "us":"http://blog.openstreetmap.de/wp-uploads//2016/01/us.svg",
  "united states":"http://blog.openstreetmap.de/wp-uploads//2016/01/us.svg",
  "austria":"http://blog.openstreetmap.de/wp-uploads//2016/02/at.svg",
  "österreich":"http://blog.openstreetmap.de/wp-uploads//2016/02/at.svg",
  "philippines":"http://blog.openstreetmap.de/wp-uploads//2016/01/ph.svg",
  "belgium":"http://blog.openstreetmap.de/wp-uploads//2016/01/be-1.svg",
  "argentina":"http://blog.openstreetmap.de/wp-uploads//2016/01/ar.svg",
  "england":"http://blog.openstreetmap.de/wp-uploads//2015/01/en.svg",
  "uk":"http://blog.openstreetmap.de/wp-uploads//2015/01/en.svg",
  "germany":"http://blog.openstreetmap.de/wp-uploads//2016/01/de.svg",
  "deutschland":"http://blog.openstreetmap.de/wp-uploads//2016/01/de.svg",
  "bolivia":"http://blog.openstreetmap.de/wp-uploads//2016/01/bo.svg",
  "canada":"http://blog.openstreetmap.de/wp-uploads//2016/01/ca.svg",
  "hungary":"http://blog.openstreetmap.de/wp-uploads//2016/02/hu.svg",
  "india":"http://blog.openstreetmap.de/wp-uploads//2016/01/in.svg",
  "saint lucia":"http://blog.openstreetmap.de/wp-uploads//2016/02/lc.svg",
  "finland":"http://blog.openstreetmap.de/wp-uploads//2016/02/fi.svg",
  "haiti":"http://blog.openstreetmap.de/wp-uploads//2016/02/ht.svg",
  "mexico":"http://blog.openstreetmap.de/wp-uploads//2016/02/mx.svg",
  "colombia":"http://blog.openstreetmap.de/wp-uploads//2016/02/co.svg"

};
<commit_msg>Bolivia and UK size adjusted size<commit_after>"use strict";

module.exports = {
  "japan":"http://blog.openstreetmap.de/wp-uploads//2016/02/jp.svgen.s",
  "france":"http://blog.openstreetmap.de/wp-uploads//2016/02/fr.svg",
  "spain":"http://blog.openstreetmap.de/wp-uploads//2015/01/es.svg",
  "czech republic":"http://blog.openstreetmap.de/wp-uploads//2015/01/cz.svg",
  "russia":"http://blog.openstreetmap.de/wp-uploads//2016/01/ru.svg",
  "romania":"http://blog.openstreetmap.de/wp-uploads//2015/10/ro.svg",
  "netherland":"http://blog.openstreetmap.de/wp-uploads//2015/07/nl.svg",
  "brasil":"http://blog.openstreetmap.de/wp-uploads//2015/01/pt-br.svg",
  "poland":"http://blog.openstreetmap.de/wp-uploads//2015/10/pl.svg",
  "taiwan":"http://blog.openstreetmap.de/wp-uploads//2016/01/tw.svg",
  "switzerland":"http://blog.openstreetmap.de/wp-uploads//2016/02/ch.svg",
  "schweiz":"http://blog.openstreetmap.de/wp-uploads//2016/01/ch.svg",
  "italy":"http://blog.openstreetmap.de/wp-uploads//2016/02/it.svg",
  "us":"http://blog.openstreetmap.de/wp-uploads//2016/01/us.svg",
  "united states":"http://blog.openstreetmap.de/wp-uploads//2016/01/us.svg",
  "austria":"http://blog.openstreetmap.de/wp-uploads//2016/02/at.svg",
  "österreich":"http://blog.openstreetmap.de/wp-uploads//2016/02/at.svg",
  "philippines":"http://blog.openstreetmap.de/wp-uploads//2016/01/ph.svg",
  "belgium":"http://blog.openstreetmap.de/wp-uploads//2016/01/be-1.svg",
  "argentina":"http://blog.openstreetmap.de/wp-uploads//2016/01/ar.svg",
  "england":"http://blog.openstreetmap.de/wp-uploads//2016/03/en.svg",
  "uk":"http://blog.openstreetmap.de/wp-uploads//2016/03/en.svg",
  "germany":"http://blog.openstreetmap.de/wp-uploads//2016/01/de.svg",
  "deutschland":"http://blog.openstreetmap.de/wp-uploads//2016/01/de.svg",
  "bolivia":"http://blog.openstreetmap.de/wp-uploads//2016/03/bo.svg",
  "canada":"http://blog.openstreetmap.de/wp-uploads//2016/01/ca.svg",
  "hungary":"http://blog.openstreetmap.de/wp-uploads//2016/02/hu.svg",
  "india":"http://blog.openstreetmap.de/wp-uploads//2016/01/in.svg",
  "saint lucia":"http://blog.openstreetmap.de/wp-uploads//2016/02/lc.svg",
  "finland":"http://blog.openstreetmap.de/wp-uploads//2016/02/fi.svg",
  "haiti":"http://blog.openstreetmap.de/wp-uploads//2016/02/ht.svg",
  "mexico":"http://blog.openstreetmap.de/wp-uploads//2016/02/mx.svg",
  "colombia":"http://blog.openstreetmap.de/wp-uploads//2016/02/co.svg"

};
<|endoftext|>


<commit_before>Template['actionPlanComposeForm'].helpers({
  getMilestones: function () {
    return Milestones.find({ _id: { $in: this.milestone_ids } });
  },
  getSubtasks: function () {
    return Subtasks.find({ _id: { $in: this.subtask_ids } });
  }
});

Template['actionPlanComposeForm'].events({
  'submit #ap_request': function (event) {
    event.preventDefault();
    if (!confirm('Are you sure you want to submit? You cannot edit the action plan after submission.'))
      return;

    var actionPlanId = Router.current().params._id;

    saveMilestonesAndSubtasks();

    var actionPlan = {
      _id: actionPlanId,
      isComplete: true
    };

    Meteor.call('action_plan_edit', actionPlan, function (err) {
      if (!err) {
        Router.go('action_plans')
      }
    });
  },
  'input input#title': function (event) {
    updateMilestone(event);
  },
  'input textarea#motivation': function (event) {
    updateMilestone(event);
  },
  'input input#description': function (event) {
    updateSubtask(event);
  },
  'input input#links': function (event) {
    updateSubtask(event);
  },
  'click .add-subtask': function (event) {
    event.preventDefault();

    var milestone = $(event.target).parent().parent();
    var actionPlanId = Router.current().params._id;

    // check that milestone has a title and motivation first
    if ($('input#title', milestone).val() && $('textarea#motivation', milestone).val()) {
      Meteor.call('subtask_new', {description: "", links: [], milestone_id: $('#_id', milestone).val()}, function (err) {
        if (!err) {
          console.log('subtask saved');
        }
      });
    } else {
      alert("Add a milestone title and motivation first.");
      return;
    }
  },
  'click .add-milestone': function (event) {
    event.preventDefault();
    var actionPlanId = Router.current().params._id;

    Meteor.call('milestone_new', {title: "", motivation: "", subtask_ids: []}, actionPlanId, function (err, res) {
      if (!err) {
        console.log('milestone saved');
      }
    });
  },
  'click .delete-subtask': function (event) {
    event.preventDefault();
    var subtask = $(event.target).parent().parent();
    var id = $('#_id', subtask).val();

    Meteor.call('subtask_delete', id, function (err, res) {
      if (!err) {
        console.log('subtask deleted');
      }
    });
  },
  'click .delete-milestone': function (event) {
    event.preventDefault();
    var milestone = $(event.target).parent().parent();
    var id = $('#_id', milestone).val();
    var actionPlanId = Session.get("ap")._id;

    Meteor.call('milestone_delete', id, actionPlanId, function (err, res) {
      if (!err) {
        console.log('milestone deleted');
      }
    });
  }
});

var handle = null; // used for timeout

function saveMilestonesAndSubtasks() {
  var milestonesAndSubtasks = getMilestonesAndSubtasks();

  milestonesAndSubtasks.subtasks.forEach(function(e, i, a) {
    Meteor.call('subtask_edit', e, function (err) {
      if (!err) {
        console.log('subtask updated');
      }
    });
  });

  milestonesAndSubtasks.milestones.forEach(function(e, i, a) {
    Meteor.call('milestone_edit', e, function (err) {
      if (!err) {
        console.log('milestone updated');
      }
    });
  });

  return;
}

function getMilestonesAndSubtasks() {
  var milestones = [];
  var subtasks = [];
  var milestone = {};

  $('.milestone').each(function() {
    milestone = {
      _id: $('#_id', this).val(),
      title: $('#title', this).val(),
      motivation: $('#motivation', this).val()
    }
    milestones.push(milestone);
    var newSubtasks = getCorrespondingSubtasks(this);
    subtasks = subtasks.concat(newSubtasks);
  });

  var milestonesAndSubtasks = {
    milestones: milestones,
    subtasks: subtasks
  }

  return milestonesAndSubtasks;
}

function getCorrespondingSubtasks(milestone) {
  var correspondingSubtasks = [];
  var subtask = {};

  $('.subtask', milestone).each(function() {
    subtask = {
      _id: $('#_id', this).val(),
      description: $('#description', this).val(),
      links: [$('#links', this).val()],
      milestone_id: $('#_id', milestone).val()
    }
    correspondingSubtasks.push(subtask);
  });

  return correspondingSubtasks;
}

function updateMilestone(event) {
  if (handle)
    clearTimeout(handle);

  handle = setTimeout(function() {
    var milestoneSelector = $(event.target).parent().parent();
    var milestone = {
      _id: $('#_id', milestoneSelector).val(),
      title: $('#title', milestoneSelector).val(),
      motivation: $('#motivation', milestoneSelector).val()
    }

    Meteor.call('milestone_edit', milestone, function (err) {
      if (!err) {
        console.log('milestone updated');
      }
    });
  }, 500);
}

function updateSubtask(event) {
  if (handle)
    clearTimeout(handle);

  handle = setTimeout(function() {
    var subtaskSelector = $(event.target).parent().parent();
    var subtask = {
      _id: $('#_id', subtaskSelector).val(),
      description: $('#description', subtaskSelector).val(),
      links: [$('#links', subtaskSelector).val()]
    }

    Meteor.call('subtask_edit', subtask, function (err) {
      if (!err) {
        console.log('subtask updated');
      }
    });
  }, 500);
}<commit_msg>Update on blur instead of while user is typing<commit_after>Template['actionPlanComposeForm'].helpers({
  getMilestones: function () {
    return Milestones.find({ _id: { $in: this.milestone_ids } });
  },
  getSubtasks: function () {
    return Subtasks.find({ _id: { $in: this.subtask_ids } });
  }
});

Template['actionPlanComposeForm'].events({
  'submit #ap_request': function (event) {
    event.preventDefault();
    if (!confirm('Are you sure you want to submit? You cannot edit the action plan after submission.'))
      return;

    var actionPlanId = Router.current().params._id;

    saveMilestonesAndSubtasks();

    var actionPlan = {
      _id: actionPlanId,
      isComplete: true
    };

    Meteor.call('action_plan_edit', actionPlan, function (err) {
      if (!err) {
        Router.go('action_plans')
      }
    });
  },
  'blur input#title': function (event) {
    updateMilestone(event);
  },
  'blur textarea#motivation': function (event) {
    updateMilestone(event);
  },
  'blur input#description': function (event) {
    updateSubtask(event);
  },
  'blur input#links': function (event) {
    updateSubtask(event);
  },
  'click .add-subtask': function (event) {
    event.preventDefault();

    var milestone = $(event.target).parent().parent();
    var actionPlanId = Router.current().params._id;

    // check that milestone has a title and motivation first
    if ($('input#title', milestone).val() && $('textarea#motivation', milestone).val()) {
      Meteor.call('subtask_new', {description: "", links: [], milestone_id: $('#_id', milestone).val()}, function (err) {
        if (!err) {
          console.log('subtask saved');
        }
      });
    } else {
      alert("Add a milestone title and motivation first.");
      return;
    }
  },
  'click .add-milestone': function (event) {
    event.preventDefault();
    var actionPlanId = Router.current().params._id;

    Meteor.call('milestone_new', {title: "", motivation: "", subtask_ids: []}, actionPlanId, function (err, res) {
      if (!err) {
        console.log('milestone saved');
      }
    });
  },
  'click .delete-subtask': function (event) {
    event.preventDefault();
    var subtask = $(event.target).parent().parent();
    var id = $('#_id', subtask).val();

    Meteor.call('subtask_delete', id, function (err, res) {
      if (!err) {
        console.log('subtask deleted');
      }
    });
  },
  'click .delete-milestone': function (event) {
    event.preventDefault();
    var milestone = $(event.target).parent().parent();
    var id = $('#_id', milestone).val();
    var actionPlanId = Session.get("ap")._id;

    Meteor.call('milestone_delete', id, actionPlanId, function (err, res) {
      if (!err) {
        console.log('milestone deleted');
      }
    });
  }
});

function saveMilestonesAndSubtasks() {
  var milestonesAndSubtasks = getMilestonesAndSubtasks();

  milestonesAndSubtasks.subtasks.forEach(function(e, i, a) {
    Meteor.call('subtask_edit', e, function (err) {
      if (!err) {
        console.log('subtask updated');
      }
    });
  });

  milestonesAndSubtasks.milestones.forEach(function(e, i, a) {
    Meteor.call('milestone_edit', e, function (err) {
      if (!err) {
        console.log('milestone updated');
      }
    });
  });

  return;
}

function getMilestonesAndSubtasks() {
  var milestones = [];
  var subtasks = [];
  var milestone = {};

  $('.milestone').each(function() {
    milestone = {
      _id: $('#_id', this).val(),
      title: $('#title', this).val(),
      motivation: $('#motivation', this).val()
    }
    milestones.push(milestone);
    var newSubtasks = getCorrespondingSubtasks(this);
    subtasks = subtasks.concat(newSubtasks);
  });

  var milestonesAndSubtasks = {
    milestones: milestones,
    subtasks: subtasks
  }

  return milestonesAndSubtasks;
}

function getCorrespondingSubtasks(milestone) {
  var correspondingSubtasks = [];
  var subtask = {};

  $('.subtask', milestone).each(function() {
    subtask = {
      _id: $('#_id', this).val(),
      description: $('#description', this).val(),
      links: [$('#links', this).val()],
      milestone_id: $('#_id', milestone).val()
    }
    correspondingSubtasks.push(subtask);
  });

  return correspondingSubtasks;
}

function updateMilestone(event) {
  var milestoneSelector = $(event.target).parent().parent();
  var milestone = {
    _id: $('#_id', milestoneSelector).val(),
    title: $('#title', milestoneSelector).val(),
    motivation: $('#motivation', milestoneSelector).val()
  }

  Meteor.call('milestone_edit', milestone, function (err) {
    if (!err) {
      console.log('milestone updated');
    }
  });
}

function updateSubtask(event) {
  var subtaskSelector = $(event.target).parent().parent();
  var subtask = {
    _id: $('#_id', subtaskSelector).val(),
    description: $('#description', subtaskSelector).val(),
    links: [$('#links', subtaskSelector).val()]
  }

  Meteor.call('subtask_edit', subtask, function (err) {
    if (!err) {
      console.log('subtask updated');
    }
  });
}<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name $exceptionHandler
 * @requires ng.$log
 *
 * @description
 * Any uncaught exception in angular expressions is delegated to this service.
 * The default implementation simply delegates to `$log.error` which logs it into
 * the browser console.
 *
 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
 *
 * ## Example:
 *
 * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
 * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
 * of `$log.error()`.
 *
 * ```js
 *   angular.
 *     module('exceptionOverwrite', []).
 *     factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
 *       return function myExceptionHandler(exception, cause) {
 *         logErrorsToBackend(exception, cause);
 *         $log.warn(exception, cause);
 *       };
 *     });
 * ```
 *
 *

 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
 * (unless executed during a digest).
 *
 * If you wish, you can manually delegate exceptions, e.g.
 * `try { ... } catch(e) { $exceptionHandler(e); }`
 *
 * @param {Error} exception Exception associated with the error.
 * @param {string=} cause Optional information about the context in which
 *       the error was thrown.
 *
 */
function $ExceptionHandlerProvider() {
  this.$get = ['$log', function($log) {
    return function(exception, cause) {
      $log.error.apply($log, arguments);
    };
  }];
}
<commit_msg>docs($exceptionHandler): add missing end bracket in example<commit_after>'use strict';

/**
 * @ngdoc service
 * @name $exceptionHandler
 * @requires ng.$log
 *
 * @description
 * Any uncaught exception in angular expressions is delegated to this service.
 * The default implementation simply delegates to `$log.error` which logs it into
 * the browser console.
 *
 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
 *
 * ## Example:
 *
 * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
 * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
 * of `$log.error()`.
 *
 * ```js
 *   angular.
 *     module('exceptionOverwrite', []).
 *     factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
 *       return function myExceptionHandler(exception, cause) {
 *         logErrorsToBackend(exception, cause);
 *         $log.warn(exception, cause);
 *       };
 *     }]);
 * ```
 *
 *

 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
 * (unless executed during a digest).
 *
 * If you wish, you can manually delegate exceptions, e.g.
 * `try { ... } catch(e) { $exceptionHandler(e); }`
 *
 * @param {Error} exception Exception associated with the error.
 * @param {string=} cause Optional information about the context in which
 *       the error was thrown.
 *
 */
function $ExceptionHandlerProvider() {
  this.$get = ['$log', function($log) {
    return function(exception, cause) {
      $log.error.apply($log, arguments);
    };
  }];
}
<|endoftext|>


<commit_before>var TiCarousel = require('com.obscure.ticarousel');

var win = Ti.UI.createWindow();

// --- carousel transform -----
var txopts = {
      arc: Math.PI / 2.0,
      radius: 220.0,
      tilt: 0.9,
      spacing: 1.0,
      yoffset: 20.0,
      zoffset: -400.0
   };

// -- carousel ---
var	iconList = [
		{ image: 'images/add-text.png', id: 'text' },
		{ image: 'images/add-photo.png', id: 'photo' },
		{ image: 'images/add-button.png', id: 'button' },
		{ image: 'images/add-link.png', id: 'link' },
		{ image: 'images/add-video.png', id: 'video' }
	];

var buttons = [];

for (var i=0; i<iconList.length; i++) {
	var icon = iconList[i];
	var button = Ti.UI.createImageView({
		image: icon.image,
		width: 60,
		height: 60
	});
	buttons.push(button);
}

var carousel = TiCarousel.createCarouselView({
    carouselType: TiCarousel.CAROUSEL_TYPE_WHEEL,
    views: buttons,
    height: 190,
    itemWidth: 60,
    numberOfVisibleItems: 5,
    wrap: false,
    transformOptions: txopts,
    bounceDistance: 10
});
carousel.addEventListener('select', function() {
	showMenu = !showMenu;

	carouselHolder.animate({
		opacity: showMenu ? 1 : 0,
		duration: 500
	});
});

var addBtn = Ti.UI.createImageView({
	image: 'images/add.png',
	bottom: 0,
	zIndex: 100
});
win.add(addBtn);

var showMenu = false;

var carouselHolder = Ti.UI.createView({
	height: 200,
	bottom: 0,
	opacity: showMenu ? 1 : 0
});
carouselHolder.add(carousel);
win.add(carouselHolder);
carousel.reloadData();

addBtn.addEventListener('click', function() {
	showMenu = !showMenu;

	carouselHolder.animate({
		opacity: showMenu ? 1 : 0,
		duration: 500
	});

	carousel.scrollToIndex(-5);
});

win.open();
<commit_msg>scroll to 2<commit_after>var TiCarousel = require('com.obscure.ticarousel');

var win = Ti.UI.createWindow();

// --- carousel transform -----
var txopts = {
      arc: Math.PI / 2.0,
      radius: 220.0,
      tilt: 0.9,
      spacing: 1.0,
      yoffset: 20.0,
      zoffset: -400.0
   };

// -- carousel ---
var	iconList = [
		{ image: 'images/add-text.png', id: 'text' },
		{ image: 'images/add-photo.png', id: 'photo' },
		{ image: 'images/add-button.png', id: 'button' },
		{ image: 'images/add-link.png', id: 'link' },
		{ image: 'images/add-video.png', id: 'video' }
	];

var buttons = [];

for (var i=0; i<iconList.length; i++) {
	var icon = iconList[i];
	var button = Ti.UI.createImageView({
		image: icon.image,
		width: 60,
		height: 60
	});
	buttons.push(button);
}

var carousel = TiCarousel.createCarouselView({
    carouselType: TiCarousel.CAROUSEL_TYPE_WHEEL,
    views: buttons,
    height: 190,
    itemWidth: 60,
    numberOfVisibleItems: 5,
    wrap: false,
    transformOptions: txopts,
    bounceDistance: 10
});
carousel.addEventListener('select', function() {
	showMenu = !showMenu;

	carouselHolder.animate({
		opacity: showMenu ? 1 : 0,
		duration: 500
	});
});

var addBtn = Ti.UI.createImageView({
	image: 'images/add.png',
	bottom: 0,
	zIndex: 100
});
win.add(addBtn);

var showMenu = false;

var carouselHolder = Ti.UI.createView({
	height: 200,
	bottom: 0,
	opacity: showMenu ? 1 : 0
});
carouselHolder.add(carousel);
win.add(carouselHolder);
carousel.reloadData();

addBtn.addEventListener('click', function() {
	showMenu = !showMenu;

	carouselHolder.animate({
		opacity: showMenu ? 1 : 0,
		duration: 500
	});

	carousel.scrollToIndex(2);
});

win.open();
<|endoftext|>


<commit_before>import assert from 'node:assert'
import { dirname, resolve } from 'node:path'
import { env } from 'node:process'
import { fileURLToPath } from 'node:url'
import { WebSocket } from 'ws'
import { joinUrl, setup, teardown } from '../_testHelpers/index.js'
import websocketSend from '../_testHelpers/websocketPromise.js'

const __dirname = dirname(fileURLToPath(import.meta.url))

describe('websocket authorizer tests', function desc() {
  beforeEach(async () =>
    setup({
      servicePath: resolve(__dirname),
    }),
  )

  afterEach(() => teardown())

  it('websocket authorization with valid request', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'isValid')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err, undefined)
    assert.equal(data, '{}')
  })

  it('websocket authorization without valid request', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'isNotValid')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err.message, 'Unexpected server response: 403')
    assert.equal(data, undefined)
  })

  it('websocket authorization without context', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'noContext')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err, undefined)
    assert.equal(data, '{}')
  })

  it('websocket authorization with authorizer crash', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'exception')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err.message, 'Unexpected server response: 500')
    assert.equal(data, undefined)
  })

  it('websocket authorization without credentials', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err.message, 'Unexpected server response: 401')
    assert.equal(data, undefined)
  })
})
<commit_msg>test: remove async<commit_after>import assert from 'node:assert'
import { dirname, resolve } from 'node:path'
import { env } from 'node:process'
import { fileURLToPath } from 'node:url'
import { WebSocket } from 'ws'
import { joinUrl, setup, teardown } from '../_testHelpers/index.js'
import websocketSend from '../_testHelpers/websocketPromise.js'

const __dirname = dirname(fileURLToPath(import.meta.url))

describe('websocket authorizer tests', function desc() {
  beforeEach(() =>
    setup({
      servicePath: resolve(__dirname),
    }),
  )

  afterEach(() => teardown())

  it('websocket authorization with valid request', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'isValid')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err, undefined)
    assert.equal(data, '{}')
  })

  it('websocket authorization without valid request', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'isNotValid')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err.message, 'Unexpected server response: 403')
    assert.equal(data, undefined)
  })

  it('websocket authorization without context', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'noContext')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err, undefined)
    assert.equal(data, '{}')
  })

  it('websocket authorization with authorizer crash', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'
    url.searchParams.append('credential', 'exception')

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err.message, 'Unexpected server response: 500')
    assert.equal(data, undefined)
  })

  it('websocket authorization without credentials', async () => {
    const url = new URL(joinUrl(env.TEST_BASE_URL, '/dev'))
    url.port = url.port ? '3001' : url.port
    url.protocol = 'ws'

    const ws = new WebSocket(url)
    const { code, data, err } = await websocketSend(ws, '{}')

    assert.equal(code, undefined)
    assert.equal(err.message, 'Unexpected server response: 401')
    assert.equal(data, undefined)
  })
})
<|endoftext|>


<commit_before>var m = mapbox.map('map');

function stationVoronoi() {
    var v = {}, stationData, stations, stationCoords, voronoi, city,
        stationAnimation;
    var svg = d3.select(document.body).append("svg").attr("id", "d3svg");

    // var cityGroup = svg.append("g").attr("id", "cityGroup");
    var voronoiGroup = svg.append("g").attr("id", "voronoiGroup");
    var stationsGroup = svg.append("g").attr("id", "stationsGroup");

    var fadeInTime = 500;

    var color = function(station) {
        var bikes = station.poles - station.available;
        if (bikes === 0) {
            return 0;
        } else if (bikes <=5) {
            return 1;
        } else if (station.available <= 5) {
            return 3;
        } else if (station.available === 0) {
            return 4;
        } else {
            return 2;  // middle state is normal.
        }
    };

    var stationDotSize = d3.scale.quantize()
        .domain([minZoom, maxZoom])
        .range([2, 3, 4]);

    v.parent = svg.node();

    // Project a lat/lon location onto the displayed map (point)
    v.project = function(location) {
        var point = v.map.locationPoint({lat: location[1], lon: location[0]});
        return [point.x, point.y];
    };

    // redraw the layer
    // called every time something changes
    v.draw = function() {
        console.log("Draw called!");

        // position the overlay
        svg.attr("width", $("#map").width())
           .attr("height", $("#map").height());

        var delays = [];

        voronoi = voronoiGroup.selectAll("path")
            .data(stationData);

        // fade in when added
        voronoi.enter().append("path")
            .attr('id', function(d, i) { return 'station' + stationData[i].id; })
            .attr("class", function(d, i) {
                return "station_cell q" + color(stationData[i]) + "-5";
            })
            .attr("opacity", 0)
          .transition().delay(function(d, i) {
                wait = stationAnimation(stationData[i].latitude);
                delays[i] = wait;
                return 600 + (fadeInTime-wait);
            }).duration(200)
            .attr("opacity", 0.5);

        // project the station cell polys onto the map
        voronoi
            .attr("d", function(d, i) {
                var poly = d3.geom.polygon(stationData[i].polygon);
                var projected = _.map(poly, v.project);
                return "M" + projected.join("L") + "Z";
            });

        // render the station dots
        // =============================================================
        stations = stationsGroup.selectAll("circle")
            .data(stationCoords);

        // Grow in when added
        stations.enter().append("circle")
            .attr("opacity", 0.0)
            .attr("r", 0)
          .transition().delay(150).duration(450)
            .attr("opacity", 0.15)
            .attr("r", 8 * stationDotSize(v.map.zoom()))
          .transition().delay(function(d, i) {
                return 600 + (fadeInTime - delays[i]);
            }).duration(200)
            .attr("r", stationDotSize(v.map.zoom()))
            .attr("opacity", 1);

        // Postion them
        stations
            // .attr("r", stationDotSize(v.map.zoom()))
            .attr("transform", function(d) { return "translate(" + v.project(d) + ")"; });
    };

    // supply the data
    // called once on load
    v.data = function(data) {
        console.log("data called!");
        stationData = data;
        stationCoords = _.map(stationData, function(s) {
            return [s.longitude, s.latitude];
        });

        stationAnimation = d3.scale.linear()
            .domain(d3.extent(stationCoords, function(coord) { return coord[1]; }))
            // .domain([0,1])
            .range([0, fadeInTime]);

        return v;
    };

    return v;
}

var telostats_tiles = {
    "tilejson": "2.0.0",
    "tiles": [TILESERVER_URL]
};
var minZoom = 13;
var maxZoom = 17;
m.addLayer(mapbox.layer().tilejson(telostats_tiles));
m.ui.zoomer.add();

var mapbounds = new MM.Extent(
    32.14920666588464,34.74252281494142,
    32.02678694143692,34.85478935546873);

m.setExtent(mapbounds);
m.setPanLimits(mapbounds);
m.setZoomRange(minZoom, maxZoom);

d3.json('/api/v1/station/', function(stations) {
    var stationMap = stationVoronoi().data(stations.objects);
    m.addLayer(stationMap);
    console.log("added d3 layer!");
    $('#map').on('click', function(event) {
        var p = m.pointLocation({x:event.pageX, y:event.pageY});
        console.log([p.lon, p.lat]);
    });
});<commit_msg>Removing unneeded code<commit_after>var m = mapbox.map('map');

function stationVoronoi() {
    var v = {}, stationData, stations, stationCoords, voronoi, city,
        stationAnimation;
    var svg = d3.select(document.body).append("svg").attr("id", "d3svg");

    var voronoiGroup = svg.append("g").attr("id", "voronoiGroup");
    var stationsGroup = svg.append("g").attr("id", "stationsGroup");

    var fadeInTime = 500;

    var color = function(station) {
        var bikes = station.poles - station.available;
        if (bikes === 0) {
            return 0;
        } else if (bikes <=5) {
            return 1;
        } else if (station.available <= 5) {
            return 3;
        } else if (station.available === 0) {
            return 4;
        } else {
            return 2;  // middle state is normal.
        }
    };

    var stationDotSize = d3.scale.quantize()
        .domain([minZoom, maxZoom])
        .range([2, 3, 4]);

    v.parent = svg.node();

    // Project a lat/lon location onto the displayed map (point)
    v.project = function(location) {
        var point = v.map.locationPoint({lat: location[1], lon: location[0]});
        return [point.x, point.y];
    };

    // redraw the layer
    // called every time something changes
    v.draw = function() {
        console.log("Draw called!");

        // position the overlay
        svg.attr("width", $("#map").width())
           .attr("height", $("#map").height());

        var delays = [];

        voronoi = voronoiGroup.selectAll("path")
            .data(stationData);

        // fade in when added
        voronoi.enter().append("path")
            .attr('id', function(d, i) { return 'station' + stationData[i].id; })
            .attr("class", function(d, i) {
                return "station_cell q" + color(stationData[i]) + "-5";
            })
            .attr("opacity", 0)
          .transition().delay(function(d, i) {
                wait = stationAnimation(stationData[i].latitude);
                delays[i] = wait;
                return 600 + (fadeInTime-wait);
            }).duration(200)
            .attr("opacity", 0.5);

        // project the station cell polys onto the map
        voronoi
            .attr("d", function(d, i) {
                var poly = d3.geom.polygon(stationData[i].polygon);
                var projected = _.map(poly, v.project);
                return "M" + projected.join("L") + "Z";
            });

        // render the station dots
        // =============================================================
        stations = stationsGroup.selectAll("circle")
            .data(stationCoords);

        // Grow in when added
        stations.enter().append("circle")
            .attr("opacity", 0.0)
            .attr("r", 0)
          .transition().delay(150).duration(450)
            .attr("opacity", 0.15)
            .attr("r", 8 * stationDotSize(v.map.zoom()))
          .transition().delay(function(d, i) {
                return 600 + (fadeInTime - delays[i]);
            }).duration(200)
            .attr("r", stationDotSize(v.map.zoom()))
            .attr("opacity", 1);

        // Postion them
        stations
            // .attr("r", stationDotSize(v.map.zoom()))
            .attr("transform", function(d) { return "translate(" + v.project(d) + ")"; });
    };

    // supply the data
    // called once on load
    v.data = function(data) {
        console.log("data called!");
        stationData = data;
        stationCoords = _.map(stationData, function(s) {
            return [s.longitude, s.latitude];
        });

        stationAnimation = d3.scale.linear()
            .domain(d3.extent(stationCoords, function(coord) { return coord[1]; }))
            // .domain([0,1])
            .range([0, fadeInTime]);

        return v;
    };

    return v;
}

var telostats_tiles = {
    "tilejson": "2.0.0",
    "tiles": [TILESERVER_URL]
};
var minZoom = 13;
var maxZoom = 17;
m.addLayer(mapbox.layer().tilejson(telostats_tiles));
m.ui.zoomer.add();

var mapbounds = new MM.Extent(
    32.14920666588464,34.74252281494142,
    32.02678694143692,34.85478935546873);

m.setExtent(mapbounds);
m.setPanLimits(mapbounds);
m.setZoomRange(minZoom, maxZoom);

d3.json('/api/v1/station/', function(stations) {
    var stationMap = stationVoronoi().data(stations.objects);
    m.addLayer(stationMap);
    console.log("added d3 layer!");
    $('#map').on('click', function(event) {
        var p = m.pointLocation({x:event.pageX, y:event.pageY});
        console.log([p.lon, p.lat]);
    });
});<|endoftext|>


<commit_before>/*
Copyright 2017 Vector Creations Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Analytics from '../Analytics';
import { createPromiseActionCreator } from './actionCreators';
import TagOrderStore from '../stores/TagOrderStore';

const TagOrderActions = {};

TagOrderActions.commitTagOrdering = createPromiseActionCreator(
    'TagOrderActions.commitTagOrdering',
    (matrixClient) => {
        Analytics.trackEvent('TagOrderActions', 'commitTagOrdering');
        return matrixClient.setAccountData('im.vector.web.tag_ordering', {
            tags: TagOrderStore.getOrderedTags(),
        });
    },
);

export default TagOrderActions;
<commit_msg>Only commit a non-falsy tags list<commit_after>/*
Copyright 2017 Vector Creations Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Analytics from '../Analytics';
import { createPromiseActionCreator } from './actionCreators';
import TagOrderStore from '../stores/TagOrderStore';

const TagOrderActions = {};

TagOrderActions.commitTagOrdering = createPromiseActionCreator(
    'TagOrderActions.commitTagOrdering',
    (matrixClient) => {
        // Only commit tags if the state is ready, i.e. not null
        const tags = TagOrderStore.getOrderedTags();
        if (!tags) {
            return;
        }

        Analytics.trackEvent('TagOrderActions', 'commitTagOrdering');
        return matrixClient.setAccountData('im.vector.web.tag_ordering', {tags});
    },
);

export default TagOrderActions;
<|endoftext|>


<commit_before>module.exports = {
    metadata: {
        plugin: "lightSensor",
        label: "Light Sensor",
        role: "sensor",
        family: "light",
        deviceTypes: ["microcontroller/microcontroller"],
        unit: "LUX",
        configuration: [
            {
                label: "Controller",
                id: "controller",
                type: {
                    family: "enumeration",
                    values: [{
                        label: "BH1750  (I2C)",
                        id: "BH1750"
                    }, {
                        label: "TSL2561 (I2C)",
                        id: "TSL2561"
                    }]
                }
            }]
    },
    create: function () {
        return new LightSensor();
    }
};

/**
 *
 */
function LightSensor() {
    /**
     *
     */
    LightSensor.prototype.start = function () {
        try {
            if (!this.isSimulated()) {
                var five = require("johnny-five");

                this.lightSensor = new five.Light({
                    freq: this.configuration.rate,
                    controller: this.configuration.controller,
                });

                var self = this;

                this.lightSensor.on("change", function (event) {

                });

                this.lightSensor.on("data", function (data) {

                });
            }
        } catch (x) {
            this.publishMessage("Cannot initialize " + this.device.id + "/"
                + this.id + ":" + x);
        }
    };
};<commit_msg>implement light sensor<commit_after>module.exports = {
    metadata: {
        plugin: "lightSensor",
        label: "Light Sensor",
        role: "sensor",
        family: "light",
        deviceTypes: ["microcontroller/microcontroller"],
        unit: "LUX",
        state: [{
            id: "luminance",
            label: "Luminance",
            type: {
                id: "number"
            }
        }],
        configuration: [{
            label: "Controller",
            id: "controller",
            type: {
                family: "enumeration",
                values: [{
                    label: "BH1750  (I2C)",
                    id: "BH1750"
                }, {
                    label: "TSL2561 (I2C)",
                    id: "TSL2561"
                }]
            }
        }, {
            label: "Threshold",
            id: "threshold",
            type: {
                id: "number"
            },
            unit: "LUX",
            defaultValue: 10,
        }, {
            label: "Average Time",
            id: "averageTime",
            type: {
                id: "number"
            },
            unit: "sec",
            defaultValue: 30,
        }]
    },
    create: function () {
        return new LightSensor();
    }
};

/**
 *
 */
function LightSensor() {
    /**
     *
     */
    LightSensor.prototype.start = function () {
        try {
            if (!this.isSimulated()) {

                this.logLevel = 'debug';

                var five = require("johnny-five");

                this.state = {
                    luminance: 0
                };

                this.lightSensor = new five.Light({
                    controller: this.configuration.controller,
                    freq: 500,
                });

                var value = [];
                var self = this;

                this.lightSensor.on("data", function (data) {

                    value.push(data.lux);

                    if (value.length > self.configuration.averageTime * 2) {
                        value.shift();
                        let sum = value.reduce(function (a, b) {
                            return (a + b)
                        });

                        let average = (sum / value.length).toFixed(2);

                        if ((Math.abs(average - self.state.luminance)) >= self.configuration.threshold) {
                            self.state.luminance = average;
                            self.logDebug("\x1b[36mLuminance: \x1b[0m" + self.state.luminance);
                            self.publishStateChange();
                        }
                    }
                });
            }
        } catch (x) {
            this.publishMessage("Cannot initialize " + this.device.id + "/"
                + this.id + ":" + x);
        }
    };
    /**
     *
     */
    LightSensor.prototype.getState = function () {
        return this.state;
    };
}<|endoftext|>


<commit_before>var through = require('through2'),
  path = require('path'),
  gutil = require('gulp-util'),
  File = require('vinyl'),
  minimist = require('minimist'),

  kssSplitter = require('../kss-splitter');

module.exports = function(options) {
  var throughOpts = {
      objectMode: true,
      allowHalfOpen: false
    };

  function bufferFileContents(file, enc, done) {
    console.log('I am file');
    this.push(file);
    done();
  };

  // Parameters
  var args = minimist(process.argv.slice(2)),
    params = {
      name: args.name || args.n,
      order: args.order || args.o
    };

  var parsers = options && options.parsers || 'undefined';

  // Validate params

  if (!params.name) {
    gutil.beep();
    gutil.log(gutil.colors.red("Define name with --name=my-name"));
    return;
  }

  if (!params.order) {
    gutil.beep();
    gutil.log(gutil.colors.red("Define name with --order=1.2.3"));
    return;
  }

  params.order = params.order.toString();

  var sectionRegExp = /(Styleguide )([0-9]+(\.[0-9]+)*)/;

  var allFiles = [];

  var nearestSibling = null;

  function addSection(file) {
    changeNumber(file, params.order)
  }

  function isLess(left, right) {
    left = left.split(".");
    right = right.split(".");

    var l = false;

    for (var i = 0; i < Math.max(left.length, right.length); i++) {
      if (parseInt(left[i]) < parseInt(right[i])) {
        l = true;
        break;
      }
      if (parseInt(left[i]) > parseInt(right[i])) {
        l = false;
        break;
      }
    }

    return l;
  }

  function ifBelongsToParent(parentSection, section) {
    var belongs = true;
    parentSection = parentSection && parentSection.split(".");
    section = section.split(".");

    parentSection && parentSection.forEach(function(val, n) {
      if (val !== section[n]) {
        belongs = false;
      }
    });
    return belongs;
  }

  function increaseSection(section, diff) {
    section = section.split(".");
    var last = section.pop();
    section.push(parseInt(last) + diff);
    return section.join(".");
  }

  function changeNumber(blocks, order) {
    return blocks.map(function(block){
      if (!block.kss) {
        return block;
      }
      var match = block.kss.match(sectionRegExp);
      var currentNumber = match[2];

      if (isLess(currentNumber, order)) {
        return block;
      }

      var parentSection = order.split(".");
      parentSection.pop();
      parentSection = parentSection.join(".");

      if (!ifBelongsToParent(parentSection, currentNumber)) {
        return block;
      }

      if (parentSection === currentNumber) {
        return block;
      }

      var newVal = increaseSection(currentNumber, 1);

      block.kss = block.kss.replace(sectionRegExp, "$1" + newVal);

      return block;
    });
  }

  function bufferFileContents(file, enc, done) {

    this.push(file);

    var contents = file.contents.toString(),
      syntax = path.extname(file.path).substring(1),
      parser = parsers  ? parsers[syntax] : 'undefined',
      blocks = kssSplitter.getBlocks(contents, syntax, parser);

    blocks = changeNumber(blocks, params.order);

    // check if a block is nearest sibling;
    blocks.forEach(function(block, index) {
      if (!block.kss) {
        return;
      }
      var match = block.kss.match(sectionRegExp);
      var currentNumber = match[2];
      if (!nearestSibling) {
        nearestSibling = {
          number: currentNumber,
          file: file,
          blockIndex: index
        }
        return;
      }

      // to become a nearestSibling currentNumber should be
      // less than newNumber but more than actual nearestSibling
      if (isLess(currentNumber, params.order) && !isLess(currentNumber, nearestSibling.number)) {
        nearestSibling = {
          number: currentNumber,
          file: file,
          blockIndex: index
        }
      }
    });

    allFiles.push({
      file: file,
      blocks: blocks
    })
    done();
  }

  return through(throughOpts, bufferFileContents, function(cb) {

    // write files back
    var stream = this;

    allFiles.forEach(function(fileSource, k) {
      if(fileSource.file.path === nearestSibling.file.path) {
        fileSource.blocks.splice(nearestSibling.blockIndex + 1, 0, {
          kss: ['/*',
            params.name,
            '',
            'Styleguide ' + params.order,
            '*/'].join('\n'),
          code: ''
        });
      };
      allFiles[k] = fileSource;
    });

    allFiles.forEach(function(fileSource){

      var content = fileSource.blocks.map(function(block){
        return block.kss + block.code;
      }).join('');

      stream.push(new File({
        path: fileSource.file.relative,
        contents: new Buffer(content)
      }));
    });

    cb();
  });

}
<commit_msg>Modify only the files which need changes<commit_after>var through = require('through2'),
  path = require('path'),
  gutil = require('gulp-util'),
  File = require('vinyl'),
  minimist = require('minimist'),

  kssSplitter = require('../kss-splitter');

module.exports = function(options) {
  var throughOpts = {
      objectMode: true,
      allowHalfOpen: false
    };

  function bufferFileContents(file, enc, done) {
    console.log('I am file');
    this.push(file);
    done();
  };

  // Parameters
  var args = minimist(process.argv.slice(2)),
    params = {
      name: args.name || args.n,
      order: args.order || args.o
    };

  var parsers = options && options.parsers || 'undefined';

  // Validate params

  if (!params.name) {
    gutil.beep();
    gutil.log(gutil.colors.red("Define name with --name=my-name"));
    return;
  }

  if (!params.order) {
    gutil.beep();
    gutil.log(gutil.colors.red("Define name with --order=1.2.3"));
    return;
  }

  params.order = params.order.toString();

  var sectionRegExp = /(Styleguide )([0-9]+(\.[0-9]+)*)/;

  var allFiles = [];

  var nearestSibling = null;

  function addSection(file) {
    changeNumber(file, params.order)
  }

  function isLess(left, right) {
    left = left.split(".");
    right = right.split(".");

    var l = false;

    for (var i = 0; i < Math.max(left.length, right.length); i++) {
      if (parseInt(left[i]) < parseInt(right[i])) {
        l = true;
        break;
      }
      if (parseInt(left[i]) > parseInt(right[i])) {
        l = false;
        break;
      }
    }

    return l;
  }

  function ifBelongsToParent(parentSection, section) {
    var belongs = true;
    parentSection = parentSection && parentSection.split(".");
    section = section.split(".");

    parentSection && parentSection.forEach(function(val, n) {
      if (val !== section[n]) {
        belongs = false;
      }
    });
    return belongs;
  }

  function increaseSection(section, diff) {
    section = section.split(".");
    var last = section.pop();
    section.push(parseInt(last) + diff);
    return section.join(".");
  }

  function changeNumber(blocks, order, fileIndex) {
    return blocks.map(function(block){
      if (!block.kss) {
        return block;
      }
      var match = block.kss.match(sectionRegExp);
      var currentNumber = match[2];

      if (isLess(currentNumber, order)) {
        return block;
      }

      var parentSection = order.split(".");
      parentSection.pop();
      parentSection = parentSection.join(".");

      if (!ifBelongsToParent(parentSection, currentNumber)) {
        return block;
      }

      if (parentSection === currentNumber) {
        return block;
      }

      var newVal = increaseSection(currentNumber, 1);

      block.kss = block.kss.replace(sectionRegExp, "$1" + newVal);
      allFiles[fileIndex].modified = true;

      return block;
    });
  }

  function bufferFileContents(file, enc, done) {

    this.push(file);

    var contents = file.contents.toString(),
      syntax = path.extname(file.path).substring(1),
      parser = parsers  ? parsers[syntax] : 'undefined',
      blocks = kssSplitter.getBlocks(contents, syntax, parser);

    // check if a block is nearest sibling;
    blocks.forEach(function(block, index) {
      if (!block.kss) {
        return;
      }
      var match = block.kss.match(sectionRegExp);
      var currentNumber = match[2];
      if (!nearestSibling) {
        nearestSibling = {
          number: currentNumber,
          file: file,
          blockIndex: index
        }
        return;
      }

      // to become a nearestSibling currentNumber should be
      // less than newNumber but more than actual nearestSibling
      if (isLess(currentNumber, params.order) && !isLess(currentNumber, nearestSibling.number)) {
        nearestSibling = {
          number: currentNumber,
          file: file,
          blockIndex: index
        }
      }
    });

    allFiles.push({
      file: file,
      blocks: blocks
    })
    done();
  }

  return through(throughOpts, bufferFileContents, function(cb) {

    // increment numbers
    allFiles.forEach(function(fileSource, k) {
      var blocks = changeNumber(fileSource.blocks, params.order, k);
      fileSource.blocks = blocks;
      allFiles[k] = fileSource;
    });

    // add new section
    allFiles.forEach(function(fileSource, k) {
      if(fileSource.file.path === nearestSibling.file.path) {
        fileSource.blocks.splice(nearestSibling.blockIndex + 1, 0, {
          kss: ['/*',
            params.name,
            '',
            'Styleguide ' + params.order,
            '*/'].join('\n'),
          code: ''
        });
        fileSource.modified = true;
        allFiles[k] = fileSource;
      };
    });

    // write files back
    var stream = this;

    allFiles.forEach(function(fileSource){

      var content = fileSource.modified ? fileSource.blocks.map(function(block){
        return block.kss + block.code;
      }).join('') : fileSource.file.contents;

      stream.push(new File({
        path: fileSource.file.relative,
        contents: new Buffer(content)
      }));
    });

    cb();
  });

}
<|endoftext|>