<commit_before>"use strict";

/*eslint-disable no-magic-numbers, no-bitwise*/

var guid = require("./util/guid");
var argv = require("marge").argv;
var env = process.env;
var fs = require("fs");
var path = require("path");

// Allow an external build id (eg: from CI system, for example) to be used. If we're not given one,
// we generate a random build id instead. NOTE: This build id must work as a part of a filename.
var buildId = argv.external_build_id || "magellan-" + guid();

// Create a temporary directory for child build assets like configuration, screenshots, etc.
var mkdirSync = require("./mkdir_sync");
var TEMP_DIR = path.resolve(argv.temp_dir || "./temp");

try {
  // Check if TEMP_DIR already exists
  fs.accessSync(TEMP_DIR, fs.R_OK | fs.W_OK);
} catch (e) {
  // Create it if it doesn't..
  mkdirSync(TEMP_DIR);
}

try {
  // Check if creation worked or if we have access to the directory we were told to use.
  fs.accessSync(TEMP_DIR, fs.R_OK | fs.W_OK);
  console.log("Magellan is creating temporary files at: " + TEMP_DIR);
} catch (e) {
  throw new Error("Magellan cannot write to or create the temporary directory: " + TEMP_DIR);
}

module.exports = {

  // Port allocation scheme:
  // - All port allocation starts at BASE_PORT_START
  // - Magellan gets a block of ports offset from the start BASE_PORT_RANGE wide
  // - Each worker instance gets BASE_PORT_SPACING ports to use
  //
  //           [...........[0,1,2][0,1,2]...............]
  //            ^ start                ^ spacing (eg: 3)
  //            ---------------- range -----------------
  //
  BASE_PORT_START: parseInt(argv.base_port_start) || 12000,
  BASE_PORT_RANGE: parseInt(argv.base_port_range) || 2000,
  BASE_PORT_SPACING: parseInt(argv.base_port_spacing) || 3,

  environment: env,

  debug: argv.debug,

  gatherTrends: argv.gather_trends,

  aggregateScreenshots: argv.aggregate_screenshots,
  tempDir: TEMP_DIR,

  // By default, kill time of long running tests is 8 minutes *only if bail options are set*
  // Otherwise bailTime is only explicitly used if explicitly set -- tests are otherwise allowed
  // to run "forever".
  bailTime: argv.bail_time || 8 * 60 * 1000,
  bailTimeExplicitlySet: typeof argv.bail_time !== "undefined",

  // For --bail_early, we have two settings:
  // threshold: the ratio (out of 1) of how many tests we need to see fail before we bail early.
  // min attempts: how many tests we need to see first before we apply the threshold
  bailThreshold: parseFloat(argv.early_bail_threshold) || 0.1,
  bailMinAttempts: parseInt(argv.early_bail_min_attempts) || 10,

  buildId: buildId,

  framework: argv.framework || "nightwatch",

  customSauceBrowsers: argv.customSauceBrowsers || []
};
<commit_msg>patch for node 0.10<commit_after>"use strict";

/*eslint-disable no-magic-numbers, no-bitwise*/

var guid = require("./util/guid");
var argv = require("marge").argv;
var env = process.env;
var fs = require("fs");
var path = require("path");

// Allow an external build id (eg: from CI system, for example) to be used. If we're not given one,
// we generate a random build id instead. NOTE: This build id must work as a part of a filename.
var buildId = argv.external_build_id || "magellan-" + guid();

// Create a temporary directory for child build assets like configuration, screenshots, etc.
var mkdirSync = require("./mkdir_sync");
var TEMP_DIR = path.resolve(argv.temp_dir || "./temp");

try {
  // Check if TEMP_DIR already exists.
  // NOTE: This doesn't work in node 0.10. Those envs will suffer as a result
  if (fs.accessSync) {
    fs.accessSync(TEMP_DIR, fs.R_OK | fs.W_OK);
  }
} catch (e) {
  // Create it if it doesn't..
  mkdirSync(TEMP_DIR);
}

try {
  // Check if creation worked or if we have access to the directory we were told to use.
  // NOTE: This doesn't work in node 0.10. Those envs will suffer as a result
  if (fs.accessSync) {
    fs.accessSync(TEMP_DIR, fs.R_OK | fs.W_OK);
  }
  console.log("Magellan is creating temporary files at: " + TEMP_DIR);
} catch (e) {
  throw new Error("Magellan cannot write to or create the temporary directory: " + TEMP_DIR);
}

module.exports = {

  // Port allocation scheme:
  // - All port allocation starts at BASE_PORT_START
  // - Magellan gets a block of ports offset from the start BASE_PORT_RANGE wide
  // - Each worker instance gets BASE_PORT_SPACING ports to use
  //
  //           [...........[0,1,2][0,1,2]...............]
  //            ^ start                ^ spacing (eg: 3)
  //            ---------------- range -----------------
  //
  BASE_PORT_START: parseInt(argv.base_port_start) || 12000,
  BASE_PORT_RANGE: parseInt(argv.base_port_range) || 2000,
  BASE_PORT_SPACING: parseInt(argv.base_port_spacing) || 3,

  environment: env,

  debug: argv.debug,

  gatherTrends: argv.gather_trends,

  aggregateScreenshots: argv.aggregate_screenshots,
  tempDir: TEMP_DIR,

  // By default, kill time of long running tests is 8 minutes *only if bail options are set*
  // Otherwise bailTime is only explicitly used if explicitly set -- tests are otherwise allowed
  // to run "forever".
  bailTime: argv.bail_time || 8 * 60 * 1000,
  bailTimeExplicitlySet: typeof argv.bail_time !== "undefined",

  // For --bail_early, we have two settings:
  // threshold: the ratio (out of 1) of how many tests we need to see fail before we bail early.
  // min attempts: how many tests we need to see first before we apply the threshold
  bailThreshold: parseFloat(argv.early_bail_threshold) || 0.1,
  bailMinAttempts: parseInt(argv.early_bail_min_attempts) || 10,

  buildId: buildId,

  framework: argv.framework || "nightwatch",

  customSauceBrowsers: argv.customSauceBrowsers || []
};
<|endoftext|>


<commit_before>const SettingsClient = require('../vendor/settingsClient')
const Promise = require('promise')

/**
 * @class SettingsValues
 * @classdesc
 *  The SettingsValues class provides access to all settings values of the (most of the time authenticated) user.
 *
 * @author Benedikt Kulmann
 * @version 1.0.0
 * @param {object}  helperFile  instance of the helpers class
 */
class SettingsValues {
  constructor (helpers) {
    this.helpers = helpers
  }

  /**
   * Gets all settings values for the given account uuid. If no uuid is provided, settings values
   * for the authenticated user will be fetched. If the settings service is unavailable, a set of
   * default values will be returned (if there are any defaults).
   * @param   {string} accountUuid The accountUuid to fetch settings for. Most of the time we want to fetch settings
   *                               for the authenticated user. So this defaults to `me`, which will resolve the
   *                               account uuid of the authenticated user in the settings service.
   * @returns {Promise.<settings>} array: all available settings values
   * @returns {Promise.<error>}    string: error message, if any.
   */
  async getSettingsValues (accountUuid = 'me') {
    try {
      const baseUrl = this.helpers.getInstance().replace(/\/$/, '')
      const response = await SettingsClient.ValueService_ListSettingsValues({
        $domain: baseUrl,
        body: {
          identifier: {
            account_uuid: accountUuid
          }
        }
      })
      if (response.status === 201) {
        return Promise.resolve(response.data.settingsValues)
      }
    } catch (error) {
      // fail on anything except settings service being unavailable
      // TODO: if this changes to GET requests in the future, this will be 404 instead of 502
      if (error.response.status !== 502) {
        return Promise.reject(error)
      }
    }
    // TODO: build a sensible set of defaults here, if necessary.
    return Promise.resolve([])
  }
}

module.exports = SettingsValues
<commit_msg>Also ignore 404 for settings service, not just 502.<commit_after>const SettingsClient = require('../vendor/settingsClient')
const Promise = require('promise')

/**
 * @class SettingsValues
 * @classdesc
 *  The SettingsValues class provides access to all settings values of the (most of the time authenticated) user.
 *
 * @author Benedikt Kulmann
 * @version 1.0.0
 * @param {object}  helperFile  instance of the helpers class
 */
class SettingsValues {
  constructor (helpers) {
    this.helpers = helpers
  }

  /**
   * Gets all settings values for the given account uuid. If no uuid is provided, settings values
   * for the authenticated user will be fetched. If the settings service is unavailable, a set of
   * default values will be returned (if there are any defaults).
   * @param   {string} accountUuid The accountUuid to fetch settings for. Most of the time we want to fetch settings
   *                               for the authenticated user. So this defaults to `me`, which will resolve the
   *                               account uuid of the authenticated user in the settings service.
   * @returns {Promise.<settings>} array: all available settings values
   * @returns {Promise.<error>}    string: error message, if any.
   */
  async getSettingsValues (accountUuid = 'me') {
    try {
      const baseUrl = this.helpers.getInstance().replace(/\/$/, '')
      const response = await SettingsClient.ValueService_ListSettingsValues({
        $domain: baseUrl,
        body: {
          identifier: {
            account_uuid: accountUuid
          }
        }
      })
      if (response.status === 201) {
        return Promise.resolve(response.data.settingsValues)
      }
    } catch (error) {
      // fail on anything except settings service being unavailable
      if (error.response.status !== 502 && error.response.status !== 404) {
        return Promise.reject(error)
      }
    }
    // TODO: build a sensible set of defaults here, if necessary.
    return Promise.resolve([])
  }
}

module.exports = SettingsValues
<|endoftext|>


<commit_before>// Copyright 2014 Flávio Ribeiro <flavio@bem.tv>.
// All rights reserved.
// Use of this source code is governed by a Apache
// license that can be found in the LICENSE file.

class Settings {
}

/* logging
Turn on/off logging on browser's console on
initialization. You can always turn on/off
by pressing ctrl+shift+l on your browser tab. */
Settings.logging = false

/* maxStorageChunks
Maximum size of the storage in number of chunks. */
Settings.maxStorageChunks = 10

/* maxContributors
The maximum number of contributors one peer can handle.
Contributors are used to be requested for video segments. */
Settings.maxContributors = 5

/* maxSwarmSize
Maximum number of peers on our particular swarm view.
When reach this number, P2PManager will ignore new peers. */
Settings.maxSwarmSize = 50

/* maxUploadSlots
Maximum number of peers one can serve. */
Settings.maxUploadSlots = 10

/* uploadSlotTimeout
Time in milliseconds in which an upload slot will be expired.
If a given downloader stops to request segments for
uploadSlotTimeout seconds, this slot will be emptied. */
Settings.uploadSlotTimeout = 8000

/* tracker
Place where your rtc-switchboard server is running */
Settings.tracker = 'http://server.bem.tv:8080'

/* lowBufferLength
Local buffer threshold in seconds in which the player
will try to use P2P. Smaller than lowBufferLength, player will
request chunks only for CDN. */
Settings.lowBufferLength = 5

/* points
How many points a contributor win/loss when send a segment
or not. This serves to reorganize peers and promoting or
demoting then as contributors. */
Settings.points = 1

/* stunServers
STUN servers used to match peers. */
Settings.stunServers = [
  {"url": "stun:stun.bem.tv:3478"},
  {"url": "stun:stun.l.google.com:19302"},
  {"url": "stun:stun1.l.google.com:19302"},
  {"url": "stun:stun2.l.google.com:19302"},
  {"url": "stun:stun3.l.google.com:19302"},
  {"url": "stun:stun4.l.google.com:19302"},
  {"url": "stun:stun.stunprotocol.org:3478"},
]

/* forceAllowCredentials
Some HLS servers use cookies to authenticate and create user
sessions. This option enables BemTV to make requests to CDN
using the cookies received when getting the master playlist. */
Settings.forceAllowCredentials = false

module.exports = Settings
<commit_msg>settings: update tracker with latest rtc-switchboard<commit_after>// Copyright 2014 Flávio Ribeiro <flavio@bem.tv>.
// All rights reserved.
// Use of this source code is governed by a Apache
// license that can be found in the LICENSE file.

class Settings {
}

/* logging
Turn on/off logging on browser's console on
initialization. You can always turn on/off
by pressing ctrl+shift+l on your browser tab. */
Settings.logging = false

/* maxStorageChunks
Maximum size of the storage in number of chunks. */
Settings.maxStorageChunks = 10

/* maxContributors
The maximum number of contributors one peer can handle.
Contributors are used to be requested for video segments. */
Settings.maxContributors = 5

/* maxSwarmSize
Maximum number of peers on our particular swarm view.
When reach this number, P2PManager will ignore new peers. */
Settings.maxSwarmSize = 50

/* maxUploadSlots
Maximum number of peers one can serve. */
Settings.maxUploadSlots = 10

/* uploadSlotTimeout
Time in milliseconds in which an upload slot will be expired.
If a given downloader stops to request segments for
uploadSlotTimeout seconds, this slot will be emptied. */
Settings.uploadSlotTimeout = 8000

/* tracker
Place where your rtc-switchboard server is running */
Settings.tracker = 'http://tracker.bem.tv'

/* lowBufferLength
Local buffer threshold in seconds in which the player
will try to use P2P. Smaller than lowBufferLength, player will
request chunks only for CDN. */
Settings.lowBufferLength = 5

/* points
How many points a contributor win/loss when send a segment
or not. This serves to reorganize peers and promoting or
demoting then as contributors. */
Settings.points = 1

/* stunServers
STUN servers used to match peers. */
Settings.stunServers = [
  {"url": "stun:stun.bem.tv:3478"},
  {"url": "stun:stun.l.google.com:19302"},
  {"url": "stun:stun1.l.google.com:19302"},
  {"url": "stun:stun2.l.google.com:19302"},
  {"url": "stun:stun3.l.google.com:19302"},
  {"url": "stun:stun4.l.google.com:19302"},
  {"url": "stun:stun.stunprotocol.org:3478"},
]

/* forceAllowCredentials
Some HLS servers use cookies to authenticate and create user
sessions. This option enables BemTV to make requests to CDN
using the cookies received when getting the master playlist. */
Settings.forceAllowCredentials = false

module.exports = Settings
<|endoftext|>


<commit_before>/*
 sideburn.js
 http://scrappit.org/sideburn
 MIT License
 Author: Josh Dzielak, Copyright (c) 2011

 Convert HTML to mustache-friendly JSON.

 Given this DOM:

sideburn

  sideburn.js produces a superset of this JSON object structure:

  {
    div : {
      img : { src : 'foo.png' },
      text : 'sideburn'
    }
  }

 To maximize the Child nodes are reachable from their parent by
 attribute names, element names, classes, or ID.

 */
(function(context, document) {

  var version = '0.1.0+',
    undef = undefined,
    strUndef = '' + undef,
    toString = Object.prototype.toString,

    //used to generate property names
    pfx = '_',

    //used for internal/private property names: _children
    internalPfx = pfx,

    //used for array property names: _span
    arrayPfx = pfx,

    //used for internal arrays that add elements by selector type: _by_id
    selectorPfx = internalPfx + 'by' + internalPfx,

    nmAttributes = 'attributes',
    nmChildren = 'children',

    nmNode = 'node',
    nmNodeName = 'node_name',

    //the five sources of properties
    nmText = 'text',
    nmAttribute = 'attribute',
    nmElement = 'element',
    nmClass = 'class',
    nmId = 'id',

    nmTrimmed = internalPfx + 'trimmed',
    nmTextTrimmed = nmText + nmTrimmed,

    formatRegex = /-/g,
    trimRegex = /^\s+|\s+$/gm;

  function isArray(obj) {
    return toString.call(obj) === '[object Array]';
  }

  function nodeName(node) {
    return (node.localName) ? node.localName : node.baseName;
  }

  function trim(str) {
    return str.replace(trimRegex, '');
  }

  function format(name) {
    //change dash to underscore for ease of referencing literals
    return String(name).replace(formatRegex, '_');
  }

 function _get(obj, key) {
    return obj[format(key)];
  }

  function put(obj, key, value) {
    obj[format(key)] = value;
  }

  function selectorKey(key) {
    return selectorPfx + key;
  }

  function arrayKey(key) {
    return arrayPfx + key;
  }

  function internalKey(key) {
    return internalPfx + key;
  }

  function newObj(node) {
    var newObj = {
      toString: function() {
        return this[nmText];
      }
    };

    newObj[internalKey(nmNode)] = node;
    newObj[internalKey(nmNodeName)] = nodeName(node);
    newObj[internalKey(nmChildren)] = [];
    newObj[internalKey(nmAttributes)] = {};
    newObj[arrayKey(nmText)] = [];

    var selectorNmList = [nmAttribute, nmElement, nmClass, nmId];
    for (var i=0,l=selectorNmList.length; i < l; i++) {
      var selectorNm = selectorNmList[i];
      newObj[selectorKey(selectorNm)] = {};
    }

    return newObj;
  }

  function extendAttributes(node, obj) {
    var attrs = node.attributes;
    for (var i=0, l=attrs.length; i < l; i++) {
      var attr = attrs[i],
        attrName = attr.name,
        attrValue = attr.value;
      put(obj[arrayKey(nmAttributes)], attrName, attrValue);
      put(obj, attrName, attrValue);
    }
  }

  function extendByAttribute(node, cObj, obj) {
    var attrs = node.attributes;
    for (var i=0, l=attrs.length; i < l; i++) {
      var attr = attrs[i];
      if (attr.name !== nmText) { //dont override _text here
        pushToArrayAtKey(obj[selectorKey(nmAttribute)], attr.name, cObj);
      }
    }
  }

  function extendByClass(node, cObj, obj) {
    var klassAttr = node.attributes.getNamedItem(nmClass);
    if (klassAttr) {
      var klasses = klassAttr.value.split(' ');
      for (var i=0, l=klasses.length; i < l; i++) {
        var className = klasses[i];
        if (className !== nmText) { //dont override _text here
          pushToArrayAtKey(obj[selectorKey(nmClass)], className, cObj);
        }
      }
    }
  }

  function extendById(node, cObj, obj) {
    var idAttr = node.attributes.getNamedItem(nmId);
    if (idAttr) {
      var idValue = idAttr.value;
      if (idValue !== nmText) { //dont override _text here
        pushToArrayAtKey(obj[selectorKey(nmId)], idValue, cObj);
      }
    }
  }

  function extendByElement(node, cObj, obj) {
    var  _nodeName = nodeName(node);
    if (_nodeName !== nmText) {
      pushToArrayAtKey(obj[selectorKey(nmElement)], _nodeName, cObj);
    }
  }

  function pushIfAbsent(obj, arry) {
    var seen = false;
    for (var i=0, l=arry.length; i < l; i++) {
      var thisElem = arry[i];
      if (thisElem == obj) {
        seen = true;
        break;
      }
    }
    if (!seen) {
      arry.push(obj);
    }
  }

  function pushToArrayAtKey(obj, key, value, suppressDup) {
    var arryAtKey;
    if (!(arryAtKey = _get(obj, key))) {
      put(obj, key, arryAtKey = []);
    }

    if (!isArray(value)) {
      value = [value];
    }

    for (var i=0, l=value.length; i < l; i++) {
      var thisVal = value[i];
      suppressDup ?
        arryAtKey.push(thisVal) : pushIfAbsent(thisVal, arryAtKey);
    }
  }

  function flatIndexKey(key, index) {
    return arrayKey(key + arrayKey(index));
  }

  function expandToArrayIndices(obj, key, list) {
    for (var i=0, l=list.length; i < l; i++) {
      put(obj, flatIndexKey(key, i), list[i]);
    }
  }

  function extend(obj, selectorHashes) {
    for(var i=0, l=selectorHashes.length; i < l; i++) {
      var selectorHash = selectorHashes[i];
      for(key in selectorHash) {
        var cObjList = selectorHash[key];

        //handle special keys that should not be overridden
        //currently, just 'text'
        //to get the skipped value, use _text[0]
        if (key !== nmText) {
          put(obj, key, cObjList[0]);
        }

        pushToArrayAtKey(obj, arrayKey(key), cObjList);
        expandToArrayIndices(obj, key, cObjList);

        //also add each value to the overall children hash
        pushToArrayAtKey(obj, internalKey(nmChildren), cObjList);
      }
    }
  }

  function setTrimmed(str) {
    //trim any string {{#text}}{{_trimmed}}{{/text}}
    str[nmTrimmed] = trim(str);
  }

  function extendText(obj) {
    var texts = obj[arrayKey(nmText)],
        trimmedTexts = [];

    //concat the text nodes
    var buf = '';
    for(var i=0, l=texts.length; i<l; i++) {
      var str = texts[i];
      trimmedTexts.push(trim(str));
      buf += str;
    }
    obj[nmText] = buf;
    obj[nmTextTrimmed] = trim(buf);

    expandToArrayIndices(obj, nmText, texts);
    expandToArrayIndices(obj, nmTextTrimmed, trimmedTexts);
  }

  function setObjects(obj) {
    var node = obj[internalKey(nmNode)];
    if (node && node.hasChildNodes()) {
      var nodeCount = node.childNodes.length - 1;
      var n = 0;
      do {
        var cnode = node.childNodes[n];
        switch (cnode.nodeType) {
          case 1:
            var cObj = newObj(cnode);
            extendByAttribute(cnode, cObj, obj);
            extendByElement(cnode, cObj, obj);
            extendByClass(cnode, cObj, obj);
            extendById(cnode, cObj, obj);

            //recurse of the mummy
            if (cnode.hasChildNodes()) {
              setObjects(cObj, cnode);
            }
            break;
          case 3:
            pushToArrayAtKey(obj, arrayKey(nmText), cnode.nodeValue, true);
            break;
          case 4: //CDATA
            pushToArrayAtKey(obj, arrayKey(nmText), cnode.text ? cnode.text : cnode.nodeValue, true);
            break;
          }
      } while (n++ < nodeCount);
    }

    //after child nodes processed, add properties based on priority
    extend(obj,
     [obj[selectorKey(nmAttribute)],
      obj[selectorKey(nmElement)],
      obj[selectorKey(nmClass)],
      obj[selectorKey(nmId)]]);

    extendAttributes(node, obj);
    extendText(obj);

    return obj;
  }

  function domToJSON(xdoc) {
    return setObjects(newObj(xdoc));
  }

  function textToDocument(strXML) {
    var xmlDoc = (document.all) ? new ActiveXObject('Microsoft.XMLDOM') : new DOMParser();
    xmlDoc.async = false;

    if (document.all) {
      return (xmlDoc.loadXML(strXML)) ? xmlDoc : false;
    } else {
      return xmlDoc.parseFromString(strXML, 'text/xml');
    }
  }

  var _sideburn = function() {
    var sideburn = function(input) {
      if (typeof(input) === 'string') {
        input = textToDocument(input).documentElement;
      }
      return domToJSON(input);
    }
    sideburn.textToDocument = textToDocument;
    return sideburn;
  };

  //export to amd, commonjs, or context
  var exportToContext = true;

  if (typeof define === 'function' && define.amd) {
    define(_sideburn);
    exportToContext = false;
  }

  if ((typeof module !== strUndef) && module.exports) {
    module.exports = _sideburn(); //unwrap
    exportToContext = false;
  }

  if (exportToContext) {
    context.sideburn = _sideburn(); //unwrap
  }

})(this, document);
<commit_msg>Change define block to avoid r.js optimizer bug that can leave the module anonymous<commit_after>/*
 sideburn.js
 http://scrappit.org/sideburn
 MIT License
 Author: Josh Dzielak, Copyright (c) 2011

 Convert HTML to mustache-friendly JSON.

 Given this DOM:

sideburn

  sideburn.js produces a superset of this JSON object structure:

  {
    div : {
      img : { src : 'foo.png' },
      text : 'sideburn'
    }
  }

 To maximize the Child nodes are reachable from their parent by
 attribute names, element names, classes, or ID.

 */
(function(context, document) {

  var version = '0.1.0+',
    undef = undefined,
    strUndef = '' + undef,
    toString = Object.prototype.toString,

    //used to generate property names
    pfx = '_',

    //used for internal/private property names: _children
    internalPfx = pfx,

    //used for array property names: _span
    arrayPfx = pfx,

    //used for internal arrays that add elements by selector type: _by_id
    selectorPfx = internalPfx + 'by' + internalPfx,

    nmAttributes = 'attributes',
    nmChildren = 'children',

    nmNode = 'node',
    nmNodeName = 'node_name',

    //the five sources of properties
    nmText = 'text',
    nmAttribute = 'attribute',
    nmElement = 'element',
    nmClass = 'class',
    nmId = 'id',

    nmTrimmed = internalPfx + 'trimmed',
    nmTextTrimmed = nmText + nmTrimmed,

    formatRegex = /-/g,
    trimRegex = /^\s+|\s+$/gm;

  function isArray(obj) {
    return toString.call(obj) === '[object Array]';
  }

  function nodeName(node) {
    return (node.localName) ? node.localName : node.baseName;
  }

  function trim(str) {
    return str.replace(trimRegex, '');
  }

  function format(name) {
    //change dash to underscore for ease of referencing literals
    return String(name).replace(formatRegex, '_');
  }

 function _get(obj, key) {
    return obj[format(key)];
  }

  function put(obj, key, value) {
    obj[format(key)] = value;
  }

  function selectorKey(key) {
    return selectorPfx + key;
  }

  function arrayKey(key) {
    return arrayPfx + key;
  }

  function internalKey(key) {
    return internalPfx + key;
  }

  function newObj(node) {
    var newObj = {
      toString: function() {
        return this[nmText];
      }
    };

    newObj[internalKey(nmNode)] = node;
    newObj[internalKey(nmNodeName)] = nodeName(node);
    newObj[internalKey(nmChildren)] = [];
    newObj[internalKey(nmAttributes)] = {};
    newObj[arrayKey(nmText)] = [];

    var selectorNmList = [nmAttribute, nmElement, nmClass, nmId];
    for (var i=0,l=selectorNmList.length; i < l; i++) {
      var selectorNm = selectorNmList[i];
      newObj[selectorKey(selectorNm)] = {};
    }

    return newObj;
  }

  function extendAttributes(node, obj) {
    var attrs = node.attributes;
    for (var i=0, l=attrs.length; i < l; i++) {
      var attr = attrs[i],
        attrName = attr.name,
        attrValue = attr.value;
      put(obj[arrayKey(nmAttributes)], attrName, attrValue);
      put(obj, attrName, attrValue);
    }
  }

  function extendByAttribute(node, cObj, obj) {
    var attrs = node.attributes;
    for (var i=0, l=attrs.length; i < l; i++) {
      var attr = attrs[i];
      if (attr.name !== nmText) { //dont override _text here
        pushToArrayAtKey(obj[selectorKey(nmAttribute)], attr.name, cObj);
      }
    }
  }

  function extendByClass(node, cObj, obj) {
    var klassAttr = node.attributes.getNamedItem(nmClass);
    if (klassAttr) {
      var klasses = klassAttr.value.split(' ');
      for (var i=0, l=klasses.length; i < l; i++) {
        var className = klasses[i];
        if (className !== nmText) { //dont override _text here
          pushToArrayAtKey(obj[selectorKey(nmClass)], className, cObj);
        }
      }
    }
  }

  function extendById(node, cObj, obj) {
    var idAttr = node.attributes.getNamedItem(nmId);
    if (idAttr) {
      var idValue = idAttr.value;
      if (idValue !== nmText) { //dont override _text here
        pushToArrayAtKey(obj[selectorKey(nmId)], idValue, cObj);
      }
    }
  }

  function extendByElement(node, cObj, obj) {
    var  _nodeName = nodeName(node);
    if (_nodeName !== nmText) {
      pushToArrayAtKey(obj[selectorKey(nmElement)], _nodeName, cObj);
    }
  }

  function pushIfAbsent(obj, arry) {
    var seen = false;
    for (var i=0, l=arry.length; i < l; i++) {
      var thisElem = arry[i];
      if (thisElem == obj) {
        seen = true;
        break;
      }
    }
    if (!seen) {
      arry.push(obj);
    }
  }

  function pushToArrayAtKey(obj, key, value, suppressDup) {
    var arryAtKey;
    if (!(arryAtKey = _get(obj, key))) {
      put(obj, key, arryAtKey = []);
    }

    if (!isArray(value)) {
      value = [value];
    }

    for (var i=0, l=value.length; i < l; i++) {
      var thisVal = value[i];
      suppressDup ?
        arryAtKey.push(thisVal) : pushIfAbsent(thisVal, arryAtKey);
    }
  }

  function flatIndexKey(key, index) {
    return arrayKey(key + arrayKey(index));
  }

  function expandToArrayIndices(obj, key, list) {
    for (var i=0, l=list.length; i < l; i++) {
      put(obj, flatIndexKey(key, i), list[i]);
    }
  }

  function extend(obj, selectorHashes) {
    for(var i=0, l=selectorHashes.length; i < l; i++) {
      var selectorHash = selectorHashes[i];
      for(key in selectorHash) {
        var cObjList = selectorHash[key];

        //handle special keys that should not be overridden
        //currently, just 'text'
        //to get the skipped value, use _text[0]
        if (key !== nmText) {
          put(obj, key, cObjList[0]);
        }

        pushToArrayAtKey(obj, arrayKey(key), cObjList);
        expandToArrayIndices(obj, key, cObjList);

        //also add each value to the overall children hash
        pushToArrayAtKey(obj, internalKey(nmChildren), cObjList);
      }
    }
  }

  function setTrimmed(str) {
    //trim any string {{#text}}{{_trimmed}}{{/text}}
    str[nmTrimmed] = trim(str);
  }

  function extendText(obj) {
    var texts = obj[arrayKey(nmText)],
        trimmedTexts = [];

    //concat the text nodes
    var buf = '';
    for(var i=0, l=texts.length; i<l; i++) {
      var str = texts[i];
      trimmedTexts.push(trim(str));
      buf += str;
    }
    obj[nmText] = buf;
    obj[nmTextTrimmed] = trim(buf);

    expandToArrayIndices(obj, nmText, texts);
    expandToArrayIndices(obj, nmTextTrimmed, trimmedTexts);
  }

  function setObjects(obj) {
    var node = obj[internalKey(nmNode)];
    if (node && node.hasChildNodes()) {
      var nodeCount = node.childNodes.length - 1;
      var n = 0;
      do {
        var cnode = node.childNodes[n];
        switch (cnode.nodeType) {
          case 1:
            var cObj = newObj(cnode);
            extendByAttribute(cnode, cObj, obj);
            extendByElement(cnode, cObj, obj);
            extendByClass(cnode, cObj, obj);
            extendById(cnode, cObj, obj);

            //recurse of the mummy
            if (cnode.hasChildNodes()) {
              setObjects(cObj, cnode);
            }
            break;
          case 3:
            pushToArrayAtKey(obj, arrayKey(nmText), cnode.nodeValue, true);
            break;
          case 4: //CDATA
            pushToArrayAtKey(obj, arrayKey(nmText), cnode.text ? cnode.text : cnode.nodeValue, true);
            break;
          }
      } while (n++ < nodeCount);
    }

    //after child nodes processed, add properties based on priority
    extend(obj,
     [obj[selectorKey(nmAttribute)],
      obj[selectorKey(nmElement)],
      obj[selectorKey(nmClass)],
      obj[selectorKey(nmId)]]);

    extendAttributes(node, obj);
    extendText(obj);

    return obj;
  }

  function domToJSON(xdoc) {
    return setObjects(newObj(xdoc));
  }

  function textToDocument(strXML) {
    var xmlDoc = (document.all) ? new ActiveXObject('Microsoft.XMLDOM') : new DOMParser();
    xmlDoc.async = false;

    if (document.all) {
      return (xmlDoc.loadXML(strXML)) ? xmlDoc : false;
    } else {
      return xmlDoc.parseFromString(strXML, 'text/xml');
    }
  }

  var _sideburn = function() {
    var sideburn = function(input) {
      if (typeof(input) === 'string') {
        input = textToDocument(input).documentElement;
      }
      return domToJSON(input);
    }
    sideburn.textToDocument = textToDocument;
    return sideburn;
  };

  //export to amd, commonjs, or context
  var exportToContext = true;

  if (typeof define === 'function' && define.amd) {
    define([], _sideburn);
    exportToContext = false;
  }

  if ((typeof module !== strUndef) && module.exports) {
    module.exports = _sideburn(); //unwrap
    exportToContext = false;
  }

  if (exportToContext) {
    context.sideburn = _sideburn(); //unwrap
  }

})(this, document);
<|endoftext|>


<commit_before>(function ( root, factory ) {
  'use strict';
  if ( typeof define === 'function' && define.amd ) {
    define( factory );
  } else if( typeof module === 'object' && module.exports ) {
    module.exports = ( root.simplate = factory() );
  } else {
    root.simplate = factory();
  }
}( this, function() {

  'use strict';

  var cache = [];  /* Stores templates */

  /************
   * setTemplate ( string, string );
  ************/
  function setTemplate( name, data ) {
    if ( ! hasTemplate( name ) ) { cache[ name ] = data; return true; } else { return false; }
  }

  /************
   * getTemplate ( string [, array/object ] );
  ************/
  function getTemplate( name , data ){
    var tmpl =  (name.indexOf('#') === 0 ) ?
                getDomElement( name ) :
                ( cache[name] || false );

    return ( data && parseTemplate( tmpl, data ) ) || tmpl;
  }

  function getDomElement( name ) {
    name = name.replace('#','') + '';
    if ( document && name ) {
      return document.getElementById( name ).innerText;
    }
    return false;
  }

  /************
  * hasTemplate ( string );
  ************/
  function hasTemplate( name ) {
    return !!( cache[ name ] );
  }

  /************
   * parseTemplate ( string [, array/object ] );
  ************/
  function parseTemplate( template, data ) {
    var i = 0, len, str='';
    if ( data.constructor === Array ) {
      len = data.length;
      for(; i < len; i++){
        str += replaceValues( template, data[i] );
      }
    } else {
      str = replaceValues( template, data );
    }
    return str;
  }

  /************
   * replaceValues ( string , object );
  ************/
  function replaceValues( template, data ) {
    if ( template ){
      return template.replace(/{{([a-z_]+[a-z0-9_]*)}}/gi, function( tag, val ) {
        return  data[ val ] ? data[ val ]  : '{{'+val+'}}';
      });
    } else {
      return '';
    }
  }

  return {
    get : getTemplate,
    set : setTemplate,
    has : hasTemplate
  };

}));
<commit_msg>Updated to v0.4.0<commit_after>(function ( root, factory ) {
  'use strict';
  if ( typeof define === 'function' && define.amd ) {
    define( factory );
  } else if( typeof module === 'object' && module.exports ) {
    module.exports = ( root.simplate = factory() );
  } else {
    root.simplate = factory();
  }
}( this, function() {

  'use strict';

  var cache = [];  /* Stores templates */

  /************
   * setTemplate ( string, string );
  ************/
  function setTemplate( name, data ) {
    if ( ! hasTemplate( name ) ) { cache[ name ] = data; return data; } else { return false; }
  }

  /************
   * getTemplate ( string [, array/object ] );
  ************/
  function getTemplate( name , data ){
    var tmpl =  (name.indexOf('#') === 0 ) ?
                getDomElement( name ) :
                ( cache[name] || false );

    return ( data && parseTemplate( tmpl, data ) ) || tmpl;
  }

  function getDomElement( name ) {
    name = name.replace('#','') + '';
    if ( document && name ) {
      return document.getElementById( name ).innerText;
    }
    return false;
  }

  /************
  * hasTemplate ( string );
  ************/
  function hasTemplate( name ) {
    return !!( cache[ name ] );
  }

  /************
   * parseTemplate ( string [, array/object ] );
  ************/
  function parseTemplate( template, data ) {
    var i = 0, len, str='';
    if ( data.constructor === Array ) {
      len = data.length;
      for(; i < len; i++){
        str += replaceValues( template, data[i] );
      }
    } else {
      str = replaceValues( template, data );
    }
    return str;
  }

  /************
   * replaceValues ( string , object );
  ************/
  function replaceValues( template, data ) {
    if ( template ){
      return template.replace(/{{([a-z_]+[a-z0-9_]*)}}/gi, function( tag, val ) {
        return  data[ val ] ? data[ val ]  : '{{'+val+'}}';
      });
    } else {
      return '';
    }
  }

  return {
    get : getTemplate,
    set : setTemplate,
    has : hasTemplate
  };

}));
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.

var fs = require('fs'),
    cordovaServe = require('cordova-serve'),
    path = require('path'),
    config = require('./server/config'),
    log = require('./server/log'),
    simServer = require('./server/server'),
    simSocket = require('./server/socket'),
    dirs = require('./server/dirs');

var server = cordovaServe();

var launchServer = function (opts) {
    opts = opts || {};

    var platform = opts.platform || 'browser';
    var appUrl, simHostUrl, simHostOpts;

    if (opts.simhostui && fs.existsSync(opts.simhostui)) {
        simHostOpts = { simHostRoot: opts.simhostui };
    } else {
        /* use the default simulation UI */
        simHostOpts = { simHostRoot: path.join(__dirname, 'sim-host', 'ui') };
    }

    config.platform = platform;
    config.simHostOptions = simHostOpts;
    config.telemetry = opts.telemetry;
    config.liveReload = opts.hasOwnProperty('livereload') ? !!opts.livereload : true;
    config.forcePrepare = !!opts.forceprepare;
    config.xhrProxy = opts.hasOwnProperty('corsproxy') ? !!opts.corsproxy : true;
    config.touchEvents = opts.hasOwnProperty('touchevents') ? !!opts.touchevents : true;

    /* attach simulation host middleware */
    var middlewarePath = path.join(simHostOpts.simHostRoot, 'server', 'server');
    if (fs.existsSync(middlewarePath + '.js')) {
        require(middlewarePath).attach(server.app, dirs);
    }

    /* attach CORS proxy middleware */
    if (config.xhrProxy) {
        require('./server/xhr-proxy').attach(server.app);
    }

    simServer.attach(server.app);

    return server.servePlatform(platform, {
        port: opts.port,
        root: opts.dir,
        noServerInfo: true
    }).then(function () {
        simSocket.init(server.server);
        config.server = server.server;
        var projectRoot = server.projectRoot;
        config.projectRoot = projectRoot;
        configureSimulationDirectory(config.projectRoot, opts);
        config.platformRoot = server.root;
        var urlRoot = 'http://localhost:' + server.port + '/';
        appUrl = urlRoot + parseStartPage(projectRoot);
        simHostUrl = urlRoot + 'simulator/index.html';
        log.log('Server started:\n- App running at: ' + appUrl + '\n- Sim host running at: ' + simHostUrl);
        return { urlRoot: urlRoot, appUrl: appUrl, simHostUrl: simHostUrl };
    });
};

var closeServer = function () {
    return server.server && server.server.close();
};

var launchBrowser = function (target, url) {
    return cordovaServe.launchBrowser({ target: target, url: url });
};

var simulate = function (opts) {
    var target = opts.target || 'chrome';
    var simHostUrl;

    return launchServer(opts)
        .then(function (urls) {
            simHostUrl = urls.simHostUrl;
            return launchBrowser(target, urls.appUrl);
        }).then(function () {
            return launchBrowser(target, simHostUrl);
        }).catch(function (error) {
            // Ensure server is closed, then rethrow so it can be handled by downstream consumers.
            closeServer();
            if (error instanceof Error) {
                throw error;
            } else {
                throw new Error(error);
            }
        });
};

var parseStartPage = function (projectRoot) {
    // Start Page is defined as <content src="some_uri" /> in config.xml
    var configFile = path.join(projectRoot, 'config.xml');
    if (!fs.existsSync(configFile)) {
        throw new Error('Cannot find project config file: ' + configFile);
    }

    var startPageRegexp = /<content\s+src\s*=\s*"(.+)"\s*\/>/ig,
        configFileContent = fs.readFileSync(configFile);

    var match = startPageRegexp.exec(configFileContent);
    if (match) {
        return match[1];
    }

    return 'index.html'; // default uri
};

/**
 *  Helper function to check if a file or directory exists
 */
var existsSync = function (filename) {
    try {
        /* fs.existsSync is deprecated
           fs.statSync throws if the path does not exists */
        fs.statSync(filename);
        return true;
    } catch (error) {
        return false;
    }
};

/**
 *  Helper function to create a directory recursively
 */
var makeDirectoryRecursiveSync = function (dirPath) {
    var parentPath = path.dirname(dirPath);
    if (!existsSync(parentPath) && (parentPath !== dirPath)) {
        makeDirectoryRecursiveSync(parentPath);
    }

    fs.mkdirSync(dirPath);
};

var configureSimulationDirectory = function (projectRoot, opts) {
    var simPath = opts.simulationpath || path.join(config.projectRoot, 'simulation');
    config.simulationFilePath = path.resolve(simPath);

    if (!fs.existsSync(config.simulationFilePath)) {
        makeDirectoryRecursiveSync(config.simulationFilePath);
    }
};

module.exports = simulate;
module.exports.launchBrowser = launchBrowser;
module.exports.launchServer = launchServer;
module.exports.closeServer = closeServer;
module.exports.dirs = dirs;
module.exports.app = server.app;
module.exports.log = log;
<commit_msg>Export stopSimulate.<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.

var fs = require('fs'),
    cordovaServe = require('cordova-serve'),
    path = require('path'),
    config = require('./server/config'),
    log = require('./server/log'),
    simServer = require('./server/server'),
    simSocket = require('./server/socket'),
    dirs = require('./server/dirs');

var server = cordovaServe();

var launchServer = function (opts) {
    opts = opts || {};

    var platform = opts.platform || 'browser';
    var appUrl, simHostUrl, simHostOpts;

    if (opts.simhostui && fs.existsSync(opts.simhostui)) {
        simHostOpts = { simHostRoot: opts.simhostui };
    } else {
        /* use the default simulation UI */
        simHostOpts = { simHostRoot: path.join(__dirname, 'sim-host', 'ui') };
    }

    config.platform = platform;
    config.simHostOptions = simHostOpts;
    config.telemetry = opts.telemetry;
    config.liveReload = opts.hasOwnProperty('livereload') ? !!opts.livereload : true;
    config.forcePrepare = !!opts.forceprepare;
    config.xhrProxy = opts.hasOwnProperty('corsproxy') ? !!opts.corsproxy : true;
    config.touchEvents = opts.hasOwnProperty('touchevents') ? !!opts.touchevents : true;

    /* attach simulation host middleware */
    var middlewarePath = path.join(simHostOpts.simHostRoot, 'server', 'server');
    if (fs.existsSync(middlewarePath + '.js')) {
        require(middlewarePath).attach(server.app, dirs);
    }

    /* attach CORS proxy middleware */
    if (config.xhrProxy) {
        require('./server/xhr-proxy').attach(server.app);
    }

    simServer.attach(server.app);

    return server.servePlatform(platform, {
        port: opts.port,
        root: opts.dir,
        noServerInfo: true
    }).then(function () {
        simSocket.init(server.server);
        config.server = server.server;
        var projectRoot = server.projectRoot;
        config.projectRoot = projectRoot;
        configureSimulationDirectory(config.projectRoot, opts);
        config.platformRoot = server.root;
        var urlRoot = 'http://localhost:' + server.port + '/';
        appUrl = urlRoot + parseStartPage(projectRoot);
        simHostUrl = urlRoot + 'simulator/index.html';
        log.log('Server started:\n- App running at: ' + appUrl + '\n- Sim host running at: ' + simHostUrl);
        return { urlRoot: urlRoot, appUrl: appUrl, simHostUrl: simHostUrl };
    });
};

var closeServer = function () {
    return server.server && server.server.close();
};

var stopSimulate = function () {
    return simServer.stop();
};

var launchBrowser = function (target, url) {
    return cordovaServe.launchBrowser({ target: target, url: url });
};

var simulate = function (opts) {
    var target = opts.target || 'chrome';
    var simHostUrl;

    return launchServer(opts)
        .then(function (urls) {
            simHostUrl = urls.simHostUrl;
            return launchBrowser(target, urls.appUrl);
        }).then(function () {
            return launchBrowser(target, simHostUrl);
        }).catch(function (error) {
            // Ensure server is closed, then rethrow so it can be handled by downstream consumers.
            closeServer();
            if (error instanceof Error) {
                throw error;
            } else {
                throw new Error(error);
            }
        });
};

var parseStartPage = function (projectRoot) {
    // Start Page is defined as <content src="some_uri" /> in config.xml
    var configFile = path.join(projectRoot, 'config.xml');
    if (!fs.existsSync(configFile)) {
        throw new Error('Cannot find project config file: ' + configFile);
    }

    var startPageRegexp = /<content\s+src\s*=\s*"(.+)"\s*\/>/ig,
        configFileContent = fs.readFileSync(configFile);

    var match = startPageRegexp.exec(configFileContent);
    if (match) {
        return match[1];
    }

    return 'index.html'; // default uri
};

/**
 *  Helper function to check if a file or directory exists
 */
var existsSync = function (filename) {
    try {
        /* fs.existsSync is deprecated
           fs.statSync throws if the path does not exists */
        fs.statSync(filename);
        return true;
    } catch (error) {
        return false;
    }
};

/**
 *  Helper function to create a directory recursively
 */
var makeDirectoryRecursiveSync = function (dirPath) {
    var parentPath = path.dirname(dirPath);
    if (!existsSync(parentPath) && (parentPath !== dirPath)) {
        makeDirectoryRecursiveSync(parentPath);
    }

    fs.mkdirSync(dirPath);
};

var configureSimulationDirectory = function (projectRoot, opts) {
    var simPath = opts.simulationpath || path.join(config.projectRoot, 'simulation');
    config.simulationFilePath = path.resolve(simPath);

    if (!fs.existsSync(config.simulationFilePath)) {
        makeDirectoryRecursiveSync(config.simulationFilePath);
    }
};

module.exports = simulate;
module.exports.launchBrowser = launchBrowser;
module.exports.launchServer = launchServer;
module.exports.closeServer = closeServer;
module.exports.stopSimulate = stopSimulate;
module.exports.dirs = dirs;
module.exports.app = server.app;
module.exports.log = log;
<|endoftext|>


<commit_before>var cumulativeOffset = function(element) {
  var top = 0, left = 0;
  do {
    top  += element.offsetTop  || 0;
    left += element.offsetLeft || 0;
  } while (element = element.offsetParent);
  return {left: left, top: top};
};

var stopEvent = function(e) {
  e.preventDefault();
  e.stopPropagation();
};

var ColorConverter = {
  HSV2RGB: function(h, s, v, a) {
    if (h + 0.0000000001 >= 1) {h = 0}
    h *= 6;

    var i = parseInt(h, 10),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - s * f),
        t = v * (1 - s * (1 - f)),
        r, g, b;

    switch (i) {
        case 0: r=v; g=t; b=p; break;
        case 1: r=q; g=v; b=p; break;
        case 2: r=p; g=v; b=t; break;
        case 3: r=p; g=q; b=v; break;
        case 4: r=t; g=p; b=v; break;
        case 5: r=v; g=p; b=q; break;
    }

    return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a && (Math.round(a * 100) / 100));
  },

  HSV2RGBString: function(h, s, v, a) {
    return this.HSV2RGB(h, s, v, a).toString();
  },

  RGB2HSV: function(rgb) {
    var r = rgb.r, g = rgb.g, b = rgb.b, a = rgb.a;

    var max   = Math.max(r, g, b),
        min   = Math.min(r, g, b),
        delta = max - min,
        s     = (max === 0) ? 0 : 1-(min/max),
        v     = max, h;

    switch (max) {
       case min: h=0; break;
       case r:   h=(g-b)/delta;
                 if (g<b) {h+=6}
                 break;
       case g:   h=2+(b-r)/delta; break;
       case b:   h=4+(r-g)/delta; break;
    }

    return {h: h / 6, s: s, v: v / 255, a: a};
  }
};

var ColorPicker = function(element, color, callback) {
  this.document = element.ownerDocument;
  this.setupSB(element.querySelector('div.saturation_brightness'));
  this.setupOpacity(element.querySelector('div.opacity'));
  this.setupHue(element.querySelector('div.hue'));
  this.setupBounds();
  this.setupObservers();
  this.callback = callback;
  this.setColor(color);
};

ColorPicker.prototype = {
  dispose: function() {
    this.sbPicker.removeEventListener('mousedown', this.sbMousedown);
    this.huePicker.removeEventListener('mousedown', this.hueMousedown);
    var body = this.document.body;
    body.removeEventListener('mousemove', this.mouseMove);
    body.removeEventListener('mouseup', this.mouseUp);
    body.removeEventListener('mousedown', this.bodyMouseDown);
  },

  setupSB: function(sbElement) {
    this.sbPicker     = sbElement;
    sbElement.borders = this.getBorderWidths(sbElement);
    this.sbHandle     = sbElement.querySelector('img');
    this.sbWidth      = sbElement.offsetWidth  - sbElement.borders.left - sbElement.borders.right;
    this.sbHeight     = sbElement.offsetHeight - sbElement.borders.top  - sbElement.borders.bottom;
  },

  setupOpacity: function(opacityElement) {
    this.opacityPicker     = opacityElement;
    opacityElement.borders = this.getBorderWidths(opacityElement);
    this.opacityHandle     = opacityElement.querySelector('img');
    this.opacityWidth      = opacityElement.offsetWidth  - opacityElement.borders.left - opacityElement.borders.right;
  },

  getBorderWidths: function(el) {
    var borders = {}, borderTypes = ['top', 'right', 'bottom', 'left'], borderType, borderCSSName;
    for (var i = 0; borderType = borderTypes[i++];) {
      borderCSSName = 'border' + borderType.charAt(0).toUpperCase() + borderType.substring(1) + 'Width';
      borders[borderType] = parseInt(el.style[borderCSSName] || document.defaultView.getComputedStyle(el, null)[borderCSSName], 10);
    }
    return borders;
  },

  setupHue: function(hueElement) {
    this.huePicker     = hueElement;
    hueElement.borders = this.getBorderWidths(hueElement);
    this.hueHandle     = hueElement.querySelector('img');
    this.hueHeight     = hueElement.offsetHeight - hueElement.borders.top - hueElement.borders.bottom;
  },

  setupBounds: function() {
    var methodsToBind = ['sbMousedown', 'opacityMousedown', 'hueMousedown', 'mouseMove', 'mouseUp', 'browserMouseUp'], i = methodsToBind.length;
    while(i--) { this[methodsToBind[i]] = bind(this[methodsToBind[i]], this); }
  },

  setupObservers: function() {
    this.sbPicker.addEventListener('mousedown', this.sbMousedown, false);
    this.opacityPicker.addEventListener('mousedown', this.opacityMousedown, false);
    this.huePicker.addEventListener('mousedown', this.hueMousedown, false);
    var body = this.document.body;
    body.addEventListener('mousemove', this.mouseMove, false);
    body.addEventListener('mouseup', this.mouseUp, false);
    body.addEventListener('mousedown', this.bodyMouseDown, false);
  },

  popUpOpened: function() {
    globalDocument.addEventListener('mouseup', this.browserMouseUp, false);
  },

  popUpClosed: function() {
    globalDocument.removeEventListener('mouseup', this.browserMouseUp, false);
  },

  cumulativeOffsetWithBorders: function(element) {
    var offset = cumulativeOffset(element);
    return {top: offset.top + element.borders.top, left: offset.left + element.borders.left};
  },

  sbMousedown: function(e) {
    this.sbDrag = true;
    this.offset = this.cumulativeOffsetWithBorders(this.sbPicker);
    this.mouseMove(e);
  },

  opacityMousedown: function(e) {
    this.opacityDrag = true;
    this.offset = this.cumulativeOffsetWithBorders(this.opacityPicker);
    this.mouseMove(e);
  },

  hueMousedown: function(e) {
    this.hueDrag = true;
    this.offset  = this.cumulativeOffsetWithBorders(this.huePicker);
    this.mouseMove(e);
  },

  mouseMove: function(e) {
    if (this.sbDrag) {
      stopEvent(e);
      this.setSbPicker(e.pageY - this.offset.top, e.pageX - this.offset.left);
      this.colorChanged();
    } else if (this.opacityDrag) {
      stopEvent(e);
      this.setOpacity(e.pageX - this.offset.left);
      this.colorChanged();
    } else if (this.hueDrag) {
      stopEvent(e);
      this.setHue(e.pageY - this.offset.top);
      this.colorChanged();
    }
  },

  mouseUp: function(e) {
    this.mouseMove(e);
    this.notDragging();
  },

  notDragging: function() {
    this.sbDrag = this.hueDrag = this.opacityDrag = false;
  },

  browserMouseUp: function() {
    this.notDragging();
  },

  bodyMouseDown: function(e) {
    // stop user from accidentally doing mouse selection (dragger IMG elements are selectable and look ugly when in selection)
    e.preventDefault();
  },

  setColor: function(rgb) {
    var hsv = ColorConverter.RGB2HSV(rgb);
    this.setHue(Math.round(Math.abs(1 - hsv.h) * this.hueHeight));
    this.setSbPicker(this.sbHeight - Math.round(hsv.v * this.sbHeight), Math.round(hsv.s * this.sbWidth));
    this.setOpacity(Math.round(rgb.a * this.opacityWidth));
  },

  setHue: function(top) {
    top    = this.makeWithin(top, 0, this.hueHeight);
    this.h = (this.hueHeight - top) / this.hueHeight;
    this.hueHandle.style.top            = top + 'px';

    this.updateSbPickerColor();
    this.updateOpacityPickerColor();
  },

  updateSbPickerColor: function() {
    this.sbPicker.style.backgroundColor = ColorConverter.HSV2RGBString(this.h, 1, 1);
  },

  updateOpacityPickerColor: function() {
    var startColor = ColorConverter.HSV2RGBString(this.h, this.s, this.v, 0);
    var endColor   = ColorConverter.HSV2RGBString(this.h, this.s, this.v, 1);
    this.opacityPicker.style.backgroundImage = '-moz-linear-gradient(0deg, ' + startColor + ', ' + endColor + '), url("chrome://firepicker/skin/checkboard.png")';
  },

  setOpacity: function(left) {
    left = this.makeWithin(left, 0, this.opacityWidth);
    this.a = left / this.opacityWidth;
    this.opacityHandle.style.left = left + 'px';
  },

  setSbPicker: function(top, left) {
    top  = this.makeWithin(top,  0, this.sbHeight);
    left = this.makeWithin(left, 0, this.sbWidth);
    this.v = (this.sbHeight - top) / this.sbHeight;
    this.s = left / this.sbWidth;
    this.sbHandle.style.top  = top  + 'px';
    this.sbHandle.style.left = left + 'px';

    this.updateOpacityPickerColor();
  },

  colorChanged: function() {
    this.callback(this.getRGBColor());
  },

  getRGBColor: function() {
    return ColorConverter.HSV2RGB(this.h, this.s, this.v, this.a);
  },

  makeWithin: function(val, min, max) {
    return val < min ? min : (val > max ? max : val);
  }
};

document.expose = function(values) {
  for (var valueName in values) {
    window[valueName] = values[valueName];
  }
};

document.initColorPicker = function(color, callback) {
  if (!window.colorPicker) {
    colorPicker = new ColorPicker(document.getElementById('picker'), color, callback);
  } else {
    colorPicker.callback = callback;
    colorPicker.setColor(color);
  }
  colorPicker.popUpOpened();
};

document.popUpClosed = function() {
  if (window.colorPicker) { colorPicker.popUpClosed(); }
};<commit_msg>Whacky whitespace.<commit_after>var cumulativeOffset = function(element) {
  var top = 0, left = 0;
  do {
    top  += element.offsetTop  || 0;
    left += element.offsetLeft || 0;
  } while (element = element.offsetParent);
  return {left: left, top: top};
};

var stopEvent = function(e) {
  e.preventDefault();
  e.stopPropagation();
};

var ColorConverter = {
  HSV2RGB: function(h, s, v, a) {
    if (h + 0.0000000001 >= 1) {h = 0}
    h *= 6;

    var i = parseInt(h, 10),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - s * f),
        t = v * (1 - s * (1 - f)),
        r, g, b;

    switch (i) {
        case 0: r=v; g=t; b=p; break;
        case 1: r=q; g=v; b=p; break;
        case 2: r=p; g=v; b=t; break;
        case 3: r=p; g=q; b=v; break;
        case 4: r=t; g=p; b=v; break;
        case 5: r=v; g=p; b=q; break;
    }

    return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a && (Math.round(a * 100) / 100));
  },

  HSV2RGBString: function(h, s, v, a) {
    return this.HSV2RGB(h, s, v, a).toString();
  },

  RGB2HSV: function(rgb) {
    var r = rgb.r, g = rgb.g, b = rgb.b, a = rgb.a;

    var max   = Math.max(r, g, b),
        min   = Math.min(r, g, b),
        delta = max - min,
        s     = (max === 0) ? 0 : 1-(min/max),
        v     = max, h;

    switch (max) {
       case min: h=0; break;
       case r:   h=(g-b)/delta;
                 if (g<b) {h+=6}
                 break;
       case g:   h=2+(b-r)/delta; break;
       case b:   h=4+(r-g)/delta; break;
    }

    return {h: h / 6, s: s, v: v / 255, a: a};
  }
};

var ColorPicker = function(element, color, callback) {
  this.document = element.ownerDocument;
  this.setupSB(element.querySelector('div.saturation_brightness'));
  this.setupOpacity(element.querySelector('div.opacity'));
  this.setupHue(element.querySelector('div.hue'));
  this.setupBounds();
  this.setupObservers();
  this.callback = callback;
  this.setColor(color);
};

ColorPicker.prototype = {
  dispose: function() {
    this.sbPicker.removeEventListener('mousedown', this.sbMousedown);
    this.huePicker.removeEventListener('mousedown', this.hueMousedown);
    var body = this.document.body;
    body.removeEventListener('mousemove', this.mouseMove);
    body.removeEventListener('mouseup', this.mouseUp);
    body.removeEventListener('mousedown', this.bodyMouseDown);
  },

  setupSB: function(sbElement) {
    this.sbPicker     = sbElement;
    sbElement.borders = this.getBorderWidths(sbElement);
    this.sbHandle     = sbElement.querySelector('img');
    this.sbWidth      = sbElement.offsetWidth  - sbElement.borders.left - sbElement.borders.right;
    this.sbHeight     = sbElement.offsetHeight - sbElement.borders.top  - sbElement.borders.bottom;
  },

  setupOpacity: function(opacityElement) {
    this.opacityPicker     = opacityElement;
    opacityElement.borders = this.getBorderWidths(opacityElement);
    this.opacityHandle     = opacityElement.querySelector('img');
    this.opacityWidth      = opacityElement.offsetWidth  - opacityElement.borders.left - opacityElement.borders.right;
  },

  getBorderWidths: function(el) {
    var borders = {}, borderTypes = ['top', 'right', 'bottom', 'left'], borderType, borderCSSName;
    for (var i = 0; borderType = borderTypes[i++];) {
      borderCSSName = 'border' + borderType.charAt(0).toUpperCase() + borderType.substring(1) + 'Width';
      borders[borderType] = parseInt(el.style[borderCSSName] || document.defaultView.getComputedStyle(el, null)[borderCSSName], 10);
    }
    return borders;
  },

  setupHue: function(hueElement) {
    this.huePicker     = hueElement;
    hueElement.borders = this.getBorderWidths(hueElement);
    this.hueHandle     = hueElement.querySelector('img');
    this.hueHeight     = hueElement.offsetHeight - hueElement.borders.top - hueElement.borders.bottom;
  },

  setupBounds: function() {
    var methodsToBind = ['sbMousedown', 'opacityMousedown', 'hueMousedown', 'mouseMove', 'mouseUp', 'browserMouseUp'], i = methodsToBind.length;
    while(i--) { this[methodsToBind[i]] = bind(this[methodsToBind[i]], this); }
  },

  setupObservers: function() {
    this.sbPicker.addEventListener('mousedown', this.sbMousedown, false);
    this.opacityPicker.addEventListener('mousedown', this.opacityMousedown, false);
    this.huePicker.addEventListener('mousedown', this.hueMousedown, false);
    var body = this.document.body;
    body.addEventListener('mousemove', this.mouseMove, false);
    body.addEventListener('mouseup', this.mouseUp, false);
    body.addEventListener('mousedown', this.bodyMouseDown, false);
  },

  popUpOpened: function() {
    globalDocument.addEventListener('mouseup', this.browserMouseUp, false);
  },

  popUpClosed: function() {
    globalDocument.removeEventListener('mouseup', this.browserMouseUp, false);
  },

  cumulativeOffsetWithBorders: function(element) {
    var offset = cumulativeOffset(element);
    return {top: offset.top + element.borders.top, left: offset.left + element.borders.left};
  },

  sbMousedown: function(e) {
    this.sbDrag = true;
    this.offset = this.cumulativeOffsetWithBorders(this.sbPicker);
    this.mouseMove(e);
  },

  opacityMousedown: function(e) {
    this.opacityDrag = true;
    this.offset = this.cumulativeOffsetWithBorders(this.opacityPicker);
    this.mouseMove(e);
  },

  hueMousedown: function(e) {
    this.hueDrag = true;
    this.offset  = this.cumulativeOffsetWithBorders(this.huePicker);
    this.mouseMove(e);
  },

  mouseMove: function(e) {
    if (this.sbDrag) {
      stopEvent(e);
      this.setSbPicker(e.pageY - this.offset.top, e.pageX - this.offset.left);
      this.colorChanged();
    } else if (this.opacityDrag) {
      stopEvent(e);
      this.setOpacity(e.pageX - this.offset.left);
      this.colorChanged();
    } else if (this.hueDrag) {
      stopEvent(e);
      this.setHue(e.pageY - this.offset.top);
      this.colorChanged();
    }
  },

  mouseUp: function(e) {
    this.mouseMove(e);
    this.notDragging();
  },

  notDragging: function() {
    this.sbDrag = this.hueDrag = this.opacityDrag = false;
  },

  browserMouseUp: function() {
    this.notDragging();
  },

  bodyMouseDown: function(e) {
    // stop user from accidentally doing mouse selection (dragger IMG elements are selectable and look ugly when in selection)
    e.preventDefault();
  },

  setColor: function(rgb) {
    var hsv = ColorConverter.RGB2HSV(rgb);
    this.setHue(Math.round(Math.abs(1 - hsv.h) * this.hueHeight));
    this.setSbPicker(this.sbHeight - Math.round(hsv.v * this.sbHeight), Math.round(hsv.s * this.sbWidth));
    this.setOpacity(Math.round(rgb.a * this.opacityWidth));
  },

  setHue: function(top) {
    top    = this.makeWithin(top, 0, this.hueHeight);
    this.h = (this.hueHeight - top) / this.hueHeight;
    this.hueHandle.style.top = top + 'px';

    this.updateSbPickerColor();
    this.updateOpacityPickerColor();
  },

  updateSbPickerColor: function() {
    this.sbPicker.style.backgroundColor = ColorConverter.HSV2RGBString(this.h, 1, 1);
  },

  updateOpacityPickerColor: function() {
    var startColor = ColorConverter.HSV2RGBString(this.h, this.s, this.v, 0);
    var endColor   = ColorConverter.HSV2RGBString(this.h, this.s, this.v, 1);
    this.opacityPicker.style.backgroundImage = '-moz-linear-gradient(0deg, ' + startColor + ', ' + endColor + '), url("chrome://firepicker/skin/checkboard.png")';
  },

  setOpacity: function(left) {
    left = this.makeWithin(left, 0, this.opacityWidth);
    this.a = left / this.opacityWidth;
    this.opacityHandle.style.left = left + 'px';
  },

  setSbPicker: function(top, left) {
    top  = this.makeWithin(top,  0, this.sbHeight);
    left = this.makeWithin(left, 0, this.sbWidth);
    this.v = (this.sbHeight - top) / this.sbHeight;
    this.s = left / this.sbWidth;
    this.sbHandle.style.top  = top  + 'px';
    this.sbHandle.style.left = left + 'px';

    this.updateOpacityPickerColor();
  },

  colorChanged: function() {
    this.callback(this.getRGBColor());
  },

  getRGBColor: function() {
    return ColorConverter.HSV2RGB(this.h, this.s, this.v, this.a);
  },

  makeWithin: function(val, min, max) {
    return val < min ? min : (val > max ? max : val);
  }
};

document.expose = function(values) {
  for (var valueName in values) {
    window[valueName] = values[valueName];
  }
};

document.initColorPicker = function(color, callback) {
  if (!window.colorPicker) {
    colorPicker = new ColorPicker(document.getElementById('picker'), color, callback);
  } else {
    colorPicker.callback = callback;
    colorPicker.setColor(color);
  }
  colorPicker.popUpOpened();
};

document.popUpClosed = function() {
  if (window.colorPicker) { colorPicker.popUpClosed(); }
};<|endoftext|>


<commit_before>
/* globals Q */

/***
*
*
*
*/

// current stargateVersion
var stargateVersion = 2;

// logger function
var log = function(msg, obj) {
    if (typeof obj !== 'undefined') {
        console.log("[Stargate] "+msg+" ",obj);
    } else {
        console.log("[Stargate] "+msg);
    }
    return true;
};
var err = function(msg, obj) {
    if (typeof obj !== 'undefined') {
        console.error("[Stargate] "+msg+" ",obj);
    } else {
        console.error("[Stargate] "+msg);
    }
    return false;
};

// device informations   // examples
var runningDevice = {
    available: false,    // true
    cordova: "",         // 4.1.1
    manufacturer: "",    // samsung
    model: "",           // GT-I9505
    platform: "",        // Android
    uuid: "",            // ac7245e38e3dfecb
    version: ""          // 5.0.1
};
var isRunningOnAndroid = function() {
    return runningDevice.platform == "Android";
};
var isRunningOnIos = function() {
    return runningDevice.platform == "iOS";
};
// - not used, enable if needed -
//var isRunningOnCordova = function () {
//    return (typeof window.cordova !== "undefined");
//};
var initDevice = function() {
    if (typeof window.device === 'undefined') {
        return err("Missing cordova device plugin");
    }
    for (var key in runningDevice) {
        if (window.device.hasOwnProperty(key)) {
            runningDevice[key] = window.device[key];
        }
    }
    return true;
};

var getManifest = function() {

    var deferred = Q.defer();

    window.hostedwebapp.getManifest(
        function(manifest){
            deferred.resolve(manifest);
        },
        function(error){
            deferred.reject(new Error(error));
            console.error(error);
        }
    );
    return deferred.promise;
};

var launchUrl = function (url) {
    log("launchUrl: "+url);
    document.location.href = url;
};

var isStargateInitialized = false;
var isStargateOpen = false;
var initializeCallback = null;
var initializeDeferred = null;

var appVersion = '';

/**
 *
 * variables sent by server configuration
 *
 */
var country = '',
    selector = '',
    api_selector = '',
    app_prefix = '',
    hybrid_conf = {};

/**
 *
 * this is got from manifest
 *
 */
var baseUrl;

var updateStatusBar = function() {

    if (typeof window.StatusBar === "undefined") {
        // missing cordova plugin
        return err("[StatusBar] missing cordova plugin");
    }
    if (typeof stargateConf.stausbar === "undefined") {
        return;
    }
    if (typeof stargateConf.stausbar.hideOnUrlPattern !== "undefined" &&
        stargateConf.stausbar.hideOnUrlPattern.constructor === Array) {

        var currentLocation = document.location.href;
        var hide = false;

        for (var i=0; i<stargateConf.stausbar.hideOnUrlPattern.length; i++) {

            var re = new RegExp(stargateConf.stausbar.hideOnUrlPattern[i]);

            if (re.test(currentLocation)) {
                hide = true;
                break;
            }
        }

        if (hide) {
            window.StatusBar.hide();
        }
        else {
            window.StatusBar.show();
        }
    }
};

var onPluginReady = function () {

    // FIXME: this is needed ??
    document.title = stargateConf.title;

    updateStatusBar();

    if (hasFeature('mfp')) {
        MFP.check();
    }

    if (hasFeature('deltadna')) {
        window.deltadna.startSDK(
            stargateConf.deltadna.environmentKey,
            stargateConf.deltadna.collectApi,
            stargateConf.deltadna.engageApi,

            onDeltaDNAStartedSuccess,
            onDeltaDNAStartedError,

            stargateConf.deltadna.settings
        );
    }

    navigator.splashscreen.hide();
    setBusy(false);

    IAP.initialize();

    document.cookie="hybrid=1; path=/";
    document.cookie="stargateVersion="+stargateVersion+"; path=/";

    if (window.localStorage.getItem('hybrid') !== null) {
        window.localStorage.setItem('hybrid', 1);
    }
    if (window.localStorage.getItem('stargateVersion') !== null) {
        window.localStorage.setItem('stargateVersion', stargateVersion);
    }

    // initialize finished
    isStargateOpen = true;

    //execute callback
    initializeCallback();

    initializeDeferred.resolve("Stargate.initialize() done");
};

var onDeviceReady = function () {
    initDevice();

    Q.all([
        // include here all needed initializazion
        cordova.getAppVersion.getVersionNumber(),
        getManifest()
    ])
    .then(function(results) {

        appVersion = results[0];

		if (!(typeof results[1] === 'object')) {
        	results[1] = JSON.parse(results[1]);
        }

        baseUrl = results[1].start_url;

        stargateConf = results[1].stargateConf;

        onPluginReady();
    })
    .fail(function (error) {
        err("onDeviceReady() error: "+error);
    });
};

var stargateBusy = false;

// - not used, enable if needed -
//var isBusy = function() { return stargateBusy; };

var setBusy = function(value) {
    if (value) {
        stargateBusy = true;
        startLoading();
    }
    else {
        stargateBusy = false;
        stopLoading();
    }
};

var stargateConf = {};

var hasFeature = function(feature) {
    return (typeof stargateConf.features[feature] !== 'undefined' && stargateConf.features[feature]);
};

<commit_msg>fix check if getManifest result is not an object<commit_after>
/* globals Q */

/***
*
*
*
*/

// current stargateVersion
var stargateVersion = 2;

// logger function
var log = function(msg, obj) {
    if (typeof obj !== 'undefined') {
        console.log("[Stargate] "+msg+" ",obj);
    } else {
        console.log("[Stargate] "+msg);
    }
    return true;
};
var err = function(msg, obj) {
    if (typeof obj !== 'undefined') {
        console.error("[Stargate] "+msg+" ",obj);
    } else {
        console.error("[Stargate] "+msg);
    }
    return false;
};

// device informations   // examples
var runningDevice = {
    available: false,    // true
    cordova: "",         // 4.1.1
    manufacturer: "",    // samsung
    model: "",           // GT-I9505
    platform: "",        // Android
    uuid: "",            // ac7245e38e3dfecb
    version: ""          // 5.0.1
};
var isRunningOnAndroid = function() {
    return runningDevice.platform == "Android";
};
var isRunningOnIos = function() {
    return runningDevice.platform == "iOS";
};
// - not used, enable if needed -
//var isRunningOnCordova = function () {
//    return (typeof window.cordova !== "undefined");
//};
var initDevice = function() {
    if (typeof window.device === 'undefined') {
        return err("Missing cordova device plugin");
    }
    for (var key in runningDevice) {
        if (window.device.hasOwnProperty(key)) {
            runningDevice[key] = window.device[key];
        }
    }
    return true;
};

var getManifest = function() {

    var deferred = Q.defer();

    window.hostedwebapp.getManifest(
        function(manifest){
            deferred.resolve(manifest);
        },
        function(error){
            deferred.reject(new Error(error));
            console.error(error);
        }
    );
    return deferred.promise;
};

var launchUrl = function (url) {
    log("launchUrl: "+url);
    document.location.href = url;
};

var isStargateInitialized = false;
var isStargateOpen = false;
var initializeCallback = null;
var initializeDeferred = null;

var appVersion = '';

/**
 *
 * variables sent by server configuration
 *
 */
var country = '',
    selector = '',
    api_selector = '',
    app_prefix = '',
    hybrid_conf = {};

/**
 *
 * this is got from manifest
 *
 */
var baseUrl;

var updateStatusBar = function() {

    if (typeof window.StatusBar === "undefined") {
        // missing cordova plugin
        return err("[StatusBar] missing cordova plugin");
    }
    if (typeof stargateConf.stausbar === "undefined") {
        return;
    }
    if (typeof stargateConf.stausbar.hideOnUrlPattern !== "undefined" &&
        stargateConf.stausbar.hideOnUrlPattern.constructor === Array) {

        var currentLocation = document.location.href;
        var hide = false;

        for (var i=0; i<stargateConf.stausbar.hideOnUrlPattern.length; i++) {

            var re = new RegExp(stargateConf.stausbar.hideOnUrlPattern[i]);

            if (re.test(currentLocation)) {
                hide = true;
                break;
            }
        }

        if (hide) {
            window.StatusBar.hide();
        }
        else {
            window.StatusBar.show();
        }
    }
};

var onPluginReady = function () {

    // FIXME: this is needed ??
    document.title = stargateConf.title;

    updateStatusBar();

    if (hasFeature('mfp')) {
        MFP.check();
    }

    if (hasFeature('deltadna')) {
        window.deltadna.startSDK(
            stargateConf.deltadna.environmentKey,
            stargateConf.deltadna.collectApi,
            stargateConf.deltadna.engageApi,

            onDeltaDNAStartedSuccess,
            onDeltaDNAStartedError,

            stargateConf.deltadna.settings
        );
    }

    navigator.splashscreen.hide();
    setBusy(false);

    IAP.initialize();

    document.cookie="hybrid=1; path=/";
    document.cookie="stargateVersion="+stargateVersion+"; path=/";

    if (window.localStorage.getItem('hybrid') !== null) {
        window.localStorage.setItem('hybrid', 1);
    }
    if (window.localStorage.getItem('stargateVersion') !== null) {
        window.localStorage.setItem('stargateVersion', stargateVersion);
    }

    // initialize finished
    isStargateOpen = true;

    //execute callback
    initializeCallback();

    initializeDeferred.resolve("Stargate.initialize() done");
};

var onDeviceReady = function () {
    initDevice();

    Q.all([
        // include here all needed initializazion
        cordova.getAppVersion.getVersionNumber(),
        getManifest()
    ])
    .then(function(results) {

        appVersion = results[0];

		if (typeof results[1] !== 'object') {
			results[1] = JSON.parse(results[1]);
		}

        baseUrl = results[1].start_url;

        stargateConf = results[1].stargateConf;

        onPluginReady();
    })
    .fail(function (error) {
        err("onDeviceReady() error: "+error);
    });
};

var stargateBusy = false;

// - not used, enable if needed -
//var isBusy = function() { return stargateBusy; };

var setBusy = function(value) {
    if (value) {
        stargateBusy = true;
        startLoading();
    }
    else {
        stargateBusy = false;
        stopLoading();
    }
};

var stargateConf = {};

var hasFeature = function(feature) {
    return (typeof stargateConf.features[feature] !== 'undefined' && stargateConf.features[feature]);
};

<|endoftext|>


<commit_before>/* globals define */

define([
  'jquery',
  'underscore',
  'backbone',
  'marionette',
  'buses/event-bus',
  'models/settings-model'
], function ($, _, Backbone, Marionette, EventBus, Settings) {
  'use strict';

  var schema = {
    'url':   function (page) {
      return 'page/' + page;
    },
    'query': function (page) {
      return '&page=' + page;
    }
  };

  function routeIsPaged (route) {
    var isPaged = route.match(/(page\/\d+\/?$)|([?&]page=\d+)/);
    return isPaged !== null && isPaged.length > 0;
  }

  function buildUri(route, replace) {
    var pageRegex   = /(\(\/?page\/.*\))/g;
    var pageSection = route.match(pageRegex);

    pageSection = (_.isEmpty(pageSection)) ? '' : pageSection[0];

    if (!replace.paged || replace.paged < 2) {
      route = route.replace(pageSection, '');
      delete replace.paged;
    } else {
      var pageSectionContentRegex = new RegExp(pageSection, 'g');
      var pageSectionContent      = pageSection.match(pageSectionContentRegex);

      route = route.replace(pageSection, pageSectionContent);
    }

    return route.supplant(replace);
  }

  function getCurlyKey (key) {
    var attrs = key.match(/(:([^\/:()*]+)|(\*([^\/:()*]+)))/g);
    _.each(attrs, function (attr) {
      key = key.replace(attr, '{' + attr.replace(/(:)|(\*)/g, '') + '}');
    });

    return key;
  }

  var Navigator = Backbone.Model.extend({
    initialize: function () {
      this.routes = this._processRoutes(Settings.get('routes'));
    },

    navigateToCurrent: function () {
      Backbone.history.loadUrl();
    },

    navigate: function (route, trigger) {
      route = this._routeFromAbsoluteUrl(route);
      EventBus.trigger('router:nav', {route: route, options: {trigger: trigger}});
    },

    navigateToHome: function (home, paged, trigger) {
      this._navigateToType(this.routes.root[0], {paged: paged}, trigger);
    },

    navigateToSearch: function (search, paged, trigger) {
      this._navigateToType(this.routes.search[0], {search: search, paged: paged}, trigger);
    },

    navigateToAuthor: function (author, paged, trigger) {
      this._navigateToType(this.routes.author[0], {author: author, paged: paged}, trigger);
    },

    navigateToDate: function (date, paged, trigger) {
      var numValues = _.keys(date).length;
      this._navigateToType(this.routes.date[numValues - 1], _.extend(date, {paged: paged}), trigger);
    },

    navigateToPost: function (post, paged, trigger) {
      this.navigateToPostType('post', post, paged, trigger);
    },

    navigateToPage: function (page, paged, trigger) {
      this.navigateToPostType('page', page, paged, trigger);
    },

    navigateToPostType: function (type, post, paged, trigger) {
      var routeParams = {paged: paged};
      routeParams[type] = post;
      this._navigateToType(this.routes[type][0], routeParams, trigger);
    },

    navigateToTaxonomy: function (taxonomy, term, paged, trigger) {
      var routeParams = {paged: paged};
      routeParams[taxonomy] = term;
      this._navigateToType(this.routes[taxonomy][0], routeParams, trigger);
    },

    getRouteOfType: function (type, slug, paged) {
      var data   = {};
      data[type] = slug;
      data.paged = paged;
      return buildUri(this.routes[type][0], data);
    },

    getRoute: function () {
      return Backbone.history.fragment;
    },

    getPagedRoute: function (filter, page) {
      var url   = schema[filter.get('paging-schema')],
          regex = /(page\/\d)|(&page=\d)/,
          route = this.getRoute();

      route = (routeIsPaged(route)) ? route.replace(regex, url(page))
                                    : route + '/' + url(page);
      return route;
    },

    /**
     * Extract route string from an absolute URL.
     * @param  {String} url Absolute or relative URL.
     * @return {String}     Route.
     */
    _routeFromAbsoluteUrl: function (url) {
      if (Settings.get('site_url') + '/' === url) {
        return '';
      }

      var re = new RegExp('^' + Settings.get('site_url') + '/(.+?)/?$', 'g');
      return url.replace(re, '$1');
    },

    _navigateToType: function (type, data, trigger) {
      var route = buildUri(type, data);
      this.navigate(route, trigger);
    },

    _processRoutes: function (routes) {
      var keys    = _.keys(routes),
          mapping = {};

      _.each(keys, function (key) {
        var route = routes[key];
        if (!mapping.hasOwnProperty(route.type)) {
          mapping[route.type] = [];
        }

        mapping[route.type].push(getCurlyKey(key));
      });

      return mapping;
    },
  });

  return new Navigator();
});
<commit_msg>Be gone spawn of darkness (regex)<commit_after>/* globals define */

define([
  'jquery',
  'underscore',
  'backbone',
  'marionette',
  'buses/event-bus',
  'models/settings-model'
], function ($, _, Backbone, Marionette, EventBus, Settings) {
  'use strict';

  var schema = {
    'url':   function (page) {
      return 'page/' + page;
    },
    'query': function (page) {
      return '&page=' + page;
    }
  };

  function routeIsPaged (route) {
    var isPaged = route.match(/(page\/\d+\/?$)|([?&]page=\d+)/);
    return isPaged !== null && isPaged.length > 0;
  }

  function buildUri(route, replace) {
    var pageRegex   = /(\(\/?page\/.*\))/g;
    var pageSection = route.match(pageRegex);

    pageSection = (_.isEmpty(pageSection)) ? '' : pageSection[0];

    if (!replace.paged || replace.paged < 2) {
      route = route.replace(pageSection, '');
      delete replace.paged;
    } else {
      var pageSectionContentRegex = new RegExp(pageSection, 'g');
      var pageSectionContent      = pageSection.match(pageSectionContentRegex);

      route = route.replace(pageSection, pageSectionContent);
    }

    return route.supplant(replace);
  }

  function getCurlyKey (key) {
    var attrs = key.match(/([:*]([^\/:()*]+))/g);
    _.each(attrs, function (attr) {
      key = key.replace(attr, '{' + attr.replace(/(:)|(\*)/g, '') + '}');
    });

    return key;
  }

  var Navigator = Backbone.Model.extend({
    initialize: function () {
      this.routes = this._processRoutes(Settings.get('routes'));
    },

    navigateToCurrent: function () {
      Backbone.history.loadUrl();
    },

    navigate: function (route, trigger) {
      route = this._routeFromAbsoluteUrl(route);
      EventBus.trigger('router:nav', {route: route, options: {trigger: trigger}});
    },

    navigateToHome: function (home, paged, trigger) {
      this._navigateToType(this.routes.root[0], {paged: paged}, trigger);
    },

    navigateToSearch: function (search, paged, trigger) {
      this._navigateToType(this.routes.search[0], {search: search, paged: paged}, trigger);
    },

    navigateToAuthor: function (author, paged, trigger) {
      this._navigateToType(this.routes.author[0], {author: author, paged: paged}, trigger);
    },

    navigateToDate: function (date, paged, trigger) {
      var numValues = _.keys(date).length;
      this._navigateToType(this.routes.date[numValues - 1], _.extend(date, {paged: paged}), trigger);
    },

    navigateToPost: function (post, paged, trigger) {
      this.navigateToPostType('post', post, paged, trigger);
    },

    navigateToPage: function (page, paged, trigger) {
      this.navigateToPostType('page', page, paged, trigger);
    },

    navigateToPostType: function (type, post, paged, trigger) {
      var routeParams = {paged: paged};
      routeParams[type] = post;
      this._navigateToType(this.routes[type][0], routeParams, trigger);
    },

    navigateToTaxonomy: function (taxonomy, term, paged, trigger) {
      var routeParams = {paged: paged};
      routeParams[taxonomy] = term;
      this._navigateToType(this.routes[taxonomy][0], routeParams, trigger);
    },

    getRouteOfType: function (type, slug, paged) {
      var data   = {};
      data[type] = slug;
      data.paged = paged;
      return buildUri(this.routes[type][0], data);
    },

    getRoute: function () {
      return Backbone.history.fragment;
    },

    getPagedRoute: function (filter, page) {
      var url   = schema[filter.get('paging-schema')],
          regex = /(page\/\d)|(&page=\d)/,
          route = this.getRoute();

      route = (routeIsPaged(route)) ? route.replace(regex, url(page))
                                    : route + '/' + url(page);
      return route;
    },

    /**
     * Extract route string from an absolute URL.
     * @param  {String} url Absolute or relative URL.
     * @return {String}     Route.
     */
    _routeFromAbsoluteUrl: function (url) {
      if (Settings.get('site_url') + '/' === url) {
        return '';
      }

      var re = new RegExp('^' + Settings.get('site_url') + '/(.+?)/?$', 'g');
      return url.replace(re, '$1');
    },

    _navigateToType: function (type, data, trigger) {
      var route = buildUri(type, data);
      this.navigate(route, trigger);
    },

    _processRoutes: function (routes) {
      var keys    = _.keys(routes),
          mapping = {};

      _.each(keys, function (key) {
        var route = routes[key];
        if (!mapping.hasOwnProperty(route.type)) {
          mapping[route.type] = [];
        }

        mapping[route.type].push(getCurlyKey(key));
      });

      return mapping;
    },
  });

  return new Navigator();
});
<|endoftext|>


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

'use strict';

// Optimization of the deceptive trap function
// It might take a long time... or never end. Just ctrl-C when you're done.

var Classic = require('../lib/classic.js'),
trap = require('../lib/trap.js');

var population_size = process.argv[2] || 256;
var traps = process.argv[3] || 100;
var trap_len = process.argv[4] || 4;
var trap_b = process.argv[5] || 2;
var chromosome_size = traps*trap_len;
var trap_fitness = new trap.Trap(  { "l": trap_len,
				     "a": 1,
				     "b": trap_b,
				     "z": trap_len -1  } );

var eo = new Classic( { population_size: population_size,
			chromosome_size: chromosome_size,
			fitness_func: trap_fitness } );

do {
    eo.generation();
    console.log( eo.population[0] );
} while ( eo.population[0].fitness < traps*trap_b );

console.log(eo.population);
<commit_msg>Adapts another refs #7<commit_after>#!/usr/bin/env node

'use strict';

// Optimization of the deceptive trap function
// It might take a long time... or never end. Just ctrl-C when you're done.

var  nodeo = require('../lib/nodeo.js'),
Classic = nodeo.classic,
trap = nodeo.trap;

var population_size = process.argv[2] || 256;
var traps = process.argv[3] || 100;
var trap_len = process.argv[4] || 4;
var trap_b = process.argv[5] || 2;
var chromosome_size = traps*trap_len;
var trap_fitness = new trap.Trap(  { "l": trap_len,
				     "a": 1,
				     "b": trap_b,
				     "z": trap_len -1  } );

var eo = new Classic( { population_size: population_size,
			chromosome_size: chromosome_size,
			fitness_func: trap_fitness } );

do {
    eo.generation();
    console.log( eo.population[0] );
} while ( eo.population[0].fitness < traps*trap_b );

console.log(eo.population);
<|endoftext|>


<commit_before>import React from 'react'
import { withRouter } from 'react-router-dom'
import Character from './character'
import SingleCharacterRolling from "./single-character-rolling";

class Game extends React.Component {
  constructor() {
    super()

    this.addCharacter = this.addCharacter.bind(this)

    this.state = {
      gameName: ''
    }
  }

  componentWillMount() {
    var path = this.props.history.location.pathname.split('/')
    this.setState({ gameName: path[path.length - 1]})
  }

  addCharacter(character) {
    const characters = {...this.props.games[this.state.gameName].characters}
    characters[character.name] = character
    this.props.addNewCharacter(this.state.gameName, character)
  }

  render() {
    return (

            <button type="button" className="btn btn-primary" onClick={() => {this.props.history.push('/')} }>Game List -></button>
            <SingleCharacterRolling addCharacter={this.addCharacter}/>

              {
                Object.keys(this.props.games[this.state.gameName].characters)
                  .map(name => <Character key={name} character={this.props.games[this.state.gameName].characters[name]}/>)
              }

    );
  }
}

export default withRouter(Game)<commit_msg>Add game title at the top of the page<commit_after>import React from 'react'
import { withRouter } from 'react-router-dom'
import Character from './character'
import SingleCharacterRolling from "./single-character-rolling";

class Game extends React.Component {
  constructor() {
    super()

    this.addCharacter = this.addCharacter.bind(this)

    this.state = {
      gameName: ''
    }
  }

  componentWillMount() {
    var path = this.props.history.location.pathname.split('/')
    this.setState({ gameName: path[path.length - 1]})
  }

  addCharacter(character) {
    const characters = {...this.props.games[this.state.gameName].characters}
    characters[character.name] = character
    this.props.addNewCharacter(this.state.gameName, character)
  }

  render() {
    return (

          {this.state.gameName}

            <button type="button" className="btn btn-primary" onClick={() => {this.props.history.push('/')} }>Game List -></button>
            <SingleCharacterRolling addCharacter={this.addCharacter}/>

              {
                Object.keys(this.props.games[this.state.gameName].characters)
                  .map(name => <Character key={name} character={this.props.games[this.state.gameName].characters[name]}/>)
              }

    );
  }
}

export default withRouter(Game)<|endoftext|>


<commit_before>import React, { Component } from 'react';
import styles from './Home.css';
import axios from 'axios';
import jarvis from 'file!../jarvis-bkrd.png';
import RaisedButton from 'material-ui/lib/raised-button';
import ActionRecordVoiceOver from 'material-ui/lib/svg-icons/action/record-voice-over';
import Modal from 'react-modal';
import VisitorModal from './VisitorModal';
import Motion from '../sensors/motion';
import * as Camera from '../sensors/camera';
import fs from 'fs';
import io from 'socket.io-client';
let socket = io(`http://jarviscsg.herokuapp.com:80`);

export default class Home extends Component {

  constructor(props) {
    super(props);

    this.state = {
      visitors: [],
      modalIsOpen: false
    }
  }

  closeModal = () => {
        this.setState({ modalIsOpen: false});
    }

  checkIn = () => {
    let self = this;
    axios.get('http://jarviscsg-api.herokuapp.com/api/schedules/now').then(function(response) {
      if (response.data.length > 0) {
        self.setState({
          visitors: response.data,
          modalIsOpen: true
        });
      } else {

        // need to create proper data object for office manager // jeff
        data = {
          firstName: "someone",
          userName: "erichardson"
        };
        self.notifyEmployee(data);
      }
    });
  }

  notifyEmployee = (data) => {
    responsiveVoice.speak("Thank you. I will let " + data.firstName + "know you are here.", "UK English Male", {rate: 0.8});
    Camera.takePicture(data);
    this.closeModal();
  }

  render() {

    return (

          <RaisedButton
            backgroundColor="#218EC1"
            className={styles.button}
            style={style}
            label="Check In"
            labelColor="#FFF"
            onClick={this.checkIn}
            icon={<ActionRecordVoiceOver />}
          />

          <VisitorModal
            open={this.state.modalIsOpen}
            close = {this.closeModal}
            visitors = {this.state.visitors}
            notifyEmployee = {this.notifyEmployee} />

    );
  }
}

const style = {
  position: 'fixed',
  bottom: '20px',
  left: '200px',
  height: '60px',
  width: '400px'
}
<commit_msg>Fixing some js<commit_after>import React, { Component } from 'react';
import styles from './Home.css';
import axios from 'axios';
import jarvis from 'file!../jarvis-bkrd.png';
import RaisedButton from 'material-ui/lib/raised-button';
import ActionRecordVoiceOver from 'material-ui/lib/svg-icons/action/record-voice-over';
import Modal from 'react-modal';
import VisitorModal from './VisitorModal';
import Motion from '../sensors/motion';
import * as Camera from '../sensors/camera';
import fs from 'fs';
import io from 'socket.io-client';
let socket = io(`http://jarviscsg.herokuapp.com:80`);

export default class Home extends Component {

  constructor(props) {
    super(props);

    this.state = {
      visitors: [],
      modalIsOpen: false
    }
  }

  closeModal = () => {
        this.setState({ modalIsOpen: false});
    }

  checkIn = () => {
    let self = this;
    axios.get('http://jarviscsg-api.herokuapp.com/api/schedules/now').then(function(response) {
      if (response.data.length > 0) {
        self.setState({
          visitors: response.data,
          modalIsOpen: true
        });
      } else {

        // need to create proper data object for office manager // jeff
        var data = {
          firstName: "someone",
          userName: "erichardson"
        };
        self.notifyEmployee(data);
      }
    });
  }

  notifyEmployee = (data) => {
    responsiveVoice.speak("Thank you. I will let " + data.firstName + "know you are here.", "UK English Male", {rate: 0.8});
    Camera.takePicture(data);
    this.closeModal();
  }

  render() {

    return (

          <RaisedButton
            backgroundColor="#218EC1"
            className={styles.button}
            style={style}
            label="Check In"
            labelColor="#FFF"
            onClick={this.checkIn}
            icon={<ActionRecordVoiceOver />}
          />

          <VisitorModal
            open={this.state.modalIsOpen}
            close = {this.closeModal}
            visitors = {this.state.visitors}
            notifyEmployee = {this.notifyEmployee} />

    );
  }
}

const style = {
  position: 'fixed',
  bottom: '20px',
  left: '200px',
  height: '60px',
  width: '400px'
}
<|endoftext|>


<commit_before>import React, {
  Dimensions,
  StyleSheet,
  ScrollView,
  View,
  Image,
  Text,
  Component,
} from 'react-native';
const window = Dimensions.get('window');
const uri = 'http://pickaface.net/includes/themes/clean/img/slide2.png';

const styles = StyleSheet.create({
  menu: {
    flex: 1,
    width: window.width,
    height: window.height,
    backgroundColor: 'gray',
    padding: 20,
  },
  avatarContainer: {
    marginBottom: 20,
    marginTop: 20,
  },
  avatar: {
    width: 48,
    height: 48,
    borderRadius: 24,
    flex: 1,
  },
  name: {
    position: 'absolute',
    left: 70,
    top: 20,
  },
  item: {
    fontSize: 14,
    fontWeight: '300',
    paddingTop: 5,
  },
});

export default class Menu extends Component {
  static propTypes = {
    onItemSelected: React.PropTypes.func.isRequired,
  };
  render() {
    return (
      <ScrollView scrollsToTop={false} style={styles.menu}>
        <View style={styles.avatarContainer}>
          <Image
            style={styles.avatar}
            source={{ uri, }}/>
          <Text style={styles.name}>Hi, Tiffany</Text>
        </View>

        <Text
          onPress={() => this.props.onItemSelected('Map')}
          style={styles.item}>
          Map
        </Text>

        <Text
          onPress={() => this.props.onItemSelected('Settings')}
          style={styles.item}>
          Settings
        </Text>
      </ScrollView>
    );
  }
};
<commit_msg>add note to menu component<commit_after>// Note: this is not finished, only shows menu for now
//menu options not functional
import React, {
  Dimensions,
  StyleSheet,
  ScrollView,
  View,
  Image,
  Text,
  Component,
} from 'react-native';
const window = Dimensions.get('window');
const uri = 'http://pickaface.net/includes/themes/clean/img/slide2.png';

const styles = StyleSheet.create({
  menu: {
    flex: 1,
    width: window.width,
    height: window.height,
    backgroundColor: 'gray',
    padding: 20,
  },
  avatarContainer: {
    marginBottom: 20,
    marginTop: 20,
  },
  avatar: {
    width: 48,
    height: 48,
    borderRadius: 24,
    flex: 1,
  },
  name: {
    position: 'absolute',
    left: 70,
    top: 20,
  },
  item: {
    fontSize: 14,
    fontWeight: '300',
    paddingTop: 5,
  },
});

export default class Menu extends Component {
  static propTypes = {
    onItemSelected: React.PropTypes.func.isRequired,
  };
  render() {
    return (
      <ScrollView scrollsToTop={false} style={styles.menu}>
        <View style={styles.avatarContainer}>
          <Image
            style={styles.avatar}
            source={{ uri, }}/>
          <Text style={styles.name}>Hi, InterruptedLobster!</Text>
        </View>

        <Text
          onPress={() => this.props.onItemSelected('Map')}
          style={styles.item}>
          Map
        </Text>

        <Text
          onPress={() => this.props.onItemSelected('Settings')}
          style={styles.item}>
          Settings
        </Text>
      </ScrollView>
    );
  }
};
<|endoftext|>