<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'superhero',
    environment: environment,
    firebase: 'https://superhero-demo.firebaseio.com/',
    baseURL: '/',
    locationType: 'auto',
    contentSecurityPolicy: {
      'connect-src': "'self' gateway.marvel.com wss://*.firebaseio.com",
      'img-src': "'self' i.annihil.us"
    },
    hostURL: 'https://gateway.marvel.com',
    MARVEL_PUBLIC_KEY: process.env.MARVEL_PUBLIC_KEY,
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';

    ENV.hostURL = undefined;
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>Update content security policy for remote dev server<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'superhero',
    environment: environment,
    firebase: 'https://superhero-demo.firebaseio.com/',
    baseURL: '/',
    locationType: 'auto',
    contentSecurityPolicy: {
      'connect-src': "'self' gateway.marvel.com wss://*.firebaseio.com ws://46.101.63.236:*",
      'img-src': "'self' i.annihil.us",
      'script-src': "'self' localhost:35729 0.0.0.0:35729 46.101.63.236:*"
    },
    hostURL: 'https://gateway.marvel.com',
    MARVEL_PUBLIC_KEY: process.env.MARVEL_PUBLIC_KEY,
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';

    ENV.hostURL = undefined;
  }

  if (environment === 'production') {

  }

  return ENV;
};
<|endoftext|>


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

/**
 * @fileoverview Generalised trie for indexing speech rule.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

goog.provide('sre.Trie');

goog.require('sre.Engine');
goog.require('sre.TrieNode');
goog.require('sre.TrieNodeFactory');

/**
 * @constructor
 * @param {sre.SpeechRuleStore} store The store the trie belongs to.
 */
sre.Trie = function(store) {
  this.store = store;
  this.root = sre.TrieNodeFactory.getNode(
    sre.TrieNode.Kind.ROOT, '', this.store);
};

/**
 * Inserts a speech rule into the trie.
 * @param {sre.SpeechRule} rule The speech rule to add.
 */
sre.Trie.prototype.addRule = function(rule) {
  var node = this.root;
  var dynamicCstr = rule.dynamicCstr.getValues();
  for (var i = 0, l = dynamicCstr.length; i < l; i++) {
    node = this.addNode_(node, dynamicCstr[i], sre.TrieNode.Kind.DYNAMIC);
  }
  node = this.addNode_(node, rule.precondition.query, sre.TrieNode.Kind.QUERY);
  var booleans = rule.precondition.constraints;
  for (i = 0, l = booleans.length; i < l; i++) {
    node = this.addNode_(node, booleans[i], sre.TrieNode.Kind.BOOLEAN);
  }
  node.setRule(rule);
};

/**
 * Retrieves node for the given constraing. Adds a new node if necessary.
 * @param {sre.TrieNode} node The current node in the trie.
 * @param {string} constraint The constraint string.
 * @param {sre.TrieNode.Kind} kind The kind of node.
 * @return {sre.TrieNode} The next node in the trie.
 * @private
 */
sre.Trie.prototype.addNode_ = function(node, constraint, kind) {
  var nextNode = node.getChild(constraint);
  if (!nextNode) {
    nextNode = sre.TrieNodeFactory.getNode(kind, constraint, this.store);
    node.addChild(nextNode);
  }
  return nextNode;
};

// TODO
sre.Trie.prototype.deleteRule = function(rule) {

};

// TODO: Extend the dynamic constraint to allow for multiple constraints and
//       priority ordering.
sre.Trie.prototype.lookupRules = function(element, dynamic) {
  var nodes = [this.root];
  var rules = [];
  var dynamicSets = this.dynamicCstrSets(dynamic);
  // We might need to take care of multiple layers of root nodes.
  //
  // Pop node, get children,
  // add child if constraint is correct.
  // add rule if child has a rule.
  //
  // First deal with dynamic constraints.
  // var queryNodes = [];
  while (dynamicSets.length) {
    var dynamicSet = dynamicSets.shift();
    var newNodes = [];
    while (nodes.length) {
      var node = nodes.shift();
      var children = node.getChildren();
      children.forEach(
        function(child) {
          if (child.getKind() !== sre.TrieNode.Kind.DYNAMIC ||
              dynamicSet.indexOf(child.getConstraint()) !== -1) {
            newNodes.push(child);
          }
        });
    }
    nodes = newNodes.slice();
  }
  // Then we deal with static constraints, while collecting rules.
  while (nodes.length) {
    node = nodes.shift();
    if (node.getRule) {
      var rule = node.getRule();
      if (rule) {
        rules.push(rule);
      }
    }
    children = node.findChildren(element);
    nodes = nodes.concat(children);
  }
  return rules;
};

// This is temporary:
sre.Trie.prototype.dynamicCstrSets = function(dynamic) {
  var values = dynamic.getValues();
  if (sre.Engine.getInstance().strict) {
    return values.map(function(value) {return [value];});
  }
  return values.map(function(value) {
    return value === 'default' ? [value] : [value, 'default'];
  });
};

/**
 * @override
 */
sre.Trie.prototype.toString = function() {
  return sre.Trie.printWithDepth_(this.root, 0, '');
};

sre.Trie.prototype.collectRules = function() {
  var rules = [];
  var collectRules = function(node) {
    if (node.getKind() === sre.TrieNode.Kind.QUERY ||
        node.getKind() === sre.TrieNode.Kind.BOOLEAN) {
      var rule = node.getRule();
      if (rule) rules.unshift(rule);
    }
    node.getChildren().forEach(collectRules);
  };
  collectRules(this.root);
  return rules;
};

/**
 * Prints tree to a string.
 * @param {sre.TrieNode} node The current try node to print.
 * @param {number} depth The current depth of the node.
 * @param {string} str The string that has already been assembled.
 * @return {string}
 * @private
 */
sre.Trie.printWithDepth_ = function(node, depth, str) {
  var prefix = new Array(depth + 2).join(depth) + ': ';
  str += prefix + node.toString() + '\n';
  var children = node.getChildren();
  for (var i = 0, child; child = children[i]; i++) {
    str = sre.Trie.printWithDepth_(child, depth + 1, str);
  }
  return str;
};

sre.Trie.maxOrder = function(node) {
  var children = node.getChildren();
  if (!children.length) {
    return 0;
  }
  var max = Math.max.apply(null, children.map(sre.Trie.maxOrder));
  return Math.max(children.length, max);
};

// 566 test successful.
// Time for tests: 173650ms

// 564 test successful.
// Time for tests: 49412ms
<commit_msg>Some code cleanup.<commit_after>// Copyright 2016 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Supported by the Mozilla Foundation.

/**
 * @fileoverview Generalised trie for indexing speech rule.
 *
 * As trie is a pure indexing structure, we currently assume that we will not
 * remove rules from the trie. I.e., if a rule is removed from a speech rule
 * store, we have to rebuild the trie. This is the same worst case complexity as
 * removing a single rule.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

goog.provide('sre.Trie');

goog.require('sre.Engine');
goog.require('sre.TrieNode');
goog.require('sre.TrieNodeFactory');

/**
 * @constructor
 * @param {sre.SpeechRuleStore} store The store the trie belongs to.
 */
sre.Trie = function(store) {
  this.store = store;
  this.root = sre.TrieNodeFactory.getNode(
    sre.TrieNode.Kind.ROOT, '', this.store);
};

/**
 * Inserts a speech rule into the trie.
 * @param {sre.SpeechRule} rule The speech rule to add.
 */
sre.Trie.prototype.addRule = function(rule) {
  var node = this.root;
  var dynamicCstr = rule.dynamicCstr.getValues();
  for (var i = 0, l = dynamicCstr.length; i < l; i++) {
    node = this.addNode_(node, dynamicCstr[i], sre.TrieNode.Kind.DYNAMIC);
  }
  node = this.addNode_(node, rule.precondition.query, sre.TrieNode.Kind.QUERY);
  var booleans = rule.precondition.constraints;
  for (i = 0, l = booleans.length; i < l; i++) {
    node = this.addNode_(node, booleans[i], sre.TrieNode.Kind.BOOLEAN);
  }
  node.setRule(rule);
};

/**
 * Retrieves node for the given constraint. Adds a new node if necessary.
 * @param {sre.TrieNode} node The current node in the trie.
 * @param {string} constraint The constraint string.
 * @param {sre.TrieNode.Kind} kind The kind of node.
 * @return {sre.TrieNode} The trie node corresponding to the constraint.
 * @private
 */
sre.Trie.prototype.addNode_ = function(node, constraint, kind) {
  var nextNode = node.getChild(constraint);
  if (!nextNode) {
    nextNode = sre.TrieNodeFactory.getNode(kind, constraint, this.store);
    node.addChild(nextNode);
  }
  return nextNode;
};

/**
 * Retrieves a set of speech rules that are applicable to a given XML node
 * wrt. to a dynamic constraint.
 * @param {!Node} xml An XML node.
 * @param {sre.DynamicCstr} dynamic A dynamic constraint.
 * @return {!Array.<sre.SpeechRule>} The speech rules that can be applied to the
 *     given node.
 */
sre.Trie.prototype.lookupRules = function(xml, dynamic) {
  var nodes = [this.root];
  var rules = [];
  var dynamicSets = this.dynamicCstrSets_(dynamic);
  // Algorithm:
  // Pop node, get children,
  // add child if constraint is correct.
  // add rule if child has a rule.
  //
  // First deal with dynamic constraints.
  while (dynamicSets.length) {
    var dynamicSet = dynamicSets.shift();
    var newNodes = [];
    while (nodes.length) {
      var node = nodes.shift();
      var children = node.getChildren();
      children.forEach(
        function(child) {
          if (child.getKind() !== sre.TrieNode.Kind.DYNAMIC ||
              dynamicSet.indexOf(child.getConstraint()) !== -1) {
            newNodes.push(child);
          }
        });
    }
    nodes = newNodes.slice();
  }
  // Then we deal with static constraints, while collecting rules.
  while (nodes.length) {
    node = nodes.shift();
    if (node.getRule) {
      var rule = node.getRule();
      if (rule) {
        rules.push(rule);
      }
    }
    children = node.findChildren(xml);
    nodes = nodes.concat(children);
  }
  return rules;
};

// TODO: This is temporary until it is finalised how to deal with default
// constraints.
/**
 * Enriches the dynamic constraint into sets containing default values.
 * @param {sre.DynamicCstr} dynamic A dynamic constraint.
 * @return {!Array.<Array<string>>} Sets of dynamic constraint values.
 * @private
 */
sre.Trie.prototype.dynamicCstrSets_ = function(dynamic) {
  var values = dynamic.getValues();
  if (sre.Engine.getInstance().strict) {
    return values.map(function(value) {return [value];});
  }
  return values.map(function(value) {
    return value === 'default' ? [value] : [value, 'default'];
  });
};

/**
 * @override
 */
sre.Trie.prototype.toString = function() {
  return sre.Trie.printWithDepth_(this.root, 0, '');
};

/**
 * @return {!Array.<sre.SpeechRule>} Set of speech rules in the trie.
 */
sre.Trie.prototype.collectRules = function() {
  var rules = [];
  var collectRules = function(node) {
    if (node.getKind() === sre.TrieNode.Kind.QUERY ||
        node.getKind() === sre.TrieNode.Kind.BOOLEAN) {
      var rule = node.getRule();
      if (rule) rules.unshift(rule);
    }
    node.getChildren().forEach(collectRules);
  };
  collectRules(this.root);
  return rules;
};

/**
 * @return {number} The order of the trie.
 */
sre.Trie.prototype.order = function() {
  return sre.Trie.order_(this.root);
};

/**
 * Prints tree to a string.
 * @param {sre.TrieNode} node The current try node to print.
 * @param {number} depth The current depth of the node.
 * @param {string} str The string that has already been assembled.
 * @return {string}
 * @private
 */
sre.Trie.printWithDepth_ = function(node, depth, str) {
  var prefix = new Array(depth + 2).join(depth) + ': ';
  str += prefix + node.toString() + '\n';
  var children = node.getChildren();
  for (var i = 0, child; child = children[i]; i++) {
    str = sre.Trie.printWithDepth_(child, depth + 1, str);
  }
  return str;
};

/**
 * Computes the maximal order of the trie beneath the given node.
 * @param {sre.TrieNode} node The trie node considered as root.
 * @return {number} The order of the trie.
 * @private
 */
sre.Trie.order_ = function(node) {
  var children = node.getChildren();
  if (!children.length) {
    return 0;
  }
  var max = Math.max.apply(null, children.map(sre.Trie.order_));
  return Math.max(children.length, max);
};

// 566 test successful.
// Time for tests: 173650ms

// 564 test successful.
// Time for tests: 49412ms

// 566 test successful.
// Time for tests: 48076ms
<|endoftext|>


<commit_before>const { KeyValueCollection } = require('./key_value_collection');
const { PassThrough } = require('stream');

const spaces = /\s+/;
const newline = "\n";

class ManifestParser {
    constructor(bagItFile) {
        var parser = this;
        if (bagItFile.keyValueCollection == null) {
            bagItFile.keyValueCollection = new KeyValueCollection();
        }
        this.bagItFile = bagItFile;
        this.stream = new PassThrough();
        this.stream.setEncoding('utf8');
        this.lastFragment = '';
        parser.stream.on('data', function(data) {
            var lines = data.split(newline);
            var lastIndex = lines.length - 1;
            for (var i=0; i < lines.length; i++) {
                var line = lines[i];
                if (i == 0) {
                    // First chunk of new data may begin in the middle of a line.
                    line = parser.lastFragment + line;
                    parser.lastFragment = '';
                } else if (i == lastIndex && !data.endsWith(newline)) {
                    // Last chunk of data is an incomplete line fragment
                    parser.lastFragment = line;
                    continue;
                }
                // First item on line is the fixity value.
                // Second item is file name, which may contain spaces.
                // Split with limit will give us truncated file name.
                var parts = line.split(spaces);
                if (i < lastIndex) {
                    var value = parts.shift().trim();  // fixity value
                    var key = parts.join(' ').trim();  // file name
                    parser.bagItFile.keyValueCollection.add(key, value);
                }
            }
        });
        parser.stream.on('end', function() {
            // Anything to do here?
            // Handle remaining lastFragment?
        });
    }
}

module.exports.ManifestParser = ManifestParser;
<commit_msg>PT #156706950: Preserve multiple consecutive spaces in file name<commit_after>const { KeyValueCollection } = require('./key_value_collection');
const { PassThrough } = require('stream');

const spaces = /\s+/;
const newline = "\n";

class ManifestParser {
    constructor(bagItFile) {
        var parser = this;
        if (bagItFile.keyValueCollection == null) {
            bagItFile.keyValueCollection = new KeyValueCollection();
        }
        this.bagItFile = bagItFile;
        this.stream = new PassThrough();
        this.stream.setEncoding('utf8');
        this.lastFragment = '';
        parser.stream.on('data', function(data) {
            var lines = data.split(newline);
            var lastIndex = lines.length - 1;
            for (var i=0; i < lines.length; i++) {
                var line = lines[i];
                if (i == 0) {
                    // First chunk of new data may begin in the middle of a line.
                    line = parser.lastFragment + line;
                    parser.lastFragment = '';
                } else if (i == lastIndex && !data.endsWith(newline)) {
                    // Last chunk of data is an incomplete line fragment
                    parser.lastFragment = line;
                    continue;
                }
                // First item on line is the fixity value.
                // Second item is file name, which may contain multiple spaces.
                // PT #156706950: Preserve multiple consecutive spaces in file name
                if (i < lastIndex) {
                    var fixityValue = line.split(spaces, 1);
                    var filename = line.replace(fixityValue, '').trim();
                    //console.log(`"${filename}" = "${fixityValue}"`);
                    parser.bagItFile.keyValueCollection.add(filename, fixityValue);
                }
            }
        });
        parser.stream.on('end', function() {
            // Anything to do here?
            // Handle remaining lastFragment?
        });
    }
}

module.exports.ManifestParser = ManifestParser;
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'hexo-plugin-site',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
      apiHost: '',
      version: '0.0.1-alpha'
    },

    contentSecurityPolicy: {
      "style-src": "'self' fonts.googleapis.com",
      "font-src": "fonts.gstatic.com"
    },

  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;

    ENV.APP.apiHost = 'http://localhost:1337';
    ENV.contentSecurityPolicy['connect-src'] = "http://localhost:1337";
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'auto';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.APP.apiHost = 'http://api.hexo-plugins.com';
    ENV.contentSecurityPolicy['connect-src'] = "http://api.hexo-plugins.com";
  }

  return ENV;
};
<commit_msg>Fix content security policy for 'font-src'<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'hexo-plugin-site',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
      apiHost: '',
      version: '0.1.2-alpha'
    },

    contentSecurityPolicy: {
      "style-src": "'self' fonts.googleapis.com",
      "font-src": "'self' fonts.gstatic.com"
    },

  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;

    ENV.APP.apiHost = 'http://localhost:1337';
    ENV.contentSecurityPolicy['connect-src'] = "http://localhost:1337";
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'auto';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.APP.apiHost = 'http://api.hexo-plugins.com';
    ENV.contentSecurityPolicy['connect-src'] = "http://api.hexo-plugins.com";
  }

  return ENV;
};
<|endoftext|>


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

/**
 * @module elements-sk/checkbox-sk
 * @description
checkbox-sk

 *
 *

 *   The checkbox-sk and element contains a native 'input'
 *   element in light DOM so that it can participate in a form element.
 *

 *
 *

 *    Each element also supports the following attributes exactly as the
 *    native checkbox element:
 *

 *
checked

 *
disabled

 *
name

 *

 *

 *
 *

 *    All the normal events of a native checkbox are supported.
 *

 *
 * @attr label - A string, with no markup, that is to be used as the label for
 *            the checkbox. If you wish to have a label with markup then set
 *            'label' to the empty string and create your own
 *            label element in the DOM with the 'for' attribute
 *            set to match the name of the checkbox-sk.
 *
 * @prop {boolean} checked This mirrors the checked attribute.
 * @prop {boolean} disabled This mirrors the disabled attribute.
 * @prop {string} name This mirrors the name attribute.
 * @prop {string} label This mirrors the label attribute.
 *
 */
import { upgradeProperty } from '../upgradeProperty'

export class CheckOrRadio extends HTMLElement {
  get _role() { return 'checkbox'; }

  static get observedAttributes() {
    return ['checked', 'disabled', 'name', 'label'];
  }

  connectedCallback() {
    this.innerHTML = `<label><input type=${this._role}></input><span class=box></span><span class=label></span></label>`;
    this._label = this.querySelector('.label');
    this._input = this.querySelector('input');
    upgradeProperty(this, 'checked');
    upgradeProperty(this, 'disabled');
    upgradeProperty(this, 'name');
    upgradeProperty(this, 'label');
    // Since attributeChangedCallback can be called before connectedCallback,
    // and we have non-trivial actions when the attributes change to reflect
    // the values to this._input, we need trigger each setter on
    // connectedCallback.
    this.checked = this.checked;
    this.disabled = this.disabled;
    this.name = this.name;
    this.label = this.label;

    this._input.checked = this.checked;
    this._input.disabled = this.disabled;
    this._input.setAttribute('name', this.getAttribute('name'));
    this._label.textContent = this.getAttribute('label');
    // TODO(jcgregorio) Do we capture and alter the 'input' and 'change' events generated
    // by the input element so that the evt.target points to 'this'?
    this._input.addEventListener('change', (e) => {
      this.checked = e.target.checked;
    });
    this.addEventListener('click', (e) => {
      if (e.target == this) {
        if (this.checked && this._role === 'radio') {
          return
        }
        this._input.click();
      }
    });
  }

  get checked() { return this.hasAttribute('checked'); }
  set checked(val) {
    let isTrue = !!val;
    this._input.checked = isTrue;
    if (val) {
      this.setAttribute('checked', '');
    } else {
      this.removeAttribute('checked');
    }
  }

  get disabled() { return this.hasAttribute('disabled'); }
  set disabled(val) {
    let isTrue = !!val;
    this._input.disabled = isTrue;
    if (isTrue) {
      this.setAttribute('disabled', '');
    } else {
      this.removeAttribute('disabled');
    }
  }

  get name() { return this.getAttribute('name'); }
  set name(val) {
    this.setAttribute('name', val);
    this._input.setAttribute('name', val);
  }

  get label() { return this.getAttribute('label'); }
  set label(val) {
    this.setAttribute('label', val);
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (!this._input) {
      return
    }
    // Strictly check for null since an empty string doesn't mean false
    // for a boolean attribute.
    let isTrue = newValue != null;
    switch (name) {
      case 'checked':
        this._input.checked = isTrue;
        break;
      case 'disabled':
        this._input.disabled = isTrue;
        break;
      case 'name':
        this._input.name = newValue;
        break;
      case 'label':
        this._label.textContent = newValue;
        break;
    }
  }
}

window.customElements.define('checkbox-sk', CheckOrRadio);
<commit_msg>Reject null and undefined as valid values for label and name.<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @module elements-sk/checkbox-sk
 * @description
checkbox-sk

 *
 *

 *   The checkbox-sk and element contains a native 'input'
 *   element in light DOM so that it can participate in a form element.
 *

 *
 *

 *    Each element also supports the following attributes exactly as the
 *    native checkbox element:
 *

 *
checked

 *
disabled

 *
name

 *

 *

 *
 *

 *    All the normal events of a native checkbox are supported.
 *

 *
 * @attr label - A string, with no markup, that is to be used as the label for
 *            the checkbox. If you wish to have a label with markup then set
 *            'label' to the empty string and create your own
 *            label element in the DOM with the 'for' attribute
 *            set to match the name of the checkbox-sk.
 *
 * @prop {boolean} checked This mirrors the checked attribute.
 * @prop {boolean} disabled This mirrors the disabled attribute.
 * @prop {string} name This mirrors the name attribute.
 * @prop {string} label This mirrors the label attribute.
 *
 */
import { upgradeProperty } from '../upgradeProperty'

export class CheckOrRadio extends HTMLElement {
  get _role() { return 'checkbox'; }

  static get observedAttributes() {
    return ['checked', 'disabled', 'name', 'label'];
  }

  connectedCallback() {
    this.innerHTML = `<label><input type=${this._role}></input><span class=box></span><span class=label></span></label>`;
    this._label = this.querySelector('.label');
    this._input = this.querySelector('input');
    upgradeProperty(this, 'checked');
    upgradeProperty(this, 'disabled');
    upgradeProperty(this, 'name');
    upgradeProperty(this, 'label');
    // Since attributeChangedCallback can be called before connectedCallback,
    // and we have non-trivial actions when the attributes change to reflect
    // the values to this._input, we need trigger each setter on
    // connectedCallback.
    this.checked = this.checked;
    this.disabled = this.disabled;
    this.name = this.name;
    this.label = this.label;

    this._input.checked = this.checked;
    this._input.disabled = this.disabled;
    this._input.setAttribute('name', this.getAttribute('name'));
    this._label.textContent = this.getAttribute('label');
    // TODO(jcgregorio) Do we capture and alter the 'input' and 'change' events generated
    // by the input element so that the evt.target points to 'this'?
    this._input.addEventListener('change', (e) => {
      this.checked = e.target.checked;
    });
    this.addEventListener('click', (e) => {
      if (e.target == this) {
        if (this.checked && this._role === 'radio') {
          return
        }
        this._input.click();
      }
    });
  }

  get checked() { return this.hasAttribute('checked'); }
  set checked(val) {
    let isTrue = !!val;
    this._input.checked = isTrue;
    if (val) {
      this.setAttribute('checked', '');
    } else {
      this.removeAttribute('checked');
    }
  }

  get disabled() { return this.hasAttribute('disabled'); }
  set disabled(val) {
    let isTrue = !!val;
    this._input.disabled = isTrue;
    if (isTrue) {
      this.setAttribute('disabled', '');
    } else {
      this.removeAttribute('disabled');
    }
  }

  get name() { return this.getAttribute('name'); }
  set name(val) {
    if (val === null || val === undefined) {
      return;
    }
    this.setAttribute('name', val);
    this._input.setAttribute('name', val);
  }

  get label() { return this.getAttribute('label'); }
  set label(val) {
    if (val === null || val === undefined) {
      return;
    }
    this.setAttribute('label', val);
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (!this._input) {
      return
    }
    // Strictly check for null since an empty string doesn't mean false
    // for a boolean attribute.
    let isTrue = newValue != null;
    switch (name) {
      case 'checked':
        this._input.checked = isTrue;
        break;
      case 'disabled':
        this._input.disabled = isTrue;
        break;
      case 'name':
        this._input.name = newValue;
        break;
      case 'label':
        this._label.textContent = newValue;
        break;
    }
  }
}

window.customElements.define('checkbox-sk', CheckOrRadio);
<|endoftext|>


<commit_before>'use strict';

module.exports = function(environment) {
    const ENV = {
        modulePrefix: 'ember-share',
        environment,
        rootURL: '/share/',
        creativeworkName: 'Not Categorized',
        maxSources: 500,
        locationType: 'auto',
        EmberENV: {
            EXTEND_PROTOTYPES: {
                Date: false,
                Array: true,
                String: true,
                Function: true,
            },
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            },
        },

        sentryDSN: null,
        sentryOptions: {
            release: process.env.GIT_COMMIT,
        },

        APP: { // jscs:ignore
            // Here you can pass flags/options to your application instance
            // when it is created
        },

        contentSecurityPolicy: {
            'default-src': "'none'",
            'script-src': "'self' www.google-analytics.com",
            'font-src': "'self'",
            'connect-src': "'self' www.google-analytics.com",
            'img-src': "'self'",
            'style-src': "'self'",
            'media-src': "'self'",
        },

        modelIDs: {
            creativework: 49,
            publication: 49,
            preprint: 49,
            project: 49,
            registration: 49,
            dataset: 49,
            person: 47,
        },

    };
    // this needs to go in an actual env at some point
    ENV.csrfCookie = 'csrftoken';
    ENV.apiBaseUrl = 'http://localhost:8000';
    ENV.apiUrl = 'http://localhost:8000/api/v2';

    // if (environment === 'development') {
    //     ENV.APP.LOG_RESOLVER = true;
    //     ENV.APP.LOG_ACTIVE_GENERATION = true;
    //     ENV.APP.LOG_TRANSITIONS = true;
    //     ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    //     ENV.APP.LOG_VIEW_LOOKUPS = true;
    // }

    if (environment === 'staging') {
        ENV.apiBaseUrl = 'https://staging-share.osf.io';
        ENV.apiUrl = 'https://staging-share.osf.io/api/v2';

        // Testem prefers this...
        ENV.rootURL = '/';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.modelIDs = {
            person: 100,
            creativework: 70,
        };

        // ENV.APP.rootElement = '#ember-staging';
    }

    if (environment === 'production') {
        ENV.apiBaseUrl = 'https://share.osf.io';
        ENV.apiUrl = 'https://share.osf.io/api/v2';
        ENV.metricsAdapters = [{
            name: 'GoogleAnalytics',
            environments: ['production'],
            config: {
                id: 'UA-83881781-1',
                setFields: {
                    anonymizeIp: true,
                },
            },
        }];

        ENV.modelIDs = {
            person: 100,
            creativework: 70,
        };

        // Testem prefers this...
        ENV.rootURL = '/';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;
    }

    return ENV;
};
<commit_msg>update local-share ports<commit_after>'use strict';

module.exports = function(environment) {
    const ENV = {
        modulePrefix: 'ember-share',
        environment,
        rootURL: '/share/',
        creativeworkName: 'Not Categorized',
        maxSources: 500,
        locationType: 'auto',
        EmberENV: {
            EXTEND_PROTOTYPES: {
                Date: false,
                Array: true,
                String: true,
                Function: true,
            },
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            },
        },

        sentryDSN: null,
        sentryOptions: {
            release: process.env.GIT_COMMIT,
        },

        APP: { // jscs:ignore
            // Here you can pass flags/options to your application instance
            // when it is created
        },

        contentSecurityPolicy: {
            'default-src': "'none'",
            'script-src': "'self' www.google-analytics.com",
            'font-src': "'self'",
            'connect-src': "'self' www.google-analytics.com",
            'img-src': "'self'",
            'style-src': "'self'",
            'media-src': "'self'",
        },

        modelIDs: {
            creativework: 49,
            publication: 49,
            preprint: 49,
            project: 49,
            registration: 49,
            dataset: 49,
            person: 47,
        },

    };
    // this needs to go in an actual env at some point
    ENV.csrfCookie = 'csrftoken';
    ENV.apiBaseUrl = 'http://localhost:8003';
    ENV.apiUrl = 'http://localhost:8003/api/v2';

    // if (environment === 'development') {
    //     ENV.APP.LOG_RESOLVER = true;
    //     ENV.APP.LOG_ACTIVE_GENERATION = true;
    //     ENV.APP.LOG_TRANSITIONS = true;
    //     ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    //     ENV.APP.LOG_VIEW_LOOKUPS = true;
    // }

    if (environment === 'staging') {
        ENV.apiBaseUrl = 'https://staging-share.osf.io';
        ENV.apiUrl = 'https://staging-share.osf.io/api/v2';

        // Testem prefers this...
        ENV.rootURL = '/';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.modelIDs = {
            person: 100,
            creativework: 70,
        };

        // ENV.APP.rootElement = '#ember-staging';
    }

    if (environment === 'production') {
        ENV.apiBaseUrl = 'https://share.osf.io';
        ENV.apiUrl = 'https://share.osf.io/api/v2';
        ENV.metricsAdapters = [{
            name: 'GoogleAnalytics',
            environments: ['production'],
            config: {
                id: 'UA-83881781-1',
                setFields: {
                    anonymizeIp: true,
                },
            },
        }];

        ENV.modelIDs = {
            person: 100,
            creativework: 70,
        };

        // Testem prefers this...
        ENV.rootURL = '/';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;
    }

    return ENV;
};
<|endoftext|>


<commit_before>/* Gratefully copied from https://github.com/brentvatne/react-native-animated-demo-tinder */
'use strict';

import React, {Component} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Animated,
    PanResponder,
    Image
} from 'react-native';

import clamp from 'clamp';

import Defaults from './Defaults.js';

var SWIPE_THRESHOLD = 120;

class SwipeCards extends Component {
  constructor(props) {
    super(props);

    this.state = {
      pan: new Animated.ValueXY(),
      enter: new Animated.Value(0.5),
      card: this.props.cards[0],
    }
  }

  _goToNextCard() {
    let currentCardIdx = this.props.cards.indexOf(this.state.card);
    let newIdx = currentCardIdx + 1;

    // Checks to see if last card.
    // If props.loop=true, will start again from the first card.
    let card = newIdx > this.props.cards.length - 1
      ? this.props.loop ? this.props.cards[0] : null
      : this.props.cards[newIdx];

    this.setState({
      card: card
    });
  }

  componentDidMount() {
    this._animateEntrance();
  }

  _animateEntrance() {
    Animated.spring(
      this.state.enter,
      { toValue: 1, friction: 8 }
    ).start();
  }

  componentWillMount() {
    this._panResponder = PanResponder.create({
      onMoveShouldSetResponderCapture: () => true,
      onMoveShouldSetPanResponderCapture: () => true,

      onPanResponderGrant: (e, gestureState) => {
        this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
        this.state.pan.setValue({x: 0, y: 0});
      },

      onPanResponderMove: Animated.event([
        null, {dx: this.state.pan.x, dy: this.state.pan.y},
      ]),

      onPanResponderRelease: (e, {vx, vy}) => {
        this.state.pan.flattenOffset();
        var velocity;

        if (vx >= 0) {
          velocity = clamp(vx, 3, 5);
        } else if (vx < 0) {
          velocity = clamp(vx * -1, 3, 5) * -1;
        }

        if (Math.abs(this.state.pan.x._value) > SWIPE_THRESHOLD) {

          this.state.pan.x._value > 0
            ? this.props.handleYup(this.state.card)
            : this.props.handleNope(this.state.card)

          this.props.cardRemoved
            ? this.props.cardRemoved(this.props.cards.indexOf(this.state.card))
            : null

          Animated.decay(this.state.pan, {
            velocity: {x: velocity, y: vy},
            deceleration: 0.98
          }).start(this._resetState.bind(this))
        } else {
          Animated.spring(this.state.pan, {
            toValue: {x: 0, y: 0},
            friction: 4
          }).start()
        }
      }
    })
  }

  _resetState() {
    this.state.pan.setValue({x: 0, y: 0});
    this.state.enter.setValue(0);
    this._goToNextCard();
    this._animateEntrance();
  }

  renderNoMoreCards() {
    if (this.props.renderNoMoreCards)
      return this.props.renderNoMoreCards();

    return (
      <Defaults.NoMoreCards />
    )
  }

  renderCard(cardData) {
    return this.props.renderCard(cardData)
  }

  render() {
    let { pan, enter, } = this.state;

    let [translateX, translateY] = [pan.x, pan.y];

    let rotate = pan.x.interpolate({inputRange: [-200, 0, 200], outputRange: ["-30deg", "0deg", "30deg"]});
    let opacity = pan.x.interpolate({inputRange: [-200, 0, 200], outputRange: [0.5, 1, 0.5]});
    let scale = enter;

    let animatedCardstyles = {transform: [{translateX}, {translateY}, {rotate}, {scale}], opacity};

    let yupOpacity = pan.x.interpolate({inputRange: [0, 150], outputRange: [0, 1]});
    let yupScale = pan.x.interpolate({inputRange: [0, 150], outputRange: [0.5, 1], extrapolate: 'clamp'});
    let animatedYupStyles = {transform: [{scale: yupScale}], opacity: yupOpacity}

    let nopeOpacity = pan.x.interpolate({inputRange: [-150, 0], outputRange: [1, 0]});
    let nopeScale = pan.x.interpolate({inputRange: [-150, 0], outputRange: [1, 0.5], extrapolate: 'clamp'});
    let animatedNopeStyles = {transform: [{scale: nopeScale}], opacity: nopeOpacity}

    return (
      <View style={styles.container}>
        { this.state.card
            ? (
            <Animated.View style={[styles.card, animatedCardstyles]} {...this._panResponder.panHandlers}>
              {this.renderCard(this.state.card)}
            </Animated.View>
            )
            : this.renderNoMoreCards() }

        { this.props.renderNope
          ? this.props.renderNope(pan)
          : (
              this.props.showNope
              ? (
                <Animated.View style={[styles.nope, animatedNopeStyles]}>
                  <Text style={styles.nopeText}>Nope!</Text>
                </Animated.View>
                )
              : null
            )
        }

        { this.props.renderYup
          ? this.props.renderYup(pan)
          : (
              this.props.showYup
              ? (
                <Animated.View style={[styles.yup, animatedYupStyles]}>
                  <Text style={styles.yupText}>Yup!</Text>
                </Animated.View>
              )
              : null
            )
        }

      </View>
    );
  }
}

SwipeCards.propTypes = {
  cards: React.PropTypes.array,
  renderCards: React.PropTypes.func,
  loop: React.PropTypes.bool,
  renderNoMoreCards: React.PropTypes.func,
  showYup: React.PropTypes.bool,
  showNope: React.PropTypes.bool,
  handleYup: React.PropTypes.func,
  handleNope: React.PropTypes.func
};

SwipeCards.defaultProps = {
  loop: false,
  showYup: true,
  showNope: true
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  yup: {
    borderColor: 'green',
    borderWidth: 2,
    position: 'absolute',
    padding: 20,
    bottom: 20,
    borderRadius: 5,
    right: 20,
  },
  yupText: {
    fontSize: 16,
    color: 'green',
  },
  nope: {
    borderColor: 'red',
    borderWidth: 2,
    position: 'absolute',
    bottom: 20,
    padding: 20,
    borderRadius: 5,
    left: 20,
  },
  nopeText: {
    fontSize: 16,
    color: 'red',
  }
});

export default SwipeCards
<commit_msg>Expose styles as props<commit_after>/* Gratefully copied from https://github.com/brentvatne/react-native-animated-demo-tinder */
'use strict';

import React, {Component} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Animated,
    PanResponder,
    Image
} from 'react-native';

import clamp from 'clamp';

import Defaults from './Defaults.js';

var SWIPE_THRESHOLD = 120;

class SwipeCards extends Component {
    constructor(props) {
        super(props);

        this.state = {
            pan: new Animated.ValueXY(),
            enter: new Animated.Value(0.5),
            card: this.props.cards[0],
        }
    }

    _goToNextCard() {
        let currentCardIdx = this.props.cards.indexOf(this.state.card);
        let newIdx = currentCardIdx + 1;

        // Checks to see if last card.
        // If props.loop=true, will start again from the first card.
        let card = newIdx > this.props.cards.length - 1
            ? this.props.loop ? this.props.cards[0] : null
            : this.props.cards[newIdx];

        this.setState({
            card: card
        });
    }

    componentDidMount() {
        this._animateEntrance();
    }

    _animateEntrance() {
        Animated.spring(
            this.state.enter,
            {toValue: 1, friction: 8}
        ).start();
    }

    componentWillMount() {
        this._panResponder = PanResponder.create({
            onMoveShouldSetResponderCapture: () => true,
            onMoveShouldSetPanResponderCapture: () => true,

            onPanResponderGrant: (e, gestureState) => {
                this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
                this.state.pan.setValue({x: 0, y: 0});
            },

            onPanResponderMove: Animated.event([
                null, {dx: this.state.pan.x, dy: this.state.pan.y},
            ]),

            onPanResponderRelease: (e, {vx, vy}) => {
                this.state.pan.flattenOffset();
                var velocity;

                if (vx >= 0) {
                    velocity = clamp(vx, 3, 5);
                } else if (vx < 0) {
                    velocity = clamp(vx * -1, 3, 5) * -1;
                }

                if (Math.abs(this.state.pan.x._value) > SWIPE_THRESHOLD) {

                    this.state.pan.x._value > 0
                        ? this.props.handleYup(this.state.card)
                        : this.props.handleNope(this.state.card)

                    this.props.cardRemoved
                        ? this.props.cardRemoved(this.props.cards.indexOf(this.state.card))
                        : null

                    Animated.decay(this.state.pan, {
                        velocity: {x: velocity, y: vy},
                        deceleration: 0.98
                    }).start(this._resetState.bind(this))
                } else {
                    Animated.spring(this.state.pan, {
                        toValue: {x: 0, y: 0},
                        friction: 4
                    }).start()
                }
            }
        })
    }

    _resetState() {
        this.state.pan.setValue({x: 0, y: 0});
        this.state.enter.setValue(0);
        this._goToNextCard();
        this._animateEntrance();
    }

    renderNoMoreCards() {
        if (this.props.renderNoMoreCards)
            return this.props.renderNoMoreCards();

        return (
            <Defaults.NoMoreCards />
        )
    }

    renderCard(cardData) {
        return this.props.renderCard(cardData)
    }

    render() {
        let {pan, enter,} = this.state;

        let [translateX, translateY] = [pan.x, pan.y];

        let rotate = pan.x.interpolate({inputRange: [-200, 0, 200], outputRange: ["-30deg", "0deg", "30deg"]});
        let opacity = pan.x.interpolate({inputRange: [-200, 0, 200], outputRange: [0.5, 1, 0.5]});
        let scale = enter;

        let animatedCardstyles = {transform: [{translateX}, {translateY}, {rotate}, {scale}], opacity};

        let yupOpacity = pan.x.interpolate({inputRange: [0, 150], outputRange: [0, 1]});
        let yupScale = pan.x.interpolate({inputRange: [0, 150], outputRange: [0.5, 1], extrapolate: 'clamp'});
        let animatedYupStyles = {transform: [{scale: yupScale}], opacity: yupOpacity}

        let nopeOpacity = pan.x.interpolate({inputRange: [-150, 0], outputRange: [1, 0]});
        let nopeScale = pan.x.interpolate({inputRange: [-150, 0], outputRange: [1, 0.5], extrapolate: 'clamp'});
        let animatedNopeStyles = {transform: [{scale: nopeScale}], opacity: nopeOpacity}

        return (
            <View style={this.props.containerStyle}>
                { this.state.card
                    ? (
                    <Animated.View style={[styles.card, animatedCardstyles]} {...this._panResponder.panHandlers}>
                        {this.renderCard(this.state.card)}
                    </Animated.View>
                )
                    : this.renderNoMoreCards() }

                { this.props.renderNope
                    ? this.props.renderNope(pan)
                    : (
                    this.props.showNope
                        ? (
                        <Animated.View style={[this.props.nopeStyle, animatedNopeStyles]}>
                            <Text style={this.props.nopeTextStyle}>Nope!</Text>
                        </Animated.View>
                    )
                        : null
                )
                }

                { this.props.renderYup
                    ? this.props.renderYup(pan)
                    : (
                    this.props.showYup
                        ? (
                        <Animated.View style={[this.props.yupStyle, animatedYupStyles]}>
                            <Text style={this.props.yupTextStyle}>Yup!</Text>
                        </Animated.View>
                    )
                        : null
                )
                }

            </View>
        );
    }
}

SwipeCards.propTypes = {
    cards: React.PropTypes.array,
    renderCards: React.PropTypes.func,
    loop: React.PropTypes.bool,
    renderNoMoreCards: React.PropTypes.func,
    showYup: React.PropTypes.bool,
    showNope: React.PropTypes.bool,
    handleYup: React.PropTypes.func,
    handleNope: React.PropTypes.func
};

SwipeCards.defaultProps = {
    loop: false,
    showYup: true,
    showNope: true,
    containerStyle: styles.container,
    yupStyle: styles.yup,
    yupTextStyle: styles.yupText,
    nopeStyle: styles.nope,
    nopeTextStyle: styles.nopeText
};

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    yup: {
        borderColor: 'green',
        borderWidth: 2,
        position: 'absolute',
        padding: 20,
        bottom: 20,
        borderRadius: 5,
        right: 20,
    },
    yupText: {
        fontSize: 16,
        color: 'green',
    },
    nope: {
        borderColor: 'red',
        borderWidth: 2,
        position: 'absolute',
        bottom: 20,
        padding: 20,
        borderRadius: 5,
        left: 20,
    },
    nopeText: {
        fontSize: 16,
        color: 'red',
    }
});

export default SwipeCards
<|endoftext|>


<commit_before>/* eslint-env node */

// https://dummy@getsentry.com/dummy
function getSentryServer(dsn, withProtocol = true) {
  const dsnArray = dsn.split('/');
  dsnArray.pop();
  return `${withProtocol ? `${dsnArray[0]}//` : ''}${dsnArray[2].split('@')[1]}`;
}

module.exports = function(environment) {
  let ENV = {
    appName                  : process.env.APP_NAME || 'Open Event',
    modulePrefix             : 'open-event-frontend',
    environment,
    rootURL                  : process.env.ROOT_URL || '/',
    locationType             : 'router-scroll',
    historySupportMiddleware : true,
    EmberENV                 : {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    APP: {
      apiHost      : process.env.API_HOST || 'https://open-event-api-dev.herokuapp.com',
      apiNamespace : process.env.API_NAMESPACE || 'v1'
    },

    metricsAdapters: [
      {
        name         : 'GoogleAnalytics',
        environments : ['production'],
        config       : {
          id          : process.env.GOOGLE_ANALYTICS_PROPERTY_ID || 'UA-XXXX-Y',
          debug       : environment === 'development',
          trace       : environment === 'development',
          sendHitTask : environment !== 'development'
        }
      }
    ],

    moment: {
      includeTimezone: 'subset' /* ,
      localeOutputPath : 'assets/moment-locales'*/
    },

    pace: {
      theme : 'minimal',
      color : 'blue'
    },

    SemanticUI: {
      source: {
        css        : 'bower_components/open-event-theme/dist',
        javascript : 'bower_components/open-event-theme/dist',
        images     : 'bower_components/open-event-theme/dist/themes/default/assets/images',
        fonts      : 'bower_components/open-event-theme/dist/themes/default/assets/fonts'
      }
    },

    sentry: {
      dsn         : process.env.SENTRY_DSN || 'https://dummy@getsentry.com/dummy',
      debug       : !!process.env.SENTRY_DSN,
      development : !process.env.SENTRY_DSN
    },

    emberFullCalendar: {
      includeScheduler: true
    },

    ifa: {
      enabled : false,
      inline  : false
    },

    fastboot: {
      hostWhitelist: [/.+/]
    },

    torii: { }
  };

  if (environment === 'production') {
    ENV.ifa.enabled = true;
  }

  ENV['ember-simple-auth'] = {
    authorizer: 'authorizer:jwt'
  };

  ENV['ember-cli-mirage'] = {
    enabled: false
  };

  ENV['ember-simple-auth-token'] = {
    refreshAccessTokens      : false,
    serverTokenEndpoint      : `${ENV.APP.apiHost}/auth/session`,
    identificationField      : 'email',
    passwordField            : 'password',
    tokenPropertyName        : 'access_token',
    refreshTokenPropertyName : 'refresh_token',
    authorizationPrefix      : 'JWT ',
    authorizationHeaderName  : 'Authorization',
    headers                  : {}
  };

  ENV['g-map'] = {
    libraries : ['places'],
    key       : process.env.GOOGLE_API_KEY,
    protocol  : 'https'
  };

  ENV.sentry.hostname = getSentryServer(ENV.sentry.dsn, false);
  ENV.sentry.server = getSentryServer(ENV.sentry.dsn, true);

  ENV.contentSecurityPolicy = {
    'default-src' : '\'none\'',
    'connect-src' : [
      '\'self\'',
      'ws://eventyay.local:65520',
      'ws://localhost:49153',
      'https://maps.gstatic.com',
      'https://*.eventyay.com',
      'https://eventyay.com',
      'https://open-event-api-dev.herokuapp.com',
      'www.google-analytics.com',
      'http://127.0.0.1:5000',
      ENV.sentry.hostname
    ],
    'script-src': [
      '\'self\'',
      '\'unsafe-inline\'',
      'https://*.googleapis.com',
      'https://maps.gstatic.com',
      'https://eventyay.com',
      'https://*.eventyay.com',
      'http://eventyay.local:65520',
      'http://localhost:49153',
      'www.google-analytics.com',
      'https://platform.twitter.com',
      'https://cdn.syndication.twimg.com',
      'http://127.0.0.1:5000',
      'cdn.ravenjs.com'
    ],
    'font-src': [
      '\'self\'',
      'data:',
      'https://fonts.gstatic.com'
    ],
    'img-src': [
      '*',
      'data:',
      'app.getsentry.com',
      ENV.sentry.hostname
    ],
    'style-src': [
      '\'self\'',
      '\'unsafe-inline\'',
      'https://fonts.googleapis.com',
      'https://maps.gstatic.com',
      'platform.twitter.com',
      'https://ton.twimg.com'
    ],
    'frame-src' : '*',
    'media-src' : '\'none\''
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV['ember-cli-mirage'] = {
      enabled: true
    };
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.autoboot = false;

    ENV['simple-auth'] = {
      store: 'simple-auth-session-store:ephemeral'
    };
  }

  if (environment === 'production') {
    if (process.env.DEPLOY_TARGET && process.env.DEPLOY_TARGET === 'gh-pages') {
      ENV.locationType = 'hash';
      ENV.rootURL = `/${process.env.REPO_SLUG || 'open-event-frontend'}`;
    }
  }

  return ENV;
};
<commit_msg>Add a condition to check for enviromental variable (#1366)<commit_after>/* eslint-env node */

// https://dummy@getsentry.com/dummy
function getSentryServer(dsn, withProtocol = true) {
  const dsnArray = dsn.split('/');
  dsnArray.pop();
  return `${withProtocol ? `${dsnArray[0]}//` : ''}${dsnArray[2].split('@')[1]}`;
}

module.exports = function(environment) {
  let ENV = {
    appName                  : process.env.APP_NAME || 'Open Event',
    modulePrefix             : 'open-event-frontend',
    environment,
    rootURL                  : process.env.ROOT_URL || '/',
    locationType             : 'router-scroll',
    historySupportMiddleware : true,
    EmberENV                 : {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    APP: {
      apiHost      : process.env.API_HOST || 'https://open-event-api-dev.herokuapp.com',
      apiNamespace : process.env.API_NAMESPACE || 'v1'
    },

    metricsAdapters: [{
      name         : 'GoogleAnalytics',
      environments : ['production'],
      config       : {
        id          : process.env.GOOGLE_ANALYTICS_PROPERTY_ID || 'UA-XXXX-Y',
        debug       : environment === 'development',
        trace       : environment === 'development',
        sendHitTask : environment !== 'development'
      }
    }],

    moment: {
      includeTimezone: 'subset'
      /* ,
           localeOutputPath : 'assets/moment-locales'*/
    },

    pace: {
      theme : 'minimal',
      color : 'blue'
    },

    SemanticUI: {
      source: {
        css        : 'bower_components/open-event-theme/dist',
        javascript : 'bower_components/open-event-theme/dist',
        images     : 'bower_components/open-event-theme/dist/themes/default/assets/images',
        fonts      : 'bower_components/open-event-theme/dist/themes/default/assets/fonts'
      }
    },

    sentry: {
      dsn         : process.env.SENTRY_DSN || 'https://dummy@getsentry.com/dummy',
      debug       : !!process.env.SENTRY_DSN,
      development : !process.env.SENTRY_DSN
    },

    emberFullCalendar: {
      includeScheduler: true
    },

    ifa: {
      enabled : false,
      inline  : false
    },

    fastboot: {
      hostWhitelist: [/.+/]
    },

    torii: {}
  };

  if (environment === 'production') {
    ENV.ifa.enabled = true;
  }

  ENV['ember-simple-auth'] = {
    authorizer: 'authorizer:jwt'
  };

  ENV['ember-cli-mirage'] = {
    enabled: false
  };

  ENV['ember-simple-auth-token'] = {
    refreshAccessTokens      : false,
    serverTokenEndpoint      : `${ENV.APP.apiHost}/auth/session`,
    identificationField      : 'email',
    passwordField            : 'password',
    tokenPropertyName        : 'access_token',
    refreshTokenPropertyName : 'refresh_token',
    authorizationPrefix      : 'JWT ',
    authorizationHeaderName  : 'Authorization',
    headers                  : {}
  };

  ENV['g-map'] = {
    libraries : ['places'],
    key       : process.env.GOOGLE_API_KEY,
    protocol  : 'https'
  };

  ENV.sentry.hostname = getSentryServer(ENV.sentry.dsn, false);
  ENV.sentry.server = getSentryServer(ENV.sentry.dsn, true);
  if (process.env.CSPPermissive) {
    ENV.contentSecurityPolicy = { 'default-src': ['*', '', 'data:', 'blob:', '\'unsafe-inline\'', '\'unsafe-eval\''], 'script-src': ['*', '\'unsafe-inline\'', '\'unsafe-eval\''], 'connect-src': ['*', '\'unsafe-inline\''], 'img-src': ['*', 'data:', 'blob:', '\'unsafe-inline\''], 'frame-src': ['*'], 'style-src': ['*', 'data:', 'blob:', '\'unsafe-inline\''], 'font-src': ['*', 'data:', 'blob:', '\'unsafe-inline\''] };
  } else {
    ENV.contentSecurityPolicy = {
      'default-src' : '\'none\'',
      'connect-src' : [
        '\'self\'',
        'ws://eventyay.local:65520',
        'ws://localhost:49153',
        'https://maps.gstatic.com',
        'https://*.eventyay.com',
        'https://eventyay.com',
        'https://open-event-api-dev.herokuapp.com',
        'www.google-analytics.com',
        'http://127.0.0.1:5000',
        ENV.sentry.hostname
      ],
      'script-src': [
        '\'self\'',
        '\'unsafe-inline\'',
        'https://*.googleapis.com',
        'https://maps.gstatic.com',
        'https://eventyay.com',
        'https://*.eventyay.com',
        'http://eventyay.local:65520',
        'http://localhost:49153',
        'www.google-analytics.com',
        'https://platform.twitter.com',
        'https://cdn.syndication.twimg.com',
        'http://127.0.0.1:5000',
        'cdn.ravenjs.com'
      ],
      'font-src': [
        '\'self\'',
        'data:',
        'https://fonts.gstatic.com'
      ],
      'img-src': [
        '*',
        'data:',
        'app.getsentry.com',
        ENV.sentry.hostname
      ],
      'style-src': [
        '\'self\'',
        '\'unsafe-inline\'',
        'https://fonts.googleapis.com',
        'https://maps.gstatic.com',
        'platform.twitter.com',
        'https://ton.twimg.com'
      ],
      'frame-src' : '*',
      'media-src' : '\'none\''
    };
  }
  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
    ENV['ember-cli-mirage'] = {
      enabled: true
    };
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.autoboot = false;

    ENV['simple-auth'] = {
      store: 'simple-auth-session-store:ephemeral'
    };
  }

  if (environment === 'production') {
    if (process.env.DEPLOY_TARGET && process.env.DEPLOY_TARGET === 'gh-pages') {
      ENV.locationType = 'hash';
      ENV.rootURL = `/${process.env.REPO_SLUG || 'open-event-frontend'}`;
    }
  }

  return ENV;
};
<|endoftext|>


<commit_before>/* global process */

const fs = require('fs');
const path = require('path');

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var plugin_folders;
var plugin_directory;
var exec_dir;
try { //try loading plugins from a non standalone install first
    plugin_directory = './commands/';
    plugin_folders = getDirectories(plugin_directory);
} catch (e) {//load paths for an Electrify install
    exec_dir = path.dirname(process.execPath) + '/resources/default_app/'; //need this to change node prefix for npm installs
    plugin_directory = path.dirname(process.execPath) + '/resources/default_app/plugins/';
    plugin_folders = getDirectories(plugin_directory);
}

exports.init = function() {
    preload_plugins();
};

function createNpmDependenciesArray(packageFilePath) {
    var p = require(packageFilePath);
    if (!p.dependencies) return [];
    var deps = [];
    for (var mod in p.dependencies) {
        deps.push(mod + "@" + p.dependencies[mod]);
    }

    return deps;
}

function preload_plugins() {
    var deps = [];
    var npm = require('npm');
    for (var i = 0; i < plugin_folders.length; i++) {
        try{
            require(plugin_directory + plugin_folders[i]);
        } catch(e) {
            deps = deps.concat(createNpmDependenciesArray(plugin_directory + plugin_folders[i] + '/package.json'));
        }
    }
    if(deps.length > 0) {
        npm.load({
            loaded: false
        }, function (err) {
            // catch errors
            if (plugin_directory !== './commands'){ //install plugin modules for Electrify builds
                npm.prefix = exec_dir;
                console.log(npm.prefix);
            }
            npm.commands.install(deps, function (er, data) {
                if(er){
                    console.log(er);
                }
                console.log('Plugin preload complete.');
                load_plugins();
            });

            if (err) {
                console.log('preload_plugins: ' + err);
            }
        });
    } else {
        load_plugins();
    }
}

function load_plugins() {
    var dbot = require('./bot.js');
    for (var i = 0; i < plugin_folders.length; i++) {
        var plugin;
        try{
            plugin = require(plugin_directory + plugin_folders[i]);
        } catch (err){
            console.log("Improper setup of the '" + plugin_folders[i] +"' plugin: " + err);
        }
        if (plugin){
            if ('commands' in plugin){
                for (var j = 0; j < plugin.commands.length; j++) {
                    if (plugin.commands[j] in plugin){
                        dbot.addCommand(plugin.commands[j], plugin[plugin.commands[j]]);
                    }
                }
            }
        }
    }
    console.log('Loaded ' + dbot.commandCount() + ' chat commands type <Prefix> + help in Discord for a commands list.');
}
<commit_msg>reverted things in init_commands<commit_after>/* global process */

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

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var plugin_folders;
var plugin_directory;
var exec_dir;
try { //try loading plugins from a non standalone install first
    plugin_directory = "./commands/";
    plugin_folders = getDirectories(plugin_directory);
} catch (e) { //load paths for an Electrify install
    exec_dir = path.dirname(process.execPath) + "/resources/default_app/"; //need this to change node prefix for npm installs
    plugin_directory = path.dirname(process.execPath) + "/resources/default_app/plugins/";
    plugin_folders = getDirectories(plugin_directory);
}

exports.init = function() {
    preload_plugins();
};

function createNpmDependenciesArray(packageFilePath) {
    var p = require(packageFilePath);
    if (!p.dependencies) return [];
    var deps = [];
    for (var mod in p.dependencies) {
        deps.push(mod + "@" + p.dependencies[mod]);
    }

    return deps;
}

function preload_plugins() {
    var deps = [];
    var npm = require("npm");
    for (var i = 0; i < plugin_folders.length; i++) {
        try {
            require(plugin_directory + plugin_folders[i]);
        } catch (e) {
            deps = deps.concat(createNpmDependenciesArray(plugin_directory + plugin_folders[i] + "/package.json"));
        }
    }
    if (deps.length > 0) {
        npm.load({
            loaded: false
        }, function(err) {
            // catch errors
            if (plugin_directory !== "./commands/") { //install plugin modules for Electrify builds
                npm.prefix = exec_dir;
                console.log(npm.prefix);
            }
            npm.commands.install(deps, function(er, data) {
                if (er) {
                    console.log(er);
                }
                console.log("Plugin preload complete");
                load_plugins();
            });

            if (err) {
                console.log("preload_plugins: " + err);
            }
        });
    } else {
        load_plugins();
    }
}

function load_plugins() {
    var dbot = require("./bot.js");
    for (var i = 0; i < plugin_folders.length; i++) {
        var plugin;
        try {
            plugin = require(plugin_directory + plugin_folders[i]);
        } catch (err) {
            console.log("Improper setup of the '" + plugin_folders[i] + "' plugin. : " + err);
        }
        if (plugin) {
            if ("commands" in plugin) {
                for (var j = 0; j < plugin.commands.length; j++) {
                    if (plugin.commands[j] in plugin) {
                        dbot.addCommand(plugin.commands[j], plugin[plugin.commands[j]]);
                    }
                }
            }
        }
    }
    console.log("Loaded " + dbot.commandCount() + " chat commands type <Prefix> + help in Discord for a commands list.");
}<|endoftext|>


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

function camelCase(name, capitalizeFirst) {
  return name.split('-').map(function(part, index) {
    return index || capitalizeFirst ? part[0].toUpperCase() + part.substr(1) : part;
  }).join('');
}

// new Builder(baseURL)
// new Builder(baseURL, {cfg})
// new Builder({cfg})
function Builder(baseURL, cfg) {
  if (typeof baseURL == 'object') {
    cfg = baseURL;
    baseURL = null;
  }
  config.loadSync(true);
  cfg = extendSystemConfig(config.getLoaderConfig(), cfg || {});
  if (baseURL)
    cfg.baseURL = baseURL;
  SystemJSBuilder.call(this, cfg);
}
Builder.prototype = Object.create(SystemJSBuilder.prototype);

// extend build functions with jspm 0.16 compatibility options
Builder.prototype.bundle = function(expressionOrTree, outFile, opts) {
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = opts || {};

  if (outFile)
    opts.outFile = outFile;

  /* jspm default bundle options */

  // by default we build for the browser
  if (!('browser' in opts) && !('node' in opts))
    opts.browser = true;

  if (!('lowResSourceMaps' in opts))
    opts.lowResSourceMaps = true;

  opts.buildConfig = true;

  return SystemJSBuilder.prototype.bundle.call(this, expressionOrTree, opts)
  .then(function(output) {
    // Add the bundle to config if the inject flag was given.
    if (opts.injectConfig) {
      config.loaderBrowser.file.setValue(['bundles', output.bundleName], output.modules);
      return Promise.resolve(config.save())
      .then(function() {
        return output;
      });
    }

    return output;
  });
};

Builder.prototype.buildStatic = function(expressionOrTree, outFile, opts) {
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = opts || {};

  if (outFile)
    opts.outFile = outFile;

  /* jspm default build options */

  if (!('browser' in opts) && !('node' in opts))
    opts.browser = true;

  if (!('lowResSourceMaps' in opts))
    opts.lowResSourceMaps = true;

  opts.format = opts.format || 'umd';

  if (!('rollup' in opts))
    opts.rollup = true;

  return SystemJSBuilder.prototype.buildStatic.call(this, expressionOrTree, opts);
};

exports.Builder = Builder;

exports.depCache = function(expression) {
  var systemBuilder = new Builder();

  expression = expression || config.loader.main;

  ui.log('info', 'Injecting the traced dependency tree for `' + expression + '`...');

  return systemBuilder.trace(expression, { browser: true })
  .then(function(tree) {
    var depCacheConfig = config.loaderBrowser.file.getObject(['depCache']) || {};
    var depCache = systemBuilder.getDepCache(tree);
    Object.keys(depCache).forEach(function(dep) {
      depCacheConfig[dep] = depCache[dep];
    });
    var modules = Object.keys(tree).filter(function(moduleName) {
      return tree[moduleName] && !tree[moduleName].conditional;
    });
    logTree(modules);
    config.loaderBrowser.file.setObject(['depCache'], depCacheConfig);
  })
  .then(config.save)
  .then(function() {
    ui.log('ok', 'Dependency tree injected');
  })
  .catch(function(e) {
    ui.log('err', e.stack || e);
  });
};

// options.inject, options.sourceMaps, options.minify
exports.bundle = function(moduleExpression, fileName, opts) {
  var systemBuilder = new Builder();

  opts = opts || {};
  fileName = fileName || path.resolve(config.pjson.baseURL, 'build.js');

  function bundle() {
    return Promise.resolve()
    .then(function() {
      if (!opts.sourceMaps)
        return removeExistingSourceMap(fileName);
    })
    .then(function() {
      ui.log('info', 'Building the bundle tree for %' + moduleExpression + '%...');

      return systemBuilder.bundle(moduleExpression, fileName, opts);
    })
    .then(function(output) {
      logTree(output.modules);

      if (opts.injectConfig)
        ui.log('ok', '`' + output.bundleName + '` added to config bundles.');

      logBuild(path.relative(process.cwd(), fileName), opts);
      return output;
    })
    .catch(function(e) {
      ui.log('err', e.stack || e);
      throw e;
    })
    .then(function(output) {
      if (!opts.watch)
        return output;

      // create a watcher
      buildWatch(output.modules.map(function(name) {
        return output.tree[name] && output.tree[name].path;
      }).filter(function(name) {
        return name;
      }).map(function(file) {
        return path.resolve(config.pjson.baseURL, file);
      }), function(invalidated, rebuild) {
        if (invalidated)
          systemBuilder.invalidate(toFileURL(invalidated));
        if (rebuild)
          return bundle();
      });
    });
  }

  return bundle();
};

exports.unbundle = function() {
  return config.load()
  .then(function() {
    config.loaderBrowser.file.remove(['bundles']);
    config.loaderBrowser.file.remove(['depCache']);
    return config.save();
  })
  .then(function() {
    ui.log('ok', 'Bundle configuration removed.');
  });
};

function logBuild(outFile, opts) {
  var resolution = opts.lowResSourceMaps ? '' : 'high-res ';
  ui.log('ok', 'Built into `' + outFile + '`' +
    (opts.sourceMaps ? ' with ' + resolution + 'source maps' : '') + ', ' +
    (opts.minify ? '' : 'un') + 'minified' +
    (opts.minify ? (opts.mangle ? ', ' : ', un') + 'mangled' : '') +
    (opts.extra ? opts.extra : '') + '.');
}

// options.minify, options.sourceMaps
exports.build = function(expression, fileName, opts) {
  var systemBuilder = new Builder();

  opts = opts || {};
  fileName = fileName || path.resolve(config.pjson.baseURL, 'build.js');

  function build() {
    return Promise.resolve()
    .then(function() {
      if (!opts.sourceMaps)
        return removeExistingSourceMap(fileName);
    })
    .then(function() {
      ui.log('info', 'Creating the single-file build for %' + expression + '%...');

      return systemBuilder.buildStatic(expression, fileName, opts);
    })
    .then(function(output) {
      logTree(output.modules, output.inlineMap ? output.inlineMap : opts.rollup);
      opts.extra = ' as %' + opts.format + '%';
      logBuild(path.relative(process.cwd(), fileName), opts);
      return output;
    })
    .catch(function(e) {
      // catch sfx globals error to give a better error message
      if (e.toString().indexOf('globalDeps option') != -1) {
        var module = e.toString().match(/dependency "([^"]+)"/);
        module = module && module[1];
        throw 'Build exclusion "' + module + '" needs an external reference.\n\t\t\tEither output to a module format like %--format amd% or map the external module to an environment global ' +
            'via %--global-deps "{\'' + module + '\': \'' + camelCase(module, true) + '\'}"%';
      }
      if (e.toString().indexOf('globalName option') != -1) {
        var generatedGlobalName = camelCase((expression.substr(expression.length - 3, 3) == '.js' ? expression.substr(0, expression.length - 3) : expression).split(/ |\//)[0]);
        ui.log('warn', 'Build output to %' + opts.format + '% requires the global name to be set.\n' +
          'Added default %--global-name ' + generatedGlobalName + '% option.\n');
        opts.globalName = generatedGlobalName;
        return build();
      }
      else
        throw e;
    })
    .catch(function(e) {
      ui.log('err', e.stack || e);
      throw e;
    })
    .then(function(output) {
      if (!opts.watch)
        return output;

      // create a watcher
      buildWatch(output.modules.map(function(name) {
        return output.tree[name] && output.tree[name].path;
      }).filter(function(name) {
        return name;
      }), function(invalidated, rebuild) {
        if (invalidated)
          systemBuilder.invalidate(invalidated);
        if (rebuild)
          return build();
      });
    });
  }

  return build();
};

var watchman = true;
function buildWatch(files, fn) {
  var sane = require('sane');

  // get the lowest directory from the files listing
  files.sort(function(f1,f2){
    return path.dirname(f1).length -  path.dirname(f2).length;
  });
  var lowestDir = path.dirname(files[0]);

  var relFiles = files.map(function(file) {
    if (lowestDir == '.')
      return file;
    return file.substr(lowestDir.length + 1);
  });

  var watcher = sane(lowestDir, { glob: relFiles, watchman: watchman });
  watcher.on('error', function(e) {
    if (e.toString().indexOf('Watchman was not found in PATH') == -1) {
      ui.log('err', e.stack || e);
      return;
    }

    watchman = false;
    buildWatch(files, fn);
  });

  watcher.on('ready', function() {
    ui.log('info', 'Watching %' + lowestDir + '% for changes ' + (watchman ? 'with Watchman' : 'with Node native watcher') + '...');
  });
  watcher.on('add', function(filepath) {
    var file = path.join(lowestDir, filepath);
    ui.log('ok', 'File `' + file + '` created, rebuilding...');
    fn(file, true)
    .then(function() {
      watcher.close();
    });
  });
  watcher.on('delete', function(filepath) {
    var file = path.join(lowestDir, filepath);
    ui.log('warn', 'File `' + file + '` removed, cache invalidated pending rebuild...');
    fn(file, false);
  });
  watcher.on('change', function(filepath) {
    var file = path.join(lowestDir, filepath);
    ui.log('ok', 'File `' + file + '` changed, rebuilding...');
    fn(file, true)
    .then(function() {
      watcher.close();
    });
  });
}

function logTree(modules, inlineMap) {
  inlineMap = inlineMap || {};
  var inlinedModules = [];

  Object.keys(inlineMap).forEach(function(inlineParent) {
    inlinedModules = inlinedModules.concat(inlineMap[inlineParent]);
  });

  ui.log('info', '');

  if (inlineMap['@dummy-entry-point'])
    logDepTree(inlineMap['@dummy-entry-point'], false);

  if (inlineMap !== true)
    modules.sort().forEach(function(name) {
      if (inlinedModules.indexOf(name) == -1)
        ui.log('info', '  `' + name + '`');

      if (inlineMap[name])
        logDepTree(inlineMap[name], true);
    });
  else
    logDepTree(modules, false);

  if (inlinedModules.length || inlineMap === true)
    ui.log('info', '');

  if (inlinedModules.length)
    ui.log('ok', '%Optimized% - modules in bold inlined via Rollup static optimizations.');
  if (inlineMap === true)
    ui.log('ok', '%Fully-optimized% - entire tree built via Rollup static optimization.');
  ui.log('info', '');
}

function logDepTree(items, firstParent) {
  items.forEach(function(item, index) {
    ui.log('info', '  `' + (items.length == 1 ? '──' : index == items.length - 1 ? '└─' : index == 0 && !firstParent ? '┌─' : '├─') + ' %' + item + '%`');
  });
}

function removeExistingSourceMap(fileName) {
  return asp(fs.unlink)(fileName + '.map')
  .catch(function(e) {
    if (e.code === 'ENOENT')
      return;
    throw e;
  });
}
<commit_msg>Split and compare length of folders<commit_after>/*
 *   Copyright 2014-2016 Guy Bedford (http://guybedford.com)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
var ui = require('./ui');
var path = require('path');
var config = require('./config');
var SystemJSBuilder = require('systemjs-builder');
var fs = require('fs');
var asp = require('bluebird').Promise.promisify;
var extendSystemConfig = require('./common').extendSystemConfig;
var toFileURL = require('./common').toFileURL;

function camelCase(name, capitalizeFirst) {
  return name.split('-').map(function(part, index) {
    return index || capitalizeFirst ? part[0].toUpperCase() + part.substr(1) : part;
  }).join('');
}

// new Builder(baseURL)
// new Builder(baseURL, {cfg})
// new Builder({cfg})
function Builder(baseURL, cfg) {
  if (typeof baseURL == 'object') {
    cfg = baseURL;
    baseURL = null;
  }
  config.loadSync(true);
  cfg = extendSystemConfig(config.getLoaderConfig(), cfg || {});
  if (baseURL)
    cfg.baseURL = baseURL;
  SystemJSBuilder.call(this, cfg);
}
Builder.prototype = Object.create(SystemJSBuilder.prototype);

// extend build functions with jspm 0.16 compatibility options
Builder.prototype.bundle = function(expressionOrTree, outFile, opts) {
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = opts || {};

  if (outFile)
    opts.outFile = outFile;

  /* jspm default bundle options */

  // by default we build for the browser
  if (!('browser' in opts) && !('node' in opts))
    opts.browser = true;

  if (!('lowResSourceMaps' in opts))
    opts.lowResSourceMaps = true;

  opts.buildConfig = true;

  return SystemJSBuilder.prototype.bundle.call(this, expressionOrTree, opts)
  .then(function(output) {
    // Add the bundle to config if the inject flag was given.
    if (opts.injectConfig) {
      config.loaderBrowser.file.setValue(['bundles', output.bundleName], output.modules);
      return Promise.resolve(config.save())
      .then(function() {
        return output;
      });
    }

    return output;
  });
};

Builder.prototype.buildStatic = function(expressionOrTree, outFile, opts) {
  if (outFile && typeof outFile === 'object') {
    opts = outFile;
    outFile = undefined;
  }

  opts = opts || {};

  if (outFile)
    opts.outFile = outFile;

  /* jspm default build options */

  if (!('browser' in opts) && !('node' in opts))
    opts.browser = true;

  if (!('lowResSourceMaps' in opts))
    opts.lowResSourceMaps = true;

  opts.format = opts.format || 'umd';

  if (!('rollup' in opts))
    opts.rollup = true;

  return SystemJSBuilder.prototype.buildStatic.call(this, expressionOrTree, opts);
};

exports.Builder = Builder;

exports.depCache = function(expression) {
  var systemBuilder = new Builder();

  expression = expression || config.loader.main;

  ui.log('info', 'Injecting the traced dependency tree for `' + expression + '`...');

  return systemBuilder.trace(expression, { browser: true })
  .then(function(tree) {
    var depCacheConfig = config.loaderBrowser.file.getObject(['depCache']) || {};
    var depCache = systemBuilder.getDepCache(tree);
    Object.keys(depCache).forEach(function(dep) {
      depCacheConfig[dep] = depCache[dep];
    });
    var modules = Object.keys(tree).filter(function(moduleName) {
      return tree[moduleName] && !tree[moduleName].conditional;
    });
    logTree(modules);
    config.loaderBrowser.file.setObject(['depCache'], depCacheConfig);
  })
  .then(config.save)
  .then(function() {
    ui.log('ok', 'Dependency tree injected');
  })
  .catch(function(e) {
    ui.log('err', e.stack || e);
  });
};

// options.inject, options.sourceMaps, options.minify
exports.bundle = function(moduleExpression, fileName, opts) {
  var systemBuilder = new Builder();

  opts = opts || {};
  fileName = fileName || path.resolve(config.pjson.baseURL, 'build.js');

  function bundle() {
    return Promise.resolve()
    .then(function() {
      if (!opts.sourceMaps)
        return removeExistingSourceMap(fileName);
    })
    .then(function() {
      ui.log('info', 'Building the bundle tree for %' + moduleExpression + '%...');

      return systemBuilder.bundle(moduleExpression, fileName, opts);
    })
    .then(function(output) {
      logTree(output.modules);

      if (opts.injectConfig)
        ui.log('ok', '`' + output.bundleName + '` added to config bundles.');

      logBuild(path.relative(process.cwd(), fileName), opts);
      return output;
    })
    .catch(function(e) {
      ui.log('err', e.stack || e);
      throw e;
    })
    .then(function(output) {
      if (!opts.watch)
        return output;

      // create a watcher
      buildWatch(output.modules.map(function(name) {
        return output.tree[name] && output.tree[name].path;
      }).filter(function(name) {
        return name;
      }).map(function(file) {
        return path.resolve(config.pjson.baseURL, file);
      }), function(invalidated, rebuild) {
        if (invalidated)
          systemBuilder.invalidate(toFileURL(invalidated));
        if (rebuild)
          return bundle();
      });
    });
  }

  return bundle();
};

exports.unbundle = function() {
  return config.load()
  .then(function() {
    config.loaderBrowser.file.remove(['bundles']);
    config.loaderBrowser.file.remove(['depCache']);
    return config.save();
  })
  .then(function() {
    ui.log('ok', 'Bundle configuration removed.');
  });
};

function logBuild(outFile, opts) {
  var resolution = opts.lowResSourceMaps ? '' : 'high-res ';
  ui.log('ok', 'Built into `' + outFile + '`' +
    (opts.sourceMaps ? ' with ' + resolution + 'source maps' : '') + ', ' +
    (opts.minify ? '' : 'un') + 'minified' +
    (opts.minify ? (opts.mangle ? ', ' : ', un') + 'mangled' : '') +
    (opts.extra ? opts.extra : '') + '.');
}

// options.minify, options.sourceMaps
exports.build = function(expression, fileName, opts) {
  var systemBuilder = new Builder();

  opts = opts || {};
  fileName = fileName || path.resolve(config.pjson.baseURL, 'build.js');

  function build() {
    return Promise.resolve()
    .then(function() {
      if (!opts.sourceMaps)
        return removeExistingSourceMap(fileName);
    })
    .then(function() {
      ui.log('info', 'Creating the single-file build for %' + expression + '%...');

      return systemBuilder.buildStatic(expression, fileName, opts);
    })
    .then(function(output) {
      logTree(output.modules, output.inlineMap ? output.inlineMap : opts.rollup);
      opts.extra = ' as %' + opts.format + '%';
      logBuild(path.relative(process.cwd(), fileName), opts);
      return output;
    })
    .catch(function(e) {
      // catch sfx globals error to give a better error message
      if (e.toString().indexOf('globalDeps option') != -1) {
        var module = e.toString().match(/dependency "([^"]+)"/);
        module = module && module[1];
        throw 'Build exclusion "' + module + '" needs an external reference.\n\t\t\tEither output to a module format like %--format amd% or map the external module to an environment global ' +
            'via %--global-deps "{\'' + module + '\': \'' + camelCase(module, true) + '\'}"%';
      }
      if (e.toString().indexOf('globalName option') != -1) {
        var generatedGlobalName = camelCase((expression.substr(expression.length - 3, 3) == '.js' ? expression.substr(0, expression.length - 3) : expression).split(/ |\//)[0]);
        ui.log('warn', 'Build output to %' + opts.format + '% requires the global name to be set.\n' +
          'Added default %--global-name ' + generatedGlobalName + '% option.\n');
        opts.globalName = generatedGlobalName;
        return build();
      }
      else
        throw e;
    })
    .catch(function(e) {
      ui.log('err', e.stack || e);
      throw e;
    })
    .then(function(output) {
      if (!opts.watch)
        return output;

      // create a watcher
      buildWatch(output.modules.map(function(name) {
        return output.tree[name] && output.tree[name].path;
      }).filter(function(name) {
        return name;
      }), function(invalidated, rebuild) {
        if (invalidated)
          systemBuilder.invalidate(invalidated);
        if (rebuild)
          return build();
      });
    });
  }

  return build();
};

var watchman = true;
function buildWatch(files, fn) {
  var sane = require('sane');

  // get the lowest directory from the files listing
  var lowestDir = path.dirname(files[0]);
  files.forEach(function(file) {
    if (path.dirname(file).split('/').length < lowestDir.split('/').length)
      lowestDir = path.dirname(file);
  });

  var relFiles = files.map(function(file) {
    if (lowestDir == '.')
      return file;
    return file.substr(lowestDir.length + 1);
  });

  var watcher = sane(lowestDir, { glob: relFiles, watchman: watchman });
  watcher.on('error', function(e) {
    if (e.toString().indexOf('Watchman was not found in PATH') == -1) {
      ui.log('err', e.stack || e);
      return;
    }

    watchman = false;
    buildWatch(files, fn);
  });

  watcher.on('ready', function() {
    ui.log('info', 'Watching %' + lowestDir + '% for changes ' + (watchman ? 'with Watchman' : 'with Node native watcher') + '...');
  });
  watcher.on('add', function(filepath) {
    var file = path.join(lowestDir, filepath);
    ui.log('ok', 'File `' + file + '` created, rebuilding...');
    fn(file, true)
    .then(function() {
      watcher.close();
    });
  });
  watcher.on('delete', function(filepath) {
    var file = path.join(lowestDir, filepath);
    ui.log('warn', 'File `' + file + '` removed, cache invalidated pending rebuild...');
    fn(file, false);
  });
  watcher.on('change', function(filepath) {
    var file = path.join(lowestDir, filepath);
    ui.log('ok', 'File `' + file + '` changed, rebuilding...');
    fn(file, true)
    .then(function() {
      watcher.close();
    });
  });
}

function logTree(modules, inlineMap) {
  inlineMap = inlineMap || {};
  var inlinedModules = [];

  Object.keys(inlineMap).forEach(function(inlineParent) {
    inlinedModules = inlinedModules.concat(inlineMap[inlineParent]);
  });

  ui.log('info', '');

  if (inlineMap['@dummy-entry-point'])
    logDepTree(inlineMap['@dummy-entry-point'], false);

  if (inlineMap !== true)
    modules.sort().forEach(function(name) {
      if (inlinedModules.indexOf(name) == -1)
        ui.log('info', '  `' + name + '`');

      if (inlineMap[name])
        logDepTree(inlineMap[name], true);
    });
  else
    logDepTree(modules, false);

  if (inlinedModules.length || inlineMap === true)
    ui.log('info', '');

  if (inlinedModules.length)
    ui.log('ok', '%Optimized% - modules in bold inlined via Rollup static optimizations.');
  if (inlineMap === true)
    ui.log('ok', '%Fully-optimized% - entire tree built via Rollup static optimization.');
  ui.log('info', '');
}

function logDepTree(items, firstParent) {
  items.forEach(function(item, index) {
    ui.log('info', '  `' + (items.length == 1 ? '──' : index == items.length - 1 ? '└─' : index == 0 && !firstParent ? '┌─' : '├─') + ' %' + item + '%`');
  });
}

function removeExistingSourceMap(fileName) {
  return asp(fs.unlink)(fileName + '.map')
  .catch(function(e) {
    if (e.code === 'ENOENT')
      return;
    throw e;
  });
}
<|endoftext|>


<commit_before>chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

		var setTimeOut;
		$('#bodyContent a').on('mouseenter', function(event){
			var obj = $(this);

			setTimeOut = setTimeout(function(){
				if(obj.children('img').length === 0)
				{
					performWork(obj, event);
				}
			}, 200);

		}).on('mouseleave', function(){
			clearTimeout(setTimeOut);
			clearData();
		});;

		$('body').on('click', function(){
			clearData();
		});

		function clearData()
		{
			$('#popup-notification').remove();
			$(this).attr('title', $(this).attr('data-title'));
		}

		function performWork(element, event)
		{
			//Clear the data
			clearData();
			//Remove the title attribute
			element.removeAttr('title');

			var baseURL = window.location.origin, //Get the URL
			    url     = element.attr('href'), //Get the href of the link
			    fullURL = baseURL+url, //Combine those two together to get the link
			    x = event.pageX, // Get x position of mouse
			    y = event.pageY; // get right position of mouse

			$.get(fullURL, function(data) {
			    var content = $(data).find('#bodyContent').find('p').html(),
			        cssRules = {
			        	position: 'fixed',
			        	top: 10+"px",
			        	left: 10+"px",
			        	right: 10+"px",
			        	maxHeight: 500+"px",
			        	padding: 1.4+"em",
			        	background: "#fff",
			        	boxShadow: "2px 2px 15px rgba(50,50,50,.75)",
			        	zIndex: 100
			        };

			    $('
'+content+'
').css(cssRules).appendTo('body').fadeIn();
			});
		}
	}
	}, 10);
});<commit_msg>fix typo<commit_after>chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

		var setTimeOut;
		$('#bodyContent a').on('mouseenter', function(event){
			var obj = $(this);

			setTimeOut = setTimeout(function(){
				if(obj.children('img').length === 0)
				{
					performWork(obj, event);
				}
			}, 200);

		}).on('mouseleave', function(){
			clearTimeout(setTimeOut);
			clearData();
		});

		$('body').on('click', function(){
			clearData();
		});

		function clearData()
		{
			$('#popup-notification').remove();
			$(this).attr('title', $(this).attr('data-title'));
		}

		function performWork(element, event)
		{
			//Clear the data
			clearData();
			//Remove the title attribute
			element.removeAttr('title');

			var baseURL = window.location.origin, //Get the URL
			    url     = element.attr('href'), //Get the href of the link
			    fullURL = baseURL+url, //Combine those two together to get the link
			    x = event.pageX, // Get x position of mouse
			    y = event.pageY; // get right position of mouse

			$.get(fullURL, function(data) {
			    var content = $(data).find('#bodyContent').find('p').html(),
			        cssRules = {
			        	position: 'fixed',
			        	top: 10+"px",
			        	left: 10+"px",
			        	right: 10+"px",
			        	maxHeight: 500+"px",
			        	padding: 1.4+"em",
			        	background: "#fff",
			        	boxShadow: "2px 2px 15px rgba(50,50,50,.75)",
			        	zIndex: 100
			        };

			    $('
'+content+'
').css(cssRules).appendTo('body').fadeIn();
			});
		}
	}
	}, 10);
});<|endoftext|>