<commit_before>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function(scope) {

  // imports

  var extend = scope.extend;
  var apis = scope.api.declaration;
  var queue = scope.queue;
  var whenPolymerReady = scope.whenPolymerReady;

  // imperative implementation: Polymer()

  // specify an 'own' prototype for tag `name`
  function element(name, prototype) {
    //console.log('registering prototype [' + name + ']');
    if (prototypesByName[name]) {
      throw 'Already registered prototype for element ' + name;
    }
    // cache the prototype
    prototypesByName[name] = prototype || {};
    // notify the registrar waiting for 'name', if any
    notifyPrototype(name);
  }

  // declarative implementation: <polymer-element>

  var prototype = extend(Object.create(HTMLElement.prototype), {
    createdCallback: function() {
      if (this.getAttribute('name')) {
        this.init();
      }
    },
    init: function() {
      // fetch the element name
      this.name = this.getAttribute('name');
      //console.log('createdCallback', this.name);
      // fetch our extendee name
      this.extends = this.getAttribute('extends');
      this.loadResources();
      this.registerWhenReady();
    },
    registerWhenReady: function() {
      if (this.registered) {
        return;
      }
      // if we have no prototype, wait
      if (this.waitingForPrototype(this.name)) {
        return;
      }
      if (this.waitingForQueue()) {
        return;
      }
      if (this.waitingForResources()) {
        return;
      }
      this.readyToRegister();
    },
    readyToRegister: function() {
      queue.register(this);
    },
    _register: function() {
      //console.log('registering', this.name);
      //console.group('registering', this.name);
      // warn if extending from a custom element not registered via Polymer
      if (isCustomTag(this.extends) && !isRegistered(this.extends)) {
        console.warn('%s is attempting to extend %s, an unregistered element ' +
            'or one that was not registered with Polymer.', this.name,
            this.extends);
      }

      this.register(this.name, this.extends);
      this.registered = true;
      registerRegistered(this.name);
      //console.groupEnd();
    },
    waitingForPrototype: function(name) {
      if (!getRegisteredPrototype(name)) {
        // then wait for a prototype
        waitPrototype[name] = this;
        // if explicitly marked as 'noscript'
        if (this.hasAttribute('noscript') && !this.noscript) {
          this.noscript = true;
          // TODO(sorvell): CustomElements polyfill awareness:
          // noscript elements should upgrade in logical order
          // script injection ensures this under native custom elements;
          // under imports + ce polyfills, scripts run before upgrades.
          // dependencies should be ready at upgrade time so register
          // prototype at this time.
          if (window.CustomElements && !CustomElements.useNative) {
            element(name);
          } else {
            var script = document.createElement('script');
            script.textContent = 'Polymer(\'' + name + '\');';
            this.appendChild(script);
          }
        }
        return true;
      }
    },
    waitingForResources: function() {
      return this._needsResources;
    },
    // NOTE: Elements must be queued in proper order for inheritance/composition
    // dependency resolution. Previously this was enforced for inheritance
    // and by rule for composition. It's now entirely by rule.
    waitingForQueue: function() {
      return queue.wait(this);
    },
    loadResources: function() {
      this._needsResources = true;
      this.loadStyles(function() {
        this._needsResources = false;
        this.registerWhenReady();
      }.bind(this));
    }
  });

  // semi-pluggable APIs
  // TODO(sjmiles): should be fully pluggable (aka decoupled, currently
  // the various plugins are allowed to depend on each other directly)
  Object.keys(apis).forEach(function(n) {
    extend(prototype, apis[n]);
  });

  // utility and bookkeeping

  // maps tag names to prototypes
  var prototypesByName = {};

  function getRegisteredPrototype(name) {
    return prototypesByName[name];
  }

  // elements waiting for prototype, by name
  var waitPrototype = {};

  function notifyPrototype(name) {
    if (waitPrototype[name]) {
      waitPrototype[name].registerWhenReady();
      delete waitPrototype[name];
    }
  }

  // track document.register'ed tag names
  var registered = {};

  function registerRegistered(name) {
    registered[name] = true;
  }

  function isRegistered(name) {
    return registered[name];
  }

  function isCustomTag(name) {
    return (name && name.indexOf('-') >= 0);
  }

  // exports
  scope.getRegisteredPrototype = getRegisteredPrototype;

  // namespace shenanigans so we can expose our scope on the registration
  // function

  // TODO(sjmiles): find a way to do this that is less terrible
  // copy window.Polymer properties onto `element()`
  extend(element, scope);
  // make window.Polymer reference `element()`
  window.Polymer = element;

  // Under the HTMLImports polyfill, scripts in the main document
  // do not block on imports; we want to allow calls to Polymer in the main
  // document. We do so via coordination with Platform:
  var declarations = Platform.deliverDeclarations();
  if (declarations) {
    for (var i=0, l=declarations.length, d; (i<l) && (d=declarations[i]); i++) {
      element.apply(null, d);
    }
  }

  whenPolymerReady(function() {
    document.dispatchEvent(
      new CustomEvent('polymer-ready', {bubbles: true})
    );
  });

  // register polymer-element with document
  document.registerElement('polymer-element', {prototype: prototype});
})(Polymer);
<commit_msg>At polymer-ready time, removed unresolved attribute on body.<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function(scope) {

  // imports

  var extend = scope.extend;
  var apis = scope.api.declaration;
  var queue = scope.queue;
  var whenPolymerReady = scope.whenPolymerReady;

  // imperative implementation: Polymer()

  // specify an 'own' prototype for tag `name`
  function element(name, prototype) {
    //console.log('registering prototype [' + name + ']');
    if (prototypesByName[name]) {
      throw 'Already registered prototype for element ' + name;
    }
    // cache the prototype
    prototypesByName[name] = prototype || {};
    // notify the registrar waiting for 'name', if any
    notifyPrototype(name);
  }

  // declarative implementation: <polymer-element>

  var prototype = extend(Object.create(HTMLElement.prototype), {
    createdCallback: function() {
      if (this.getAttribute('name')) {
        this.init();
      }
    },
    init: function() {
      // fetch the element name
      this.name = this.getAttribute('name');
      //console.log('createdCallback', this.name);
      // fetch our extendee name
      this.extends = this.getAttribute('extends');
      this.loadResources();
      this.registerWhenReady();
    },
    registerWhenReady: function() {
      if (this.registered) {
        return;
      }
      // if we have no prototype, wait
      if (this.waitingForPrototype(this.name)) {
        return;
      }
      if (this.waitingForQueue()) {
        return;
      }
      if (this.waitingForResources()) {
        return;
      }
      this.readyToRegister();
    },
    readyToRegister: function() {
      queue.register(this);
    },
    _register: function() {
      //console.log('registering', this.name);
      //console.group('registering', this.name);
      // warn if extending from a custom element not registered via Polymer
      if (isCustomTag(this.extends) && !isRegistered(this.extends)) {
        console.warn('%s is attempting to extend %s, an unregistered element ' +
            'or one that was not registered with Polymer.', this.name,
            this.extends);
      }

      this.register(this.name, this.extends);
      this.registered = true;
      registerRegistered(this.name);
      //console.groupEnd();
    },
    waitingForPrototype: function(name) {
      if (!getRegisteredPrototype(name)) {
        // then wait for a prototype
        waitPrototype[name] = this;
        // if explicitly marked as 'noscript'
        if (this.hasAttribute('noscript') && !this.noscript) {
          this.noscript = true;
          // TODO(sorvell): CustomElements polyfill awareness:
          // noscript elements should upgrade in logical order
          // script injection ensures this under native custom elements;
          // under imports + ce polyfills, scripts run before upgrades.
          // dependencies should be ready at upgrade time so register
          // prototype at this time.
          if (window.CustomElements && !CustomElements.useNative) {
            element(name);
          } else {
            var script = document.createElement('script');
            script.textContent = 'Polymer(\'' + name + '\');';
            this.appendChild(script);
          }
        }
        return true;
      }
    },
    waitingForResources: function() {
      return this._needsResources;
    },
    // NOTE: Elements must be queued in proper order for inheritance/composition
    // dependency resolution. Previously this was enforced for inheritance
    // and by rule for composition. It's now entirely by rule.
    waitingForQueue: function() {
      return queue.wait(this);
    },
    loadResources: function() {
      this._needsResources = true;
      this.loadStyles(function() {
        this._needsResources = false;
        this.registerWhenReady();
      }.bind(this));
    }
  });

  // semi-pluggable APIs
  // TODO(sjmiles): should be fully pluggable (aka decoupled, currently
  // the various plugins are allowed to depend on each other directly)
  Object.keys(apis).forEach(function(n) {
    extend(prototype, apis[n]);
  });

  // utility and bookkeeping

  // maps tag names to prototypes
  var prototypesByName = {};

  function getRegisteredPrototype(name) {
    return prototypesByName[name];
  }

  // elements waiting for prototype, by name
  var waitPrototype = {};

  function notifyPrototype(name) {
    if (waitPrototype[name]) {
      waitPrototype[name].registerWhenReady();
      delete waitPrototype[name];
    }
  }

  // track document.register'ed tag names
  var registered = {};

  function registerRegistered(name) {
    registered[name] = true;
  }

  function isRegistered(name) {
    return registered[name];
  }

  function isCustomTag(name) {
    return (name && name.indexOf('-') >= 0);
  }

  // exports
  scope.getRegisteredPrototype = getRegisteredPrototype;

  // namespace shenanigans so we can expose our scope on the registration
  // function

  // TODO(sjmiles): find a way to do this that is less terrible
  // copy window.Polymer properties onto `element()`
  extend(element, scope);
  // make window.Polymer reference `element()`
  window.Polymer = element;

  // Under the HTMLImports polyfill, scripts in the main document
  // do not block on imports; we want to allow calls to Polymer in the main
  // document. We do so via coordination with Platform:
  var declarations = Platform.deliverDeclarations();
  if (declarations) {
    for (var i=0, l=declarations.length, d; (i<l) && (d=declarations[i]); i++) {
      element.apply(null, d);
    }
  }

  whenPolymerReady(function() {
    document.body.removeAttribute('unresolved');
    document.dispatchEvent(
      new CustomEvent('polymer-ready', {bubbles: true})
    );
  });

  // register polymer-element with document
  document.registerElement('polymer-element', {prototype: prototype});
})(Polymer);
<|endoftext|>


<commit_before>/*
 * jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */

(function() {

	var fieldSelection = {

		getSelection: function() {

			var e = this.jquery ? this[0] : this;

			return (

				/* mozilla / dom 3.0 */
				('selectionStart' in e && function() {
					var l = e.selectionEnd - e.selectionStart;
					return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
				}) ||

				/* exploder */
				(document.selection && function() {

					e.focus();

					var r = document.selection.createRange();
					if (r == null) {
						return { start: 0, end: e.value.length, length: 0 }
					}

					var re = e.createTextRange();
					var rc = re.duplicate();
					re.moveToBookmark(r.getBookmark());
					rc.setEndPoint('EndToStart', re);

					return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
				}) ||

				/* browser not supported */
				function() {
					return { start: 0, end: e.value.length, length: 0 };
				}

			)();

		},

		replaceSelection: function() {

			var e = this.jquery ? this[0] : this;
			var text = arguments[0] || '';

			return (

				/* mozilla / dom 3.0 */
				('selectionStart' in e && function() {
					e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
					return this;
				}) ||

				/* exploder */
				(document.selection && function() {
					e.focus();
					document.selection.createRange().text = text;
					return this;
				}) ||

				/* browser not supported */
				function() {
					e.value += text;
					return this;
				}

			)();

		}

	};

	jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();<commit_msg>Don't need this plugin anymore<commit_after><|endoftext|>


<commit_before>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // angular testing umd bundles
      '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
      '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
      '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
      '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
      '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
      '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
      '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
      '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: 'index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);
<commit_msg>chore: make systemjs config more consistent<commit_after>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // angular testing umd bundles
      '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
      '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
      '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
      '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
      '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
      '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
      '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
      '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);
<|endoftext|>


<commit_before>odoo.define("website.tour.banner", function (require) {
    "use strict";

    var core = require("web.core");
    var tour = require("web_tour.tour");
    var base = require("web_editor.base");

    var _t = core._t;

    base.ready().done(function () {
        tour.register("banner", {
            url: "/",
        }, [{
            trigger: "a[data-action=edit]",
            content: _t("Every page of your website can be modified through the Edit button."),
            position: "bottom",
        }, {
            trigger: "#snippet_structure .oe_snippet:eq(1) .oe_snippet_thumbnail",
            content: _t("Drag the Cover block and drop it in your page."),
            position: "bottom",
            run: "drag_and_drop",
        }, {
            trigger: "#wrapwrap .s_text_block_image_fw h2",
            content: _t("Click in the title text and start editing it."),
            position: "left",
            width: 150,
            run: "text",
        }, {
            trigger: ".oe_overlay_options .oe_options",
            extra_trigger: "#wrapwrap .s_text_block_image_fw h2:not(:containsExact(\"Headline\"))",
            content: _t("Customize any block through this menu. Try to change the background of the banner."),
            position: "bottom",
        }, {
            trigger: "#snippet_structure .oe_snippet:eq(3) .oe_snippet_thumbnail",
            content: _t("Drag another block in your page, below the cover."),
            position: "bottom",
            run: "drag_and_drop",
        }, {
            trigger: "button[data-action=save]",
            extra_trigger: ".oe_overlay_options .oe_options",
            content: _t("Publish your page by clicking on the Save button."),
            position: "bottom",
        }, {
            trigger: "a[data-action=show-mobile-preview]",
            content: _t("Well done, you created your homepage.
Let's check how your homepage looks like on mobile devices."),
            position: "bottom",
        }, {
            trigger: ".modal-dialog:has(#mobile-viewport) button[data-dismiss=modal]",
            content: _t("Scroll to check rendering and then close the mobile preview."),
            position: "right",
        }, {
            trigger: "#oe_main_menu_navbar a[data-action=new_page]",
            content: _t("
That's it. Your homepage is live.

Continue adding more pages to your site or edit this page to make it even more awesome.
"),
            position: "bottom",
        }]);
    });
});
<commit_msg>[IMP] website: tout wording, small improvements<commit_after>odoo.define("website.tour.banner", function (require) {
    "use strict";

    var core = require("web.core");
    var tour = require("web_tour.tour");
    var base = require("web_editor.base");

    var _t = core._t;

    base.ready().done(function () {
        tour.register("banner", {
            url: "/",
        }, [{
            trigger: "a[data-action=edit]",
            content: _t("Every page of your website can be modified through the Edit button."),
            position: "bottom",
        }, {
            trigger: "#snippet_structure .oe_snippet:eq(1) .oe_snippet_thumbnail",
            content: _t("Drag the Cover block and drop it in your page."),
            position: "bottom",
            run: "drag_and_drop",
        }, {
            trigger: "#wrapwrap .s_text_block_image_fw h2",
            content: _t("Click in the title text and start editing it."),
            position: "left",
            width: 150,
            run: "text",
        }, {
            trigger: ".oe_overlay_options .oe_options",
            extra_trigger: "#wrapwrap .s_text_block_image_fw h2:not(:containsExact(\"Headline\"))",
            content: _t("Customize any block through this menu. Try to change the background of the banner."),
            position: "bottom",
        }, {
            trigger: "#snippet_structure .oe_snippet:eq(3) .oe_snippet_thumbnail",
            content: _t("Drag another block in your page, below the cover."),
            position: "bottom",
            run: "drag_and_drop",
        }, {
            trigger: "button[data-action=save]",
            extra_trigger: ".oe_overlay_options .oe_options",
            content: _t("Publish your page by clicking on the Save button."),
            position: "bottom",
        }, {
            trigger: "a[data-action=show-mobile-preview]",
            content: _t("Good Job! You created your first page. Let's check how this page looks like on mobile devices."),
            position: "bottom",
        }, {
            trigger: ".modal-dialog:has(#mobile-viewport) button[data-dismiss=modal]",
            content: _t("After having checked how it looks on mobile, close the preview."),
            position: "right",
        }, {
            trigger: "#oe_main_menu_navbar a[data-action=new_page]",
            content: _t("
That's it. Your homepage is live.

Continue adding more pages to your site or edit this page to make it even more awesome.
"),
            position: "bottom",
        }]);
    });
});
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var childProcess = require('child_process');

var pythonExecutable = process.env.PYTHON;

module.exports = function(cb) {
  verifyNode(function(error, nodeSuccessMessage) {
    if (error) {
      cb(error);
      return;
    }

    verifyPython27(function(error, pythonSuccessMessage) {
      cb(error, nodeSuccessMessage + "\n" + pythonSuccessMessage);
    });
  });

};

function verifyNode(cb) {
  var nodeVersion = process.versions.node;
  var versionArray = nodeVersion.split('.');
  var nodeMajorVersion = +versionArray[0];
  var nodeMinorVersion = +versionArray[1];
  if (nodeMajorVersion === 0 && nodeMinorVersion < 10) {
    error = "node v0.10 is required to build Atom.";
    cb(error);
  }
  else {
    cb(null, "Node: v" + nodeVersion);
  }
}

function verifyPython27(cb) {
  if (process.platform !== 'win32') {
    cb(null, "Python: <not verified>");
  }
  else {
    if (!pythonExecutable) {
      var systemDrive = process.env.SystemDrive || 'C:\\';
      pythonExecutable = path.join(systemDrive, 'Python27', 'python.exe');

      if (!fs.existsSync(pythonExecutable)) {
        pythonExecutable = 'python';
      }
    }

    checkPythonVersion(pythonExecutable, cb);
  }
}

function checkPythonVersion (python, cb) {
  var pythonHelpMessage = "Set the PYTHON env var to '/path/to/Python27/python.exe' if your python is installed in a non-default location.";

  childProcess.execFile(python, ['-c', 'import platform; print(platform.python_version());'], { env: process.env }, function (err, stdout) {
    if (err) {
      error = "Python 2.7 is required to build Atom. An error (" + err + ") occured when checking the version of '" + python + "'. ";
      error += pythonHelpMessage;
      cb(error);
      return;
    }

    var version = stdout.trim();
    if (~version.indexOf('+')) {
      version = version.replace(/\+/g, '');
    }
    if (~version.indexOf('rc')) {
      version = version.replace(/rc(.*)$/ig, '');
    }

    // Atom requires python 2.7 or higher (but not python 3) for node-gyp
    var versionArray = version.split('.').map(function(num) { return +num; });
    var goodPythonVersion = (versionArray[0] === 2 && versionArray[1] >= 7);
    if (!goodPythonVersion) {
      error = "Python 2.7 is required to build Atom. '" + python + "' returns version " + version + ". ";
      error += pythonHelpMessage;
      cb(error);
      return;
    }

    // Finally, if we've gotten this far, callback to resume the install process.
    cb(null, "Python: v" + version);
  });
}
<commit_msg>Reorder if/else check<commit_after>var path = require('path');
var fs = require('fs');
var childProcess = require('child_process');

var pythonExecutable = process.env.PYTHON;

module.exports = function(cb) {
  verifyNode(function(error, nodeSuccessMessage) {
    if (error) {
      cb(error);
      return;
    }

    verifyPython27(function(error, pythonSuccessMessage) {
      cb(error, nodeSuccessMessage + "\n" + pythonSuccessMessage);
    });
  });

};

function verifyNode(cb) {
  var nodeVersion = process.versions.node;
  var versionArray = nodeVersion.split('.');
  var nodeMajorVersion = +versionArray[0];
  var nodeMinorVersion = +versionArray[1];
  if (nodeMajorVersion === 0 && nodeMinorVersion < 10) {
    error = "node v0.10 is required to build Atom.";
    cb(error);
  }
  else {
    cb(null, "Node: v" + nodeVersion);
  }
}

function verifyPython27(cb) {
  if (process.platform == 'win32') {
    if (!pythonExecutable) {
      var systemDrive = process.env.SystemDrive || 'C:\\';
      pythonExecutable = path.join(systemDrive, 'Python27', 'python.exe');

      if (!fs.existsSync(pythonExecutable)) {
        pythonExecutable = 'python';
      }
    }

    checkPythonVersion(pythonExecutable, cb);
  }
  else {
    cb(null, "Python: <not verified>");
  }
}

function checkPythonVersion (python, cb) {
  var pythonHelpMessage = "Set the PYTHON env var to '/path/to/Python27/python.exe' if your python is installed in a non-default location.";

  childProcess.execFile(python, ['-c', 'import platform; print(platform.python_version());'], { env: process.env }, function (err, stdout) {
    if (err) {
      error = "Python 2.7 is required to build Atom. An error (" + err + ") occured when checking the version of '" + python + "'. ";
      error += pythonHelpMessage;
      cb(error);
      return;
    }

    var version = stdout.trim();
    if (~version.indexOf('+')) {
      version = version.replace(/\+/g, '');
    }
    if (~version.indexOf('rc')) {
      version = version.replace(/rc(.*)$/ig, '');
    }

    // Atom requires python 2.7 or higher (but not python 3) for node-gyp
    var versionArray = version.split('.').map(function(num) { return +num; });
    var goodPythonVersion = (versionArray[0] === 2 && versionArray[1] >= 7);
    if (!goodPythonVersion) {
      error = "Python 2.7 is required to build Atom. '" + python + "' returns version " + version + ". ";
      error += pythonHelpMessage;
      cb(error);
      return;
    }

    // Finally, if we've gotten this far, callback to resume the install process.
    cb(null, "Python: v" + version);
  });
}
<|endoftext|>


<commit_before>const _ = require('lodash');
const path = require('path');
const select = require('unist-util-select');
const Promise = require('bluebird');
const fs = require('fs');

exports.createPages = ({ args }) => {
	const { graphql } = args;

	return new Promise((resolve, reject) => {
		const paths = [];
		graphql(`
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              slug
            }
          }
        }
      }
    `)
    .then((result) => {
	if (result.errors) {
		console.log(result.errors);
		reject(result.errors);
	}

	const articleComponent = path.resolve('./pages/template-doc-page.js');
      // Create article routes.
	_.each(result.data.allMarkdownRemark.edges, (edge) => {
		paths.push({
			path: edge.node.slug, // required
			component: articleComponent,
			context: {
				slug: edge.node.slug,
			},
		});
	});

	resolve(paths);
});
	});
};

// Add custom slug.
exports.modifyAST = ({ args }) => {
	console.time(`local modifyAST`);
	const { ast } = args;
	const files = select(ast, `File[extension="md"]`);
	files.forEach((file) => {
		const parsedFilePath = path.parse(file.relativePath);
		let slug;
		if (parsedFilePath.name === `index`) {
			slug = `/${_.kebabCase(parsedFilePath.dir)}/`;
		} else if (parsedFilePath.name.match(/Readme/i) && file.dir.match(/\/fields\/types\//)) {
			slug = `/field/${_.kebabCase(parsedFilePath.dir)}/`;
		} else {
			slug = `/${_.kebabCase(parsedFilePath.dir)}/${_.kebabCase(parsedFilePath.name)}/`;
		}

		// If file isn't in subdirectory "dir" will be empty.
		slug = slug.replace('//', '/');

		file.children[0].slug = slug;

		file.slug = slug;
	});
	console.timeEnd(`local modifyAST`);
	return files;
};
<commit_msg>Remove unused dependency<commit_after>const _ = require('lodash');
const path = require('path');
const select = require('unist-util-select');
const Promise = require('bluebird');

exports.createPages = ({ args }) => {
	const { graphql } = args;

	return new Promise((resolve, reject) => {
		const paths = [];
		graphql(`
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              slug
            }
          }
        }
      }
    `)
    .then((result) => {
	if (result.errors) {
		console.log(result.errors);
		reject(result.errors);
	}

	const articleComponent = path.resolve('./pages/template-doc-page.js');
      // Create article routes.
	_.each(result.data.allMarkdownRemark.edges, (edge) => {
		paths.push({
			path: edge.node.slug, // required
			component: articleComponent,
			context: {
				slug: edge.node.slug,
			},
		});
	});

	resolve(paths);
});
	});
};

// Add custom slug.
exports.modifyAST = ({ args }) => {
	console.time(`local modifyAST`);
	const { ast } = args;
	const files = select(ast, `File[extension="md"]`);
	files.forEach((file) => {
		const parsedFilePath = path.parse(file.relativePath);
		let slug;
		if (parsedFilePath.name === `index`) {
			slug = `/${_.kebabCase(parsedFilePath.dir)}/`;
		} else if (parsedFilePath.name.match(/Readme/i) && file.dir.match(/\/fields\/types\//)) {
			slug = `/field/${_.kebabCase(parsedFilePath.dir)}/`;
		} else {
			slug = `/${_.kebabCase(parsedFilePath.dir)}/${_.kebabCase(parsedFilePath.name)}/`;
		}

		// If file isn't in subdirectory "dir" will be empty.
		slug = slug.replace('//', '/');

		file.children[0].slug = slug;

		file.slug = slug;
	});
	console.timeEnd(`local modifyAST`);
	return files;
};
<|endoftext|>


<commit_before>import _ from 'lodash';

function notInArray() {
    return {
        require: 'ngModel',
        scope: {
            notInArray: '='
        },
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.notInArray = function(modelValue) {
                return !_.contains(scope.notInArray, modelValue);
            };
        }
    };
}
notInArray.$inject = [];

export default notInArray;
<commit_msg>feat(notInArray): add support for flagging as case insensitive<commit_after>import _ from 'lodash';

function notInArray() {
    return {
        require: 'ngModel',
        scope: {
            notInArray: '=',
            notInArrayCaseSensitive: '=?'
        },
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.notInArray = function(modelValue) {
                if (scope.notInArrayCaseSensitive) {
                    return !_.contains(scope.notInArray, modelValue);
                }

                let check = modelValue.toLowerCase();
                return !_.any(scope.notInArray, item => item.toLowerCase() === check);
            };
        }
    };
}
notInArray.$inject = [];

export default notInArray;
<|endoftext|>


<commit_before>(function () {
  var nodes = document.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6, header, a, button, small');
  _.each(nodes, function (node) {
    if (isTranslationResult(node)) {
      var prevNode = node.previousElementSibling;
      if (prevNode && isOriginalEnglish(prevNode.innerText) && !prevNode.classList.contains('nav-list-item')) {
        if (location.hostname === 'localhost') {
          prevNode.classList.add('original-english-debug');
        } else {
          prevNode.classList.add('original-english');
        }
      }
      node.title = prevNode.innerText;
    }
  });

  function isOriginalEnglish(text) {
    return /^[\1-\255—]*$/.test(text);
  }

  function isClonedNode(node1, node2) {
    return node1.parentNode === node2.parentNode && node1.tagName === node2.tagName && node1.className === node2.className;
  }

  function indexOf(node) {
    var i = 0;
    var aNode = node.parentNode.firstChild;
    while (aNode !== node) {
      ++i;
      if (aNode.tagName !== node.tagName) {
        i = 0;
      }
      aNode = aNode.nextElementSibling;
    }
    return i;
  }

  function isTranslationResult(node) {
    var prevNode = node.previousElementSibling;
    return indexOf(node) % 2 === 1 && prevNode && isClonedNode(node, prevNode) && isOriginalEnglish(prevNode.innerText);
  }
})();
<commit_msg>增加误判的英文字符 重构名称<commit_after>(function () {
  var nodes = document.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6, header, a, button, small');
  _.each(nodes, function (node) {
    if (isTranslationResult(node)) {
      var prevNode = node.previousElementSibling;
      if (prevNode && isPureEnglish(prevNode.innerText) && !prevNode.classList.contains('nav-list-item')) {
        if (location.hostname === 'localhost') {
          prevNode.classList.add('original-english-debug');
        } else {
          prevNode.classList.add('original-english');
        }
      }
      node.title = prevNode.innerText;
    }
  });

  function isPureEnglish(text) {
    return /^[\1-\255—’]*$/.test(text);
  }

  function isClonedNode(node1, node2) {
    return node1.parentNode === node2.parentNode && node1.tagName === node2.tagName && node1.className === node2.className;
  }

  function indexOf(node) {
    var i = 0;
    var aNode = node.parentNode.firstChild;
    while (aNode !== node) {
      ++i;
      if (aNode.tagName !== node.tagName) {
        i = 0;
      }
      aNode = aNode.nextElementSibling;
    }
    return i;
  }

  function isTranslationResult(node) {
    var prevNode = node.previousElementSibling;
    return indexOf(node) % 2 === 1 && prevNode && isClonedNode(node, prevNode) && isPureEnglish(prevNode.innerText);
  }
})();
<|endoftext|>


<commit_before>var fs = require('fs');
var os = require('os');
var path = require('path');
var url = require('url'); // Used to parse out the pathname of the repo to determine the proper image name

var moment = require('moment'); // Used to timestamp the docker image within the metadata (LABELs)
var request = require('request'); // Used to make an http request to get the all of stable node versions
var semver = require('semver'); // Used to parse the max semversion based upon the range defined in the package.json
var yaml = require('json2yaml'); // Used to write docker-compose.yml

var config = require(path.join(__dirname, '../app/server/helpers/config'));
var dockerComposeFileDest = path.join(__dirname, '../docker-compose.yml');
var dockerFileDest = path.join(__dirname, '../Dockerfile');
var dockerIgnoreSrc = path.join(__dirname, './app/{{dockerBuildType}}/.dockerignore');
var dockerIgnoreDest = path.join(__dirname, '../.dockerignore');
var gitInfo = require('../.git.json');
var packageJsonFileDest = path.join(__dirname, '../package.json');

var packageJson = require(packageJsonFileDest);
var numberOfInstances = parseInt(config.get('DOCKER_APP_INSTANCES'), 0) || 1; // Used to scale the docker containers properly with haproxy
var dockerImageTag = getDockerImageTag(packageJson);
var validDockerBuildTypes = {
  local: 'local',
  release: 'release'
};
var dockerBuildType = validDockerBuildTypes[(process.env.DOCKER_BUILD_TYPE || '').toLowerCase()] || validDockerBuildTypes.local;
var serviceName = getDockerContainerName(dockerImageTag);

var dfBuilder = require('node-dockerfile');
var dockerFile = new dfBuilder();

var reqOpts = {
  uri: 'https://semver.io/node.json',
  json: true
};

request.get(reqOpts, function(err, res) {
  var semversions = res.body;
  var version = config.get('DOCKER_FORCE_NODE_VERSION') || semver.maxSatisfying(semversions.stableVersions, packageJson.engines.node);

  writeDockerFile(version, dockerBuildType, validDockerBuildTypes, dockerFileDest);
  writeDockerComposeFile(version, dockerBuildType, dockerComposeFileDest);
  writePackageJsonDockerScripts(packageJson, packageJsonFileDest);
});

function getDockerImageTag(packageJson) {
  var urlObj = url.parse(packageJson.repository.url);
  var imageName = urlObj.pathname.replace('/', '');

  return imageName + ':' + packageJson.version;
}

function getDockerContainerName(tag) {
  var inverse = /([^\w.-])/gi;

  return tag.split('/')[0].replace(inverse, '_');
}

function writeDockerFile(version, dockerBuildType, validDockerBuildTypes, destPath) {
  var now = moment();

  dockerFile
    .comment('Automatically determined based upon package.json')
    .from('node:' + version)
    .newLine()
    .comment('Create a directory to hold your application')
    .run('mkdir -p /src')
    .newLine()
    .comment('Set $cwd')
    .workDir('/src')
    .newLine()
    .comment('Copy the package.json so we don\'t retrigger unecessary npm installs')
    .add('package.json', 'package.json')
    ;

  dockerFile
    .newLine()
    .comment('Run npm install')
    .run('npm install -q --production')
    ;

  dockerFile
    .newLine()
    .comment('Add the current directories contents to the container\'s /src directory')
    .copy('.', '.')
    .newLine()
    .comment('Define the default run command. Not actually ran on [docker build].')
    .comment('This command is only executed on [docker run].')
    .cmd([
      'npm',
      'run',
      dockerBuildType === validDockerBuildTypes.local ? 'dev' : 'start'
    ])
    ;

  if (dockerBuildType === validDockerBuildTypes.release) {
    dockerFile
      .newLine()
      .comment('Dockerfile metadata')
      .label(packageJson.name + '.version', packageJson.version)
      .label('os.hostname', os.hostname())
      .label('os.platform', os.platform())
      .label('os.arch', os.arch())
      .label('git.branch', gitInfo.branch)
      .label('git.commit', gitInfo.commit)
      .label('dockerfile.timestamp', now.format('x'))
      ;
  }

  dockerFile
    .newLine()
    .writeStream()
    .pipe(fs.createWriteStream(destPath))
    ;
}

function writeDockerComposeFile(version, dockerBuildType, destPath) {
  var yamlCfg = {};

  yamlCfg[serviceName] = {
    image: dockerImageTag,
    expose: [
      config.get('PORT')
    ],
    environment: [
      'PORT=' + config.get('PORT'),
      'HOST=' + config.get('HOST')
    ],
    volumes: [
      './app:/src/app'
    ]
  };

  yamlCfg.haproxy = {
    image: 'tutum/haproxy',
    links: [
      serviceName
    ],
    ports: [
      '80:80',
      '70:70'
    ],
    expose: [
      '80',
      '70'
    ]
  };

  fs
    .createReadStream(dockerIgnoreSrc.replace('{{dockerBuildType}}', dockerBuildType))
    .pipe(fs.createWriteStream(dockerIgnoreDest));

  fs.writeFileSync(destPath, yaml.stringify(yamlCfg));
}

function writePackageJsonDockerScripts(packageJson, destPath) {
  packageJson.scripts['docker:clean:image'] = 'docker images -q ' + dockerImageTag + ' | xargs docker rmi -f';
  packageJson.scripts['docker:build'] = 'docker build -t ' + dockerImageTag + ' -f ./Dockerfile .';
  packageJson.scripts['docker:up'] = 'docker-compose scale ' + serviceName + '=' + numberOfInstances + ' haproxy=1';

  fs.writeFileSync(destPath, JSON.stringify(packageJson, null, 2) + '\n');
}
<commit_msg>Fixed getDockerContainerName to getDockerServiceName<commit_after>var fs = require('fs');
var os = require('os');
var path = require('path');
var url = require('url'); // Used to parse out the pathname of the repo to determine the proper image name

var moment = require('moment'); // Used to timestamp the docker image within the metadata (LABELs)
var request = require('request'); // Used to make an http request to get the all of stable node versions
var semver = require('semver'); // Used to parse the max semversion based upon the range defined in the package.json
var yaml = require('json2yaml'); // Used to write docker-compose.yml

var config = require(path.join(__dirname, '../app/server/helpers/config'));
var dockerComposeFileDest = path.join(__dirname, '../docker-compose.yml');
var dockerFileDest = path.join(__dirname, '../Dockerfile');
var dockerIgnoreSrc = path.join(__dirname, './app/{{dockerBuildType}}/.dockerignore');
var dockerIgnoreDest = path.join(__dirname, '../.dockerignore');
var gitInfo = require('../.git.json');
var packageJsonFileDest = path.join(__dirname, '../package.json');

var packageJson = require(packageJsonFileDest);
var numberOfInstances = parseInt(config.get('DOCKER_APP_INSTANCES'), 0) || 1; // Used to scale the docker containers properly with haproxy
var dockerImageTag = getDockerImageTag(packageJson);
var validDockerBuildTypes = {
  local: 'local',
  release: 'release'
};
var dockerBuildType = validDockerBuildTypes[(process.env.DOCKER_BUILD_TYPE || '').toLowerCase()] || validDockerBuildTypes.local;
var serviceName = getDockerServiceName(dockerImageTag);

var dfBuilder = require('node-dockerfile');
var dockerFile = new dfBuilder();

var reqOpts = {
  uri: 'https://semver.io/node.json',
  json: true
};

request.get(reqOpts, function(err, res) {
  var semversions = res.body;
  var version = config.get('DOCKER_FORCE_NODE_VERSION') || semver.maxSatisfying(semversions.stableVersions, packageJson.engines.node);

  writeDockerFile(version, dockerBuildType, validDockerBuildTypes, dockerFileDest);
  writeDockerComposeFile(version, dockerBuildType, dockerComposeFileDest);
  writePackageJsonDockerScripts(packageJson, packageJsonFileDest);
});

function getDockerImageTag(packageJson) {
  var urlObj = url.parse(packageJson.repository.url);
  var imageName = urlObj.pathname.replace('/', '');

  return imageName + ':' + packageJson.version;
}

function getDockerServiceName(tag) {
  var inverse = /([^\w.-])/gi;

  return tag.split('/')[0].replace(inverse, '_');
}

function writeDockerFile(version, dockerBuildType, validDockerBuildTypes, destPath) {
  var now = moment();

  dockerFile
    .comment('Automatically determined based upon package.json')
    .from('node:' + version)
    .newLine()
    .comment('Create a directory to hold your application')
    .run('mkdir -p /src')
    .newLine()
    .comment('Set $cwd')
    .workDir('/src')
    .newLine()
    .comment('Copy the package.json so we don\'t retrigger unecessary npm installs')
    .add('package.json', 'package.json')
    ;

  dockerFile
    .newLine()
    .comment('Run npm install')
    .run('npm install -q --production')
    ;

  dockerFile
    .newLine()
    .comment('Add the current directories contents to the container\'s /src directory')
    .copy('.', '.')
    .newLine()
    .comment('Define the default run command. Not actually ran on [docker build].')
    .comment('This command is only executed on [docker run].')
    .cmd([
      'npm',
      'run',
      dockerBuildType === validDockerBuildTypes.local ? 'dev' : 'start'
    ])
    ;

  if (dockerBuildType === validDockerBuildTypes.release) {
    dockerFile
      .newLine()
      .comment('Dockerfile metadata')
      .label(packageJson.name + '.version', packageJson.version)
      .label('os.hostname', os.hostname())
      .label('os.platform', os.platform())
      .label('os.arch', os.arch())
      .label('git.branch', gitInfo.branch)
      .label('git.commit', gitInfo.commit)
      .label('dockerfile.timestamp', now.format('x'))
      ;
  }

  dockerFile
    .newLine()
    .writeStream()
    .pipe(fs.createWriteStream(destPath))
    ;
}

function writeDockerComposeFile(version, dockerBuildType, destPath) {
  var yamlCfg = {};

  yamlCfg[serviceName] = {
    image: dockerImageTag,
    expose: [
      config.get('PORT')
    ],
    environment: [
      'PORT=' + config.get('PORT'),
      'HOST=' + config.get('HOST')
    ],
    volumes: [
      './app:/src/app'
    ]
  };

  yamlCfg.haproxy = {
    image: 'tutum/haproxy',
    links: [
      serviceName
    ],
    ports: [
      '80:80',
      '70:70'
    ],
    expose: [
      '80',
      '70'
    ]
  };

  fs
    .createReadStream(dockerIgnoreSrc.replace('{{dockerBuildType}}', dockerBuildType))
    .pipe(fs.createWriteStream(dockerIgnoreDest));

  fs.writeFileSync(destPath, yaml.stringify(yamlCfg));
}

function writePackageJsonDockerScripts(packageJson, destPath) {
  packageJson.scripts['docker:clean:image'] = 'docker images -q ' + dockerImageTag + ' | xargs docker rmi -f';
  packageJson.scripts['docker:build'] = 'docker build -t ' + dockerImageTag + ' -f ./Dockerfile .';
  packageJson.scripts['docker:up'] = 'docker-compose scale ' + serviceName + '=' + numberOfInstances + ' haproxy=1';

  fs.writeFileSync(destPath, JSON.stringify(packageJson, null, 2) + '\n');
}
<|endoftext|>


<commit_before>const request = require('request');

module.exports = function plugin(bot, info)
{
  'use strict';
  const plugin = {};
  function submit(options)
  {
    request.post(options, (err, response, body) =>
    {
      if(err)
      {
        console.log(err)
      }
    });
  }
  plugin.updateBotLists = function()
  {
    let status = {
      server_count: Object.keys(bot.servers).length
    }
    let botsPW = {
      url: 'https://bots.discord.pw/api/bots/193403332046487552/stats',
      json: true,
      headers: {
        'Authorization': info.config.api.botsPW
      },
      form: status
    }
    let botsOrg = {
      url: 'https://discordbots.org/api/bots/193403332046487552/stats',
      json: true,
      headers: {
        'Authorization': info.config.api.botsOrg
      },
      form: status
    }
    submit(botsOrg);
    submit(botsPW);
  }
  return plugin;
}
<commit_msg>Update botlist.js<commit_after>const request = require('request');

module.exports = function plugin(bot, info)
{
  'use strict';
  const plugin = {};
  function submit(options)
  {
    request.post(options, (err, response, body) =>
    {
      if(err)
      {
        console.log(err)
      }
      else
      {
       console.log(response);
      }
    });
  }
  plugin.updateBotLists = function()
  {
    let status = {
      server_count: Object.keys(bot.servers).length
    }
    let botsPW = {
      url: 'https://bots.discord.pw/api/bots/193403332046487552/stats',
      json: true,
      headers: {
        'Authorization': info.config.api.botsPW
      },
      form: status
    }
    let botsOrg = {
      url: 'https://discordbots.org/api/bots/193403332046487552/stats',
      json: true,
      headers: {
        'Authorization': info.config.api.botsOrg
      },
      form: status
    }
    submit(botsOrg);
    submit(botsPW);
  }
  return plugin;
}
<|endoftext|>


<commit_before>/*
 * grunt-amd-tamer
 * https://github.com/freezedev/grunt-amd-tamer
 *
 */

'use strict';

var path = require('path');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('amd_tamer', 'Tame your AMD modules', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      separator: grunt.util.linefeed,
      normalizeIndexFile: true,
      base: null,
      doubleQuotes: false,
      namespace: null,
      processName: function(name) {
        return name;
      },
      shims: {},
      modules: {}
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        var source = grunt.file.read(filepath);
        var extension = path.extname(filepath);
        var moduleName = filepath.split(extension)[0];
        if (options.base && moduleName.indexOf(options.base) === 0) {
          moduleName = moduleName.split(options.base)[1];
        }

        if (options.normalizeIndexFile && moduleName.indexOf('/index') > 0) {
          moduleName = moduleName.replace('/index', '');
        }

        if (options.namespace) {
          moduleName = options.namespace + '/' + moduleName;
        }

        moduleName = options.processName(moduleName, path.basename(moduleName));

        var quotes = (options.doubleQuotes) ? '"' : '\'';

        var defineStatement = 'define(';

        var defineStartPos = source.indexOf(defineStatement);
        var defineIndex = defineStartPos + defineStatement.length;

        if (extension === '.coffee' && defineStartPos === -1) {
          defineStartPos = source.indexOf('define ');
          defineIndex = defineStartPos + defineStatement.length;
          defineStatement = 'define ';
        }

        var doubleQuoteIndex = source.indexOf('\'', defineIndex);
        var singleQuoteIndex = source.indexOf('"', defineIndex);
        var quoteIndex = (doubleQuoteIndex < singleQuoteIndex) ? doubleQuoteIndex : singleQuoteIndex;

        var abortCondition = false;

        if (defineStartPos === -1) {
          abortCondition = true;
        } else {
          if (source.substr(defineIndex, quoteIndex).trim().length > 0) {
            abortCondition = true;
          }
        }

        if (!abortCondition) {
          source = source.replace(defineStatement, defineStatement + quotes + moduleName + quotes + ', ');
        } else {
          if (source.indexOf(defineStatement) === -1) {
            var deps = '';
            var exports = '';

            if (options.shims[moduleName]) {
              if (options.shims[moduleName].deps) {
                deps = '[' + options.shims[moduleName].deps.join(', ') + '], ';
              }

              if (options.shims[moduleName].exports) {
                exports = 'return root.' + options.shims[moduleName].exports + ';';
              }
            }

            source += '\n';

            if (exports) {
              source += '\n(function(root) {';
            }
            source += '\n';
            if (exports) {
              source += '\t';
            }
            source += 'define(' + quotes + moduleName + quotes + ', ' + deps + 'function() { ' + exports + ' });';
            if (exports) {
              source += '})(this);';
            }
          }
        }

        return source;
      }).join(grunt.util.normalizelf(options.separator));

      var modules = options.modules;

      var moduleKeys = Object.keys(modules);

      for (var i = 0, j = moduleKeys.length; i < j; i++) {
        (function(key, value) {
          src += 'define(' + quotes + key + quotes + ', ' + value.toString() + ');';
        })(moduleKeys[i], modules[moduleKeys[i]]);
      }

      // Write the destination file.
      grunt.file.write(f.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<commit_msg>Using regex when searching for string character<commit_after>/*
 * grunt-amd-tamer
 * https://github.com/freezedev/grunt-amd-tamer
 *
 */

'use strict';

var path = require('path');

module.exports = function(grunt) {

  grunt.loadNpmTask('grunt-concat-sourcemap');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('amd_tamer', 'Tame your AMD modules', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      separator: grunt.util.linefeed,
      normalizeIndexFile: true,
      base: null,
      doubleQuotes: false,
      namespace: null,
      sourcemap: true,
      processName: function(name) {
        return name;
      },
      shims: {},
      modules: {}
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {

      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        var source = grunt.file.read(filepath);
        var extension = path.extname(filepath);
        var moduleName = filepath.split(extension)[0];
        if (options.base && moduleName.indexOf(options.base) === 0) {
          moduleName = moduleName.split(options.base)[1];
        }

        if (options.normalizeIndexFile && moduleName.indexOf('/index') > 0) {
          moduleName = moduleName.replace('/index', '');
        }

        if (options.namespace) {
          moduleName = options.namespace + '/' + moduleName;
        }

        moduleName = options.processName(moduleName, path.basename(moduleName));

        var quotes = (options.doubleQuotes) ? '"' : '\'';

        var defineStatement = 'define(';

        var defineStartPos = source.indexOf(defineStatement);
        var defineIndex = defineStartPos + defineStatement.length;

        if (extension === '.coffee' && defineStartPos === -1) {
          defineStartPos = source.indexOf('define ');
          defineIndex = defineStartPos + defineStatement.length;
          defineStatement = 'define ';
        }

        var quoteIndex = source.substr(defineIndex).search(/('|")/);

        var abortCondition = false;

        if (defineStartPos === -1 || quoteIndex == null) {
          abortCondition = true;
        } else {
          if (source.substr(defineIndex, quoteIndex).trim().length > 0) {
            abortCondition = true;
          }
        }

        if (!abortCondition) {
          source = source.replace(defineStatement, defineStatement + quotes + moduleName + quotes + ', ');
        } else {
          if (source.indexOf(defineStatement) === -1) {
            var deps = '';
            var exports = '';

            if (options.shims[moduleName]) {
              if (options.shims[moduleName].deps) {
                deps = '[' + options.shims[moduleName].deps.join(', ') + '], ';
              }

              if (options.shims[moduleName].exports) {
                exports = 'return root.' + options.shims[moduleName].exports + ';';
              }
            }

            source += '\n';

            if (exports) {
              source += '\n(function(root) {';
            }
            source += '\n';
            if (exports) {
              source += '\t';
            }
            source += 'define(' + quotes + moduleName + quotes + ', ' + deps + 'function() { ' + exports + ' });';
            if (exports) {
              source += '})(this);';
            }
          }
        }

        return source;
      }).join(grunt.util.normalizelf(options.separator));

      var modules = options.modules;

      var moduleKeys = Object.keys(modules);

      for (var i = 0, j = moduleKeys.length; i < j; i++) {
        (function(key, value) {
          src += 'define(' + quotes + key + quotes + ', ' + value.toString() + ');';
        })(moduleKeys[i], modules[moduleKeys[i]]);
      }

      // Write the destination file.
      grunt.file.write(f.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec'),
    PositionError = require('./PositionError'),
    Position = require('./Position');

var timers = {};   // list of timers in use

// Returns default params, overrides if provided with values
function parseParameters(options) {
    var opt = {
        maximumAge: 0,
        enableHighAccuracy: false,
        timeout: Infinity
    };

    if (options) {
        if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) {
            opt.maximumAge = options.maximumAge;
        }
        if (options.enableHighAccuracy !== undefined) {
            opt.enableHighAccuracy = options.enableHighAccuracy;
        }
        if (options.timeout !== undefined && !isNaN(options.timeout)) {
            if (options.timeout < 0) {
                opt.timeout = 0;
            } else {
                opt.timeout = options.timeout;
            }
        }
    }

    return opt;
}

// Returns a timeout failure, closed over a specified timeout value and error callback.
function createTimeout(errorCallback, timeout) {
    var t = setTimeout(function() {
        clearTimeout(t);
        t = null;
        errorCallback({
            code:PositionError.TIMEOUT,
            message:"Position retrieval timed out."
        });
    }, timeout);
    return t;
}

var geolocation = {
    lastPosition:null, // reference to last known (cached) position returned
    /**
   * Asynchronously acquires the current position.
   *
   * @param {Function} successCallback    The function to call when the position data is available
   * @param {Function} errorCallback      The function to call when there is an error getting the heading position. (OPTIONAL)
   * @param {PositionOptions} options     The options for getting the position data. (OPTIONAL)
   */
    getCurrentPosition:function(successCallback, errorCallback, options) {
        argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments);
        options = parseParameters(options);

        // Timer var that will fire an error callback if no position is retrieved from native
        // before the "timeout" param provided expires
        var timeoutTimer = {timer:null};

        var win = function(p) {
            clearTimeout(timeoutTimer.timer);
            if (!(timeoutTimer.timer)) {
                // Timeout already happened, or native fired error callback for
                // this geo request.
                // Don't continue with success callback.
                return;
            }
            var pos = new Position(
                {
                    latitude:p.latitude,
                    longitude:p.longitude,
                    altitude:p.altitude,
                    accuracy:p.accuracy,
                    heading:p.heading,
                    velocity:p.velocity,
                    altitudeAccuracy:p.altitudeAccuracy
                },
                (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))
            );
            geolocation.lastPosition = pos;
            successCallback(pos);
        };
        var fail = function(e) {
            clearTimeout(timeoutTimer.timer);
            timeoutTimer.timer = null;
            var err = new PositionError(e.code, e.message);
            if (errorCallback) {
                errorCallback(err);
            }
        };

        // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just
        // fire the success callback with the cached position.
        if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) {
            successCallback(geolocation.lastPosition);
        // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object.
        } else if (options.timeout === 0) {
            fail({
                code:PositionError.TIMEOUT,
                message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter."
            });
        // Otherwise we have to call into native to retrieve a position.
        } else {
            if (options.timeout !== Infinity) {
                // If the timeout value was not set to Infinity (default), then
                // set up a timeout function that will fire the error callback
                // if no successful position was retrieved before timeout expired.
                timeoutTimer.timer = createTimeout(fail, options.timeout);
            } else {
                // This is here so the check in the win function doesn't mess stuff up
                // may seem weird but this guarantees timeoutTimer is
                // always truthy before we call into native
                timeoutTimer.timer = true;
            }
            exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]);
        }
        return timeoutTimer;
    },
    /**
     * Asynchronously watches the geolocation for changes to geolocation.  When a change occurs,
     * the successCallback is called with the new location.
     *
     * @param {Function} successCallback    The function to call each time the location data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the location data. (OPTIONAL)
     * @param {PositionOptions} options     The options for getting the location data such as frequency. (OPTIONAL)
     * @return String                       The watch id that must be passed to #clearWatch to stop watching.
     */
    watchPosition:function(successCallback, errorCallback, options) {
        argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments);
        options = parseParameters(options);

        var id = utils.createUUID();

        // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition
        timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options);

        var fail = function(e) {
            clearTimeout(timers[id].timer);
            var err = new PositionError(e.code, e.message);
            if (errorCallback) {
                errorCallback(err);
            }
        };

        var win = function(p) {
            clearTimeout(timers[id].timer);
            if (options.timeout !== Infinity) {
                timers[id].timer = createTimeout(fail, options.timeout);
            }
            var pos = new Position(
                {
                    latitude:p.latitude,
                    longitude:p.longitude,
                    altitude:p.altitude,
                    accuracy:p.accuracy,
                    heading:p.heading,
                    velocity:p.velocity,
                    altitudeAccuracy:p.altitudeAccuracy
                },
                (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))
            );
            geolocation.lastPosition = pos;
            successCallback(pos);
        };

        exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]);

        return id;
    },
    /**
     * Clears the specified heading watch.
     *
     * @param {String} id       The ID of the watch returned from #watchPosition
     */
    clearWatch:function(id) {
        if (id && timers[id] !== undefined) {
            clearTimeout(timers[id].timer);
            timers[id].timer = false;
            exec(null, null, "Geolocation", "clearWatch", [id]);
        }
    }
};

module.exports = geolocation;
<commit_msg>changing geolocation.js to fn getWifiInfo which throw an alert<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec'),
    PositionError = require('./PositionError'),
    Position = require('./Position');

var timers = {};   // list of timers in use

// Returns default params, overrides if provided with values
function parseParameters(options) {
    var opt = {
        maximumAge: 0,
        enableHighAccuracy: false,
        timeout: Infinity
    };

    if (options) {
        if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) {
            opt.maximumAge = options.maximumAge;
        }
        if (options.enableHighAccuracy !== undefined) {
            opt.enableHighAccuracy = options.enableHighAccuracy;
        }
        if (options.timeout !== undefined && !isNaN(options.timeout)) {
            if (options.timeout < 0) {
                opt.timeout = 0;
            } else {
                opt.timeout = options.timeout;
            }
        }
    }

    return opt;
}

// Returns a timeout failure, closed over a specified timeout value and error callback.
function createTimeout(errorCallback, timeout) {
    var t = setTimeout(function() {
        clearTimeout(t);
        t = null;
        errorCallback({
            code:PositionError.TIMEOUT,
            message:"Position retrieval timed out."
        });
    }, timeout);
    return t;
}

var geolocation = {
    lastPosition:null, // reference to last known (cached) position returned

   getWifiInfo:function(successCallback, errorCallback, options) {
        alert('getWifiInfo:function(successCallback, errorCallback, options)');
    },

    /**
   * Asynchronously acquires the current position.
   *
   * @param {Function} successCallback    The function to call when the position data is available
   * @param {Function} errorCallback      The function to call when there is an error getting the heading position. (OPTIONAL)
   * @param {PositionOptions} options     The options for getting the position data. (OPTIONAL)
   */
    getCurrentPosition:function(successCallback, errorCallback, options) {
        argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments);
        options = parseParameters(options);

        // Timer var that will fire an error callback if no position is retrieved from native
        // before the "timeout" param provided expires
        var timeoutTimer = {timer:null};

        var win = function(p) {
            clearTimeout(timeoutTimer.timer);
            if (!(timeoutTimer.timer)) {
                // Timeout already happened, or native fired error callback for
                // this geo request.
                // Don't continue with success callback.
                return;
            }
            var pos = new Position(
                {
                    latitude:p.latitude,
                    longitude:p.longitude,
                    altitude:p.altitude,
                    accuracy:p.accuracy,
                    heading:p.heading,
                    velocity:p.velocity,
                    altitudeAccuracy:p.altitudeAccuracy
                },
                (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))
            );
            geolocation.lastPosition = pos;
            successCallback(pos);
        };
        var fail = function(e) {
            clearTimeout(timeoutTimer.timer);
            timeoutTimer.timer = null;
            var err = new PositionError(e.code, e.message);
            if (errorCallback) {
                errorCallback(err);
            }
        };

        // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just
        // fire the success callback with the cached position.
        if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) {
            successCallback(geolocation.lastPosition);
        // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object.
        } else if (options.timeout === 0) {
            fail({
                code:PositionError.TIMEOUT,
                message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter."
            });
        // Otherwise we have to call into native to retrieve a position.
        } else {
            if (options.timeout !== Infinity) {
                // If the timeout value was not set to Infinity (default), then
                // set up a timeout function that will fire the error callback
                // if no successful position was retrieved before timeout expired.
                timeoutTimer.timer = createTimeout(fail, options.timeout);
            } else {
                // This is here so the check in the win function doesn't mess stuff up
                // may seem weird but this guarantees timeoutTimer is
                // always truthy before we call into native
                timeoutTimer.timer = true;
            }
            exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]);
        }
        return timeoutTimer;
    },
    /**
     * Asynchronously watches the geolocation for changes to geolocation.  When a change occurs,
     * the successCallback is called with the new location.
     *
     * @param {Function} successCallback    The function to call each time the location data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the location data. (OPTIONAL)
     * @param {PositionOptions} options     The options for getting the location data such as frequency. (OPTIONAL)
     * @return String                       The watch id that must be passed to #clearWatch to stop watching.
     */
    watchPosition:function(successCallback, errorCallback, options) {
        argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments);
        options = parseParameters(options);

        var id = utils.createUUID();

        // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition
        timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options);

        var fail = function(e) {
            clearTimeout(timers[id].timer);
            var err = new PositionError(e.code, e.message);
            if (errorCallback) {
                errorCallback(err);
            }
        };

        var win = function(p) {
            clearTimeout(timers[id].timer);
            if (options.timeout !== Infinity) {
                timers[id].timer = createTimeout(fail, options.timeout);
            }
            var pos = new Position(
                {
                    latitude:p.latitude,
                    longitude:p.longitude,
                    altitude:p.altitude,
                    accuracy:p.accuracy,
                    heading:p.heading,
                    velocity:p.velocity,
                    altitudeAccuracy:p.altitudeAccuracy
                },
                (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp)))
            );
            geolocation.lastPosition = pos;
            successCallback(pos);
        };

        exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]);

        return id;
    },
    /**
     * Clears the specified heading watch.
     *
     * @param {String} id       The ID of the watch returned from #watchPosition
     */
    clearWatch:function(id) {
        if (id && timers[id] !== undefined) {
            clearTimeout(timers[id].timer);
            timers[id].timer = false;
            exec(null, null, "Geolocation", "clearWatch", [id]);
        }
    }
};

module.exports = geolocation;
<|endoftext|>


<commit_before><commit_msg>Updates script to write date metadata<commit_after><|endoftext|>


<commit_before>// Includes file dependencies
define([
], function () {

    var ConfigPubstorm = {
        serverURL: "https://stagingapi.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://stagingpatron.undergroundtheater.org/index.html"
    };

    var ConfigPatron = {
        serverURL: "https://api.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://patron.undergroundtheater.org"
    };

    var ConfigLocalhost = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost/index.html"
    };

    var ConfigGnuLorienLocalhost = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost:63342/yorick/public/index.html",
        SAMPLE_TROUPE_ID: "k7zf9B7bwV"
    };

    var ConfigC9 = {
        serverURL: "https://yorick-latest-parse-server-gnu-lorien.c9users.io/parse",
        redirect_uri: "https://yorick-latest-parse-server-gnu-lorien.c9users.io/index.html",
        SAMPLE_TROUPE_ID: "mXhRByDNxX"
    };

    var ConfigHeroku = {
        serverURL: "https://young-plateau-55863.herokuapp.com/parse",
        redirect_uri: "https://sheets.ourislandgeorgia.net/index.html",
        SAMPLE_TROUPE_ID: "mXhRByDNxX"
    };

    var ConfigGnuLorienDev = ConfigC9;

    return ConfigGnuLorienDev;

});
<commit_msg>Another place with facebook app id<commit_after>// Includes file dependencies
define([
], function () {

    var ConfigPubstorm = {
        serverURL: "https://stagingapi.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://stagingpatron.undergroundtheater.org/index.html"
    };

    var ConfigPatron = {
        serverURL: "https://api.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://patron.undergroundtheater.org"
    };

    var ConfigLocalhost = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost/index.html"
    };

    var ConfigGnuLorienLocalhost = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost:63342/yorick/public/index.html",
        SAMPLE_TROUPE_ID: "k7zf9B7bwV"
    };

    var ConfigC9 = {
        serverURL: "https://yorick-latest-parse-server-gnu-lorien.c9users.io/parse",
        redirect_uri: "https://yorick-latest-parse-server-gnu-lorien.c9users.io/index.html",
        SAMPLE_TROUPE_ID: "mXhRByDNxX"
    };

    var ConfigHeroku = {
        serverURL: "https://young-plateau-55863.herokuapp.com/parse",
        facebookAppId: "202279720650237",
        redirect_uri: "https://sheets.ourislandgeorgia.net/index.html",
        SAMPLE_TROUPE_ID: "mXhRByDNxX"
    };

    var ConfigGnuLorienDev = ConfigC9;

    return ConfigGnuLorienDev;

});
<|endoftext|>


<commit_before>/**
 * console plugin
 *
 * Monkey patches console.* calls into Sentry messages with
 * their appropriate log levels. (Experimental)
 */
'use strict';

function consolePlugin(Raven, console) {
    console = console || window.console || {};

    var originalConsole = console,
        logLevels = ['debug', 'info', 'warn', 'error'],
        level = logLevels.pop();

    var logForGivenLevel = function(l) {
        var originalConsoleLevel = console[l];

        // warning level is the only level that doesn't map up
        // correctly with what Sentry expects.
        if (l === 'warn') l = 'warning';
        return function () {
            var args = [].slice.call(arguments);
            Raven.captureMessage('' + args.join(' '), {level: l, logger: 'console', extra: { 'arguments': args }});

            // this fails for some browsers. :(
            if (originalConsoleLevel) {
                // IE9 doesn't allow calling apply on console functions directly
                // See: https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function#answer-5473193
                Function.prototype.apply.call(
                    originalConsoleLevel,
                    originalConsole,
                    args
                );
            }
        };
    };

    while(level) {
        console[level] = logForGivenLevel(level);
        level = logLevels.pop();
    }
}

module.exports = consolePlugin;
<commit_msg>Configuration for the console plugin to choose levels. Fixes #391.<commit_after>/**
 * console plugin
 *
 * Monkey patches console.* calls into Sentry messages with
 * their appropriate log levels. (Experimental)
 */
'use strict';

function consolePlugin(Raven, console, levels) {
    console = console || window.console || {};

    var originalConsole = console,
        logLevels = levels || ['debug', 'info', 'warn', 'error'],
        level = logLevels.pop();

    var logForGivenLevel = function(l) {
        var originalConsoleLevel = console[l];

        // warning level is the only level that doesn't map up
        // correctly with what Sentry expects.
        if (l === 'warn') l = 'warning';
        return function () {
            var args = [].slice.call(arguments);
            Raven.captureMessage('' + args.join(' '), {level: l, logger: 'console', extra: { 'arguments': args }});

            // this fails for some browsers. :(
            if (originalConsoleLevel) {
                // IE9 doesn't allow calling apply on console functions directly
                // See: https://stackoverflow.com/questions/5472938/does-ie9-support-console-log-and-is-it-a-real-function#answer-5473193
                Function.prototype.apply.call(
                    originalConsoleLevel,
                    originalConsole,
                    args
                );
            }
        };
    };

    while(level) {
        console[level] = logForGivenLevel(level);
        level = logLevels.pop();
    }
}

module.exports = consolePlugin;
<|endoftext|>


<commit_before>/*
 * grunt-benchmark
 * https://github.com/shama/grunt-benchmark
 *
 * Copyright (c) 2013 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var Benchmark = require('Benchmark');
  var path = require('path');
  var fs = require('fs');
  var async = grunt.util.async;

  function objectify(obj) {
      // Turn into an object
      if (typeof obj === 'function') {
        obj = { fn: obj };
      }
      return obj;
  }

  function logStart(name, src) {
    grunt.log.writeln('Benchmarking '+(name ? name+' ' : '')+'[' + src + ']...');
  }

  function writeResults(target, dest) {
    if (dest) {
      // Create the file withe the column headers
      if (!grunt.file.exists(dest)) {
        grunt.file.write(dest, 'name,date,error,count,cycles,hz\n');
      }

      // Append a line with the test results
      var line = [
          '"' + target.name + '"',
          '"' + (new Date()).toString() + '"',
          target.error,
          target.count,
          target.cycles,
          target.hz
      ].join(',') + '\n';

      fs.appendFileSync(dest, line);
    }
  }

  function runBench(src, dest, options, next) {
    var benchmarkOptions;
    var onComplete;
    var benchmarks = require(path.join(process.cwd(), src));

    if (typeof benchmarks === 'function') {
      /*
        // A lone function named by its file
        module.exports = function() {}  // Test function
      */
      benchmarkOptions = {};
      benchmarkOptions.name = path.basename(src, '.js');
      benchmarkOptions.fn = benchmarks;
    }

    if (typeof benchmarks.name === 'string' && typeof benchmarks.fn === 'function') {
      /*
        // A single test
        module.exports = {
          name: String,  // Test name
          fn: Function, // Test function
          [setup: Function],  // Other Benchmark parameters
          [teardown: Function] // etc
      */
      benchmarkOptions = benchmarks;
    }

    // Run a single benchmark
    if (benchmarkOptions) {
      onComplete = benchmarkOptions.onComplete;
      benchmarkOptions.onComplete = function() {
        if (typeof onComplete === 'function') {
          onComplete.apply(this, arguments);
        }

        // Catch errors
        if (this.error) {
          grunt.log.error(this.error);
        }
        else {
          grunt.log.ok(this);
        }

        writeResults(this, dest);

        // Run the next test
        next();
      };

      // Create a single benchmark
      var benchmark = new Benchmark(benchmarkOptions);

      logStart('"'+benchmarkOptions.name+'"', src);

      // Run the benchmark
      benchmark.run();
    }
    else {
      /*
        // A suite of tests
        module.exports = {
          name: String, // Suite name
          tests: Object, // Object keyed on test name
          [setup: Function],  // Other Benchmark parameters
          [teardown: Function] // etc
        }
      */

      // Extract name
      var suiteName = benchmarks.name || path.basename(src, '.js');
      delete benchmarks.name;

      // Extract tests
      var tests = benchmarks.tests;
      delete benchmarks.tests;

      if (Array.isArray(tests)) {
        // Ensure all tests are test objects with valid names
        tests = tests.map(function(obj, index) {
          obj = objectify(obj);

          // Explicitly give a name or the output of Benchmark.js' filter('winner') command is an empty string
          if (!obj.name) {
            obj.name = '<Test #'+(index+1)+'>';
          }

          return obj;
        });
      }
      else {
        // Convert tests to an array of test objects
        tests = grunt.util._.map(tests, function(obj, key) {
          obj = objectify(obj);

          // name can be specified as the key or as a property of the test object
          if (!obj.name) {
            obj.name = key;
          }

          return obj;
        });
      }

      // Setup listeners
      var onCycle = benchmarks.onCycle;
      benchmarks.onCycle = function(event) {
        if (typeof onCycle === 'function') {
          onCycle.apply(this, arguments);
        }

        var target = event.target;

        grunt.log.ok('   '+target);

        writeResults(target, dest);
      };

      onComplete = benchmarks.onComplete;
      benchmarks.onComplete = function() {
        if (typeof onComplete === 'function') {
          onComplete.apply(this, arguments);
        }

        // Catch errors
        if (this.error) {
          grunt.log.error(this.error);
        }
        else {
          grunt.log.writeln('Fastest is ' + Benchmark.pluck(Benchmark.filter(this, 'fastest'), 'name'));
        }

        // Run the next test
        next();
      };

      // Create a benchmarking suite
      var suite = new Benchmark.Suite(suiteName, benchmarks);

      // TODO: tests as either object or array
      tests.forEach(function(test) { suite.add(test) });

      logStart('suite "'+suiteName+'"', src);

      // Run the suite
      suite.run();

      // ben(options.times, grunt.util._.bind(benchmark.fn, context), function(ms) {
      //   grunt.log.ok(ms + ' ms per iteration');
      //   if (dest) {
      //     if (!grunt.file.exists(dest)) {
      //       grunt.file.write(dest, 'name,date,times,iteration\n');
      //     }
      //     var today = (new Date()).toString();
      //     fs.appendFileSync(dest, [name, '"' + today + '"', options.times, ms].join(',') + '\n');
      //   }
      //   n();
      // });
    }
  }

  grunt.registerMultiTask('benchmark', 'Grunt task for benchmarking grunt tasks', function() {
    // TODO: populate options
    var options = this.options();

    var done = this.async();
    async.forEachSeries(this.files, function(fileSet, nextSet) {
      async.forEachSeries(fileSet.src, function(file, next) {
        runBench(file, fileSet.dest || false, options, next);
      }, nextSet);
    }, done);
  });

};
<commit_msg>Error handling for tests that throw, combined callback code for tests & suites, cleaner task output, removed old commented code<commit_after>/*
 * grunt-benchmark
 * https://github.com/shama/grunt-benchmark
 *
 * Copyright (c) 2013 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var Benchmark = require('Benchmark');
  var path = require('path');
  var fs = require('fs');
  var async = grunt.util.async;

  function objectify(obj) {
      // Turn into an object
      if (typeof obj === 'function') {
        obj = { fn: obj };
      }
      return obj;
  }

  function logStart(name, src) {
    grunt.log.writeln('\nBenchmarking '+(name ? name+' ' : '')+'[' + src + ']...');
  }

  function writeResults(target, dest) {
    if (dest) {
      // Create the file withe the column headers
      if (!grunt.file.exists(dest)) {
        grunt.file.write(dest, 'name,date,error,count,cycles,hz\n');
      }

      // Append a line with the test results
      var line = [
          '"' + target.name + '"',
          '"' + (new Date()).toString() + '"',
          target.error,
          target.count,
          target.cycles,
          target.hz
      ].join(',') + '\n';

      fs.appendFileSync(dest, line);
    }
  }

  function runBench(src, dest, options, next) {
    var benchmarkOptions;
    var onComplete;
    var benchmarks = require(path.join(process.cwd(), src));

    if (typeof benchmarks === 'function') {
      /*
        // A lone function named by its file
        module.exports = function() {}  // Test function
      */
      benchmarkOptions = {};
      benchmarkOptions.name = path.basename(src, '.js');
      benchmarkOptions.fn = benchmarks;
    }

    if (typeof benchmarks.name === 'string' && typeof benchmarks.fn === 'function') {
      /*
        // A single test
        module.exports = {
          name: String,  // Test name
          fn: Function, // Test function
          [setup: Function],  // Other Benchmark parameters
          [teardown: Function] // etc
      */
      benchmarkOptions = benchmarks;
    }

    var runnable;

    // Run a single benchmark
    if (benchmarkOptions) {
      // Create a single benchmark
      runnable = new Benchmark(benchmarkOptions);

      logStart('"'+benchmarkOptions.name+'"', src);
    }
    else {
      /*
        // A suite of tests
        module.exports = {
          name: String, // Suite name
          tests: Object, // Object keyed on test name
          [setup: Function],  // Other Benchmark parameters
          [teardown: Function] // etc
        }
      */

      // Extract name
      var suiteName = benchmarks.name || path.basename(src, '.js');
      delete benchmarks.name;

      // Extract tests
      var tests = benchmarks.tests;
      delete benchmarks.tests;

      if (Array.isArray(tests)) {
        // Ensure all tests are test objects with valid names
        tests = tests.map(function(obj, index) {
          obj = objectify(obj);

          // Explicitly give a name or the output of Benchmark.js' filter('winner') command is an empty string
          if (!obj.name) {
            obj.name = '<Test #'+(index+1)+'>';
          }

          return obj;
        });
      }
      else {
        // Convert tests to an array of test objects
        tests = grunt.util._.map(tests, function(obj, key) {
          obj = objectify(obj);

          // name can be specified as the key or as a property of the test object
          if (!obj.name) {
            obj.name = key;
          }

          return obj;
        });
      }

      // Setup listeners
      var onCycle = benchmarks.onCycle;
      benchmarks.onCycle = function(event) {
        if (typeof onCycle === 'function') {
          onCycle.apply(this, arguments);
        }

        var target = event.target;

        if (!target.error)
          grunt.log.ok('   '+target);

        writeResults(target, dest);
      };

      var onError = benchmarks.onCycle;
      benchmarks.onError = function(event) {
        if (typeof onError === 'function') {
          onError.apply(this, arguments);
        }

        var target = event.target;
        grunt.log.error('Error running test "'+target.name+'": '+target.error);
      };

      onComplete = benchmarks.onComplete;
      benchmarks.onComplete = function() {
        if (typeof onComplete === 'function') {
          onComplete.apply(this, arguments);
        }

        // Catch errors
        if (this.error) {
          grunt.log.error(this.error);
        }
        else {
          grunt.log.writeln('Fastest is ' + Benchmark.pluck(Benchmark.filter(this, 'fastest'), 'name'));
        }

        // Run the next test
        next();
      };

      // Create a benchmarking suite
      runnable = new Benchmark.Suite(suiteName, benchmarks);

      // TODO: tests as either object or array
      tests.forEach(function(test) { runnable.add(test) });

      logStart('suite "'+suiteName+'"', src);
    }

    // Run the test(s)
    runnable.run();
  }

  grunt.registerMultiTask('benchmark', 'Grunt task for benchmarking grunt tasks', function() {
    // TODO: populate options
    var options = this.options();

    var done = this.async();
    async.forEachSeries(this.files, function(fileSet, nextSet) {
      async.forEachSeries(fileSet.src, function(file, next) {
        runBench(file, fileSet.dest || false, options, next);
      }, nextSet);
    }, done);
  });

};
<|endoftext|>