<commit_before>(function (root, factory) {
    if (typeof exports === 'object') {
        module.exports.Events = factory();
    } else if (typeof define === 'function' && define.amd) {
        define('Eventsjs/Eventsjs',[],function () {
            return factory();
        });
    } else {
        root.Events = factory();
    }
}(this, function (){
    /**
     * @module Events
     */

    var use_dom = false,
        pseudo_regex = /([^:]+)(?:\:([^(]*)(?:\((.*)\))?)?/,
        addEvent, addEvents, fireEvent, removeEvent, addEventOnce, Events, fireLatchedEvent;

    try {
        use_dom = document && 'addEventListener' in document;
    }catch(e){}

    //=================
    //    UTILITIES
    //=================

    //utility function for cross-browser
    function indexOf(arr,prop){
        if (arr.indexOf) return arr.indexOf(prop);
        else return String.prototype.indexOf(arr,prop);
    }

    //handles warnings set by the library
    function warn(error){
        if (Events.strict){
            throw new Error(error);
        }else if ('console' in window){
            if (console.error) console.error(error);
            else if (console.warn) console.warn(error);
            else console.log(error);
        }
    }

    /**
     * removes the on* prefix from event names
     * @method Events.removeOn
     * @static
     *
     * @param {string} type
     *
     * @return {string}
     */
    function removeOn(string){
        return string.replace(/^on([A-Z])/, function(full, first){
            return first.toLowerCase();
        });
    }

    /**
     * returns a structured data object about a type's pseudo-events
     *
     * @method getPseudo
     * @private
     * @static
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function getPseudo(string){
        var match = string.match(pseudo_regex);

        if (string.split(':').length > 2) warn("Library does not support multiple pseudo events");

        return {
            name : match[1],
            pseudo : match[2],
            args : match[3]
        };
    }

    /**
     * proccesses an event type, returning a valid data object from that name
     * @method processType
     * @static
     * @private
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function processType(type){
        return getPseudo(removeOn(type));
    }

    /**
     * cross-browser function to create event object for fire method
     *
     * Created object will always have following properties:
     *  - dispatcher: a reference to dispatching object (since we can't use 'this')
     *  - args: arguments passed alongside the event
     *  - object_event: a flag set to true to easily check if this is an object event or a normal DOM event.
     *
     * @method Events.createEvent
     * @static
     * @private
     *
     * @param {string} type
     * @param {object} dispatcher
     * @param {mixed} args
     *
     * @return event object
     */
    function createEvent(type, dis, args, bubbles){
        var ev;

        if (use_dom){
            ev = document.createEvent('UIEvents');
            ev.initUIEvent(type, bubbles, true, window, 1);
        }else{
            ev = {};
        }

        ev.dispatcher = dis;
        ev.args = args;
        ev.object_event = true;

        return ev;
    }

    /**
     * Events Provider.
     *
     * Can function either as a standalone or a Mixin
     *
     * @class Events
     * @constructor
     *
     * @param {Element} el element to use as event target. Optional
     */
    Events = function Events(el,no_destroy){
        var $this = this, alias,
            destroy_names = "$event_element $latched $events $once addEvent addEvents fireEvent removeEvent addEventOnce fireLatchedEvent".split(' ');

        if (!use_dom){
            this.$events = {};
        }else{
            this.$event_element = el || document.createElement('events');
        }

        this.$has_events = true;
        this.$latched = {};
        this.$once    = {};

        this.addEvent = addEvent;
        this.addEvents = addEvents;
        this.fireEvent = fireEvent;
        this.removeEvent = removeEvent;
        this.addEventOnce = addEventOnce;
        this.fireLatchedEvent = fireLatchedEvent;

        for (alias in Events.aliases) {
            this[alias] = this[Events.aliases[alias]];
            destroy_names.push(alias);
        }

        //since this code removes the reference to the events provider,
        //we want to make sure it runs after the rest of the loop is done.
        if (!no_destroy) this.addEvent('destroy:delay(0)',function(){
            var i, name;

            if ($this.$no_ev_destroy) return;

            for (i=0; name = destroy_names[i]; i++) $this[name] = null;

            $this.$events_destroyed = true;
        });
    };

    //In case someone want to use these
    Events.removeOn = removeOn;
    Events.getPseudos = getPseudo;
    Events.processType = processType;
    Events.createEvent = createEvent;
    Events.strict = false;

    /**
     * A list of aliases for Events methods. Use this to add similar syntax to other event implementations
     *
     * By default, aliases include most of EventEmitter interface
     *
     * @property aliases
     * @type object
     * @public
     * @static
     */
    Events.aliases = {
        'on' : 'addEvent',
        'addListener' : 'addEvent',
        'once' : 'addEventOnce',
        'removeListener' : 'removeEvent',
        'off' : 'removeEvent',
        'emit' : 'fireEvent'
    };

    /*
     * Events.Pesudoes allows you to add pseudo behaviors
     *
     * Each object in the collection can hold both addEvent and fireEvent Methods
     *
     * The addEvent method will be fired *instead* of the normal behavior, and will be passed
     * the event type and fn
     *
     * The fireEvent method will be fired *after* the fireEvent method, and will be passed
     * the event name and the event object created
     *
     * Look at examples to see how it can be used
     *
     * @property Events.Pseudoes
     * @type {object}
     * @static
     */
    Events.Pseudoes = {
        once : {
            addEvent : function(type,fn){
                return this.addEventOnce(type, fn);
            }
        },

        latched : {
            fireEvent : function(type, args){
                return this.fireLatchedEvent(type,args);
            }
        },

        times : {
            addEvent : function(type, fn, ammount){
                var count = 0, $this = this;

                this.addEvent(type, function times(){
                    fn.apply(null, arguments);
                    count+=1;
                    if (count == ammount) $this.removeEvent(type,times);
                });
            }
        },

        delay : {
            addEvent : function(type, fn, delay){
                this.addEvent(type, function(){
                    setTimeout(fn,delay);
                });
            },
            fireEvent : function(type, args, delay){
                var $this = this;
                setTimeout(function(){
                    $this.fireEvent(type, args);
                }, delay);
            }
        }
    };

    //========================
    // cross-browser utilities
    //========================

    function register(obj, type, fn){
        if (use_dom){
            obj.$event_element.addEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) obj.$events[type] = [fn];
            else if (indexOf(obj.$events[type],fn)==-1){
                obj.$events[type].push(fn);
            }
        }
    }

    function dispatch(obj,type, ev){
        var i, fn;

        if (use_dom){
            obj.$event_element.dispatchEvent(ev);
        }else{
            if (!obj.$events[type]) return;

            for (i=0; fn = obj.$events[type][i]; i++){
                fn.apply(null,[ev]);
            }
        }
    }

    function remove(obj, type, fn){
        var index;

        if (use_dom){
            obj.$event_element.removeEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) return;

            index = indexOf(obj.$events[type],fn);

            if (index <0) return;

            obj.$events[type].splice(index,1);
        }
    }

    //=======================
    // Function Declarations
    //=======================

    /**
     * Adds an event
     *
     * @method addEvent
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEvent = function addEvent(type,fn){
        if (this.$events_destroyed) return this;

        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].addEvent,
            args = this.$latched[data.name] && this.$latched[data.name].args,
            ev;

        if (pseudo_fn){
            return pseudo_fn.apply(this,[data.name,fn,data.args]);
        }

        register(this,data.name, fn);

        if (this.$latched && this.$latched[data.name]){
            ev = createEvent(data.name, this, args);
            fn.apply(null,[ev]);
        }

        return this;
    };

    /**
     * Helper to add multiple events at once
     *
     * @method addEvents
     *
     * @param {Object} literal object of event types => callbacks
     *
     * @chainable
     */
    addEvents = function addEvents(events){
        if (this.$events_destroyed) return this;
        var type;

        for (type in events) if (events.hasOwnProperty(type)){
            this.addEvent(type, events[type]);
        }

        return this;
    };

    /**
     * dispatches an event
     *
     * @method fireEvent
     *
     * @param {String} event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireEvent = function fireEvent(type, args, bubbles){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].fireEvent,
            ev, fn,
            once_arr,
            temp_arr;

        if (bubbles == null) bubbles = true;

        if (pseudo_fn){
            return pseudo_fn.call(this,data.name,args);
        }

        //in case one of the callbacks will try and add another once event,
        //we keep a reference of the once stack, and then empty it
        once_arr = this.$once[data.name];
        this.$once[data.name] = null;

        ev = createEvent(data.name, this, args, bubbles);

        dispatch(this,data.name,ev);

        if (!once_arr) return this;

        while (fn = once_arr.pop()){
            this.removeEvent(data.name, fn, true);
        }

        return this;
    };

    /**
     * removes a function from an event
     *
     * @method removeEvent
     *
     * @param {String}   event type
     * @param {Function} function to remove from stack
     *
     * @chainable
     */
    removeEvent = function removeEvent(type, fn,no_once){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            index;

        remove(this,data.name, fn);

        if (!no_once && this.$once[data.name] && (index = indexOf(this.$once[data.name],fn))>-1){
            this.$once[data.name].splice(index,1);
        }

        return this;
    };

    /**
     * Adds an event for one execution, then removes it
     *
     * @method addEventOnce
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEventOnce = function addEventOnce(type, fn){
        if (this.$events_destroyed) return this;
        var $this = this,
            data = processType(type);

        if (!this.$once[data.name]) this.$once[data.name] = [];
        if (indexOf(this.$once[data.name],fn) == -1){
            this.$once[data.name].push(fn);
        }

        return this.addEvent(data.name, fn);
    };

    /**
     * Fires a latched event
     *
     * @method fireLatchedEvent
     *
     * @param {String} the event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireLatchedEvent = function fireLatchedEvent(type, args){
        if (this.$events_destroyed) return this;
        if (!this.$latched) this.$latched = {};

        this.$latched[type] = {args : args};
        this.fireEvent(type,args);

        return this;
    };

    Events.addEvent = addEvent;
    Events.addEvents = addEvents;
    Events.addEventOnce = addEventOnce;
    Events.fireEvent = fireEvent;
    Events.fireLatchedEvent = fireLatchedEvent;
    Events.removeEvent = removeEvent;

    //expose Mixin to provided namespace
    return Events;
}));<commit_msg>exposing processType<commit_after>(function (root, factory) {
    if (typeof exports === 'object') {
        module.exports.Events = factory();
    } else if (typeof define === 'function' && define.amd) {
        define('Eventsjs/Eventsjs',[],function () {
            return factory();
        });
    } else {
        root.Events = factory();
    }
}(this, function (){
    /**
     * @module Events
     */

    var use_dom = false,
        pseudo_regex = /([^:]+)(?:\:([^(]*)(?:\((.*)\))?)?/,
        addEvent, addEvents, fireEvent, removeEvent, addEventOnce, Events, fireLatchedEvent;

    try {
        use_dom = document && 'addEventListener' in document;
    }catch(e){}

    //=================
    //    UTILITIES
    //=================

    //utility function for cross-browser
    function indexOf(arr,prop){
        if (arr.indexOf) return arr.indexOf(prop);
        else return String.prototype.indexOf(arr,prop);
    }

    //handles warnings set by the library
    function warn(error){
        if (Events.strict){
            throw new Error(error);
        }else if ('console' in window){
            if (console.error) console.error(error);
            else if (console.warn) console.warn(error);
            else console.log(error);
        }
    }

    /**
     * removes the on* prefix from event names
     * @method Events.removeOn
     * @static
     *
     * @param {string} type
     *
     * @return {string}
     */
    function removeOn(string){
        return string.replace(/^on([A-Z])/, function(full, first){
            return first.toLowerCase();
        });
    }

    /**
     * returns a structured data object about a type's pseudo-events
     *
     * @method getPseudo
     * @private
     * @static
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function getPseudo(string){
        var match = string.match(pseudo_regex);

        if (string.split(':').length > 2) warn("Library does not support multiple pseudo events");

        return {
            name : match[1],
            pseudo : match[2],
            args : match[3]
        };
    }

    /**
     * proccesses an event type, returning a valid data object from that name
     * @method processType
     * @static
     * @private
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function processType(type){
        return getPseudo(removeOn(type));
    }

    /**
     * cross-browser function to create event object for fire method
     *
     * Created object will always have following properties:
     *  - dispatcher: a reference to dispatching object (since we can't use 'this')
     *  - args: arguments passed alongside the event
     *  - object_event: a flag set to true to easily check if this is an object event or a normal DOM event.
     *
     * @method Events.createEvent
     * @static
     * @private
     *
     * @param {string} type
     * @param {object} dispatcher
     * @param {mixed} args
     *
     * @return event object
     */
    function createEvent(type, dis, args, bubbles){
        var ev;

        if (use_dom){
            ev = document.createEvent('UIEvents');
            ev.initUIEvent(type, bubbles, true, window, 1);
        }else{
            ev = {};
        }

        ev.dispatcher = dis;
        ev.args = args;
        ev.object_event = true;

        return ev;
    }

    /**
     * Events Provider.
     *
     * Can function either as a standalone or a Mixin
     *
     * @class Events
     * @constructor
     *
     * @param {Element} el element to use as event target. Optional
     */
    Events = function Events(el,no_destroy){
        var $this = this, alias,
            destroy_names = "$event_element $latched $events $once addEvent addEvents fireEvent removeEvent addEventOnce fireLatchedEvent".split(' ');

        if (!use_dom){
            this.$events = {};
        }else{
            this.$event_element = el || document.createElement('events');
        }

        this.$has_events = true;
        this.$latched = {};
        this.$once    = {};

        this.addEvent = addEvent;
        this.addEvents = addEvents;
        this.fireEvent = fireEvent;
        this.removeEvent = removeEvent;
        this.addEventOnce = addEventOnce;
        this.fireLatchedEvent = fireLatchedEvent;

        for (alias in Events.aliases) {
            this[alias] = this[Events.aliases[alias]];
            destroy_names.push(alias);
        }

        //since this code removes the reference to the events provider,
        //we want to make sure it runs after the rest of the loop is done.
        if (!no_destroy) this.addEvent('destroy:delay(0)',function(){
            var i, name;

            if ($this.$no_ev_destroy) return;

            for (i=0; name = destroy_names[i]; i++) $this[name] = null;

            $this.$events_destroyed = true;
        });
    };

    //In case someone want to use these
    Events.removeOn = removeOn;
    Events.getPseudos = getPseudo;
    Events.processType = processType;
    Events.createEvent = createEvent;
    Events.strict = false;

    /**
     * A list of aliases for Events methods. Use this to add similar syntax to other event implementations
     *
     * By default, aliases include most of EventEmitter interface
     *
     * @property aliases
     * @type object
     * @public
     * @static
     */
    Events.aliases = {
        'on' : 'addEvent',
        'addListener' : 'addEvent',
        'once' : 'addEventOnce',
        'removeListener' : 'removeEvent',
        'off' : 'removeEvent',
        'emit' : 'fireEvent'
    };

    /*
     * Events.Pesudoes allows you to add pseudo behaviors
     *
     * Each object in the collection can hold both addEvent and fireEvent Methods
     *
     * The addEvent method will be fired *instead* of the normal behavior, and will be passed
     * the event type and fn
     *
     * The fireEvent method will be fired *after* the fireEvent method, and will be passed
     * the event name and the event object created
     *
     * Look at examples to see how it can be used
     *
     * @property Events.Pseudoes
     * @type {object}
     * @static
     */
    Events.Pseudoes = {
        once : {
            addEvent : function(type,fn){
                return this.addEventOnce(type, fn);
            }
        },

        latched : {
            fireEvent : function(type, args){
                return this.fireLatchedEvent(type,args);
            }
        },

        times : {
            addEvent : function(type, fn, ammount){
                var count = 0, $this = this;

                this.addEvent(type, function times(){
                    fn.apply(null, arguments);
                    count+=1;
                    if (count == ammount) $this.removeEvent(type,times);
                });
            }
        },

        delay : {
            addEvent : function(type, fn, delay){
                this.addEvent(type, function(){
                    setTimeout(fn,delay);
                });
            },
            fireEvent : function(type, args, delay){
                var $this = this;
                setTimeout(function(){
                    $this.fireEvent(type, args);
                }, delay);
            }
        }
    };

    //========================
    // cross-browser utilities
    //========================

    function register(obj, type, fn){
        if (use_dom){
            obj.$event_element.addEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) obj.$events[type] = [fn];
            else if (indexOf(obj.$events[type],fn)==-1){
                obj.$events[type].push(fn);
            }
        }
    }

    function dispatch(obj,type, ev){
        var i, fn;

        if (use_dom){
            obj.$event_element.dispatchEvent(ev);
        }else{
            if (!obj.$events[type]) return;

            for (i=0; fn = obj.$events[type][i]; i++){
                fn.apply(null,[ev]);
            }
        }
    }

    function remove(obj, type, fn){
        var index;

        if (use_dom){
            obj.$event_element.removeEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) return;

            index = indexOf(obj.$events[type],fn);

            if (index <0) return;

            obj.$events[type].splice(index,1);
        }
    }

    //=======================
    // Function Declarations
    //=======================

    /**
     * Adds an event
     *
     * @method addEvent
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEvent = function addEvent(type,fn){
        if (this.$events_destroyed) return this;

        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].addEvent,
            args = this.$latched[data.name] && this.$latched[data.name].args,
            ev;

        if (pseudo_fn){
            return pseudo_fn.apply(this,[data.name,fn,data.args]);
        }

        register(this,data.name, fn);

        if (this.$latched && this.$latched[data.name]){
            ev = createEvent(data.name, this, args);
            fn.apply(null,[ev]);
        }

        return this;
    };

    /**
     * Helper to add multiple events at once
     *
     * @method addEvents
     *
     * @param {Object} literal object of event types => callbacks
     *
     * @chainable
     */
    addEvents = function addEvents(events){
        if (this.$events_destroyed) return this;
        var type;

        for (type in events) if (events.hasOwnProperty(type)){
            this.addEvent(type, events[type]);
        }

        return this;
    };

    /**
     * dispatches an event
     *
     * @method fireEvent
     *
     * @param {String} event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireEvent = function fireEvent(type, args, bubbles){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].fireEvent,
            ev, fn,
            once_arr,
            temp_arr;

        if (bubbles == null) bubbles = true;

        if (pseudo_fn){
            return pseudo_fn.call(this,data.name,args);
        }

        //in case one of the callbacks will try and add another once event,
        //we keep a reference of the once stack, and then empty it
        once_arr = this.$once[data.name];
        this.$once[data.name] = null;

        ev = createEvent(data.name, this, args, bubbles);

        dispatch(this,data.name,ev);

        if (!once_arr) return this;

        while (fn = once_arr.pop()){
            this.removeEvent(data.name, fn, true);
        }

        return this;
    };

    /**
     * removes a function from an event
     *
     * @method removeEvent
     *
     * @param {String}   event type
     * @param {Function} function to remove from stack
     *
     * @chainable
     */
    removeEvent = function removeEvent(type, fn,no_once){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            index;

        remove(this,data.name, fn);

        if (!no_once && this.$once[data.name] && (index = indexOf(this.$once[data.name],fn))>-1){
            this.$once[data.name].splice(index,1);
        }

        return this;
    };

    /**
     * Adds an event for one execution, then removes it
     *
     * @method addEventOnce
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEventOnce = function addEventOnce(type, fn){
        if (this.$events_destroyed) return this;
        var $this = this,
            data = processType(type);

        if (!this.$once[data.name]) this.$once[data.name] = [];
        if (indexOf(this.$once[data.name],fn) == -1){
            this.$once[data.name].push(fn);
        }

        return this.addEvent(data.name, fn);
    };

    /**
     * Fires a latched event
     *
     * @method fireLatchedEvent
     *
     * @param {String} the event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireLatchedEvent = function fireLatchedEvent(type, args){
        if (this.$events_destroyed) return this;
        if (!this.$latched) this.$latched = {};

        this.$latched[type] = {args : args};
        this.fireEvent(type,args);

        return this;
    };

    Events.addEvent = addEvent;
    Events.addEvents = addEvents;
    Events.addEventOnce = addEventOnce;
    Events.fireEvent = fireEvent;
    Events.fireLatchedEvent = fireLatchedEvent;
    Events.removeEvent = removeEvent;
    Events.processType = processType;

    //expose Mixin to provided namespace
    return Events;
}));<|endoftext|>


<commit_before>;(function(window, undefined) {
	"use strict";
	var ess,emptyArray = [],slice = emptyArray.slice,filter = emptyArray.filter,elementTypes = [1, 9, 11],A={},
		WCJ = (function(){
		var WCJ = function( selector ) {
		    return new WCJ.fn.init(selector);
		};
		WCJ.fn = WCJ.prototype = {
			init:function( selector ){
				var dom ;
    			if (!selector)
    				dom = emptyArray,dom.selector = selector || '',dom.__proto__ = WCJ.fn.init.prototype;
    			else if (WCJ.isFunction(selector)) return WCJ(document).ready(selector)
    			else {
    				if (WCJ.isArray(selector))
    					dom = selector;
				    else if (WCJ.isObject(selector))
				    	dom = [selector], selector = null
	                else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window)
	                	dom = [selector], selector = null;
	                else dom = (function(){
				        var found;
				        return (document && /^#([\w-]+)$/.test(selector))?
				        ((found = document.getElementById(RegExp.$1)) ? [found] : emptyArray ):
					    slice.call(
						    /^\.([\w-]+)$/.test(selector) ? document.getElementsByClassName(RegExp.$1) :
						    /^[\w-]+$/.test(selector) ? document.getElementsByTagName(selector) :
						    document.querySelectorAll(selector)
					    );
					})();
					dom = dom || emptyArray;
					dom.__proto__ = WCJ.fn.init.prototype;
					dom.selector = selector || '';
    			}
    			return dom;
			},
			size:function(){return this.length;}
		}
		WCJ.fn.init.prototype = WCJ.fn;
        WCJ.extend = WCJ.fn.extend = function () {
            var options, name, src, copy,
			target = arguments[0],
			i = 1,
			length = arguments.length,
			deep = false;
            //处理深拷贝的情况
            if (typeof (target) === "boolean") {
                deep = target;
                target = arguments[1] || {};
                i = 2;
            }
            //处理时，目标是一个字符串或（深拷贝可能的情况下）的东西
            if (typeof (target) !== "object" && !WCJ.isFunction(target)) {
                target = {};
            }
            //扩展WCJ的本身，如果只有一个参数传递
            if (length === i) {
                target = this;
                --i;
            }
            for (; i < length; i++) {
                if ((options = arguments[i]) != null) {
                    for (name in options) {
                        src = target[name];
                        copy = options[name];
                        if (target === copy) {
                            continue;
                        }
                        if (copy !== undefined) {
                            target[name] = copy;
                        }
                    }
                }
            }
            return target;
        };
		return WCJ;
	})();

	WCJ.fn.extend({
		forEach: emptyArray.forEach,
		concat: emptyArray.concat,
		ready: function(callback){
			if (/complete|loaded|interactive/.test(document.readyState) && document.body) callback(WCJ)
			else document.addEventListener('DOMContentLoaded', function(){callback(WCJ) }, false)
			return this
		},
	    each: function(callback){
	      this.forEach(function(el, idx){ callback.call(el, idx, el) });
	      return this;
	    },
	    map: function(fn){
	    	return WCJ(WCJ.map(this, function(el, i){ return fn.call(el, i, el) }));
	    },
	    get: function(index){
	      return index === undefined ? slice.call(this) : this[index >= 0 ? index : index + this.length];
	    },
	    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
	    text: function(text){
	      return text === undefined ?
	        (this.length > 0 ? this[0].textContent : null) :
	        this.each(function(){ this.textContent = text });
	    },
        bind: function(type, func) {
			this.each(function(){
				if (this.addEventListener) this.addEventListener(type, func, false);
				else if (this.attachEvent) this.attachEvent("on" + type, func);
				else this["on" + type] = func;
			})
			return this;
		},
		unbind:function(type, func) {
			this.each(function(ele,obj){
				if (this.removeEventListener) this.removeEventListener(type, func, false);
				else if (this[i].detachEvent) this.detachEvent("on" + type, func);
				else this["on" + type] = null;
			})
			return this;
		},
		filter:function(selector){
			return WCJ(filter.call(this, function(element){
        		return WCJ.matches(element, selector)
		    }))
		},
		pluck: function(property){ return WCJ.map(this, function(el){ return el[property] })},
		find: function(selector){
			var nodes = this.children(),ancestors=[];
			while (nodes.length > 0)
			nodes=WCJ.map(nodes, function(node,inx){
				if (ancestors.indexOf(node)<0) ancestors.push(node);
				if ((nodes = WCJ(node).children())&&nodes.length>0 ) return nodes;
			});
			return WCJ(ancestors).filter(selector || '*');
		},
		children:function(selector){
			var arr=this.pluck('children'),e=[];
			filter.call(arr, function(item, idx){
				WCJ.map(item,function(els){ if (els.nodeType == 1) e.push(els) })
			});
			return WCJ(e).filter(selector || '*');
		},
		parent: function(){
			var arr=this.pluck('parentNode');
			return filter.call(arr, function(item, idx){
				return arr.indexOf(item) == idx
			});
		},
		parents: function(selector){
			var ancestors=WCJ.sibling(this,'parentNode');
    		return selector == null ? WCJ(ancestors) : WCJ(ancestors).filter(selector);
		},
		prev: function(selector){
			return WCJ(this.pluck('previousElementSibling')).filter(selector || '*')
		},
		next: function(selector){
			return WCJ(this.pluck('nextElementSibling')).filter(selector || '*')
		},
        nextAll: function (selector) {
      		return WCJ(WCJ.sibling(this,'nextElementSibling')).filter(selector || '*');
        },
		prevAll: function (selector) {
			return WCJ(WCJ.sibling(this,'previousElementSibling')).filter(selector || '*');
		},
		siblings: function(selector){
			var n=[];
			this.map(function(i, el){
				WCJ.map(el.childNodes,function(els){ if (els.nodeType == 1) n.push(els) })
			});
			return WCJ(n).filter(selector || '*');
		}
	});

	WCJ.extend({
		isDocument:function (obj) { return obj = obj ? obj != null && obj.nodeType ? obj.nodeType == obj.DOCUMENT_NODE : false : undefined;},
		isFunction:function (value) { return ({}).toString.call(value) == "[object Function]" },
		isObject:function (value) { return value instanceof Object },
		isArray:function (value) { return value instanceof Array },
		isContainsNode:function(parent,node){
	    	return document.documentElement.isContainsNode ?
		    parent !== node && parent.isContainsNode(node):
		    (function(){
		    	while (node && (node = node.parentNode))
		    	if (node === parent) return true
		    	return false
			})();
	    },
		likeArray:function (obj) { return typeof obj.length == 'number' },
        type: function (obj) {
            switch (obj) {
                case null: return "Null";
                case (void 0): return "Undefined";
            }
            var type = typeof (obj);
            switch (type) {
                case 'boolean': return "Boolean";
                case 'number': return "Number";
                case 'string': return "String";
                case 'function': return "Function";
            }
            return "Object";
        },
        error:function(msg) {throw msg;},
        each:function(elements, callback){
			var i, key
			if (this.likeArray(elements)) {
				for (i = 0; i < elements.length; i++)
					if (callback.call(elements[i], i, elements[i]) === false) return elements
				} else {
				for (key in elements)
					if (callback.call(elements[key], key, elements[key]) === false) return elements
			}
			return elements
		},
		map:function(elements, callback){
			var value, values = [], i, key
			if (this.likeArray(elements))
			for (i = 0; i < elements.length; i++) {
				value = callback(elements[i], i)
				if (value != null) values.push(value)
			}
			else
			for (key in elements) {
				value = callback(elements[key], key)
				if (value != null) values.push(value)
			}
			return values.length > 0 ? WCJ.fn.concat.apply([], values) : values;
		},
		matches:function(element, selector){
			if (!selector || !element || element.nodeType !== 1) return false;
		    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
		                          element.oMatchesSelector || element.msMatchesSelector || element.matchesSelector;
		    if (matchesSelector) return matchesSelector.call(element, selector);
		},
		inArray:function(elem, array, i){
			return emptyArray.indexOf.call(array, elem, i)
		},
	    sibling:function(nodes,ty){
			var ancestors = [];
			while (nodes.length > 0)
			nodes = WCJ.map(nodes, function(node){
				if ((node = node[ty]) && !WCJ.isDocument(node) && ancestors.indexOf(node) < 0)
					ancestors.push(node)
					return node
			});
			return ancestors;
	    }
	});

	['after','prepend','before','append'].forEach(function(operator, operatorIndex) {
	    WCJ.fn[operator] = function(){
	    	var argType, nodes = WCJ.map(arguments, function(arg) {
	    	      argType = WCJ.type(arg)
	    	      return argType == "object" || argType == "array" || arg == null ?
	    	        arg : arguments[0]
	    	    }),position
	    	if (nodes.length < 1) return this
	    	return this.each(function(_, target){
	    		position = 	operatorIndex == 0 ? "afterEnd" :
	    					operatorIndex == 1 ? "afterBegin":
	    					operatorIndex == 2 ? "beforeBegin":
	    					operatorIndex == 3 ? "beforeEnd":
	    					null
	    		nodes.forEach(function(node){
	                target.insertAdjacentHTML(position,node)
	    		})
	    	})
	    }
	});

	//解决低版本浏览器对filter方法的支持
	if (!Array.prototype.filter){
		Array.prototype.filter = function(fun /*, thisArg */){
			"use strict";
			if (this === void 0 || this === null)
				throw new TypeError();
			var t = Object(this);
			var len = t.length >>> 0;
			if (typeof fun !== "function")
				throw new TypeError();
			var res = [];
			var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
			for (var i = 0; i < len; i++){
				if (i in t){
					var val = t[i];
					if (fun.call(thisArg, val, i, t))
					res.push(val);
				}
			}
			return res;
		};
	}
	//低版本IE对indexOf方法的支持
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	//低版本IE对forEach方法的支持
	if (!Array.prototype.forEach) {
	    Array.prototype.forEach = function(fun /*, thisp*/){
	        var len = this.length;
	        if (typeof fun != "function")
	            throw new TypeError();
	        var thisp = arguments[1];
	        for (var i = 0; i < len; i++){
	            if (i in this)
	                fun.call(thisp, this[i], i, this);
	        }
	    };
	}

	//字符串处理
    WCJ.extend(String.prototype,{
        trim: function () {return this.replace(/(^\s*)|(\s*$)/g, "");},
        leftTrim: function () {return this.replace(/(^\s*)/g, "");}
    })
	window.WCJ = window.$$ = WCJ;
})(window);<commit_msg>fix:after/prepend/before/append添加js不执行<commit_after>;(function(window, undefined) {
	"use strict";
	var ess,emptyArray = [],slice = emptyArray.slice,filter = emptyArray.filter,elementTypes = [1, 9, 11],P={},
		WCJ = (function(){
		var WCJ = function( selector ) {
		    return new WCJ.fn.init(selector);
		};
		WCJ.fn = WCJ.prototype = {
			init:function( selector ){
				var dom ;
    			if (!selector)
    				dom = emptyArray,dom.selector = selector || '',dom.__proto__ = WCJ.fn.init.prototype;
    			else if (WCJ.isFunction(selector)) return WCJ(document).ready(selector)
    			else {
    				if (WCJ.isArray(selector))
    					dom = selector;
				    else if (WCJ.isObject(selector))
				    	dom = [selector], selector = null
	                else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window)
	                	dom = [selector], selector = null;
	                else dom = (function(){
				        var found;
				        return (document && /^#([\w-]+)$/.test(selector))?
				        ((found = document.getElementById(RegExp.$1)) ? [found] : emptyArray ):
					    slice.call(
						    /^\.([\w-]+)$/.test(selector) ? document.getElementsByClassName(RegExp.$1) :
						    /^[\w-]+$/.test(selector) ? document.getElementsByTagName(selector) :
						    document.querySelectorAll(selector)
					    );
					})();
					dom = dom || emptyArray;
					dom.__proto__ = WCJ.fn.init.prototype;
					dom.selector = selector || '';
    			}
    			return dom;
			},
			size:function(){return this.length;}
		}
		WCJ.fn.init.prototype = WCJ.fn;
        WCJ.extend = WCJ.fn.extend = function () {
            var options, name, src, copy,
			target = arguments[0],
			i = 1,
			length = arguments.length,
			deep = false;
            //处理深拷贝的情况
            if (typeof (target) === "boolean") {
                deep = target;
                target = arguments[1] || {};
                i = 2;
            }
            //处理时，目标是一个字符串或（深拷贝可能的情况下）的东西
            if (typeof (target) !== "object" && !WCJ.isFunction(target)) {
                target = {};
            }
            //扩展WCJ的本身，如果只有一个参数传递
            if (length === i) {
                target = this;
                --i;
            }
            for (; i < length; i++) {
                if ((options = arguments[i]) != null) {
                    for (name in options) {
                        src = target[name];
                        copy = options[name];
                        if (target === copy) {
                            continue;
                        }
                        if (copy !== undefined) {
                            target[name] = copy;
                        }
                    }
                }
            }
            return target;
        };
		return WCJ;
	})();

	WCJ.fn.extend({
		forEach: emptyArray.forEach,
		concat: emptyArray.concat,
		ready: function(callback){
			if (/complete|loaded|interactive/.test(document.readyState) && document.body) callback(WCJ)
			else document.addEventListener('DOMContentLoaded', function(){callback(WCJ) }, false)
			return this
		},
	    each: function(callback){
	      this.forEach(function(el, idx){ callback.call(el, idx, el) });
	      return this;
	    },
	    map: function(fn){
	    	return WCJ(WCJ.map(this, function(el, i){ return fn.call(el, i, el) }));
	    },
	    get: function(index){
	      return index === undefined ? slice.call(this) : this[index >= 0 ? index : index + this.length];
	    },
	    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
	    text: function(text){
	      return text === undefined ?
	        (this.length > 0 ? this[0].textContent : null) :
	        this.each(function(){ this.textContent = text });
	    },
        bind: function(type, func) {
			this.each(function(){
				if (this.addEventListener) this.addEventListener(type, func, false);
				else if (this.attachEvent) this.attachEvent("on" + type, func);
				else this["on" + type] = func;
			})
			return this;
		},
		unbind:function(type, func) {
			this.each(function(ele,obj){
				if (this.removeEventListener) this.removeEventListener(type, func, false);
				else if (this[i].detachEvent) this.detachEvent("on" + type, func);
				else this["on" + type] = null;
			})
			return this;
		},
		filter:function(selector){
			return WCJ(filter.call(this, function(element){
        		return WCJ.matches(element, selector)
		    }))
		},
		pluck: function(property){ return WCJ.map(this, function(el){ return el[property] })},
		find: function(selector){
			var nodes = this.children(),ancestors=[];
			while (nodes.length > 0)
			nodes=WCJ.map(nodes, function(node,inx){
				if (ancestors.indexOf(node)<0) ancestors.push(node);
				if ((nodes = WCJ(node).children())&&nodes.length>0 ) return nodes;
			});
			return WCJ(ancestors).filter(selector || '*');
		},
		children:function(selector){
			var arr=this.pluck('children'),e=[];
			filter.call(arr, function(item, idx){
				WCJ.map(item,function(els){ if (els.nodeType == 1) e.push(els) })
			});
			return WCJ(e).filter(selector || '*');
		},
		parent: function(){
			var arr=this.pluck('parentNode');
			return filter.call(arr, function(item, idx){
				return arr.indexOf(item) == idx
			});
		},
		parents: function(selector){
			var ancestors=WCJ.sibling(this,'parentNode');
    		return selector == null ? WCJ(ancestors) : WCJ(ancestors).filter(selector);
		},
		prev: function(selector){
			return WCJ(this.pluck('previousElementSibling')).filter(selector || '*')
		},
		next: function(selector){
			return WCJ(this.pluck('nextElementSibling')).filter(selector || '*')
		},
        nextAll: function (selector) {
      		return WCJ(WCJ.sibling(this,'nextElementSibling')).filter(selector || '*');
        },
		prevAll: function (selector) {
			return WCJ(WCJ.sibling(this,'previousElementSibling')).filter(selector || '*');
		},
		siblings: function(selector){
			var n=[];
			this.map(function(i, el){
				WCJ.map(el.childNodes,function(els){ if (els.nodeType == 1) n.push(els) })
			});
			return WCJ(n).filter(selector || '*');
		}
	});

	WCJ.extend({
		isDocument:function (obj) { return obj = obj ? obj != null && obj.nodeType ? obj.nodeType == obj.DOCUMENT_NODE : false : undefined;},
		isFunction:function (value) { return ({}).toString.call(value) == "[object Function]" },
		isObject:function (value) { return value instanceof Object },
		isArray:function (value) { return value instanceof Array },
		isContainsNode:function(parent,node){
	    	return document.documentElement.isContainsNode ?
		    parent !== node && parent.isContainsNode(node):
		    (function(){
		    	while (node && (node = node.parentNode))
		    	if (node === parent) return true
		    	return false
			})();
	    },
		likeArray:function (obj) { return typeof obj.length == 'number' },
        type: function (obj) {
            switch (obj) {
                case null: return "Null";
                case (void 0): return "Undefined";
            }
            var type = typeof (obj);
            switch (type) {
                case 'boolean': return "Boolean";
                case 'number': return "Number";
                case 'string': return "String";
                case 'function': return "Function";
            }
            return "Object";
        },
        error:function(msg) {throw msg;},
        each:function(elements, callback){
			var i, key
			if (this.likeArray(elements)) {
				for (i = 0; i < elements.length; i++)
					if (callback.call(elements[i], i, elements[i]) === false) return elements
				} else {
				for (key in elements)
					if (callback.call(elements[key], key, elements[key]) === false) return elements
			}
			return elements
		},
		map:function(elements, callback){
			var value, values = [], i, key
			if (this.likeArray(elements))
			for (i = 0; i < elements.length; i++) {
				value = callback(elements[i], i)
				if (value != null) values.push(value)
			}
			else
			for (key in elements) {
				value = callback(elements[key], key)
				if (value != null) values.push(value)
			}
			return values.length > 0 ? WCJ.fn.concat.apply([], values) : values;
		},
		matches:function(element, selector){
			if (!selector || !element || element.nodeType !== 1) return false;
		    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
		                          element.oMatchesSelector || element.msMatchesSelector || element.matchesSelector;
		    if (matchesSelector) return matchesSelector.call(element, selector);
		},
		inArray:function(elem, array, i){
			return emptyArray.indexOf.call(array, elem, i)
		},
	    sibling:function(nodes,ty){
			var ancestors = [];
			while (nodes.length > 0)
			nodes = WCJ.map(nodes, function(node){
				if ((node = node[ty]) && !WCJ.isDocument(node) && ancestors.indexOf(node) < 0)
					ancestors.push(node)
					return node
			});
			return ancestors;
	    }
	});

	P = {
		singleTagRE:/^<(\w+)\s*\/?>(?:<\/\1>|)$/,
		tagExpanderRE:/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
		fragment:function(html){
    		var dom, container
    		if (this.singleTagRE.test(html)) dom = WCJ(document.createElement(RegExp.$1));
    		if (!dom) {
				if (html.replace) html = html.replace(this.tagExpanderRE, "<$1></$2>")
				container=document.createElement('div')
      			container.innerHTML = '' + html
				dom = WCJ.each(slice.call(container.childNodes), function(){
					container.removeChild(this)
				})
    		}
    		return dom;
		}
	};

	['after','prepend','before','append'].forEach(function(operator, operatorIndex) {
    	var inside = operatorIndex % 2;
	    WCJ.fn[operator] = function(){
	    	var argType, nodes = WCJ.map(arguments, function(arg) {
	    	    	argType = WCJ.type(arg)
	    	    	return argType == "object" || argType == "array" || arg == null ? arg : P.fragment(arg)
	    	    }),parent,script,copyByClone = this.length > 1
	    	if (nodes.length < 1) return this
	    	return this.each(function(_, target){
    			parent = inside ? target : target.parentNode
		        target = operatorIndex == 0 ? target.nextSibling :
		                 operatorIndex == 1 ? target.firstChild :
		                 operatorIndex == 2 ? target :
		                 null
    			var parentInDocument = WCJ.isContainsNode(document.documentElement, parent)
		        nodes.forEach(function(node){
		        	var txt
		        	if (copyByClone) node = node.cloneNode(true)
      				parent.insertBefore(node, target);
		        	if(parentInDocument && node.nodeName != null && node.nodeName.toUpperCase() === 'SCRIPT' &&
              			(!node.type || node.type === 'text/javascript') && !node.src) txt=node.innerHTML;
              		else if(parentInDocument &&node.children && node.children.length>0&&WCJ(node)&&(script=WCJ(node).find("script")))
              			if(script.length>0) script.each(function(_,item){
              				txt=item.innerHTML
          				});
              			txt?window['eval'].call(window, txt):undefined;
		        })
	    	})
	    }
	});

	//解决低版本浏览器对filter方法的支持
	if (!Array.prototype.filter){
		Array.prototype.filter = function(fun /*, thisArg */){
			"use strict";
			if (this === void 0 || this === null)
				throw new TypeError();
			var t = Object(this);
			var len = t.length >>> 0;
			if (typeof fun !== "function")
				throw new TypeError();
			var res = [];
			var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
			for (var i = 0; i < len; i++){
				if (i in t){
					var val = t[i];
					if (fun.call(thisArg, val, i, t))
					res.push(val);
				}
			}
			return res;
		};
	}
	//低版本IE对indexOf方法的支持
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	//低版本IE对forEach方法的支持
	if (!Array.prototype.forEach) {
	    Array.prototype.forEach = function(fun /*, thisp*/){
	        var len = this.length;
	        if (typeof fun != "function")
	            throw new TypeError();
	        var thisp = arguments[1];
	        for (var i = 0; i < len; i++){
	            if (i in this)
	                fun.call(thisp, this[i], i, this);
	        }
	    };
	}

	//字符串处理
    WCJ.extend(String.prototype,{
        trim: function () {return this.replace(/(^\s*)|(\s*$)/g, "");},
        leftTrim: function () {return this.replace(/(^\s*)/g, "");}
    })
	window.WCJ = window.$$ = WCJ;
})(window);<|endoftext|>


<commit_before>Mosque = function(game, x, y, resource) {
	this.type = "Mosque";
	Building.call(this, game, x, y, resource);
};

Mosque.prototype = Object.create(Building.prototype);
Mosque.prototype.constructor = Mosque;

Mosque.prototype.emit = function() {
	console.log("MOSQUE SENDING WAVES");
	var smallWave = this.game.make.sprite(this.width/2, 0, "mosque_wave_small");
	var bigWave = this.game.make.sprite(this.width/2, 0, "mosque_wave_big");
	bigWave.anchor.setTo(0.5, 0.5);
	smallWave.anchor.setTo(0.5, 0.5);

    var bigWaveAnim = this.createWaveAnimation(bigWave);
    var smallWaveAnim = this.createWaveAnimation(smallWave);
    bigWaveAnim.start();
    setInterval(function() {
    	smallWaveAnim.start();
    }, 160);
    var sound = game.add.audio('mosque_sound1');
    sound.play();
};

Mosque.prototype.createWaveAnimation = function(waveEntity) {
	waveEntity.scale.setTo(0.0, 0.0);
	this.addChild(waveEntity);
	var anim = this.game.add.tween(waveEntity.scale);
	anim.to({ x: 1.0, y: 1.0 }, 1000);
	var loopCount = 3;
	var mosque = this;

	var animationStarted = function() {
    	waveEntity.scale.setTo(0.0, 0.0);
    };
	var animationStopped = function() {
    	mosque.removeChild(waveEntity);
    };
    var animationLooped = function() {
    	loopCount = Math.max(0, loopCount - 1);
    	if (loopCount == 0) {
    		anim.loop = false;
    	}
    }
    anim.onStart.add(animationStarted, this);
    anim.onLoop.add(animationLooped, this);
    anim.onComplete.add(animationStopped, this);
    anim.loop = true;
    return anim;

}

<commit_msg>anim fix<commit_after>Mosque = function(game, x, y, resource) {
	this.type = "Mosque";
	Building.call(this, game, x, y, resource);
};

Mosque.prototype = Object.create(Building.prototype);
Mosque.prototype.constructor = Mosque;

Mosque.prototype.emit = function() {
	console.log("MOSQUE SENDING WAVES");
	var smallWave = this.game.make.sprite(this.width/2, -this.height/2, "mosque_wave_small");
	var bigWave = this.game.make.sprite(this.width/2, -this.height/2, "mosque_wave_big");
	bigWave.anchor.setTo(0.5, 0.5);
	smallWave.anchor.setTo(0.5, 0.5);

    var bigWaveAnim = this.createWaveAnimation(bigWave);
    var smallWaveAnim = this.createWaveAnimation(smallWave);
    bigWaveAnim.start();
    setInterval(function() {
    	smallWaveAnim.start();
    }, 160);
    var sound = game.add.audio('mosque_sound1');
    sound.play();
};

Mosque.prototype.createWaveAnimation = function(waveEntity) {
	waveEntity.scale.setTo(0.0, 0.0);
	this.addChild(waveEntity);
	var anim = this.game.add.tween(waveEntity.scale);
	anim.to({ x: 1.0, y: 1.0 }, 1000);
	var loopCount = 3;
	var mosque = this;

	var animationStarted = function() {
    	waveEntity.scale.setTo(0.0, 0.0);
    };
	var animationStopped = function() {
    	mosque.removeChild(waveEntity);
    };
    var animationLooped = function() {
    	loopCount = Math.max(0, loopCount - 1);
    	if (loopCount == 0) {
    		anim.loop = false;
    	}
    }
    anim.onStart.add(animationStarted, this);
    anim.onLoop.add(animationLooped, this);
    anim.onComplete.add(animationStopped, this);
    anim.loop = true;
    return anim;

}

<|endoftext|>


<commit_before>/*
Copyright (c) 2016 CATTHINGS: Nicholas McHale, Andrew McCann, Susmita Awasthi,
Manpreet Bahl, Austen Ruzicka, Luke Kazmierowicz, Hillman Chen

See LICENSE.txt for full information.
*/
module.exports = {

  /****************************************************
  * /path     a/admin/stats/weeklyavg/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Returns average weekly consumption of item
  ****************************************************/
  weeklyavg: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
            console.error('Error fetching client from pool', err);
            res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id)

        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }

        // If you want to change this rolling window that is used to calculate the average,
        // just alter the INTERVAL amount per SQL guidelines.
        client.query("SELECT weekly.item_name, weekly.item_id, AVG(sum) AS weekly_avg FROM (SELECT i.item_name, i.item_id, SUM(ABS(t.qty_changed)) FROM transactions AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id AND t.qty_changed < 0 AND t.timestamp > (current_timestamp - INTERVAL '3 months') GROUP BY i.item_name, i.item_id, date_trunc('week', timestamp)) AS weekly GROUP BY 1,2", [id], function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },
  /****************************************************
  * /path     a/admin/stats/threshold/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Returns the rough day count between most recent
  *           checkin, and threshold.
  *
  * /author   Andrew McCann
  * /date     2/26/2017
  ****************************************************/
  threshold: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
            console.error('Error fetching client from pool', err);
            res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id)

        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }
        client.query("WITH last_checkin AS (SELECT MAX(timestamp) FROM transactions AS t2 WHERE t2.qty_changed > 0 AND t2.item_id = $1) SELECT i.item_name, t.item_id, EXTRACT(DAY FROM age(t.timestamp, (SELECT max from last_checkin))) AS days_til_threshold FROM transactions AS t, items AS i WHERE t.item_id = $1 AND i.item_id = t.item_id AND t.qty_remaining < i.threshold AND t.timestamp > (SELECT max from last_checkin)", [id], function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },

  /****************************************************
  * /path     a/admin/stats/avgperday/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Gets the average usage (aka checkout/day) by
  *           day of the week.
  ****************************************************/
  avg: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
           console.error('Error fetching client from pool', err);
           res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id);

        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }

        // OLD QUERY: SELECT i.item_name, i.item_id, ABS(SUM(t.qty_changed)) AS checkout_per_day, to_char(timestamp, 'day') AS dow FROM transactions AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id AND t.qty_changed < 0 AND t.timestamp > (current_timestamp - INTERVAL '3 months') GROUP BY i.item_id, i.item_name, dow

        client.query("SELECT * FROM checkout_per_day WHERE item_id = $1", [id], function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },
  /****************************************************
  * /path     a/admin/stats/avgperday/
  * /params   None
  *
  *
  * /brief    Route to pull satistics for all items
  *           Returns the net change in qty/day for
  *           the past week
  ****************************************************/
  avg_All: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
           console.error('Error fetching client from pool', err);
           res.sendStatus(500);
        }

        // OLD QUERY: SELECT i.item_name, i.item_id, ABS(SUM(t.qty_changed)) AS checkout_per_day, to_char(timestamp, 'day') AS dow FROM transactions AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id AND t.qty_changed < 0 AND t.timestamp > (current_timestamp - INTERVAL '3 months') GROUP BY i.item_id, i.item_name, dow

        client.query("SELECT item_name, item_id, AVG(checkout_per_day) FROM checkout_per_day GROUP BY item_id", function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },
  /****************************************************
  * /path     a/admin/stats/netperday/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Route to pull satistics for an item
  *           Returns the net change in qty/day for
  *           the past week
  ****************************************************/
  item_id: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
            console.error('Error fetching client from pool', err);
            res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id);
        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }

        client.query("SELECT i.item_name, i.item_id, SUM(t.qty_changed) AS Net_Change, to_char(timestamp, 'day') AS dow FROM (SELECT * FROM transactions WHERE timestamp > current_date - interval '7 days') AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id GROUP BY i.item_name, i.item_id, dow", [id], function(err, result) {
            done();

            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  }

}
<commit_msg>Some more SQL<commit_after>/*
Copyright (c) 2016 CATTHINGS: Nicholas McHale, Andrew McCann, Susmita Awasthi,
Manpreet Bahl, Austen Ruzicka, Luke Kazmierowicz, Hillman Chen

See LICENSE.txt for full information.
*/
module.exports = {

  /****************************************************
  * /path     a/admin/stats/weeklyavg/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Returns average weekly consumption of item
  ****************************************************/
  weeklyavg: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
            console.error('Error fetching client from pool', err);
            res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id)

        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }

        // If you want to change this rolling window that is used to calculate the average,
        // just alter the INTERVAL amount per SQL guidelines.
        client.query("SELECT weekly.item_name, weekly.item_id, AVG(sum) AS weekly_avg FROM (SELECT i.item_name, i.item_id, SUM(ABS(t.qty_changed)) FROM transactions AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id AND t.qty_changed < 0 AND t.timestamp > (current_timestamp - INTERVAL '3 months') GROUP BY i.item_name, i.item_id, date_trunc('week', timestamp)) AS weekly GROUP BY 1,2", [id], function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },
  /****************************************************
  * /path     a/admin/stats/threshold/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Returns the rough day count between most recent
  *           checkin, and threshold.
  *
  * /author   Andrew McCann
  * /date     2/26/2017
  ****************************************************/
  threshold: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
            console.error('Error fetching client from pool', err);
            res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id)

        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }
        client.query("WITH last_checkin AS (SELECT MAX(timestamp) FROM transactions AS t2 WHERE t2.qty_changed > 0 AND t2.item_id = $1) SELECT i.item_name, t.item_id, EXTRACT(DAY FROM age(t.timestamp, (SELECT max from last_checkin))) AS days_til_threshold FROM transactions AS t, items AS i WHERE t.item_id = $1 AND i.item_id = t.item_id AND t.qty_remaining < i.threshold AND t.timestamp > (SELECT max from last_checkin)", [id], function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },

  /****************************************************
  * /path     a/admin/stats/avgperday/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Gets the average usage (aka checkout/day) by
  *           day of the week.
  ****************************************************/
  avg: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
           console.error('Error fetching client from pool', err);
           res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id);

        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }

        // OLD QUERY: SELECT i.item_name, i.item_id, ABS(SUM(t.qty_changed)) AS checkout_per_day, to_char(timestamp, 'day') AS dow FROM transactions AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id AND t.qty_changed < 0 AND t.timestamp > (current_timestamp - INTERVAL '3 months') GROUP BY i.item_id, i.item_name, dow

        client.query("SELECT * FROM checkout_per_day WHERE item_id = $1", [id], function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },
  /****************************************************
  * /path     a/admin/stats/avgperday/
  * /params   None
  *
  *
  * /brief    Route to pull satistics for all items
  *           Returns the net change in qty/day for
  *           the past week
  ****************************************************/
  avg_All: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
           console.error('Error fetching client from pool', err);
           res.sendStatus(500);
        }

        // OLD QUERY: SELECT i.item_name, i.item_id, ABS(SUM(t.qty_changed)) AS checkout_per_day, to_char(timestamp, 'day') AS dow FROM transactions AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id AND t.qty_changed < 0 AND t.timestamp > (current_timestamp - INTERVAL '3 months') GROUP BY i.item_id, i.item_name, dow

        client.query("SELECT item_id, AVG(checkout_per_day) FROM checkout_per_day GROUP BY item_id", function(err, result) {
            done();
            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  },
  /****************************************************
  * /path     a/admin/stats/netperday/:item_id
  * /params   :item_id - item_id of what we are looking for
  *
  *
  * /brief    Route to pull satistics for an item
  *           Returns the net change in qty/day for
  *           the past week
  ****************************************************/
  item_id: (req, res) => {
    res.app.locals.pool.connect(function(err, client, done) {
        if(err) {
            console.error('Error fetching client from pool', err);
            res.sendStatus(500);
        }
        // Quickly validate if id is an int
        var id = parseInt(req.params.item_id);
        if(req.params.item_id != id) {
            done();
            console.error('Invalid ID number', err);
            res.sendStatus(400);
        }

        client.query("SELECT i.item_name, i.item_id, SUM(t.qty_changed) AS Net_Change, to_char(timestamp, 'day') AS dow FROM (SELECT * FROM transactions WHERE timestamp > current_date - interval '7 days') AS t, items AS i WHERE t.item_id = $1 AND t.item_id = i.item_id GROUP BY i.item_name, i.item_id, dow", [id], function(err, result) {
            done();

            res.app.locals.helpers.errResultHandler(err, result.rows, res);
        });
    });
  }

}
<|endoftext|>


<commit_before>define("DrawEngine", function () {
    function DrawEngine(arenaDisplay, arena) {
        this.arena = arena;
        this.display = arenaDisplay.getContext("2d");

        var size = { width: arenaDisplay.width, height: arenaDisplay.height };
        var lastTime = 0;
        var speed = 100;

        var self = this;

        var update = function (time) {
            if (lastTime === 0) lastTime = time;
            self.display.clearRect(0, 0, size.width, size.height);

            var deltaT = time - lastTime;

            for (var i = 0; i < self.arena.players.length; i++) {
                var player = self.arena.players[i].Token;
                if (player.CurrentPosition === undefined) {
                    player.CurrentPosition = player.Position;
                    player.CurrentIndex = 0;
                }

                var endPoint = player.MovePath[player.CurrentIndex];
                if (endPoint == undefined)
                    endPoint = player.CurrentPosition;

                var distance =
                    {
                        X: endPoint.X - player.CurrentPosition.X,
                        Y: endPoint.Y - player.CurrentPosition.Y
                    };

                var moveLength = Math.sqrt(distance.X * distance.X + distance.Y * distance.Y);

                var sin = distance.Y / moveLength;
                var cos = distance.X / moveLength;

                player.CurrentPosition.X = player.CurrentPosition.X + speed * cos * deltaT / 1000;
                player.CurrentPosition.Y = player.CurrentPosition.Y + speed * sin * deltaT / 1000;

                if (hasReachedEnd(distance, player.CurrentPosition, endPoint)) {
                    pointPlayerToNextTarget(player, endPoint);
                }

                paintPlayer(player.CurrentPosition, player.Size, player.MovePath.slice(player.CurrentIndex));
            }

            lastTime = time;
            requestAnimationFrame(update);
        };

        var hasReachedEnd = function (distance, currentPosition, endPoint) {
            return distance.X >= 0 && currentPosition.X >= endPoint.X ||
                   distance.X <= 0 && currentPosition.X <= endPoint.X ||
                   distance.Y >= 0 && currentPosition.Y >= endPoint.Y ||
                   distance.Y <= 0 && currentPosition.Y <= endPoint.Y;
        };

        var pointPlayerToNextTarget = function (player, endPoint) {
            player.CurrentPosition.X = endPoint.X;
            player.CurrentPosition.Y = endPoint.Y;
            while (endPoint && pointsAreEqual(player.CurrentPosition, endPoint)) {
                player.CurrentIndex++;
                endPoint = player.MovePath[player.CurrentIndex];
            }
        };

        var pointsAreEqual = function (a, b) {
            return a.X == b.X && a.Y == b.Y;
        }

        var paintPlayer = function (position, size, movePath) {
            self.display.fillRect(position.X, position.Y, size.X, size.Y);
            self.display.strokeStyle = "#777";
            self.display.beginPath();
            self.display.moveTo(position.X, position.Y);
            for (var j = 0; j < movePath.length; j++) {
                var pathPoint = movePath[j];
                self.display.lineTo(pathPoint.X, pathPoint.Y);
            }
            self.display.stroke();
        };

        requestAnimationFrame(update);
    }

    return DrawEngine;
});<commit_msg>extracted move distance calculation to separate functon<commit_after>define("DrawEngine", function () {
    function DrawEngine(arenaDisplay, arena) {
        this.arena = arena;
        this.display = arenaDisplay.getContext("2d");

        var size = { width: arenaDisplay.width, height: arenaDisplay.height };
        var lastTime = 0;
        var speed = 100;

        var self = this;

        var update = function (time) {
            if (lastTime === 0) lastTime = time;
            self.display.clearRect(0, 0, size.width, size.height);

            var deltaT = time - lastTime;

            for (var i = 0; i < self.arena.players.length; i++) {
                var player = self.arena.players[i].Token;
                if (player.CurrentPosition === undefined) {
                    player.CurrentPosition = player.Position;
                    player.CurrentIndex = 0;
                }

                var endPoint = player.MovePath[player.CurrentIndex];
                if (endPoint == undefined)
                    endPoint = player.CurrentPosition;

                var distance =
                    {
                        X: endPoint.X - player.CurrentPosition.X,
                        Y: endPoint.Y - player.CurrentPosition.Y
                    };

                var moveDistance = calculateMoveDistance(distance, deltaT);

                player.CurrentPosition.X = player.CurrentPosition.X + moveDistance.X;
                player.CurrentPosition.Y = player.CurrentPosition.Y + moveDistance.Y;

                if (hasReachedEnd(distance, player.CurrentPosition, endPoint)) {
                    pointPlayerToNextTarget(player, endPoint);
                }

                paintPlayer(player.CurrentPosition, player.Size, player.MovePath.slice(player.CurrentIndex));
            }

            lastTime = time;
            requestAnimationFrame(update);
        };

        var calculateMoveDistance = function (distance, deltaT) {
            var moveLength = Math.sqrt(distance.X * distance.X + distance.Y * distance.Y);

            var sin = distance.Y / moveLength;
            var cos = distance.X / moveLength;

            return {
                X: speed * deltaT * cos / 1000,
                Y: speed * deltaT * sin / 1000
            };
        };

        var hasReachedEnd = function (distance, currentPosition, endPoint) {
            return distance.X >= 0 && currentPosition.X >= endPoint.X ||
                   distance.X <= 0 && currentPosition.X <= endPoint.X ||
                   distance.Y >= 0 && currentPosition.Y >= endPoint.Y ||
                   distance.Y <= 0 && currentPosition.Y <= endPoint.Y;
        };

        var pointPlayerToNextTarget = function (player, endPoint) {
            player.CurrentPosition.X = endPoint.X;
            player.CurrentPosition.Y = endPoint.Y;
            while (endPoint && pointsAreEqual(player.CurrentPosition, endPoint)) {
                player.CurrentIndex++;
                endPoint = player.MovePath[player.CurrentIndex];
            }
        };

        var pointsAreEqual = function (a, b) {
            return a.X == b.X && a.Y == b.Y;
        };

        var paintPlayer = function (position, size, movePath) {
            self.display.fillRect(position.X, position.Y, size.X, size.Y);
            self.display.strokeStyle = "#777";
            self.display.beginPath();
            self.display.moveTo(position.X, position.Y);
            for (var j = 0; j < movePath.length; j++) {
                var pathPoint = movePath[j];
                self.display.lineTo(pathPoint.X, pathPoint.Y);
            }
            self.display.stroke();
        };

        requestAnimationFrame(update);
    }

    return DrawEngine;
});<|endoftext|>


<commit_before>yaml = require('js-yaml');
fs = require('fs');
var doc = yaml.safeLoad(fs.readFileSync('config.yaml', 'utf8'));

var Discord = require('discord.io');
var bot = new Discord.Client({
    autorun: true,
    token: doc.token
});
var randmsgs = ["This is an example random message.", "Randomizations!", "Random, I say!", "Random, I say.", "Look, it’s a new randomized message!", "r"];
var version = "1.5"
var sender = "";

function applyVar(thing) {
    test = eval('thing')
    test = test.replace(doc.sendervar, sender);
    test = test.replace(doc.versionvar, version);
    return test
}

if (doc.startupconsole === "") {
    console.log("Started up config successfully!");
} else {
    console.log(doc.startupconsole);
};

bot.on('ready', function(event) {
    if (doc.startupevent === "") {
        bot.sendMessage({
            to: "222393788755083264",
            message: "Logged in as " + bot.username + " (who has ID " + bot.id + ")"
        });
    } else {
        bot.sendMessage({
            to: "222393788755083264",
            message: doc.startupconsole
        });
    }
});

var path = require('path');
var includeAll = require('include-all');

var controllers = require('include-all')({
  dirname     :  path.join(__dirname, 'plugins'),
  filter      :  /(.+)\.obp$/,
});<commit_msg>Version bump for some bugfixes<commit_after>yaml = require('js-yaml');
fs = require('fs');
var doc = yaml.safeLoad(fs.readFileSync('config.yaml', 'utf8'));

var Discord = require('discord.io');
var bot = new Discord.Client({
    autorun: true,
    token: doc.token
});
var randmsgs = ["This is an example random message.", "Randomizations!", "Random, I say!", "Random, I say.", "Look, it’s a new randomized message!", "r"];
var version = "1.5.1"
var sender = "";

function applyVar(thing) {
    test = eval('thing')
    test = test.replace(doc.sendervar, sender);
    test = test.replace(doc.versionvar, version);
    return test
}

if (doc.startupconsole === "") {
    console.log("Started up config successfully!");
} else {
    console.log(doc.startupconsole);
};

bot.on('ready', function(event) {
    if (doc.startupevent === "") {
        bot.sendMessage({
            to: "222393788755083264",
            message: "Logged in as " + bot.username + " (who has ID " + bot.id + ")"
        });
    } else {
        bot.sendMessage({
            to: "222393788755083264",
            message: doc.startupconsole
        });
    }
});

var path = require('path');
var includeAll = require('include-all');

var controllers = require('include-all')({
  dirname     :  path.join(__dirname, 'plugins'),
  filter      :  /(.+)\.obp$/,
});<|endoftext|>


<commit_before>/* motion: [repeat] (h|j|k|l|w|e|b|...)
   operator: [repeat] (c|d|y)
   text_obj: [repeat] modifier (w|W|p|s|(|)|{|}|"|'|`)
   rule: operator (motion|text_obj)
   e.g: 5d2w = (repeat-five-times (delete (repeat-two-times (word-forward))))
*/
var Parser=(cur)=>{/* Convert keyboard events into Actions */
    var ParserCommand=()=>({current:'',previous:''}),

        arrow=(dec)=>{
            switch(dec.code){
            case'D':cur.down(1);break;
            case'U':cur.up(1);break;
            case'R':cur.right(1,true);break;
            case'L':cur.left(1,true);break;
            default:break;
            }
        },

        insert=(dec,t)=>{
            switch(dec.type){
            case'print':
                cur.ins(dec.code);cur.rowcol();
                // auxiliary escape methods: quickly type 'fd' or use the chord 'C-['
                if(dec.code==='f'){cur.fd=-t;}
                if(dec.code==='d'&&cur.fd<0&&t+cur.fd<500){cur.esc_fd();}
                if(dec.code==='['&&dec.mods[1]){cur.del_backward();cur.mode='normal';cur.left(1);}
                break;
            case'edit':
                if(dec.code==='B'){cur.del_backward();}// backspace
                else if(dec.code==='D'){cur.del_forward();}// forward delete
                break;
            case'escape':cur.normal_mode();break;
            default:break;
            }
        },

        single_token=(dec,repeats=1)=>{
            for(var i=0;i<repeats;++i){
                switch(dec.code){
                    // motions
                case'j':cur.down(1);break;
                case'k':cur.up(1);break;
                case'l':cur.right(1);break;
                case'h':cur.left(1);break;
                case'0':cur.to_bol();break;
                case'$':cur.to_eol();break;
                case'{':cur.backward_paragraph();break;
                case'}':cur.forward_paragraph();break;
                case'G':cur.to_eob();break;
                case'b':cur.backward_word();break;
                case'e':cur.forward_word();break;
                    // mode changers
                case'i':cur.insert_mode();break;
                case'a':cur.append_mode();break;
                    // editing actions
                case'x':cur.del_at_point();break;
                case'D':cur.del_to_eol();break;
                default:break;
                }
            }
            //case' ':console.log('SPC-');break;// TODO SPC-prefixed functions a-la Spacemacs!
        },

        append_non_chord=(d,c)=>{if(!(d.mods[0]||d.mods[1]||d.mods[2])){c.current+=d.code;}},

        /* command tokenizers */
        multiplier=/[1-9][0-9]*/g,
        modifier=/a|i/,
        operator=/[cdy]/,
        motion=/[beGhjklw$0^]/,
        object=/[wWps(){}\[\]"'`]/,

        validate=(tokens)=>{},

        tokenize=(cmd,is_obj)=>{
            var t={};
            t.times=cmd.match(multiplier)||[1];
            t.oper=cmd.search(operator);
            if(is_obj){t.modifier=cmd.search(modifier);t.txt_obj=cmd.search(object);}
            return t;
        };

    return ({
        cmd:ParserCommand(),
        parse(t,dec){
            if(dec.type==='arrow'){arrow(dec);}// parse arrows in any mode
            if(cur.mode==='insert'){insert(dec,t);}
            else{
                append_non_chord(dec,this.cmd);// build the command 1 char at a time

                // if the command ends in a text object or motion, parse the command
                var [mo,ob]=[motion,object].map(a=>!!(this.cmd.current.match(a)));
                if(mo||ob){
                    // tokenize
                    var tokens=tokenize(this.cmd.current,ob);
                    console.log(JSON.stringify(tokens));

                    // parse the command
                    if(tokens.times.length<2){single_token(dec,tokens.times.pop())}

                    // clean up
                    this.cmd.previous=this.cmd.current;this.cmd.current='';
                }
            }
        }
    });
};
<commit_msg>whitespace cleanup<commit_after>/* motion: [repeat] (h|j|k|l|w|e|b|...)
   operator: [repeat] (c|d|y)
   text_obj: [repeat] modifier (w|W|p|s|(|)|{|}|"|'|`)
   rule: operator (motion|text_obj)
   e.g: 5d2w = (repeat-five-times (delete (repeat-two-times (word-forward))))
*/
var Parser=(cur)=>{/* Convert keyboard events into Actions */
    var ParserCommand=()=>({current:'',previous:''}),

        arrow=(dec)=>{
            switch(dec.code){
            case'D':cur.down(1);break;
            case'U':cur.up(1);break;
            case'R':cur.right(1,true);break;
            case'L':cur.left(1,true);break;
            default:break;
            }
        },

        insert=(dec,t)=>{
            switch(dec.type){
            case'print':
                cur.ins(dec.code);cur.rowcol();
                // auxiliary escape methods: quickly type 'fd' or use the chord 'C-['
                if(dec.code==='f'){cur.fd=-t;}
                if(dec.code==='d'&&cur.fd<0&&t+cur.fd<500){cur.esc_fd();}
                if(dec.code==='['&&dec.mods[1]){cur.del_backward();cur.mode='normal';cur.left(1);}
                break;
            case'edit':
                if(dec.code==='B'){cur.del_backward();}// backspace
                else if(dec.code==='D'){cur.del_forward();}// forward delete
                break;
            case'escape':cur.normal_mode();break;
            default:break;
            }
        },

        single_token=(dec,repeats=1)=>{
            for(var i=0;i<repeats;++i){
                switch(dec.code){
                    // motions
                case'j':cur.down(1);break;
                case'k':cur.up(1);break;
                case'l':cur.right(1);break;
                case'h':cur.left(1);break;
                case'0':cur.to_bol();break;
                case'$':cur.to_eol();break;
                case'{':cur.backward_paragraph();break;
                case'}':cur.forward_paragraph();break;
                case'G':cur.to_eob();break;
                case'b':cur.backward_word();break;
                case'e':cur.forward_word();break;
                    // mode changers
                case'i':cur.insert_mode();break;
                case'a':cur.append_mode();break;
                    // editing actions
                case'x':cur.del_at_point();break;
                case'D':cur.del_to_eol();break;
                default:break;
                }
            }
            //case' ':console.log('SPC-');break;// TODO SPC-prefixed functions a-la Spacemacs!
        },

        append_non_chord=(d,c)=>{if(!(d.mods[0]||d.mods[1]||d.mods[2])){c.current+=d.code;}},

        /* command tokenizers */
        multiplier=/[1-9][0-9]*/g,
        modifier=/a|i/,
        operator=/[cdy]/,
        motion=/[beGhjklw$0^]/,
        object=/[wWps(){}\[\]"'`]/,

        validate=(tokens)=>{},

        tokenize=(cmd,is_obj)=>{
            var t={};
            t.times=cmd.match(multiplier)||[1];
            t.oper=cmd.search(operator);
            if(is_obj){t.modifier=cmd.search(modifier);t.txt_obj=cmd.search(object);}
            return t;
        };

    return ({
        cmd:ParserCommand(),
        parse(t,dec){
            if(dec.type==='arrow'){arrow(dec);}// parse arrows in any mode
            if(cur.mode==='insert'){insert(dec,t);}
            else{
                append_non_chord(dec,this.cmd);// build the command 1 char at a time

                // if the command ends in a text object or motion, parse the command
                var [mo,ob]=[motion,object].map(a=>!!(this.cmd.current.match(a)));
                if(mo||ob){
                    // tokenize
                    var tokens=tokenize(this.cmd.current,ob);
                    console.log(JSON.stringify(tokens));

                    // parse the command
                    if(tokens.times.length<2){single_token(dec,tokens.times.pop())}

                    // clean up
                    this.cmd.previous=this.cmd.current;this.cmd.current='';
                }
            }
        }
    });
};
<|endoftext|>


<commit_before>/**
 * JS module included on every page of the OSF. Site-wide initialization
 * code goes here.
 */
'use strict';
// CSS used on every page
require('../../vendor/bower_components/bootstrap/dist/css/bootstrap-theme.css');
require('../../vendor/bower_components/x-editable/dist/bootstrap3-editable/css/bootstrap-editable.css');
require('../../vendor/bower_components/jquery-ui/themes/base/minified/jquery.ui.resizable.min.css');
require('../../css/bootstrap-xl.css');
require('../../css/animate.css');
require('../../css/site.css');

var $ = require('jquery');
require('jquery.cookie');
require('../crossOrigin.js');

var NavbarControl = require('navbar-control');
var $osf = require('osfHelpers');

// Prevent IE from caching responses
$.ajaxSetup({ cache: false });

// Apply an empty view-model to the navbar, just so the tooltip bindingHandler
// can be used
// $osf.applyBindings({}, '#navbarScope');

$('[rel="tooltip"]').tooltip();

// If there isn't a user logged in, show the footer slide-in
var sliderSelector = '#footerSlideIn';
var SlideInViewModel = function (){
    var self = this;
    self.elem = $(sliderSelector);

    var dismissed = false;

    try {
        dismissed = dismissed || window.localStorage.getItem('slide') === '0';
    } catch (e) {}

    dismissed = dismissed || $.cookie('slide') === '0';

    if (this.elem.length > 0 && !dismissed) {
        setTimeout(function () {
            self.elem.slideDown(1000);
        }, 3000);
    }
    self.dismiss = function() {
        self.elem.slideUp(1000);
        try {
            window.localStorage.setItem('slide', '0');
        } catch (e) {
            $.cookie('slide', '0', { expires: 1, path: '/'});
        }
        self.trackClick('Dismiss');
    };
    // Google Analytics click event tracking
    self.trackClick = function(source) {
        ga('send', 'event', 'button', 'click', source);
    };
};

$(document).on('click', '.project-toggle', function() {
    var widget = $(this).closest('.addon-widget-container');
    var up = $(this).find('.icon-angle-up');
    var down = $(this).find('.icon-angle-down');
    if(up.length > 0) {
        up.removeClass('icon-angle-up').addClass('icon-angle-down');
    }
    if(down.length > 0) {
        down.removeClass('icon-angle-down').addClass('icon-angle-up');
    }

    widget.find('.addon-widget-body').slideToggle();
    return false;
});

var NO_FOOTER_PATHS = ['/', '/login/', '/getting-started/', '/register/', '/forgotpassword/', '/share/'];
$(function() {
    if(/MSIE 9.0/.test(navigator.userAgent) || /MSIE 8.0/.test(navigator.userAgent) ||/MSIE 7.0/.test(navigator.userAgent) ||/MSIE 6.0/.test(navigator.userAgent)) {
        $('.placeholder-replace').show();
    }
    if ($(sliderSelector).length > 0 &&
            $.inArray(window.location.pathname, NO_FOOTER_PATHS) === -1) {
        $osf.applyBindings(new SlideInViewModel(), sliderSelector);
    }
    new NavbarControl('.osf-nav-wrapper');
});
<commit_msg>Explicitly pull off window object<commit_after>/**
 * JS module included on every page of the OSF. Site-wide initialization
 * code goes here.
 */
'use strict';
// CSS used on every page
require('../../vendor/bower_components/bootstrap/dist/css/bootstrap-theme.css');
require('../../vendor/bower_components/x-editable/dist/bootstrap3-editable/css/bootstrap-editable.css');
require('../../vendor/bower_components/jquery-ui/themes/base/minified/jquery.ui.resizable.min.css');
require('../../css/bootstrap-xl.css');
require('../../css/animate.css');
require('../../css/site.css');

var $ = require('jquery');
require('jquery.cookie');
require('../crossOrigin.js');

var NavbarControl = require('navbar-control');
var $osf = require('osfHelpers');

// Prevent IE from caching responses
$.ajaxSetup({ cache: false });

// Apply an empty view-model to the navbar, just so the tooltip bindingHandler
// can be used
// $osf.applyBindings({}, '#navbarScope');

$('[rel="tooltip"]').tooltip();

// If there isn't a user logged in, show the footer slide-in
var sliderSelector = '#footerSlideIn';
var SlideInViewModel = function (){
    var self = this;
    self.elem = $(sliderSelector);

    var dismissed = false;

    try {
        dismissed = dismissed || window.localStorage.getItem('slide') === '0';
    } catch (e) {}

    dismissed = dismissed || $.cookie('slide') === '0';

    if (this.elem.length > 0 && !dismissed) {
        setTimeout(function () {
            self.elem.slideDown(1000);
        }, 3000);
    }
    self.dismiss = function() {
        self.elem.slideUp(1000);
        try {
            window.localStorage.setItem('slide', '0');
        } catch (e) {
            $.cookie('slide', '0', { expires: 1, path: '/'});
        }
        self.trackClick('Dismiss');
    };
    // Google Analytics click event tracking
    self.trackClick = function(source) {
        window.ga('send', 'event', 'button', 'click', source);
    };
};

$(document).on('click', '.project-toggle', function() {
    var widget = $(this).closest('.addon-widget-container');
    var up = $(this).find('.icon-angle-up');
    var down = $(this).find('.icon-angle-down');
    if(up.length > 0) {
        up.removeClass('icon-angle-up').addClass('icon-angle-down');
    }
    if(down.length > 0) {
        down.removeClass('icon-angle-down').addClass('icon-angle-up');
    }

    widget.find('.addon-widget-body').slideToggle();
    return false;
});

var NO_FOOTER_PATHS = ['/', '/login/', '/getting-started/', '/register/', '/forgotpassword/', '/share/'];
$(function() {
    if(/MSIE 9.0/.test(window.navigator.userAgent) ||
       /MSIE 8.0/.test(window.navigator.userAgent) ||
       /MSIE 7.0/.test(window.navigator.userAgent) ||
       /MSIE 6.0/.test(window.navigator.userAgent)) {
        $('.placeholder-replace').show();
    }
    if ($(sliderSelector).length > 0 &&
            $.inArray(window.location.pathname, NO_FOOTER_PATHS) === -1) {
        $osf.applyBindings(new SlideInViewModel(), sliderSelector);
    }
    new NavbarControl('.osf-nav-wrapper');
});
<|endoftext|>