<commit_before>;(function($$){

	// shamelessly taken from jQuery
	// https://github.com/jquery/jquery/blob/master/src/event.js

	$$.Event = function( src, props ) {
		// Allow instantiation without the 'new' keyword
		if ( !(this instanceof $$.Event) ) {
			return new $$.Event( src, props );
		}

		// Event object
		if ( src && src.type ) {
			this.originalEvent = src;
			this.type = src.type;

			// Events bubbling up the document may have been marked as prevented
			// by a handler lower down the tree; reflect the correct value.
			this.isDefaultPrevented = ( src.defaultPrevented || // src.returnValue === false || // commented out old IE support
				src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;

		// Event type
		} else {
			this.type = src;
		}

		// Put explicitly provided properties onto the event object
		if ( props ) {
			$$.util.extend( this, props );
		}

		// Create a timestamp if incoming event doesn't have one
		this.timeStamp = src && src.timeStamp || +new Date;

		// Mark it as fixed
		//this[ jQuery.expando ] = true;
	};

	function returnFalse() {
		return false;
	}
	function returnTrue() {
		return true;
	}

	// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
	// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
	$$.Event.prototype = {
		preventDefault: function() {
			this.isDefaultPrevented = returnTrue;

			var e = this.originalEvent;
			if ( !e ) {
				return;
			}

			// if preventDefault exists run it on the original event
			if ( e.preventDefault ) {
				e.preventDefault();

			// otherwise set the returnValue property of the original event to false (IE)
			} else {
				// e.returnValue = false; // don't support old IE anymore
			}
		},
		stopPropagation: function() {
			this.isPropagationStopped = returnTrue;

			var e = this.originalEvent;
			if ( !e ) {
				return;
			}
			// if stopPropagation exists run it on the original event
			if ( e.stopPropagation ) {
				e.stopPropagation();
			}
			// otherwise set the cancelBubble property of the original event to true (IE)
			e.cancelBubble = true;
		},
		stopImmediatePropagation: function() {
			this.isImmediatePropagationStopped = returnTrue;
			this.stopPropagation();
		},
		isDefaultPrevented: returnFalse,
		isPropagationStopped: returnFalse,
		isImmediatePropagationStopped: returnFalse
	};

})( cytoscape );
<commit_msg>more old ie support cleanup<commit_after>;(function($$){

	// shamelessly taken from jQuery
	// https://github.com/jquery/jquery/blob/master/src/event.js

	$$.Event = function( src, props ) {
		// Allow instantiation without the 'new' keyword
		if ( !(this instanceof $$.Event) ) {
			return new $$.Event( src, props );
		}

		// Event object
		if ( src && src.type ) {
			this.originalEvent = src;
			this.type = src.type;

			// Events bubbling up the document may have been marked as prevented
			// by a handler lower down the tree; reflect the correct value.
			this.isDefaultPrevented = ( src.defaultPrevented ||
				src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;

		// Event type
		} else {
			this.type = src;
		}

		// Put explicitly provided properties onto the event object
		if ( props ) {
			$$.util.extend( this, props );
		}

		// Create a timestamp if incoming event doesn't have one
		this.timeStamp = src && src.timeStamp || +new Date;

		// Mark it as fixed
		//this[ jQuery.expando ] = true;
	};

	function returnFalse() {
		return false;
	}
	function returnTrue() {
		return true;
	}

	// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
	// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
	$$.Event.prototype = {
		preventDefault: function() {
			this.isDefaultPrevented = returnTrue;

			var e = this.originalEvent;
			if ( !e ) {
				return;
			}

			// if preventDefault exists run it on the original event
			if ( e.preventDefault ) {
				e.preventDefault();
			}
		},
		stopPropagation: function() {
			this.isPropagationStopped = returnTrue;

			var e = this.originalEvent;
			if ( !e ) {
				return;
			}
			// if stopPropagation exists run it on the original event
			if ( e.stopPropagation ) {
				e.stopPropagation();
			}
		},
		stopImmediatePropagation: function() {
			this.isImmediatePropagationStopped = returnTrue;
			this.stopPropagation();
		},
		isDefaultPrevented: returnFalse,
		isPropagationStopped: returnFalse,
		isImmediatePropagationStopped: returnFalse
	};

})( cytoscape );
<|endoftext|>


<commit_before>/**
 * @license farbs - A Framework Agnostic Registry Based Skeleton for decoupled
 *  UI components
 * Copyright (c) 2013 Jens Arps
 * http://jensarps.de/
 *
 * Licensed under the MIT (X11) license
 */
define(function () {

  /**
   * The farbs object.
   *
   * @type {Object}
   * @exports farbs
   * @version 0.2
   */
  var farbs = {

    /**
     * The version of this farbs object.
     */
    version: '0.3.0',

    /**
     * The class registry.
     *
     * Use this to get access to classes.
     */
    classRegistry: {},

    /**
     * The instance registry.
     *
     * Use this to get access to instances of, e.g. UI widgets.
     */
    instRegistry: {},

    /**
     * The method registry.
     *
     * Use this to get access to methods.
     */
    methodRegistry: {},

    /**
     * Holds listeners for pub/sub mechanism.
     */
    listeners: {},

    /**
     * Registers a class for later use.
     *
     * @param {string} id The id (== class name) to register the class with
     * @param {Object} ctor The class to register
     */
    registerClass: function (id, ctor) {
      this.classRegistry[id] = ctor;
    },

    /**
     * Registers an instance of a class.
     *
     * @param {string} id The id to register the instance with
     * @param {Object} inst The instance to register
     */
    registerInstance: function (id, inst) {
      this.instRegistry[id] = inst;
    },

    /**
     * Registers a method.
     *
     * @param {string} id The id of the method to register
     * @param {Function} func The method to register
     */
    registerMethod: function (id, func) {
      this.methodRegistry[id] = func;
    },

    /**
     * Publishes a topic to registered listeners
     *
     * @param {string} topic The topic
     * @param {*} [data] The data to pass to listeners
     */
    publish: function (topic, data) {
      if (!this.listeners[topic]) {
        return;
      }
      this.listeners[topic].forEach(function (callback) {
        callback(data);
      });
    },

    /**
     * Subscribes a listener to a topic.
     *
     * @param {string} topic The topic
     * @param {Function} callback The listener
     */
    subscribe: function (topic, callback) {
      if (!this.listeners[topic]) {
        this.listeners[topic] = [];
      }
      this.listeners[topic].push(callback);
    },

    /**
     * Unsubscribes a listener from a topic.
     *
     * @param {string} topic The topic
     * @param {Function} callback The listener
     */
    unsubscribe: function (topic, callback) {
      var listeners = this.listeners[topic];
      if (!listeners) {
        return;
      }
      for (var i = listeners.length - 1; i >= 0; i--) {
        if (listeners[i] === callback) {
          listeners.splice(i, 1);
        }
      }
    },

    /**
     * Parses a DOM (Sub-)Tree and instantiates classes for nodes containing
     * a data-farbs_type attribute. Will register instances in farbs.instRegistry.
     *
     * @param {HTMLElement} [parentNode] The node in the tree to begin parsing
     *  at. Optional.
     */
    parse: function (parentNode) {
      parentNode = parentNode || document.documentElement;
      [].slice.call(parentNode.querySelectorAll('[data-farbs_type]')).forEach(function (node) {
        var type = node.dataset.farbs_type,
            ctor = farbs.classRegistry[type];

        if (!ctor) {
          return;
        }

        if (!node.id) {
          node.id = '_farbs_widget_' + _uid++;
        }
        var inst = new ctor(node, farbs);

        for (var key in node.dataset) {
          if (key.slice(0, 5) == 'farbs') {
            var propname = key.slice(6);
            if (propname != 'type') {
              inst[propname] = node.dataset[key];
            }
          }
        }
        farbs.registerInstance(node.id, inst);
      });
    }

  };

  var _uid = 0;

  return farbs;

});
<commit_msg>Make attribute name configurable<commit_after>/**
 * @license farbs - A Framework Agnostic Registry Based Skeleton for decoupled
 *  UI components
 * Copyright (c) 2013 Jens Arps
 * http://jensarps.de/
 *
 * Licensed under the MIT (X11) license
 */
define(function () {

  /**
   * The farbs object.
   *
   * @type {Object}
   * @exports farbs
   * @version 0.2
   */
  var farbs = {

    /**
     * The version of this farbs object.
     */
    version: '0.3.0',

    /**
     * The attribute name farbs uses.
     */
    attributeName: 'farbs',

    /**
     * The class registry.
     *
     * Use this to get access to classes.
     */
    classRegistry: {},

    /**
     * The instance registry.
     *
     * Use this to get access to instances of, e.g. UI widgets.
     */
    instRegistry: {},

    /**
     * The method registry.
     *
     * Use this to get access to methods.
     */
    methodRegistry: {},

    /**
     * Holds listeners for pub/sub mechanism.
     */
    listeners: {},

    /**
     * Registers a class for later use.
     *
     * @param {string} id The id (== class name) to register the class with
     * @param {Object} ctor The class to register
     */
    registerClass: function (id, ctor) {
      this.classRegistry[id] = ctor;
    },

    /**
     * Registers an instance of a class.
     *
     * @param {string} id The id to register the instance with
     * @param {Object} inst The instance to register
     */
    registerInstance: function (id, inst) {
      this.instRegistry[id] = inst;
    },

    /**
     * Registers a method.
     *
     * @param {string} id The id of the method to register
     * @param {Function} func The method to register
     */
    registerMethod: function (id, func) {
      this.methodRegistry[id] = func;
    },

    /**
     * Publishes a topic to registered listeners
     *
     * @param {string} topic The topic
     * @param {*} [data] The data to pass to listeners
     */
    publish: function (topic, data) {
      if (!this.listeners[topic]) {
        return;
      }
      this.listeners[topic].forEach(function (callback) {
        callback(data);
      });
    },

    /**
     * Subscribes a listener to a topic.
     *
     * @param {string} topic The topic
     * @param {Function} callback The listener
     */
    subscribe: function (topic, callback) {
      if (!this.listeners[topic]) {
        this.listeners[topic] = [];
      }
      this.listeners[topic].push(callback);
    },

    /**
     * Unsubscribes a listener from a topic.
     *
     * @param {string} topic The topic
     * @param {Function} callback The listener
     */
    unsubscribe: function (topic, callback) {
      var listeners = this.listeners[topic];
      if (!listeners) {
        return;
      }
      for (var i = listeners.length - 1; i >= 0; i--) {
        if (listeners[i] === callback) {
          listeners.splice(i, 1);
        }
      }
    },

    /**
     * Parses a DOM (Sub-)Tree and instantiates classes for nodes containing
     * a data-farbs_type attribute. Will register instances in farbs.instRegistry.
     *
     * @param {HTMLElement} [parentNode] The node in the tree to begin parsing
     *  at. Optional.
     */
    parse: function (parentNode) {
      parentNode = parentNode || document.documentElement;
      var n = farbs.attributeName,
          t = n + '_type',
          l = n.length;

      [].slice.call(parentNode.querySelectorAll('[data-' + t + ']')).forEach(function (node) {

        var type = node.dataset[t],
            ctor = farbs.classRegistry[type];

        if (!ctor) {
          return;
        }

        if (!node.id) {
          node.id = '_' + n + '_widget_' + _uid++;
        }
        var inst = new ctor(node, farbs);

        for (var key in node.dataset) {
          if (key.slice(0, l) == n) {
            var propname = key.slice(l + 1);
            if (propname != 'type') {
              inst[propname] = node.dataset[key];
            }
          }
        }
        farbs.registerInstance(node.id, inst);
      });
    }

  };

  var _uid = 0;

  return farbs;

});
<|endoftext|>


<commit_before><commit_msg>Add field helper fns<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

export default function(WrappedComponent) {
  class Field extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        checked: this.checked(),
        message: this.props.form.message,
        timestamp: 0,
        valid: true,
        value: this.props.form.initialValue
      };
      this.checked = this.checked.bind(this);
      this.handleChange = this.handleChange.bind(this);
      this.validate = this.validate.bind(this);
    }

    componentDidMount() {
      this.props.form.registerField(this);

      this.validators = this.props.validators || [];
      if (this.component && this.component.validators) {
        this.validators = this.component.validators.concat(this.validators);
      }
    }

    componentWillUnmount() {
      this.props.form.unregisterField(this);
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.form.message !== this.props.form.message) {
        this.setState({message: nextProps.form.message});
      }
    }

    validate() {
      for (const validator of this.validators) {
        const result = validator(this.state.value);
        if (result !== undefined) {
          this.setState({valid: false, message: result});
          return false;
        }
      }
      this.setState({valid: true, message: ''});
      return true;
    }

    handleChange(event) {
      this.setState({
        type: event.target.type,
        timestamp: Date.now()
      });

      return new Promise(resolve => {
        switch (event.target.type) {
          case 'checkbox':
            this.setState({
              checked: event.target.checked,
              value: event.target.checked ? event.target.value : null
            }, resolve);
            break;
          case 'select-multiple':
            this.setState({
              value: Array.from(event.target.options)
                .map(option => option.selected ? option.value : null)
                .filter(value => value)
            }, resolve);
            break;
          case 'file':
            this.setState({value: event.target.files}, resolve);
            break;
          default:
            this.setState({value: event.target.value}, resolve);
        }
      });
    }

    checked() {
      return (
        this.props.checked ||
        this.props.value &&
        this.props.value === this.props.form.initialValue ||
        this.props.form.initialValue && !this.props.value ||
        this.props.form.initialValue &&
        this.props.form.initialValue.constructor === Array &&
        this.props.form.initialValue.indexOf(this.props.value) >= 0
      );
    }

    elementProps() {
      const elementProps = Object.assign({
        defaultChecked: this.checked(),
        defaultValue: this.props.value || this.props.form.initialValue,
        onChange: this.handleChange
      }, this.props);

      const discard = ['checked', 'form', 'label', 'validators', 'value'];

      discard.forEach(property => {
        delete elementProps[property];
      });

      return elementProps;
    }

    render() {
      return (
        <WrappedComponent
          element={this.elementProps()}
          {...this.props}
          message={this.state.message}
          valid={this.state.valid}
          validate={this.validate}
          value={this.state.value}
          ref={component => { this.component = component;}}
        />
      );
    }
  }

  Field.propTypes = {
    name: PropTypes.string.isRequired
  };

  return Field;
}

<commit_msg>Remove unnecessary props.checked conditional<commit_after>import React from 'react';
import PropTypes from 'prop-types';

export default function(WrappedComponent) {
  class Field extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        checked: this.checked(),
        message: this.props.form.message,
        timestamp: 0,
        valid: true,
        value: this.props.form.initialValue
      };
      this.checked = this.checked.bind(this);
      this.handleChange = this.handleChange.bind(this);
      this.validate = this.validate.bind(this);
    }

    componentDidMount() {
      this.props.form.registerField(this);

      this.validators = this.props.validators || [];
      if (this.component && this.component.validators) {
        this.validators = this.component.validators.concat(this.validators);
      }
    }

    componentWillUnmount() {
      this.props.form.unregisterField(this);
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.form.message !== this.props.form.message) {
        this.setState({message: nextProps.form.message});
      }
    }

    validate() {
      for (const validator of this.validators) {
        const result = validator(this.state.value);
        if (result !== undefined) {
          this.setState({valid: false, message: result});
          return false;
        }
      }
      this.setState({valid: true, message: ''});
      return true;
    }

    handleChange(event) {
      this.setState({
        type: event.target.type,
        timestamp: Date.now()
      });

      return new Promise(resolve => {
        switch (event.target.type) {
          case 'checkbox':
            this.setState({
              checked: event.target.checked,
              value: event.target.checked ? event.target.value : null
            }, resolve);
            break;
          case 'select-multiple':
            this.setState({
              value: Array.from(event.target.options)
                .map(option => option.selected ? option.value : null)
                .filter(value => value)
            }, resolve);
            break;
          case 'file':
            this.setState({value: event.target.files}, resolve);
            break;
          default:
            this.setState({value: event.target.value}, resolve);
        }
      });
    }

    checked() {
      return (
        this.props.value &&
        this.props.value === this.props.form.initialValue ||
        this.props.form.initialValue && !this.props.value ||
        this.props.form.initialValue &&
        this.props.form.initialValue.constructor === Array &&
        this.props.form.initialValue.indexOf(this.props.value) >= 0
      );
    }

    elementProps() {
      const elementProps = Object.assign({
        defaultChecked: this.checked(),
        defaultValue: this.props.value || this.props.form.initialValue,
        onChange: this.handleChange
      }, this.props);

      const discard = ['checked', 'form', 'label', 'validators', 'value'];

      discard.forEach(property => {
        delete elementProps[property];
      });

      return elementProps;
    }

    render() {
      return (
        <WrappedComponent
          element={this.elementProps()}
          {...this.props}
          message={this.state.message}
          valid={this.state.valid}
          validate={this.validate}
          value={this.state.value}
          ref={component => { this.component = component;}}
        />
      );
    }
  }

  Field.propTypes = {
    name: PropTypes.string.isRequired
  };

  return Field;
}

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

/**
 * List of all FOAM files available to be loaded in a JSONP
 * format, so it can used from both nodejs scripts, and web
 * pages via script tags easily.
 */

FOAM_FILES([
  { name: "foam/core/poly" },
  { name: "foam/core/lib" },
  { name: "foam/core/stdlib" },
  { name: "foam/core/events" },
  { name: "foam/core/Context" },
  { name: "foam/core/Boot" },
  { name: "foam/core/FObject" },
  { name: "foam/core/Model" },
  { name: "foam/core/Property" },
  { name: "foam/core/Method" },
  { name: "foam/core/Boolean" },
  { name: "foam/core/AxiomArray" },
  { name: "foam/core/EndBoot" },
  { name: "foam/core/FObjectArray" },
  { name: "foam/core/Constant" },
  { name: "foam/core/Validation" },
  { name: "foam/pattern/Faceted" },
  { name: "foam/core/types" },
  { name: "foam/core/Topic" },
  { name: "foam/core/InnerClass" },
  { name: "foam/core/InnerEnum" },
  { name: "foam/core/Implements" },
  { name: "foam/core/ImportsExports" },
  { name: "foam/core/Listener" },
  { name: "foam/core/IDSupport" },
  { name: "foam/core/Requires" },
  { name: "foam/core/Slot" },
  { name: "foam/core/Proxy" },
  { name: "foam/core/Promised" },
  { name: "foam/core/Interface" },
  { name: "foam/core/ContextMethod" },
  { name: "foam/core/Window" },
  { name: "foam/core/ContextMultipleInheritence" },
  { name: "foam/classloader/ClassLoader" },
  { name: "foam/core/Argument" },
  { name: "foam/core/MultiMethod" },
  { name: "foam/core/debug", flags: ['debug'] },
  { name: "foam/pattern/Singleton" },
  { name: "foam/pattern/Multiton" },
  { name: "foam/core/Enum" },
  { name: "foam/core/JSON" },
  { name: "foam/parse/parse" },
  { name: "foam/core/templates" },
  { name: "foam/i18n/Messages" },
  { name: "foam/core/Action" },
  { name: "foam/core/Reaction" },
  { name: "foam/core/Serializable" },
  { name: "foam/java/Argument", flags: ['java'] },
  { name: "foam/java/Class", flags: ['java'] },
  { name: "foam/java/ClassInfo", flags: ['java'] },
  { name: "foam/java/Code", flags: ['java'] },
  { name: "foam/java/CodeProperty", flags: ['java'] },
  { name: "foam/java/Field", flags: ['java'] },
  { name: "foam/java/Interface", flags: ['java'] },
  { name: "foam/java/InterfaceMethod", flags: ['java'] },
  { name: "foam/java/Method", flags: ['java'] },
  { name: "foam/java/Enum", flags: ['java'] },
  { name: "foam/java/MultiPartGetter", flags: ['java'] },
  { name: "foam/java/MultiPartSetter", flags: ['java'] },
  { name: "foam/java/Outputter", flags: ['java'] },
  { name: "foam/java/PropertyInfo", flags: ['java'] },
  { name: "foam/java/PropertyRefinement", flags: ['java'] },
  { name: "foam/java/Skeleton", flags: ['java'] },
  { name: "foam/java/refinements", flags: ['java'] },
  { name: "foam/util/Timer" },
  { name: "foam/memento/MementoMgr" },
  { name: "lib/input", flags: ['web'] },
  { name: "foam/nanos/log/LogLevel" },
  { name: "foam/nanos/log/Logger" },
  { name: "foam/nanos/log/ConsoleLogger" },
  { name: "foam/u2/AttrSlot" },
  { name: "foam/u2/ViewSpec" },
  { name: "foam/u2/Element" },
//  { name: "foam/u2/AttrSlot", flags: ['web'] },
//  { name: "foam/u2/Element", flags: ['web'] },
  { name: "foam/u2/ProgressView", flags: ['web'] },
  { name: "foam/dao/Sink" },
  { name: "foam/dao/SinkJava", flags: ['java'] },
  { name: "foam/dao/DAO" },
  { name: "foam/dao/DAOJava", flags: ['java'] },
  { name: "foam/dao/daoUtils" },
  { name: "foam/dao/DAODecorator" },
  { name: "foam/dao/AbstractDAO" },
  { name: "foam/dao/DAOProperty" },
  { name: "foam/mlang/mlang" },
  { name: "foam/mlang/mlangJava", flags: ['java'] },
  { name: "foam/mlang/LabeledValue" },
  { name: "foam/dao/index/Plan" },
  { name: "foam/dao/index/Index" },
  { name: "foam/dao/index/ProxyIndex" },
  { name: "foam/dao/index/AltIndex" },
  { name: "foam/dao/index/ValueIndex" },
  { name: "foam/dao/index/AATree" },
  { name: "foam/dao/index/TreeIndex" },
  { name: "foam/dao/index/AutoIndex" },
  { name: "foam/dao/MDAO" },
  { name: "foam/dao/ArrayDAO" },
  { name: "foam/dao/TimestampDAO" },
  { name: "foam/dao/GUIDDAO" },
  { name: "foam/dao/ReadOnlyDAO" },
  { name: "foam/dao/JournaledDAO" },
  { name: "foam/dao/Relationship" },
  { name: "foam/dao/RelationshipDAO" },
  { name: "foam/dao/ManyToManyRelationshipDAO" },
  { name: "foam/dao/LazyCacheDAO" },
  { name: "foam/dao/CachingDAO" },
  { name: "foam/dao/DeDupDAO" },
  { name: "foam/dao/LRUDAOManager" },
  { name: "foam/dao/SequenceNumberDAO" },
  { name: "foam/dao/ContextualizingDAO" },
  { name: "foam/dao/SyncDAO" },
  { name: "foam/dao/EasyDAO" },
  { name: "foam/dao/NoSelectAllDAO" },
  { name: "foam/dao/NullDAO" },
  { name: "foam/dao/TimingDAO" },
  { name: "foam/dao/LoggingDAO" },
  { name: "foam/dao/IDBDAO", flags: ['web'] },
  { name: "foam/dao/RestDAO" },
  { name: "foam/dao/SQL", flags: ['sql'] },
  { name: "foam/parse/QueryParser" },
  { name: "foam/physics/Physical" },
  { name: "foam/physics/Collider" },
  { name: "foam/physics/PhysicsEngine" },
  { name: "foam/blob/Blob" },
  { name: "lib/node/json_dao", flags: ['node'] },
  { name: "lib/utf8" },
  { name: "lib/web/net" }, // No flags: ['web']: base classes for lib/node/net.
  { name: "lib/messageport", flags: ['web'] },
  { name: "lib/node/net", flags: ['node'] },
  { name: "lib/firebase" },
  { name: "lib/fcm" },
  { name: "lib/Stub" },
  { name: "lib/box" },
  { name: "lib/boxJava", flags: ['java'] },
  { name: "foam/core/async" },
  { name: "foam/u2/ViewFactory", flags: ['web'] },
  { name: "foam/u2/daos", flags: ['web'] },
  { name: "foam/u2/TableView", flags: ['web'] },
  { name: "foam/u2/TableSelection", flags: ['web'] },
  { name: "foam/u2/Scroller", flags: ['web'] },
  { name: "foam/u2/ActionView", flags: ['web'] },
  { name: "foam/u2/DetailPropertyView", flags: ['web'] },
  { name: "foam/u2/DetailView", flags: ['web'] },
  { name: "foam/u2/tag/Image", flags: ['web'] },
  { name: "foam/u2/tag/Input", flags: ['web'] },
  { name: "foam/u2/tag/TextArea", flags: ['web'] },
  { name: "foam/u2/TextField", flags: ['web'] },
  { name: "foam/u2/IntView", flags: ['web'] },
  { name: "foam/u2/FloatView", flags: ['web'] },
  { name: "foam/u2/CheckBox", flags: ['web'] },
  { name: "foam/u2/CitationView", flags: ['web'] },
  { name: "foam/u2/PopupView", flags: ['web'] },
  { name: "foam/u2/DateView", flags: ['web'] },
  { name: "foam/u2/DateTimeView", flags: ['web'] },
  { name: "foam/u2/RangeView", flags: ['web'] },
  { name: "foam/u2/ReadWriteView", flags: ['web'] },
  { name: "foam/u2/HTMLElement", flags: ['web'] },
  { name: "foam/u2/tag/Select", flags: ['web'] },
  { name: "foam/u2/Tabs", flags: ['web'] },
  { name: "foam/u2/view/ChoiceView", flags: ['web'] },
  { name: "foam/u2/view/RadioView", flags: ['web'] },
  { name: "foam/u2/view/TextField", flags: ['web'] },
  { name: "foam/u2/view/TreeView", flags: ['web'] },
  { name: "foam/u2/view/DualView", flags: ['web'] },
  { name: "foam/u2/view/ColorPicker", flags: ['web'] },
  { name: "foam/u2/view/TableView", flags: ['web'] },
  { name: "foam/u2/view/ScrollTableView", flags: ['web'] },
  { name: "foam/u2/view/BlobView", flags: ['web'] },
  { name: "foam/u2/view/StringArrayView", flags: ['web'] },
  { name: "foam/u2/view/ImageView", flags: ['web'] },
  { name: "foam/u2/ClassView", flags: ['web'] },
  { name: "foam/u2/view/ReferenceView", flags: ['web'] },
  { name: "foam/u2/tag/Card", flags: ['web'] },
  { name: "foam/u2/dialog/Popup", flags: ['web'] },
  { name: "foam/u2/Autocompleter", flags: ['web'] },
  { name: "foam/u2/search/FilterController", flags: ['web'] },
  { name: "foam/u2/search/GroupCompleter", flags: ['web'] },
  { name: "foam/u2/search/GroupAutocompleteSearchView", flags: ['web'] },
  { name: "foam/u2/search/GroupBySearchView", flags: ['web'] },
  { name: "foam/u2/search/SearchManager", flags: ['web'] },
  { name: "foam/u2/search/TextSearchView", flags: ['web'] },
  { name: "foam/u2/stack/Stack", flags: ['web'] },
  { name: "foam/u2/stack/StackView", flags: ['web'] },
  { name: "foam/u2/FoamTagLoader", flags: ['loader'] },
  { name: "foam/graphics/CView", flags: ['web'] },
  { name: "foam/graphics/ScrollCView", flags: ['web'] },
  { name: "foam/physics/PhysicalCircle", flags: ['web'] },
  { name: "foam/comics/DAOController" },
  { name: "foam/comics/DAOControllerView", flags: ['web'] },
  { name: "foam/comics/InlineDAOControllerView", flags: ['web'] },
  { name: "foam/comics/DAOCreateController" },
  { name: "foam/comics/DAOCreateControllerView", flags: ['web'] },
  { name: "foam/comics/DAOUpdateController" },
  { name: "foam/comics/DAOUpdateControllerView", flags: ['web'] },
  { name: "foam/comics/BrowserView", flags: ['web'] },
  { name: "foam/comics/InlineBrowserView", flags: ['web'] },
  { name: "foam/comics/RelationshipView", flags: ['web'] },
  { name: "foam/u2/view/RecipricalSearch", flags: ['web'] },
  { name: "lib/node/box", flags: ['node'] },
  { name: "foam/net/HTTPMethod" },
  { name: "lib/net" },
  { name: "foam/doc/DocBrowser", flags: ['debug'] },
  { name: "com/google/cloud/datastore/types", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/mlang", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/DatastoreDAO", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/BatchMutationDatastoreDAO", flags: ['gcloud'] },
  { name: "foam/net/node/Handler", flags: ['node'] },
  { name: "foam/net/node/FileHandler", flags: ['node'] },
  { name: "foam/net/node/StaticFileHandler", flags: ['node'] },
  { name: "foam/net/node/RestDAOHandler", flags: ['node'] },
  { name: "foam/net/node/Server", flags: ['node'] },
  { name: "foam/classloader/ClassLoader", flags: ['debug'] },
  { name: "foam/classloader/OrDAO", flags: ['debug'] },
  { name: "foam/classloader/WebModelFileDAO", flags: ['web', 'debug'] },
  { name: "foam/classloader/NodeModelFileDAO", flags: ['node', 'debug'] },
  { name: "foam/classloader/NodeJsModelExecutor", flags: ['node', 'debug'] },
  { name: "foam/parsers/html" },
  { name: "foam/parsers/HTMLLexer" }
]);
<commit_msg>Fixed typo.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

/**
 * List of all FOAM files available to be loaded in a JSONP
 * format, so it can used from both nodejs scripts, and web
 * pages via script tags easily.
 */

FOAM_FILES([
  { name: "foam/core/lib" },
  { name: "foam/core/stdlib" },
  { name: "foam/core/events" },
  { name: "foam/core/Context" },
  { name: "foam/core/Boot" },
  { name: "foam/core/FObject" },
  { name: "foam/core/Model" },
  { name: "foam/core/Property" },
  { name: "foam/core/Method" },
  { name: "foam/core/Boolean" },
  { name: "foam/core/AxiomArray" },
  { name: "foam/core/EndBoot" },
  { name: "foam/core/FObjectArray" },
  { name: "foam/core/Constant" },
  { name: "foam/core/Validation" },
  { name: "foam/pattern/Faceted" },
  { name: "foam/core/types" },
  { name: "foam/core/Topic" },
  { name: "foam/core/InnerClass" },
  { name: "foam/core/InnerEnum" },
  { name: "foam/core/Implements" },
  { name: "foam/core/ImportsExports" },
  { name: "foam/core/Listener" },
  { name: "foam/core/IDSupport" },
  { name: "foam/core/Requires" },
  { name: "foam/core/Slot" },
  { name: "foam/core/Proxy" },
  { name: "foam/core/Promised" },
  { name: "foam/core/Interface" },
  { name: "foam/core/ContextMethod" },
  { name: "foam/core/Window" },
  { name: "foam/core/ContextMultipleInheritence" },
  { name: "foam/classloader/ClassLoader" },
  { name: "foam/core/Argument" },
  { name: "foam/core/MultiMethod" },
  { name: "foam/core/debug", flags: ['debug'] },
  { name: "foam/pattern/Singleton" },
  { name: "foam/pattern/Multiton" },
  { name: "foam/core/Enum" },
  { name: "foam/core/JSON" },
  { name: "foam/parse/parse" },
  { name: "foam/core/templates" },
  { name: "foam/i18n/Messages" },
  { name: "foam/core/Action" },
  { name: "foam/core/Reaction" },
  { name: "foam/core/Serializable" },
  { name: "foam/java/Argument", flags: ['java'] },
  { name: "foam/java/Class", flags: ['java'] },
  { name: "foam/java/ClassInfo", flags: ['java'] },
  { name: "foam/java/Code", flags: ['java'] },
  { name: "foam/java/CodeProperty", flags: ['java'] },
  { name: "foam/java/Field", flags: ['java'] },
  { name: "foam/java/Interface", flags: ['java'] },
  { name: "foam/java/InterfaceMethod", flags: ['java'] },
  { name: "foam/java/Method", flags: ['java'] },
  { name: "foam/java/Enum", flags: ['java'] },
  { name: "foam/java/MultiPartGetter", flags: ['java'] },
  { name: "foam/java/MultiPartSetter", flags: ['java'] },
  { name: "foam/java/Outputter", flags: ['java'] },
  { name: "foam/java/PropertyInfo", flags: ['java'] },
  { name: "foam/java/PropertyRefinement", flags: ['java'] },
  { name: "foam/java/Skeleton", flags: ['java'] },
  { name: "foam/java/JavaImport", flags: ['java'] },
  { name: "foam/java/refinements", flags: ['java'] },
  { name: "foam/util/Timer" },
  { name: "foam/memento/MementoMgr" },
  { name: "lib/input", flags: ['web'] },
  { name: "foam/u2/AttrSlot" },
  { name: "foam/u2/ViewSpec" },
  { name: "foam/u2/Element" },
//  { name: "foam/u2/AttrSlot", flags: ['web'] },
//  { name: "foam/u2/Element", flags: ['web'] },
  { name: "foam/u2/ProgressView", flags: ['web'] },
  { name: "foam/dao/Sink" },
  { name: "foam/dao/SinkJava", flags: ['java'] },
  { name: "foam/dao/DAO" },
  { name: "foam/dao/DAOJava", flags: ['java'] },
  { name: "foam/dao/daoUtils" },
  { name: "foam/dao/DAODecorator" },
  { name: "foam/dao/AbstractDAO" },
  { name: "foam/dao/DAOProperty" },
  { name: "foam/mlang/mlang" },
  { name: "foam/mlang/mlangJava", flags: ['java'] },
  { name: "foam/mlang/LabeledValue" },
  { name: "foam/dao/index/Plan" },
  { name: "foam/dao/index/Index" },
  { name: "foam/dao/index/ProxyIndex" },
  { name: "foam/dao/index/AltIndex" },
  { name: "foam/dao/index/ValueIndex" },
  { name: "foam/dao/index/AATree" },
  { name: "foam/dao/index/TreeIndex" },
  { name: "foam/dao/index/AutoIndex" },
  { name: "foam/dao/MDAO" },
  { name: "foam/dao/ArrayDAO" },
  { name: "foam/dao/TimestampDAO" },
  { name: "foam/dao/GUIDDAO" },
  { name: "foam/dao/ReadOnlyDAO" },
  { name: "foam/dao/JournaledDAO" },
  { name: "foam/dao/Relationship" },
  { name: "foam/dao/RelationshipDAO" },
  { name: "foam/dao/ManyToManyRelationshipDAO" },
  { name: "foam/dao/LazyCacheDAO" },
  { name: "foam/dao/CachingDAO" },
  { name: "foam/dao/DeDupDAO" },
  { name: "foam/dao/LRUDAOManager" },
  { name: "foam/dao/SequenceNumberDAO" },
  { name: "foam/dao/ContextualizingDAO" },
  { name: "foam/dao/SyncDAO" },
  { name: "foam/dao/EasyDAO" },
  { name: "foam/dao/NoSelectAllDAO" },
  { name: "foam/dao/NullDAO" },
  { name: "foam/dao/TimingDAO" },
  { name: "foam/dao/LoggingDAO" },
  { name: "foam/dao/IDBDAO", flags: ['web'] },
  { name: "foam/dao/RestDAO" },
  { name: "foam/dao/SQL", flags: ['sql'] },
  { name: "foam/parse/QueryParser" },
  { name: "foam/physics/Physical" },
  { name: "foam/physics/Collider" },
  { name: "foam/physics/PhysicsEngine" },
  { name: "foam/blob/Blob" },
  { name: "lib/node/json_dao", flags: ['node'] },
  { name: "lib/utf8" },
  { name: "lib/web/net" }, // No flags: ['web']: base classes for lib/node/net.
  { name: "lib/messageport", flags: ['web'] },
  { name: "lib/node/net", flags: ['node'] },
  { name: "lib/firebase" },
  { name: "lib/fcm" },
  { name: "lib/Stub" },
  { name: "lib/box" },
  { name: "lib/boxJava", flags: ['java'] },
  { name: "foam/core/async" },
  { name: "foam/u2/ViewFactory", flags: ['web'] },
  { name: "foam/u2/daos", flags: ['web'] },
  { name: "foam/u2/TableView", flags: ['web'] },
  { name: "foam/u2/TableSelection", flags: ['web'] },
  { name: "foam/u2/Scroller", flags: ['web'] },
  { name: "foam/u2/ActionView", flags: ['web'] },
  { name: "foam/u2/DetailPropertyView", flags: ['web'] },
  { name: "foam/u2/DetailView", flags: ['web'] },
  { name: "foam/u2/tag/Image", flags: ['web'] },
  { name: "foam/u2/tag/Input", flags: ['web'] },
  { name: "foam/u2/tag/TextArea", flags: ['web'] },
  { name: "foam/u2/TextField", flags: ['web'] },
  { name: "foam/u2/IntView", flags: ['web'] },
  { name: "foam/u2/FloatView", flags: ['web'] },
  { name: "foam/u2/CheckBox", flags: ['web'] },
  { name: "foam/u2/CitationView", flags: ['web'] },
  { name: "foam/u2/PopupView", flags: ['web'] },
  { name: "foam/u2/DateView", flags: ['web'] },
  { name: "foam/u2/DateTimeView", flags: ['web'] },
  { name: "foam/u2/RangeView", flags: ['web'] },
  { name: "foam/u2/ReadWriteView", flags: ['web'] },
  { name: "foam/u2/HTMLElement", flags: ['web'] },
  { name: "foam/u2/tag/Select", flags: ['web'] },
  { name: "foam/u2/Tabs", flags: ['web'] },
  { name: "foam/u2/view/ChoiceView", flags: ['web'] },
  { name: "foam/u2/view/RadioView", flags: ['web'] },
  { name: "foam/u2/view/TextField", flags: ['web'] },
  { name: "foam/u2/view/TreeView", flags: ['web'] },
  { name: "foam/u2/view/DualView", flags: ['web'] },
  { name: "foam/u2/view/ColorPicker", flags: ['web'] },
  { name: "foam/u2/view/TableView", flags: ['web'] },
  { name: "foam/u2/view/ScrollTableView", flags: ['web'] },
  { name: "foam/u2/view/BlobView", flags: ['web'] },
  { name: "foam/u2/view/StringArrayView", flags: ['web'] },
  { name: "foam/u2/view/ImageView", flags: ['web'] },
  { name: "foam/u2/ClassView", flags: ['web'] },
  { name: "foam/u2/view/ReferenceView", flags: ['web'] },
  { name: "foam/u2/tag/Card", flags: ['web'] },
  { name: "foam/u2/dialog/Popup", flags: ['web'] },
  { name: "foam/u2/Autocompleter", flags: ['web'] },
  { name: "foam/u2/search/FilterController", flags: ['web'] },
  { name: "foam/u2/search/GroupCompleter", flags: ['web'] },
  { name: "foam/u2/search/GroupAutocompleteSearchView", flags: ['web'] },
  { name: "foam/u2/search/GroupBySearchView", flags: ['web'] },
  { name: "foam/u2/search/SearchManager", flags: ['web'] },
  { name: "foam/u2/search/TextSearchView", flags: ['web'] },
  { name: "foam/u2/stack/Stack", flags: ['web'] },
  { name: "foam/u2/stack/StackView", flags: ['web'] },
  { name: "foam/u2/FoamTagLoader", flags: ['loader'] },
  { name: "foam/graphics/CView", flags: ['web'] },
  { name: "foam/graphics/ScrollCView", flags: ['web'] },
  { name: "foam/physics/PhysicalCircle", flags: ['web'] },
  { name: "foam/comics/DAOController" },
  { name: "foam/comics/DAOControllerView", flags: ['web'] },
  { name: "foam/comics/InlineDAOControllerView", flags: ['web'] },
  { name: "foam/comics/DAOCreateController" },
  { name: "foam/comics/DAOCreateControllerView", flags: ['web'] },
  { name: "foam/comics/DAOUpdateController" },
  { name: "foam/comics/DAOUpdateControllerView", flags: ['web'] },
  { name: "foam/comics/BrowserView", flags: ['web'] },
  { name: "foam/comics/InlineBrowserView", flags: ['web'] },
  { name: "foam/comics/RelationshipView", flags: ['web'] },
  { name: "foam/u2/view/RecipricalSearch", flags: ['web'] },
  { name: "lib/node/box", flags: ['node'] },
  { name: "foam/net/HTTPMethod" },
  { name: "lib/net" },
  { name: "foam/doc/DocBrowser", flags: ['debug'] },
  { name: "com/google/cloud/datastore/types", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/mlang", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/DatastoreDAO", flags: ['gcloud'] },
  { name: "com/google/cloud/datastore/BatchMutationDatastoreDAO", flags: ['gcloud'] },
  { name: "foam/net/node/Handler", flags: ['node'] },
  { name: "foam/net/node/FileHandler", flags: ['node'] },
  { name: "foam/net/node/StaticFileHandler", flags: ['node'] },
  { name: "foam/net/node/RestDAOHandler", flags: ['node'] },
  { name: "foam/net/node/Server", flags: ['node'] },
  { name: "foam/classloader/ClassLoader", flags: ['debug'] },
  { name: "foam/classloader/OrDAO", flags: ['debug'] },
  { name: "foam/classloader/WebModelFileDAO", flags: ['web', 'debug'] },
  { name: "foam/classloader/NodeModelFileDAO", flags: ['node', 'debug'] },
  { name: "foam/classloader/NodeJsModelExecutor", flags: ['node', 'debug'] },
  { name: "foam/parsers/html" },
  { name: "foam/parsers/HTMLLexer" }
]);
<|endoftext|>


<commit_before>(function(e,t,n){"use strict";e.localStorage||Object.defineProperty(e,"localStorage",function(){var n=[],r={};Object.defineProperty(r,"getItem",{value:function(e){return e?this[e]:null},writable:!1,configurable:!1,enumerable:!1}),Object.defineProperty(r,"key",{value:function(e){return n[e]},writable:!1,configurable:!1,enumerable:!1}),Object.defineProperty(r,"setItem",{value:function(n,r){if(!n)return;t.cookie=e.escape(n)+"="+e.escape(r)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},writable:!1,configurable:!1,enumerable:!1}),Object.defineProperty(r,"length",{get:function(){return n.length},configurable:!1,enumerable:!1}),Object.defineProperty(r,"removeItem",{value:function(n){if(!n)return;t.cookie=e.escape(n)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"},writable:!1,configurable:!1,enumerable:!1}),this.get=function(){var i,s,o,u,a,f;for(s in r)i=n.indexOf(s),i===-1?r.setItem(s,r[s]):n.splice(i,1),delete r[s];for(n;n.length>0;n.splice(0,1))r.removeItem(n[0]);for(o,a,f=0,u=t.cookie.split(/\s*;\s*/);f<u.length;f++)o=u[f].split(/\s*=\s*/),o.length>1&&(r[a=e.unescape(o[0])]=e.unescape(o[1]),n.push(a));return r},this.configurable=!1,this.enumerable=!0}());var r={parse:e.JSON&&(e.JSON.parse||e.JSON.decode)||String.prototype.evalJSON&&function(e){return String(e).evalJSON()},stringify:Object.toJSON||e.JSON&&(e.JSON.stringify||e.JSON.encode)};if(!r.parse||!r.stringify)throw new Error("No JSON support found");var i=e.localStorage,s={},o=function(e){return typeof e=="string"},u=function(e){return typeof e=="number"},a=function(e){return o(e)?e:r.stringify(e)},f=function(e){try{e=r.parse(e)}catch(t){}finally{return e}},l="storagechange",c=function(n,r){var i,s=e.$||e.jQuery;if(t.createEventObject)return i=t.createEventObject(),n.fireEvent("on"+r,i);if(!s)return i=t.createEvent("HTMLEvents"),i.initEvent(r,!0,!0),!n.dispatchEvent(i);s(n).trigger(r)},h=function(){return c(t,"storagechange")},p=["wrong number of arguments","non-string value","value is not an integer or out of range","not a string value","timestamp already passed","delay not convertible to a number","source and destination objects are the same","no such key","missing storage context"],d=function(e){var t,n,r=arguments[1],i=arguments[2];if(typeof e!="number"||r&&typeof r!="string")throw new TypeError("wrong arg types");return n=p[e],i?(i=i.toLowerCase(),i==="typeerror"&&(t=new TypeError(n))):t=new Error(n),t},v=function(e){var t=":",n="e";return e=a(e),n+t+e},m=function(e,t){return r.stringify({c:t,d:e})},g=function(e){var t=v(e),n=i.getItem(t);return r.parse(n)},y=function(e){var t=g(e);return t&&t.d?t.d:null},b=function(e){var t=g(e);return t&&t.c?t.c:null},w=function(e){var t=g(e),n;return t&&t.d&&t.c&&(n=t.c+t.d-(new Date).getTime()),n},E=function(e,t,n){var r=v(e),s=m(t,n);i.setItem(r,s)},S=function(e){var t=v(e),n=g(e);i.removeItem(t)},x=function(e){var t=v(e);return!!i.getItem(t)},T=function(e){var t=w(e),n=t<0;return n},N=function(e){T(e)&&(L(e),L(v(e)))};s.setItem=function(e,t){i.setItem(e,t),h()},s.getItem=function(e){return N(e),i.getItem(e)},s.key=function(e){return i.key(e)},s.clear=function(){i.clear(),h()},s.removeItem=function(e){i.removeItem(e),h()};var C=function(e,t){e=a(e),t=a(t);try{i.setItem(e,t),h()}catch(n){throw n}},k=function(e){e=a(e),N(e);var t=i.getItem(e);return f(t)},L=function(e){e=a(e),i.removeItem(e)},A=function(e){N(e);var t=!0,n,r;if(e instanceof Array)for(n=0,r=e.length;n<r;n++)i.hasOwnProperty(e[n])||(t=!1);else t=!!i.hasOwnProperty(e);return t};s.del=function(e){var t=0,n,r;e=e instanceof Array?e:arguments;for(n=0,r=e.length;n<r;n++)A(e[n])&&(S(e[n]),L(e[n]),++t);return t},s.exists=function(e){if(arguments.length>1)throw d(0);return A(e)?1:0},s.rename=function(e,t){var r,i;arguments.length!==2?r=0:e===t?r=6:A(e)||(r=7);if(r!==n)throw d(r);x(t)&&S(t),C(t,k(e)),x(e)&&(i=w(e),this.pexpire(t,i),S(e)),L(e)},s.renamenx=function(e,t){var n;arguments.length!==2?n=0:e===t?n=6:A(e)||(n=7);if(n)throw d(n);return A(t)?0:(this.rename(e,t),1)},s.getkey=function(e){if(arguments.length>2)throw d(0);var t,n,r,s,o=[],u;u=!!arguments[1];for(t=0,n=i.length;t<n;t++){r=i.key(t),s=i.getItem(r);if(e===s){o.push(r);if(!u)break}}return o.length===1?o=o[0]:o.length||(o=null),o},s.expire=function(e,t){if(arguments.length!==2)throw d(0);if(!A(e))return 0;t=parseFloat(t,10);if(!t)throw d(5);return t*=1e3,x(e)&&S(e),E(e,t,(new Date).getTime()),1},s.expires=function(e){return e=a(e),x(e)?1:0},s.pexpire=function(e,t){if(arguments.length!==2)throw d(0);t=parseFloat(t,10);if(!t)throw d(5);return this.expire(e,t/1e3)},s.expireat=function(e,t){if(arguments.length!==2)throw d(0);var n=(new Date).getTime()/1e3,r=t-n;if(r<0)throw d(4);return this.expire(e,r)},s.pexpireat=function(e,t){if(arguments.length!==2)throw d(0);var n=t-(new Date).getTime();if(n<0)throw d(4);return this.pexpire(e,n)},s.persist=function(e){if(arguments.length!==1)throw d(0);return!A(e)||!x(e)?0:(L(v(e)),1)},s.ttl=function(e){if(arguments.length!==1)throw d(0);return!A(e)||!x(e)?-1:w(e)/1e3},s.pttl=function(e){if(arguments.length!==1)throw d(0);return this.ttl(e)*1e3},s.randomkey=function(){var e=Object.keys(i),t=i.length,n=Math.floor(Math.random()*t);return t?e[n]:null},s.keys=function(e){var t=new RegExp(e),n,r,s=[],o=Object.keys(i);for(n=0,r=o.length;n<r;n++)t.test(o[n])&&s.push(o[n]);return s.length?s:null},s.get=function(e){return k(e)},s.set=function(e,t){var n=x(e),r;try{C(e,t),n&&(r=y(e),this.persist(e))}catch(i){throw i}return this},s.getset=function(e,t){if(arguments.length!==2)throw d(0);var n=k(e);if(!o(n)&&n!==null)throw d(1);return this.set(e,t),n},s.mget=function(e){var t=[],n,r;e=e instanceof Array?e:arguments;for(n=0,r=e.length;n<r;n++)t[t.length]=k(e[n]);return t},s.mset=function(e){var t=e instanceof Array,n=e instanceof Object,r,i,s;if(n&&!t){s=Object.keys(e);for(r=0,i=s.length;r<i;r++)C(s[r],e[s[r]])}else{e=t?e:arguments;for(r=0,i=e.length;r<i;r+=2)C(e[r],e[r+1])}return this},s.setnx=function(e,t){if(arguments.length!==2)throw d(0);return A(e)?0:(C(e,t),1)},s.msetnx=function(e){var t=e instanceof Array,n=e instanceof Object,r,i,s=[];if(n&&!t)s=Object.keys(e);else{e=t?e:arguments;for(r=0,i=e.length;r<i;r+=2)s.push(e[r])}for(r=0,i=s.length;r<i;r++)if(A(s[r]))return 0;for(r=0,i=e.length;r<i;r+=2)C(e[r],e[r+1]);return 1},s.incr=function(e){if(arguments.length!==1)throw d(0);this.incrby(e,1)},s.incrby=function(e,t){if(arguments.length!==2)throw d(0);var n=k(e),r=typeof n,i=typeof t,s=parseInt(n,10),a=parseInt(t,10),f=isNaN(a),l=isNaN(s),c=n===null,h=u(r),p=o(r)&&!l,v=o(r)&&l,m=!h&&v,g=l&&A(e),y=u(i),b=o(i)&&!f,w=o(i)&&f,E=!y&&w,S=!l&&n>=Number.MAX_VALUE,x=!f&&t>=Number.MAX_VALUE,T=S||x;if(m&&!c||g||f||E||T)throw d(2);if((h||p)&&(y||b))n=s+a;else if(y||b)n=a;C(e,n)},s.mincr=function(e){var t,n;e=e instanceof Array?e:arguments;for(t=0,n=e.length;t<n;t++)this.incr(e[t])},s.mincrby=function(e){var t,n,r;if(e instanceof Array||o(e)){e=e instanceof Array?e:arguments;if((e.length&1)!==0)throw d(0);for(t=0,n=e.length;t<n;t+=2)this.incrby(e[t],e[t+1])}else if(e instanceof Object)for(r in e)this.incrby(r,e[r])},s.append=function(e,t){if(arguments.length!==2)throw d(0);var n=k(e)||"",r=o(n);return r&&(n+=t,C(e,n)),r?n.length:1},s.strlen=function(e){var t=k(e);if(!t)return 0;if(!o(t))throw d(1);return t.length},s.setex=function(e,t,n){if(arguments.length!==3)throw d(0);C(e,t),this.expire(e,n)},s.psetex=function(e,t,n){if(arguments.length!==3)throw d(0);C(e,t),this.pexpire(e,n)},e.localRedis=s})(window,document);<commit_msg>Updated min<commit_after>(function(e,t,n){"use strict";e.localStorage||Object.defineProperty(e,"localStorage",function(){var n=[],r={};Object.defineProperty(r,"getItem",{value:function(e){return e?this[e]:null},writable:!1,configurable:!1,enumerable:!1}),Object.defineProperty(r,"key",{value:function(e){return n[e]},writable:!1,configurable:!1,enumerable:!1}),Object.defineProperty(r,"setItem",{value:function(n,r){if(!n)return;t.cookie=e.escape(n)+"="+e.escape(r)+"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"},writable:!1,configurable:!1,enumerable:!1}),Object.defineProperty(r,"length",{get:function(){return n.length},configurable:!1,enumerable:!1}),Object.defineProperty(r,"removeItem",{value:function(n){if(!n)return;t.cookie=e.escape(n)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"},writable:!1,configurable:!1,enumerable:!1}),this.get=function(){var i,s,o,u,a,f;for(s in r)i=n.indexOf(s),i===-1?r.setItem(s,r[s]):n.splice(i,1),delete r[s];for(n;n.length>0;n.splice(0,1))r.removeItem(n[0]);for(o,a,f=0,u=t.cookie.split(/\s*;\s*/);f<u.length;f++)o=u[f].split(/\s*=\s*/),o.length>1&&(r[a=e.unescape(o[0])]=e.unescape(o[1]),n.push(a));return r},this.configurable=!1,this.enumerable=!0}());var r={parse:e.JSON&&(e.JSON.parse||e.JSON.decode)||String.prototype.evalJSON&&function(e){return String(e).evalJSON()},stringify:Object.toJSON||e.JSON&&(e.JSON.stringify||e.JSON.encode)};if(!r.parse||!r.stringify)throw new Error("No JSON support found");var i=e.localStorage,s={},o=function(e){return typeof e=="string"},u=function(e){return typeof e=="number"},a=function(e){return o(e)?e:r.stringify(e)},f=function(e){try{e=r.parse(e)}catch(t){}finally{return e}},l="storagechange",c=function(n,r){var i,s=e.$||e.jQuery;if(t.createEventObject)return i=t.createEventObject(),n.fireEvent("on"+r,i);if(!s)return i=t.createEvent("HTMLEvents"),i.initEvent(r,!0,!0),!n.dispatchEvent(i);s(n).trigger(r)},h=function(){return c(t,l)},p=["wrong number of arguments","non-string value","value is not an integer or out of range","not a string value","timestamp already passed","delay not convertible to a number","source and destination objects are the same","no such key","missing storage context"],d=function(e){var t,n,r=arguments[1],i=arguments[2];if(typeof e!="number"||r&&typeof r!="string")throw new TypeError("wrong arg types");return n=p[e],i?(i=i.toLowerCase(),i==="typeerror"&&(t=new TypeError(n))):t=new Error(n),t},v=function(e){var t=":",n="e";return e=a(e),n+t+e},m=function(e,t){return a({c:t,d:e})},g=function(e){var t=v(e),n=i.getItem(t);return f(n)},y=function(e){var t=g(e);return t&&t.d?t.d:null},b=function(e){var t=g(e);return t&&t.c?t.c:null},w=function(e){var t=g(e),n;return t&&t.d&&t.c&&(n=t.c+t.d-(new Date).getTime()),n},E=function(e,t,n){var r=v(e),s=m(t,n);i.setItem(r,s)},S=function(e){var t=v(e),n=g(e);i.removeItem(t)},x=function(e){var t=v(e);return!!i.getItem(t)},T=function(e){var t=w(e),n=t<0;return n},N=function(e){T(e)&&(L(e),L(v(e)))};s.setItem=function(e,t){i.setItem(e,t),h()},s.getItem=function(e){return N(e),i.getItem(e)},s.key=function(e){return i.key(e)},s.clear=function(){i.clear(),h()},s.removeItem=function(e){i.removeItem(e),h()};var C=function(e,t){e=a(e),t=a(t);try{i.setItem(e,t),h()}catch(n){throw n}},k=function(e){e=a(e),N(e);var t=i.getItem(e);return f(t)},L=function(e){e=a(e),i.removeItem(e)},A=function(e){N(e);var t=!0,n,r;if(e instanceof Array)for(n=0,r=e.length;n<r;n++)i.hasOwnProperty(e[n])||(t=!1);else t=!!i.hasOwnProperty(e);return t};s.del=function(e){var t=0,n,r;e=e instanceof Array?e:arguments;for(n=0,r=e.length;n<r;n++)A(e[n])&&(S(e[n]),L(e[n]),++t);return t},s.exists=function(e){if(arguments.length>1)throw d(0);return A(e)?1:0},s.rename=function(e,t){var r,i;arguments.length!==2?r=0:e===t?r=6:A(e)||(r=7);if(r!==n)throw d(r);x(t)&&S(t),C(t,k(e)),x(e)&&(i=w(e),this.pexpire(t,i),S(e)),L(e)},s.renamenx=function(e,t){var n;arguments.length!==2?n=0:e===t?n=6:A(e)||(n=7);if(n)throw d(n);return A(t)?0:(this.rename(e,t),1)},s.getkey=function(e){if(arguments.length>2)throw d(0);var t,n,r,s,o=[],u;u=!!arguments[1];for(t=0,n=i.length;t<n;t++){r=i.key(t),s=i.getItem(r);if(e===s){o.push(r);if(!u)break}}return o.length===1?o=o[0]:o.length||(o=null),o},s.expire=function(e,t){if(arguments.length!==2)throw d(0);if(!A(e))return 0;t=parseFloat(t,10);if(!t)throw d(5);return t*=1e3,x(e)&&S(e),E(e,t,(new Date).getTime()),1},s.expires=function(e){return e=a(e),x(e)?1:0},s.pexpire=function(e,t){if(arguments.length!==2)throw d(0);t=parseFloat(t,10);if(!t)throw d(5);return this.expire(e,t/1e3)},s.expireat=function(e,t){if(arguments.length!==2)throw d(0);var n=(new Date).getTime()/1e3,r=t-n;if(r<0)throw d(4);return this.expire(e,r)},s.pexpireat=function(e,t){if(arguments.length!==2)throw d(0);var n=t-(new Date).getTime();if(n<0)throw d(4);return this.pexpire(e,n)},s.persist=function(e){if(arguments.length!==1)throw d(0);return!A(e)||!x(e)?0:(L(v(e)),1)},s.ttl=function(e){if(arguments.length!==1)throw d(0);return A(e)&&x(e)?w(e)/1e3:-1},s.pttl=function(e){if(arguments.length!==1)throw d(0);return this.ttl(e)*1e3},s.randomkey=function(){var e=Object.keys(i),t=i.length,n=Math.floor(Math.random()*t);return t?e[n]:null},s.keys=function(e){var t=new RegExp(e),n,r,s=[],o=Object.keys(i);for(n=0,r=o.length;n<r;n++)t.test(o[n])&&s.push(o[n]);return s.length?s:null},s.get=function(e){return k(e)},s.set=function(e,t){var n=x(e),r;try{C(e,t),n&&(r=y(e),this.persist(e))}catch(i){throw i}return this},s.getset=function(e,t){if(arguments.length!==2)throw d(0);var n=k(e);if(!o(n)&&n!==null)throw d(1);return this.set(e,t),n},s.mget=function(e){var t=[],n,r;e=e instanceof Array?e:arguments;for(n=0,r=e.length;n<r;n++)t[t.length]=k(e[n]);return t},s.mset=function(e){var t=e instanceof Array,n=e instanceof Object,r,i,s;if(n&&!t){s=Object.keys(e);for(r=0,i=s.length;r<i;r++)C(s[r],e[s[r]])}else{e=t?e:arguments;for(r=0,i=e.length;r<i;r+=2)C(e[r],e[r+1])}return this},s.setnx=function(e,t){if(arguments.length!==2)throw d(0);return A(e)?0:(C(e,t),1)},s.msetnx=function(e){var t=e instanceof Array,n=e instanceof Object,r,i,s=[];if(n&&!t)s=Object.keys(e);else{e=t?e:arguments;for(r=0,i=e.length;r<i;r+=2)s.push(e[r])}for(r=0,i=s.length;r<i;r++)if(A(s[r]))return 0;for(r=0,i=e.length;r<i;r+=2)C(e[r],e[r+1]);return 1},s.incr=function(e){if(arguments.length!==1)throw d(0);this.incrby(e,1)},s.incrby=function(e,t){if(arguments.length!==2)throw d(0);var n=k(e),r=typeof n,i=typeof t,s=parseInt(n,10),a=parseInt(t,10),f=isNaN(a),l=isNaN(s),c=n===null,h=u(r),p=o(r)&&!l,v=o(r)&&l,m=!h&&v,g=l&&A(e),y=u(i),b=o(i)&&!f,w=o(i)&&f,E=!y&&w,S=!l&&n>=Number.MAX_VALUE,x=!f&&t>=Number.MAX_VALUE,T=S||x;if(m&&!c||g||f||E||T)throw d(2);if((h||p)&&(y||b))n=s+a;else if(y||b)n=a;C(e,n)},s.mincr=function(e){var t,n;e=e instanceof Array?e:arguments;for(t=0,n=e.length;t<n;t++)this.incr(e[t])},s.mincrby=function(e){var t,n,r;if(e instanceof Array||o(e)){e=e instanceof Array?e:arguments;if((e.length&1)!==0)throw d(0);for(t=0,n=e.length;t<n;t+=2)this.incrby(e[t],e[t+1])}else if(e instanceof Object)for(r in e)this.incrby(r,e[r])},s.append=function(e,t){if(arguments.length!==2)throw d(0);var n=k(e)||"",r=o(n);return r&&(n+=t,C(e,n)),r?n.length:1},s.strlen=function(e){var t=k(e);if(!t)return 0;if(!o(t))throw d(1);return t.length},s.setex=function(e,t,n){if(arguments.length!==3)throw d(0);this.set(e,n),this.expire(e,t)},s.psetex=function(e,t,n){if(arguments.length!==3)throw d(0);this.set(e,n),this.pexpire(e,t)},e.localRedis=s})(window,document);<|endoftext|>


<commit_before>/* eslint-env browser */

import './lib/displayProjectsGraph';

// TODO: Hook this up to the log out button on the graph view. It is currently not hooked up to anything,
// but functions properly
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('logOut').addEventListener('click', () => {
    document.location.href = '/logout';
  });
});

/**
 * Query the page for a set of elements given a CSS selector.
 *
 * @param selector CSS selector
 * @returns {*} Array of matched elements
 */
function querySelectorAll (selector) {
  return Array.prototype.slice.call(document.querySelectorAll(selector));
}

querySelectorAll('#projects, #hierarchy').forEach(elem => {
  elem.style.display = 'none';
});

document.addEventListener('DOMContentLoaded', () => {
  querySelectorAll('#projects a').forEach(projectAnchor => {
    projectAnchor.addEventListener('click', event => {
      let selectedProject = event.target.getAttribute('data-id');
      getHierarchyRequest('/hierarchy', selectedProject);
      getGraphRequest('/graph', selectedProject, (graph) => {
        console.log(graph);
      });
      // TODO: change query parameter (dependent on hierarchy endpoint story)
    });
  });
});

/**
 * Makes an AJAX request to the provided endpoint for the item hierarchy tree.
 *
 * @param url
 * @param projectId
 * @returns {*}
 */
function getHierarchyRequest (url, projectId) {
  let hierarchy = {};
  // TODO: Refactor to use the request module
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        hierarchy = JSON.parse(httpRequest.responseText);
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the hierarchy endpoint.');
      }
    }
  };
  httpRequest.open('GET', url);
  httpRequest.send('project=' + projectId);
  return hierarchy;
}

/**
 * Makes an AJAX request to the provided endpoint for the project graph.
 *
 * @param url
 * @param projectId
 * @param callback
 * @returns {*}
 */
function getGraphRequest (url, projectId, callback) {
  // TODO: Refactor to use the request module and promises
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        callback(JSON.parse(httpRequest.responseText));
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the graph endpoint.');
      }
    }
  };
  httpRequest.open('GET', url + '?project=' + projectId);
  httpRequest.send();
}
<commit_msg>Add show/hide toggles for project list and hierarchy<commit_after>/* eslint-env browser */

import './lib/displayProjectsGraph';

// TODO: Hook this up to the log out button on the graph view. It is currently not hooked up to anything,
// but functions properly
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('logOut').addEventListener('click', () => {
    document.location.href = '/logout';
  });
});

/**
 * Query the page for a set of elements given a CSS selector.
 *
 * @param selector CSS selector
 * @returns {*} Array of matched elements
 */
function querySelectorAll (selector) {
  return Array.prototype.slice.call(document.querySelectorAll(selector));
}

let projects = document.querySelector('#projects');
let hierarchy = document.querySelector('#hierarchy');

function toggleHierarchy() {
  if (hierarchy.classList.contains('hidden')) {
    hierarchy.classList.remove('hidden');
  } else {
    hierarchy.classList.add('hidden');
  }
}

function hideProjects() {
  projects.classList.add('hidden');
}

document.addEventListener('DOMContentLoaded', () => {
  querySelectorAll('#projects a').forEach(projectAnchor => {
    projectAnchor.addEventListener('click', event => {
      let selectedProject = event.target.getAttribute('data-id');
      getHierarchyRequest('/hierarchy', selectedProject);
      getGraphRequest('/graph', selectedProject, (graph) => {
        console.log(graph);
      });
      // TODO: change query parameter (dependent on hierarchy endpoint story)
    });
  });
});

/**
 * Makes an AJAX request to the provided endpoint for the item hierarchy tree.
 *
 * @param url
 * @param projectId
 * @returns {*}
 */
function getHierarchyRequest (url, projectId) {
  let hierarchy = {};
  // TODO: Refactor to use the request module
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        hierarchy = JSON.parse(httpRequest.responseText);
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the hierarchy endpoint.');
      }
    }
  };
  httpRequest.open('GET', url);
  httpRequest.send('project=' + projectId);
  return hierarchy;
}

/**
 * Makes an AJAX request to the provided endpoint for the project graph.
 *
 * @param url
 * @param projectId
 * @param callback
 * @returns {*}
 */
function getGraphRequest (url, projectId, callback) {
  // TODO: Refactor to use the request module and promises
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        callback(JSON.parse(httpRequest.responseText));
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the graph endpoint.');
      }
    }
  };
  httpRequest.open('GET', url + '?project=' + projectId);
  httpRequest.send();
}
<|endoftext|>


<commit_before>udefine([], function() {
  var unidentified = 'untitled';
  var unidentifiedCounter = 0;

  var Group = function() {
    this.length = 0;

    this.tags = {};
    this.names = {};
  };

  Group.prototype.push = function(obj, tags) {
    var name = obj.name || (unidentified + unidentifiedCounter++);
    if (tags == null) {
      tags = obj.tags || [];
    }

    if (Object.hasOwnProperty.call(this.names, name)) {
      return;
    }

    this[this.length] = obj;

    this.tags.forEach(function(tag) {
      this.tags[tag] = this.tags[tag] || [];
      this.tags[tag].push(this.length);
    }, this);

    this.names[name] = this.length;

    return ++this.length;
  };

  // TODO: Behavior currently stays in the list
  Group.prototype.pop = function() {
    return this[this.length];
  };

  Group.prototype.splice = function(index, how) {

  };

  Group.prototype.slice = function(begin, end) {
    if (end == null) {
      end = this.length;
    }

    var slicedGroup = new Group();

    for (var i = begin; i < end; i++) {
      slicedGroup.push(this[i]);
    }

    return slicedGroup;
  };

  Group.prototype.forEach = function(callback) {
    for (var i = 0; i < this.length; i++) {
      callback(this[i]);
    }
  };

  Group.prototype.filter = function(callback) {
    var filteredArray = [];

    for (var i = 0; i < this.length; i++) {
      if (callback(this[i])) {
        filteredArray.push(this[i]);
      }
    }

    return filteredArray;
  };

  Group.prototype.byName = function(name) {
    return this[this.names[name]];
  };

  Group.prototype.byTag = function(tag) {
    return this.tags[tag].map(function(index) {
      return this[index];
    }, this);
  };

  return Group;
});
<commit_msg>Add Group#map<commit_after>udefine([], function() {
  var unidentified = 'untitled';
  var unidentifiedCounter = 0;

  var Group = function() {
    this.length = 0;

    this.tags = {};
    this.names = {};
  };

  Group.prototype.push = function(obj, tags) {
    var name = obj.name || (unidentified + unidentifiedCounter++);
    if (tags == null) {
      tags = obj.tags || [];
    }

    if (Object.hasOwnProperty.call(this.names, name)) {
      return;
    }

    this[this.length] = obj;

    this.tags.forEach(function(tag) {
      this.tags[tag] = this.tags[tag] || [];
      this.tags[tag].push(this.length);
    }, this);

    this.names[name] = this.length;

    return ++this.length;
  };

  // TODO: Behavior currently stays in the list
  Group.prototype.pop = function() {
    return this[this.length];
  };

  Group.prototype.splice = function(index, how) {

  };

  Group.prototype.slice = function(begin, end) {
    if (end == null) {
      end = this.length;
    }

    var slicedGroup = new Group();

    for (var i = begin; i < end; i++) {
      slicedGroup.push(this[i]);
    }

    return slicedGroup;
  };

  Group.prototype.forEach = function(callback) {
    for (var i = 0; i < this.length; i++) {
      callback(this[i]);
    }
  };

  Group.prototype.map = function(callback) {
  	var mappedArray = [];

    for (var i = 0; i < this.length; i++) {
      mappedArray.push(callback(this[i]));
    }

    return mappedArray;
  };

  Group.prototype.filter = function(callback) {
    var filteredArray = [];

    for (var i = 0; i < this.length; i++) {
      if (callback(this[i])) {
        filteredArray.push(this[i]);
      }
    }

    return filteredArray;
  };

  Group.prototype.byName = function(name) {
    return this[this.names[name]];
  };

  Group.prototype.byTag = function(tag) {
    return this.tags[tag].map(function(index) {
      return this[index];
    }, this);
  };

  Group.prototype.toJSON = function() {

  };

  return Group;
});
<|endoftext|>


<commit_before>var url = require('./url');
var PullReview = require('./index');

/**
 * Set up Hubot listeners for Pull Review
 * @param  {Object} robot - Hubot reference
 */
module.exports = function(robot) {
  var rawUsers = {};
  var chatUserMap = {};
  var adapter = robot.adapterName;

  if (adapter === 'slack') {
    rawUsers = robot.adapter.client.rtm.dataStore.users;
  }

  Object.keys(rawUsers).forEach(function(userId) {
    var user = rawUsers[userId];

    if (user.real_name) {
      if (chatUserMap[user.real_name]) {
        robot.logger.error('User mapping already exists for ' + user.real_name);
      } else {
        chatUserMap[user.real_name] = userId;
      }
    }

    if (user.name) {
      if (chatUserMap[user.name]) {
        robot.logger.error('User mapping already exists for ' + user.name);
      } else {
        chatUserMap[user.name] = userId;
      }
    }
  });

  robot.hear(/github\.com\//, function(res) {
    var chatText = res.message.text;
    var chatRoom = res.message.room;
    var chatChannel = adapter === 'slack' ? 'hubot:slack' : 'hubot:generic';

    /**
     * @param  {Error} e - error
     */
    function logError(e) {
      robot.logger.error('[pull-review]', e);
      res.send('[pull-review] ' + e);
    }

    if (adapter === 'slack') {
      var slackRoom = robot.adapter.client.rtm.dataStore.getChannelGroupOrDMById(
        chatRoom
      );
      chatRoom = slackRoom.name;
    }

    var pullRequestURL;
    var retryReview;

    var urls = url.extractURLs(chatText);
    var processedText = chatText
      .replace(/\s+/g, ' ')
      .replace(/(\breview | again\b)/gi, function(m) {
        return m.toLowerCase();
      });

    for (var i = 0; i < urls.length; i++) {
      var u = urls[i];
      var uo = url.parseURL(u);

      if (uo.hostname === 'github.com') {
        var reviewIndex = processedText.indexOf('review ' + u);
        if (reviewIndex !== -1) {
          retryReview =
            processedText.indexOf('review ' + u + ' again') === reviewIndex;
          pullRequestURL = u;
          break;
        }
      }
    }

    if (!pullRequestURL) {
      return;
    }

    try {
      PullReview({
        pullRequestURL: pullRequestURL,
        retryReview: retryReview,
        chatRoom: chatRoom,
        chatChannel: chatChannel,
        isChat: true,
        notifyFn: function(message) {
          robot.logger.info(message);
          res.send(message);
        },
        userMappingFn: function(user) {
          if (adapter !== 'slack') {
            return user;
          }

          if (!typeof user === 'string') {
            return;
          } else if (user.indexOf('@') === 0) {
            return user;
          } else {
            return '<@' + chatUserMap[user] + '>';
          }
        }
      }).catch(logError);
    } catch (err) {
      logError(err);
    }
  });
};
<commit_msg>avoid @undefined mentions on Slack<commit_after>var url = require('./url');
var PullReview = require('./index');

/**
 * Set up Hubot listeners for Pull Review
 * @param  {Object} robot - Hubot reference
 */
module.exports = function(robot) {
  var rawUsers = {};
  var chatUserMap = {};
  var adapter = robot.adapterName;

  if (adapter === 'slack') {
    rawUsers = robot.adapter.client.rtm.dataStore.users;
  }

  Object.keys(rawUsers).forEach(function(userId) {
    var user = rawUsers[userId];

    if (user.real_name) {
      if (chatUserMap[user.real_name]) {
        robot.logger.error('User mapping already exists for ' + user.real_name);
      } else {
        chatUserMap[user.real_name] = userId;
      }
    }

    if (user.name) {
      if (chatUserMap[user.name]) {
        robot.logger.error('User mapping already exists for ' + user.name);
      } else {
        chatUserMap[user.name] = userId;
      }
    }
  });

  robot.hear(/github\.com\//, function(res) {
    var chatText = res.message.text;
    var chatRoom = res.message.room;
    var chatChannel = adapter === 'slack' ? 'hubot:slack' : 'hubot:generic';

    /**
     * @param  {Error} e - error
     */
    function logError(e) {
      robot.logger.error('[pull-review]', e);
      res.send('[pull-review] ' + e);
    }

    if (adapter === 'slack') {
      var slackRoom = robot.adapter.client.rtm.dataStore.getChannelGroupOrDMById(
        chatRoom
      );
      chatRoom = slackRoom.name;
    }

    var pullRequestURL;
    var retryReview;

    var urls = url.extractURLs(chatText);
    var processedText = chatText
      .replace(/\s+/g, ' ')
      .replace(/(\breview | again\b)/gi, function(m) {
        return m.toLowerCase();
      });

    for (var i = 0; i < urls.length; i++) {
      var u = urls[i];
      var uo = url.parseURL(u);

      if (uo.hostname === 'github.com') {
        var reviewIndex = processedText.indexOf('review ' + u);
        if (reviewIndex !== -1) {
          retryReview =
            processedText.indexOf('review ' + u + ' again') === reviewIndex;
          pullRequestURL = u;
          break;
        }
      }
    }

    if (!pullRequestURL) {
      return;
    }

    try {
      PullReview({
        pullRequestURL: pullRequestURL,
        retryReview: retryReview,
        chatRoom: chatRoom,
        chatChannel: chatChannel,
        isChat: true,
        notifyFn: function(message) {
          robot.logger.info(message);
          res.send(message);
        },
        userMappingFn: function(lookupUser, defaultUser) {
          if (!typeof lookupUser === 'string') {
            return;
          } else if (adapter !== 'slack') {
            return lookupUser;
          }

          if (lookupUser.indexOf('@') === 0) {
            return lookupUser;
          } else if (chatUserMap[lookupUser] !== undefined) {
            return '<@' + chatUserMap[lookupUser] + '>';
          } else if (defaultUser !== undefined) {
            return '@' + defaultUser;
          } else {
            throw Error('Could not map user: ' + lookupUser);
          }
        }
      }).catch(logError);
    } catch (err) {
      logError(err);
    }
  });
};
<|endoftext|>


<commit_before>import config from './config'
import { get, upload } from './s3'
import sharpify from './sharp'
import { makeKey, decodeS3EventKey } from './utils'

const { outputs } = config

export default (async function processItem (
  { eventName, s3: { object: { key: undecodedKey } } = { object: { key: false } } },
) {
  const key = decodeS3EventKey(undecodedKey)
  console.log('Processing: ', key)

  if (eventName.split(':')[0] !== 'ObjectCreated') {
    throw new Error(
      `Event does not contain a valid type (e.g. ObjectCreated). Invoked by event name: ${eventName}`,
    )
  }

  if (!key) {
    throw new Error(`Event does not contain a valid S3 Object Key. Invoked with key: ${key}`)
  }

  const { Body: image, ContentType: type } = await get({ Key: key })
  const streams = await sharpify(image, config)
  const context = { key, type }

  return Promise.all(
    streams.map((stream, index) =>
      upload(stream, { ...outputs[index].params, Key: makeKey(outputs[index].key, context) })),
  )
});
<commit_msg>fix: include output image's ContentType in S3 Object's parameter<commit_after>import config from './config'
import { get, upload } from './s3'
import sharpify from './sharp'
import { makeKey, decodeS3EventKey } from './utils'

const { outputs } = config

const imageMimeTypes = {
  jpeg: 'image/jpeg',
  png: 'image/png',
  webp: 'image/webp',
  gif: 'image/gif',
  svg: 'image/svg+xml',
}

export default (async function processItem ({
  eventName,
  s3: { object: { key: undecodedKey } } = { object: { key: false } },
}) {
  const key = decodeS3EventKey(undecodedKey)
  console.log('Processing: ', key)

  if (eventName.split(':')[0] !== 'ObjectCreated') {
    throw new Error(
      `Event does not contain a valid type (e.g. ObjectCreated). Invoked by event name: ${eventName}`
    )
  }

  if (!key) {
    throw new Error(`Event does not contain a valid S3 Object Key. Invoked with key: ${key}`)
  }

  const { Body: image, ContentType: type } = await get({ Key: key })
  const streams = await sharpify(image, config)
  const context = { key, type }

  return Promise.all(
    streams.map(async (stream, index) =>
      upload(stream, {
        ContentType: imageMimeTypes[(await stream.metadata()).format],
        ...outputs[index].params,
        Key: makeKey(outputs[index].key, context),
      })
    )
  )
})
<|endoftext|>


<commit_before>require("babel-polyfill");

import fs from "fs";
import gm from "gm";
import config from "config";
import log from "./log";
import uuid from "uuid/v4";
import * as fastCache from './fastCache';

const gmOptions = {};
if (config.has('timeout.conversion')) {
  const timeout = Number(config.get('timeout.conversion'));
  if (isNaN(timeout)) {
    log('warn', 'The configuration value of timeout.conversion resolved to a NaN value. Ignoring it!');
  } else if (timeout < 0) {
    log('warn', 'The configuration value of timeout.conversion did not resolve to a nonnegative value. Ignoring it!');
  } else if (timeout === 0) {
    log('info', 'Not setting any image timeout');
  } else {
    gmOptions.timeout = timeout;
  }
}

const options = Object.assign({}, {imageMagick: true}, gmOptions);
log('info', `Booting gm with the following options: ${JSON.stringify(options)}`);

const im = gm.subClass(options);

// 10 seconds
const CLEAR_TEMP_FILES_TIMEOUT = 10000;

// Wrap these calls in promises so we can use async/await
const write = (client, file) => {
  return new Promise((resolve, reject) => client.write(file, err => err ? reject(err) : resolve()));
};
const size = async (client) => {
  return await new Promise((resolve, reject) => client.size({bufferStream: true}, (err, data) => err ? reject(err) : resolve(data)));
};

// Strip the image of any profiles or comments
const strip = async (client) => {
  return client.strip();
};

// Interlacing for png isn't efficient (both in filesize as render performance), so we only do it for jpg
const interlace = async (client, params) => {
  if (params.mime === 'image/jpeg') {
    return client.interlace('Line');
  }
  return client;
};

// When cropping, we size the image first to fix completely within the bounding box
// Then we crop the requested size, and center to the center of the image
const crop = async (client, params) => {
  // Resize the image to fit within the bounding box
  // The ^ ensures the images is resized while maintaining the ratio
  // However the sizes are treated as minimum values instead of maximum values
  client = client.resize(params.width, params.height, '^');
  const tmpFile = `/tmp/${uuid()}`;
  try {
    await write(client, tmpFile);
    client = im(tmpFile).options(gmOptions);
    const imgSize = await size(client);
    setTimeout(() => fs.unlink(tmpFile, err => {
      if (err) {
        log('error', `Tempfile ${tmpFile} could not be deleted`);
      }
    }), CLEAR_TEMP_FILES_TIMEOUT);
    return client
      .repage(imgSize.width, imgSize.height, 0, 0)
      .gravity('Center')
      // Crop the image to the exact size (the ! indicates a force)
      // This is ok since we first resized appropriately
      .crop(params.width, params.height, '!');
  } catch (e) {
    log('error', 'could not write tempfile');
    log('error', e.stack);
    throw e;
  }
};

// The sizes in the params given define the bounding box. The image is sized
// proportionally such that it fits in the bounding box without cropping
const clip = async (client, params) => {
  return client.resize(params.width, params.height);
};

const cover = async (client, params) => {
  return client.resize(params.width, params.height, '^');
};

// Same as clipping, however the remainder of the bounding box is filled with
// white.
const canvas = async (client, params) => {
  client = await clip(client, params);
  return client.gravity('Center').extent(params.width, params.height);
};

// Fill a transparent background with white
const background = async (client, params) => {
  if (params.mime === 'image/jpeg') {
    return client.background('white').flatten();
  }
  return client;
};

// Fit the image appropriately.
const fit = async (client, params) => {
  //For original format
  if (!params.width || !params.height) {
    return client;
  }
  if (params.fit === 'crop') {
    return crop(client, params);
  } else if (params.fit === 'canvas') {
    return canvas(client, params);
  } else if (params.fit === 'clip') {
    return clip(client, params);
  } else if (params.fit === 'cover') {
    return cover(client, params);
  }
  throw new Error(`Format '${params.fit}' was accepted but could not be handled`);
};

const setQuality = async (client, params) => {
  if (params.quality === -1) {
    return client;
  }

  // The imagemagick 'quality' parameter has a very different meaning for
  // different image types, so it's not a good idea to just blindly pass it
  // through. For now, we only support jpg and webp compression, which is the most intuitive.
  switch (params.mime) {
    case 'image/jpeg':
    case 'image/webp':
      return client.quality(Math.min(100, Math.max(0, params.quality)));
    default:
      //No compression supported for other types
      return client;
  }
};

// Blur the image if requested in the params
const blur = async (client, params) => {
  if (params.blur === null) {
    return client;
  }
  return client.blur(params.blur.radius, params.blur.sigma);
};

export async function magic(file, params) {
  let client = im(file).options(gmOptions);
  client = await strip(client);
  client = await fit(client, params);
  client = await background(client, params);
  client = await blur(client, params);
  client = await setQuality(client, params);
  client = await interlace(client, params);
  return client;
}

export async function writeOriented(source, destination, cropParameters) {
  // if possible, crop first (since the UA had that orientation), then orient
  if (cropParameters) {
    const cropped = im(source).options(gmOptions)
      .crop(cropParameters.width, cropParameters.height, cropParameters.xOffset, cropParameters.yOffset);
    try {
      await write(cropped, source);
    } catch (e) {
      log('error', e.stack);
      throw e;
    }
  }

  const oriented = im(source).options(gmOptions).autoOrient();

  try {
    await write(oriented, destination);
  } catch (e) {
    log('error', e.stack);
    throw e;
  }

  try {
    // Set this into the cache early
    const imgSize = await imageSize(destination);
    return {
      originalHeight: imgSize.height || null,
      originalWidth: imgSize.width || null
    };
  } catch (e) {
    log('error', e.stack);
    return {
      originalHeight: null,
      originalWidth: null
    };
  }
}

export async function imageSize(path) {
  // Check whether we have this thing in cache first
  const cacheResult = await fastCache.getSizeFromCache(path);
  if (cacheResult) {
    return cacheResult;
  }
  const result = await size(im(path).options(gmOptions));
  // Dont wait for adding it to the cache
  fastCache.addSizeToCache(path, result);
  return result;
}

export async function imageArea(path) {
  try {
    const imgSize = await imageSize(path);
    return imgSize.width * imgSize.height;
  } catch (e) {
    log('error', e);
    return Number.MAX_SAFE_INTEGER;
  }
}
<commit_msg>eslintify<commit_after>require("babel-polyfill");

import fs from "fs";
import gm from "gm";
import config from "config";
import log from "./log";
import uuid from "uuid/v4";
import * as fastCache from './fastCache';

const gmOptions = {};
if (config.has('timeout.conversion')) {
  const timeout = Number(config.get('timeout.conversion'));
  if (isNaN(timeout)) {
    log('warn', 'The configuration value of timeout.conversion resolved to a NaN value. Ignoring it!');
  } else if (timeout < 0) {
    log('warn', 'The configuration value of timeout.conversion did not resolve to a nonnegative value. Ignoring it!');
  } else if (timeout === 0) {
    log('info', 'Not setting any image timeout');
  } else {
    gmOptions.timeout = timeout;
  }
}

const options = Object.assign({}, {imageMagick: true}, gmOptions);
log('info', `Booting gm with the following options: ${JSON.stringify(options)}`);

const im = gm.subClass(options);

// 10 seconds
const CLEAR_TEMP_FILES_TIMEOUT = 10000;

// Wrap these calls in promises so we can use async/await
const write = (client, file) => {
  return new Promise((resolve, reject) => client.write(file, err => err ? reject(err) : resolve()));
};
const size = async (client) => {
  return await new Promise((resolve, reject) => client.size({bufferStream: true}, (err, data) => err ? reject(err) : resolve(data)));
};

// Strip the image of any profiles or comments
const strip = async (client) => {
  return client.strip();
};

// Interlacing for png isn't efficient (both in filesize as render performance), so we only do it for jpg
const interlace = async (client, params) => {
  if (params.mime === 'image/jpeg') {
    return client.interlace('Line');
  }
  return client;
};

// When cropping, we size the image first to fix completely within the bounding box
// Then we crop the requested size, and center to the center of the image
const crop = async (client, params) => {
  // Resize the image to fit within the bounding box
  // The ^ ensures the images is resized while maintaining the ratio
  // However the sizes are treated as minimum values instead of maximum values
  client = client.resize(params.width, params.height, '^');
  const tmpFile = `/tmp/${uuid()}`;
  try {
    await write(client, tmpFile);
    client = im(tmpFile).options(gmOptions);
    const imgSize = await size(client);
    setTimeout(() => fs.unlink(tmpFile, err => {
      if (err) {
        log('error', `Tempfile ${tmpFile} could not be deleted`);
      }
    }), CLEAR_TEMP_FILES_TIMEOUT);
    return client
      .repage(imgSize.width, imgSize.height, 0, 0)
      .gravity('Center')
      // Crop the image to the exact size (the ! indicates a force)
      // This is ok since we first resized appropriately
      .crop(params.width, params.height, '!');
  } catch (e) {
    log('error', 'could not write tempfile');
    log('error', e.stack);
    throw e;
  }
};

// The sizes in the params given define the bounding box. The image is sized
// proportionally such that it fits in the bounding box without cropping
const clip = async (client, params) => {
  return client.resize(params.width, params.height);
};

const cover = async (client, params) => {
  return client.resize(params.width, params.height, '^');
};

// Same as clipping, however the remainder of the bounding box is filled with
// white.
const canvas = async (client, params) => {
  client = await clip(client, params);
  return client.gravity('Center').extent(params.width, params.height);
};

// Fill a transparent background with white
const background = async (client, params) => {
  if (params.mime === 'image/jpeg') {
    return client.background('white').flatten();
  }
  return client;
};

// Fit the image appropriately.
const fit = async (client, params) => {
  //For original format
  if (!params.width || !params.height) {
    return client;
  }
  if (params.fit === 'crop') {
    return crop(client, params);
  } else if (params.fit === 'canvas') {
    return canvas(client, params);
  } else if (params.fit === 'clip') {
    return clip(client, params);
  } else if (params.fit === 'cover') {
    return cover(client, params);
  }
  throw new Error(`Format '${params.fit}' was accepted but could not be handled`);
};

const setQuality = async (client, params) => {
  if (params.quality === -1) {
    return client;
  }

  // The imagemagick 'quality' parameter has a very different meaning for
  // different image types, so it's not a good idea to just blindly pass it
  // through. For now, we only support jpg and webp compression, which is the most intuitive.
  switch (params.mime) {
    case 'image/jpeg':
    case 'image/webp':
      return client.quality(Math.min(100, Math.max(0, params.quality)));
    default:
      //No compression supported for other types
      return client;
  }
};

// Blur the image if requested in the params
const blur = async (client, params) => {
  if (params.blur === null) {
    return client;
  }
  return client.blur(params.blur.radius, params.blur.sigma);
};

export async function magic(file, params) {
  let client = im(file).options(gmOptions);
  client = await strip(client);
  client = await fit(client, params);
  client = await background(client, params);
  client = await blur(client, params);
  client = await setQuality(client, params);
  client = await interlace(client, params);
  return client;
}

export async function imageSize(path) {
  // Check whether we have this thing in cache first
  const cacheResult = await fastCache.getSizeFromCache(path);
  if (cacheResult) {
    return cacheResult;
  }
  const result = await size(im(path).options(gmOptions));
  // Dont wait for adding it to the cache
  fastCache.addSizeToCache(path, result);
  return result;
}

export async function writeOriented(source, destination, cropParameters) {
  // if possible, crop first (since the UA had that orientation), then orient
  if (cropParameters) {
    const cropped = im(source).options(gmOptions)
      .crop(cropParameters.width, cropParameters.height, cropParameters.xOffset, cropParameters.yOffset);
    try {
      await write(cropped, source);
    } catch (e) {
      log('error', e.stack);
      throw e;
    }
  }

  const oriented = im(source).options(gmOptions).autoOrient();

  try {
    await write(oriented, destination);
  } catch (e) {
    log('error', e.stack);
    throw e;
  }

  try {
    // Set this into the cache early
    const imgSize = await imageSize(destination);
    return {
      originalHeight: imgSize.height || null,
      originalWidth: imgSize.width || null
    };
  } catch (e) {
    log('error', e.stack);
    return {
      originalHeight: null,
      originalWidth: null
    };
  }
}

export async function imageArea(path) {
  try {
    const imgSize = await imageSize(path);
    return imgSize.width * imgSize.height;
  } catch (e) {
    log('error', e);
    return Number.MAX_SAFE_INTEGER;
  }
}
<|endoftext|>