<commit_before>/*
 * validate.js 1.2
 * Copyright (c) 2011 Rick Harrison, http://rickharrison.me
 * validate.js is open sourced under the MIT license.
 * Portions of validate.js are inspired by CodeIgniter.
 * http://rickharrison.github.com/validate.js
 */

(function(window, document, undefined) {
    /*
     * If you would like an application-wide config, change these defaults.
     * Otherwise, use the setMessage() function to configure form specific messages.
     */

    var defaults = {
        messages: {
            required: 'The %s field is required.',
            matches: 'The %s field does not match the %s field.',
            valid_email: 'The %s field must contain a valid email address.',
            valid_emails: 'The %s field must contain all valid email addresses.',
            min_length: 'The %s field must be at least %s characters in length.',
            max_length: 'The %s field must not exceed %s characters in length.',
            exact_length: 'The %s field must be exactly %s characters in length.',
            greater_than: 'The %s field must contain a number greater than %s.',
            less_than: 'The %s field must contain a number less than %s.',
            alpha: 'The %s field must only contain alphabetical characters.',
            alpha_numeric: 'The %s field must only contain alpha-numeric characters.',
            alpha_dash: 'The %s field must only contain alpha-numeric characters, underscores, and dashes.',
            numeric: 'The %s field must contain only numbers.',
            integer: 'The %s field must contain an integer.',
            decimal: 'The %s field must contain a decimal number.',
            is_natural: 'The %s field must contain only positive numbers.',
            is_natural_no_zero: 'The %s field must contain a number greater than zero.',
            valid_ip: 'The %s field must contain a valid IP.',
            valid_base64: 'The %s field must contain a base64 string.',
            valid_credit_card: 'The %s field must contain a vaild credit card number',
            is_file_type: 'The %s field must contain only %s files.'
        },
        callback: function(errors) {

        }
    };

    /*
     * Define the regular expressions that will be used
     */

    var ruleRegex = /^(.+?)\[(.+)\]$/,
        numericRegex = /^[0-9]+$/,
        integerRegex = /^\-?[0-9]+$/,
        decimalRegex = /^\-?[0-9]*\.?[0-9]+$/,
        emailRegex = /^[a-zA-Z0-9.!#$%&'*+-/=?\^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
        alphaRegex = /^[a-z]+$/i,
        alphaNumericRegex = /^[a-z0-9]+$/i,
        alphaDashRegex = /^[a-z0-9_-]+$/i,
        naturalRegex = /^[0-9]+$/i,
        naturalNoZeroRegex = /^[1-9][0-9]*$/i,
        ipRegex = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i,
        base64Regex = /[^a-zA-Z0-9\/\+=]/i,
        numericDashRegex = /^[\d\-\s]+$/;

    /*
     * The exposed public object to validate a form:
     *
     * @param formName - String - The name attribute of the form (i.e. <form name="myForm"></form>)
     * @param fields - Array - [{
     *     name: The name of the element (i.e. <input name="myField" />)
     *     display: 'Field Name'
     *     rules: required|matches[password_confirm]
     * }]
     * @param callback - Function - The callback after validation has been performed.
     *     @argument errors - An array of validation errors
     *     @argument event - The javascript event
     */

    var FormValidator = function(formName, fields, callback) {
        this.callback = callback || defaults.callback;
        this.errors = [];
        this.fields = {};
        this.form = document.forms[formName] || {};
        this.messages = {};
        this.handlers = {};

        for (var i = 0, fieldLength = fields.length; i < fieldLength; i++) {
            var field = fields[i];

            // If passed in incorrectly, we need to skip the field.
            if (!field.name || !field.rules) {
                continue;
            }

            /*
             * Build the master fields array that has all the information needed to validate
             */

            this.fields[field.name] = {
                name: field.name,
                display: field.display || field.name,
                rules: field.rules,
                id: null,
                type: null,
                value: null,
                checked: null
            };
        }

        /*
         * Attach an event callback for the form submission
         */

        this.form.onsubmit = (function(that) {
            return function(event) {
                try {
                    return that._validateForm(event);
                } catch(e) {}
            }
        })(this);
    },

    attributeValue = function (element, attributeName) {
        var i;

        if ((element.length > 0) && (element[0].type === 'radio')) {
            for (i = 0; i < element.length; i++) {
                if (element[i].checked) {
                    return element[i][attributeName];
                }
            }

            return;
        }

        return element[attributeName];
    };

    /*
     * @public
     * Sets a custom message for one of the rules
     */

    FormValidator.prototype.setMessage = function(rule, message) {
        this.messages[rule] = message;

        // return this for chaining
        return this;
    };

    /*
     * @public
     * Registers a callback for a custom rule (i.e. callback_username_check)
     */

    FormValidator.prototype.registerCallback = function(name, handler) {
        if (name && typeof name === 'string' && handler && typeof handler === 'function') {
            this.handlers[name] = handler;
        }

        // return this for chaining
        return this;
    };

    /*
     * @private
     * Runs the validation when the form is submitted.
     */

    FormValidator.prototype._validateForm = function(event) {
        this.errors = [];

        for (var key in this.fields) {
            if (this.fields.hasOwnProperty(key)) {
                var field = this.fields[key] || {},
                    element = this.form[field.name];

                if (element && element !== undefined) {
                    field.id = attributeValue(element, 'id');
                    field.type = (element.length > 0) ? element[0].type : element.type;
                    field.value = attributeValue(element, 'value');
                    field.checked = attributeValue(element, 'checked');
                }

                /*
                 * Run through the rules for each field.
                 */

                this._validateField(field);
            }
        }

        if (typeof this.callback === 'function') {
            this.callback(this.errors, event);
        }

        if (this.errors.length > 0) {
            if (event && event.preventDefault) {
                event.preventDefault();
            } else {
                // IE6 doesn't pass in an event parameter so return false
                return false;
            }
        }

        return true;
    };

    /*
     * @private
     * Looks at the fields value and evaluates it against the given rules
     */

    FormValidator.prototype._validateField = function(field) {
        var rules = field.rules.split('|');

        /*
         * If the value is null and not required, we don't need to run through validation
         */

        if (field.rules.indexOf('required') === -1 && (!field.value || field.value === '' || field.value === undefined)) {
            return;
        }

        /*
         * Run through the rules and execute the validation methods as needed
         */

        for (var i = 0, ruleLength = rules.length; i < ruleLength; i++) {
            var method = rules[i],
                param = null,
                failed = false,
                parts = ruleRegex.exec(method);

            /*
             * If the rule has a parameter (i.e. matches[param]) split it out
             */

            if (parts) {
                method = parts[1];
                param = parts[2];
            }

            /*
             * If the hook is defined, run it to find any validation errors
             */

            if (typeof this._hooks[method] === 'function') {
                if (!this._hooks[method].apply(this, [field, param])) {
                    failed = true;
                }
            } else if (method.substring(0, 9) === 'callback_') {
                // Custom method. Execute the handler if it was registered
                method = method.substring(9, method.length);

                if (typeof this.handlers[method] === 'function') {
                    if (this.handlers[method].apply(this, [field.value]) === false) {
                        failed = true;
                    }
                }
            }

            /*
             * If the hook failed, add a message to the errors array
             */

            if (failed) {
                // Make sure we have a message for this rule
                var source = this.messages[method] || defaults.messages[method],
                    message = 'An error has occurred with the ' + field.display + ' field.';

                if (source) {
                    message = source.replace('%s', field.display);

                    if (param) {
                        message = message.replace('%s', (this.fields[param]) ? this.fields[param].display : param);
                    }
                }

                this.errors.push({
                    id: field.id,
                    name: field.name,
                    message: message,
                    rule: method
                });

                // Break out so as to not spam with validation errors (i.e. required and valid_email)
                break;
            }
        }
    };

    /*
     * @private
     * Object containing all of the validation hooks
     */

    FormValidator.prototype._hooks = {
        required: function(field) {
            var value = field.value;

            if ((field.type === 'checkbox') || (field.type === 'radio')) {
                return (field.checked === true);
            }

            return (value !== null && value !== '');
        },

        matches: function(field, matchName) {
            var el = this.form[matchName];

            if (el) {
                return field.value === el.value;
            }

            return false;
        },

        valid_email: function(field) {
            return emailRegex.test(field.value);
        },

        valid_emails: function(field) {
            var result = field.value.split(",");

            for (var i = 0; i < result.length; i++) {
                if (!emailRegex.test(result[i])) {
                    return false;
                }
            }

            return true;
        },

        min_length: function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }

            return (field.value.length >= parseInt(length, 10));
        },

        max_length: function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }

            return (field.value.length <= parseInt(length, 10));
        },

        exact_length: function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }

            return (field.value.length === parseInt(length, 10));
        },

        greater_than: function(field, param) {
            if (!decimalRegex.test(field.value)) {
                return false;
            }

            return (parseFloat(field.value) > parseFloat(param));
        },

        less_than: function(field, param) {
            if (!decimalRegex.test(field.value)) {
                return false;
            }

            return (parseFloat(field.value) < parseFloat(param));
        },

        alpha: function(field) {
            return (alphaRegex.test(field.value));
        },

        alpha_numeric: function(field) {
            return (alphaNumericRegex.test(field.value));
        },

        alpha_dash: function(field) {
            return (alphaDashRegex.test(field.value));
        },

        numeric: function(field) {
            return (decimalRegex.test(field.value));
        },

        integer: function(field) {
            return (integerRegex.test(field.value));
        },

        decimal: function(field) {
            return (decimalRegex.test(field.value));
        },

        is_natural: function(field) {
            return (naturalRegex.test(field.value));
        },

        is_natural_no_zero: function(field) {
            return (naturalNoZeroRegex.test(field.value));
        },

        valid_ip: function(field) {
            return (ipRegex.test(field.value));
        },

        valid_base64: function(field) {
            return (base64Regex.test(field.value));
        },

        valid_credit_card: function(field){
            // Luhn Check Code from https://gist.github.com/4075533
            // accept only digits, dashes or spaces
            if (!numericDashRegex.test(field.value)) return false;

            // The Luhn Algorithm. It's so pretty.
            var nCheck = 0, nDigit = 0, bEven = false;
            var strippedField = field.value.replace(/\D/g, "");

            for (var n = strippedField.length - 1; n >= 0; n--) {
                var cDigit = strippedField.charAt(n),
                nDigit = parseInt(cDigit, 10);
                if (bEven) {
                    if ((nDigit *= 2) > 9) nDigit -= 9;
                }

                nCheck += nDigit;
                bEven = !bEven;
            }

            return (nCheck % 10) == 0;
        },

        is_file_type: function(field,type) {
            if (field.type !== 'file') {
                return true;
            }

            var ext = field.value.substr((field.value.lastIndexOf('.') + 1)),
                typeArray = type.split(','),
                inArray = false,
                i = 0,
                len = typeArray.length;

            for (i; i < len; i++) {
                if (ext == typeArray[i]) inArray = true;
            }

            return inArray;
        }
    };

    window.FormValidator = FormValidator;

})(window, document);
<commit_msg>Fixed the case where "required" rule is not needed but a callback must still be run. Previously the callback was ignored if "required" was not present.<commit_after>/*
 * validate.js 1.2
 * Copyright (c) 2011 Rick Harrison, http://rickharrison.me
 * validate.js is open sourced under the MIT license.
 * Portions of validate.js are inspired by CodeIgniter.
 * http://rickharrison.github.com/validate.js
 */

(function(window, document, undefined) {
    /*
     * If you would like an application-wide config, change these defaults.
     * Otherwise, use the setMessage() function to configure form specific messages.
     */

    var defaults = {
        messages: {
            required: 'The %s field is required.',
            matches: 'The %s field does not match the %s field.',
            valid_email: 'The %s field must contain a valid email address.',
            valid_emails: 'The %s field must contain all valid email addresses.',
            min_length: 'The %s field must be at least %s characters in length.',
            max_length: 'The %s field must not exceed %s characters in length.',
            exact_length: 'The %s field must be exactly %s characters in length.',
            greater_than: 'The %s field must contain a number greater than %s.',
            less_than: 'The %s field must contain a number less than %s.',
            alpha: 'The %s field must only contain alphabetical characters.',
            alpha_numeric: 'The %s field must only contain alpha-numeric characters.',
            alpha_dash: 'The %s field must only contain alpha-numeric characters, underscores, and dashes.',
            numeric: 'The %s field must contain only numbers.',
            integer: 'The %s field must contain an integer.',
            decimal: 'The %s field must contain a decimal number.',
            is_natural: 'The %s field must contain only positive numbers.',
            is_natural_no_zero: 'The %s field must contain a number greater than zero.',
            valid_ip: 'The %s field must contain a valid IP.',
            valid_base64: 'The %s field must contain a base64 string.',
            valid_credit_card: 'The %s field must contain a vaild credit card number',
            is_file_type: 'The %s field must contain only %s files.'
        },
        callback: function(errors) {

        }
    };

    /*
     * Define the regular expressions that will be used
     */

    var ruleRegex = /^(.+?)\[(.+)\]$/,
        numericRegex = /^[0-9]+$/,
        integerRegex = /^\-?[0-9]+$/,
        decimalRegex = /^\-?[0-9]*\.?[0-9]+$/,
        emailRegex = /^[a-zA-Z0-9.!#$%&'*+-/=?\^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
        alphaRegex = /^[a-z]+$/i,
        alphaNumericRegex = /^[a-z0-9]+$/i,
        alphaDashRegex = /^[a-z0-9_-]+$/i,
        naturalRegex = /^[0-9]+$/i,
        naturalNoZeroRegex = /^[1-9][0-9]*$/i,
        ipRegex = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i,
        base64Regex = /[^a-zA-Z0-9\/\+=]/i,
        numericDashRegex = /^[\d\-\s]+$/;

    /*
     * The exposed public object to validate a form:
     *
     * @param formName - String - The name attribute of the form (i.e. <form name="myForm"></form>)
     * @param fields - Array - [{
     *     name: The name of the element (i.e. <input name="myField" />)
     *     display: 'Field Name'
     *     rules: required|matches[password_confirm]
     * }]
     * @param callback - Function - The callback after validation has been performed.
     *     @argument errors - An array of validation errors
     *     @argument event - The javascript event
     */

    var FormValidator = function(formName, fields, callback) {
        this.callback = callback || defaults.callback;
        this.errors = [];
        this.fields = {};
        this.form = document.forms[formName] || {};
        this.messages = {};
        this.handlers = {};

        for (var i = 0, fieldLength = fields.length; i < fieldLength; i++) {
            var field = fields[i];

            // If passed in incorrectly, we need to skip the field.
            if (!field.name || !field.rules) {
                continue;
            }

            /*
             * Build the master fields array that has all the information needed to validate
             */

            this.fields[field.name] = {
                name: field.name,
                display: field.display || field.name,
                rules: field.rules,
                id: null,
                type: null,
                value: null,
                checked: null
            };
        }

        /*
         * Attach an event callback for the form submission
         */

        this.form.onsubmit = (function(that) {
            return function(event) {
                try {
                    return that._validateForm(event);
                } catch(e) {}
            }
        })(this);
    },

    attributeValue = function (element, attributeName) {
        var i;

        if ((element.length > 0) && (element[0].type === 'radio')) {
            for (i = 0; i < element.length; i++) {
                if (element[i].checked) {
                    return element[i][attributeName];
                }
            }

            return;
        }

        return element[attributeName];
    };

    /*
     * @public
     * Sets a custom message for one of the rules
     */

    FormValidator.prototype.setMessage = function(rule, message) {
        this.messages[rule] = message;

        // return this for chaining
        return this;
    };

    /*
     * @public
     * Registers a callback for a custom rule (i.e. callback_username_check)
     */

    FormValidator.prototype.registerCallback = function(name, handler) {
        if (name && typeof name === 'string' && handler && typeof handler === 'function') {
            this.handlers[name] = handler;
        }

        // return this for chaining
        return this;
    };

    /*
     * @private
     * Runs the validation when the form is submitted.
     */

    FormValidator.prototype._validateForm = function(event) {
        this.errors = [];

        for (var key in this.fields) {
            if (this.fields.hasOwnProperty(key)) {
                var field = this.fields[key] || {},
                    element = this.form[field.name];

                if (element && element !== undefined) {
                    field.id = attributeValue(element, 'id');
                    field.type = (element.length > 0) ? element[0].type : element.type;
                    field.value = attributeValue(element, 'value');
                    field.checked = attributeValue(element, 'checked');
                }

                /*
                 * Run through the rules for each field.
                 */

                this._validateField(field);
            }
        }

        if (typeof this.callback === 'function') {
            this.callback(this.errors, event);
        }

        if (this.errors.length > 0) {
            if (event && event.preventDefault) {
                event.preventDefault();
            } else {
                // IE6 doesn't pass in an event parameter so return false
                return false;
            }
        }

        return true;
    };

    /*
     * @private
     * Looks at the fields value and evaluates it against the given rules
     */

    FormValidator.prototype._validateField = function(field) {
        var rules = field.rules.split('|');

        /*
         * If the value is null and not required, we don't need to run through validation, unless the rule is a callback, but then only if the value is not null
         */

        if ( (field.rules.indexOf('required') === -1 && (!field.value || field.value === '' || field.value === undefined)) && (field.rules.indexOf('callback_') === -1 || field.value === null) ) {
            return;
        }

        /*
         * Run through the rules and execute the validation methods as needed
         */

        for (var i = 0, ruleLength = rules.length; i < ruleLength; i++) {
            var method = rules[i],
                param = null,
                failed = false,
                parts = ruleRegex.exec(method);

            /*
             * If the rule has a parameter (i.e. matches[param]) split it out
             */

            if (parts) {
                method = parts[1];
                param = parts[2];
            }

            /*
             * If the hook is defined, run it to find any validation errors
             */

            if (typeof this._hooks[method] === 'function') {
                if (!this._hooks[method].apply(this, [field, param])) {
                    failed = true;
                }
            } else if (method.substring(0, 9) === 'callback_') {
                // Custom method. Execute the handler if it was registered
                method = method.substring(9, method.length);

                if (typeof this.handlers[method] === 'function') {
                    if (this.handlers[method].apply(this, [field.value]) === false) {
                        failed = true;
                    }
                }
            }

            /*
             * If the hook failed, add a message to the errors array
             */

            if (failed) {
                // Make sure we have a message for this rule
                var source = this.messages[method] || defaults.messages[method],
                    message = 'An error has occurred with the ' + field.display + ' field.';

                if (source) {
                    message = source.replace('%s', field.display);

                    if (param) {
                        message = message.replace('%s', (this.fields[param]) ? this.fields[param].display : param);
                    }
                }

                this.errors.push({
                    id: field.id,
                    name: field.name,
                    message: message,
                    rule: method
                });

                // Break out so as to not spam with validation errors (i.e. required and valid_email)
                break;
            }
        }
    };

    /*
     * @private
     * Object containing all of the validation hooks
     */

    FormValidator.prototype._hooks = {
        required: function(field) {
            var value = field.value;

            if ((field.type === 'checkbox') || (field.type === 'radio')) {
                return (field.checked === true);
            }

            return (value !== null && value !== '');
        },

        matches: function(field, matchName) {
            var el = this.form[matchName];

            if (el) {
                return field.value === el.value;
            }

            return false;
        },

        valid_email: function(field) {
            return emailRegex.test(field.value);
        },

        valid_emails: function(field) {
            var result = field.value.split(",");

            for (var i = 0; i < result.length; i++) {
                if (!emailRegex.test(result[i])) {
                    return false;
                }
            }

            return true;
        },

        min_length: function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }

            return (field.value.length >= parseInt(length, 10));
        },

        max_length: function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }

            return (field.value.length <= parseInt(length, 10));
        },

        exact_length: function(field, length) {
            if (!numericRegex.test(length)) {
                return false;
            }

            return (field.value.length === parseInt(length, 10));
        },

        greater_than: function(field, param) {
            if (!decimalRegex.test(field.value)) {
                return false;
            }

            return (parseFloat(field.value) > parseFloat(param));
        },

        less_than: function(field, param) {
            if (!decimalRegex.test(field.value)) {
                return false;
            }

            return (parseFloat(field.value) < parseFloat(param));
        },

        alpha: function(field) {
            return (alphaRegex.test(field.value));
        },

        alpha_numeric: function(field) {
            return (alphaNumericRegex.test(field.value));
        },

        alpha_dash: function(field) {
            return (alphaDashRegex.test(field.value));
        },

        numeric: function(field) {
            return (decimalRegex.test(field.value));
        },

        integer: function(field) {
            return (integerRegex.test(field.value));
        },

        decimal: function(field) {
            return (decimalRegex.test(field.value));
        },

        is_natural: function(field) {
            return (naturalRegex.test(field.value));
        },

        is_natural_no_zero: function(field) {
            return (naturalNoZeroRegex.test(field.value));
        },

        valid_ip: function(field) {
            return (ipRegex.test(field.value));
        },

        valid_base64: function(field) {
            return (base64Regex.test(field.value));
        },

        valid_credit_card: function(field){
            // Luhn Check Code from https://gist.github.com/4075533
            // accept only digits, dashes or spaces
            if (!numericDashRegex.test(field.value)) return false;

            // The Luhn Algorithm. It's so pretty.
            var nCheck = 0, nDigit = 0, bEven = false;
            var strippedField = field.value.replace(/\D/g, "");

            for (var n = strippedField.length - 1; n >= 0; n--) {
                var cDigit = strippedField.charAt(n),
                nDigit = parseInt(cDigit, 10);
                if (bEven) {
                    if ((nDigit *= 2) > 9) nDigit -= 9;
                }

                nCheck += nDigit;
                bEven = !bEven;
            }

            return (nCheck % 10) == 0;
        },

        is_file_type: function(field,type) {
            if (field.type !== 'file') {
                return true;
            }

            var ext = field.value.substr((field.value.lastIndexOf('.') + 1)),
                typeArray = type.split(','),
                inArray = false,
                i = 0,
                len = typeArray.length;

            for (i; i < len; i++) {
                if (ext == typeArray[i]) inArray = true;
            }

            return inArray;
        }
    };

    window.FormValidator = FormValidator;

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


<commit_before>'use strict';

module.exports = function (router) {

    router.get('/', function (req, res) {

        res.render('layouts/master', {});

    });

};
<commit_msg>feat(index.js): add authentication to routes<commit_after>'use strict';

var auth = require('../lib/auth');
var passport = require('passport');

module.exports = function (router) {
    router.get('/login', function (req, res) {

        //Include any error messages that come from the login process.
        //model.messages = req.flash('error');
        console.log(req.flash('error'));
        res.render('login/login', {});
    });

    /**
     * Receive the login credentials and authenticate.
     * Successful authentications will go to /profile or if the user was trying to access a secured resource, the URL
     * that was originally requested.
     *
     * Failed authentications will go back to the login page with a helpful error message to be displayed.
     */
    router.post('/login',
        passport.authenticate('local', {
            successRedirect: '/',
            failureRedirect: "/login"
        })
    );

    /**
     * Allow the users to log out
     */
    router.get('/logout', function (req, res) {
        req.logout();
        res.redirect('/');
    });

    router.get('/', auth.isAuthenticated('admin'), function (req, res) {
        res.render('layouts/master', {});
    });
    router.get('/session', auth.isAuthenticated('admin'), function(req, res) {
        if(typeof req.user.username !== 'undefined' && typeof req.session.passport.user !== 'undefined'){
            res.send({auth: true, id: req.user.id, username: req.user.username, role: req.user.role});
        } else {
            res.send({auth: false});
        }
    });

};
<|endoftext|>


<commit_before>const babel = require('gulp-babel');
const batch = require('gulp-batch');
const gulp = require('gulp');
const watch = require('gulp-watch');

// Copy all files except for *.js ones
gulp.task('cp', function() {
  gulp.src([
      'app/**/!(*.js)',
      'MIT-LICENSE.txt',
      'README.md',
    ])
    .pipe(gulp.dest('dist'));
});

// Copy the entire lib/ directory; it's vendor, 3rd party stuff
gulp.task('cp-lib', function() {
  gulp.src('app/lib/**')
    .pipe(gulp.dest('dist/lib'));
});

// Compile app JS with babel
gulp.task('js', function() {
  const presets = ['es2015', 'react'];

  gulp.src('app/*.js')
    .pipe(babel({
      presets: presets,
    }))
    .pipe(gulp.dest('dist'));

  gulp.src('app/js/*.js')
    .pipe(babel({
      presets: presets,
    }))
    .pipe(gulp.dest('dist/js'));
});

// Watch and re-compile when in development. Changes are batched every 500ms since switching between
// code and browser takes at least that long, save a few saves.
gulp.task('watch', function() {
  watch([
    'app/*.js',
    'app/js/*.js',
  ], batch({timeout: 500}, function(events, done) {
    gulp.start('js', done);
  }));
});

gulp.task('default', ['cp', 'cp-lib', 'js']);
<commit_msg>Watch CSS for copying, make watch uber powerful<commit_after>const babel = require('gulp-babel');
const batch = require('gulp-batch');
const gulp = require('gulp');
const watch = require('gulp-watch');

// Copy all files except for *.js ones
gulp.task('cp', function() {
  gulp.src([
      'app/**/!(*.js)',
      'MIT-LICENSE.txt',
      'README.md',
    ])
    .pipe(gulp.dest('dist'));
});

// Copy the entire lib/ directory; it's vendor, 3rd party stuff
gulp.task('cp-lib', function() {
  gulp.src('app/lib/**')
    .pipe(gulp.dest('dist/lib'));
});

// Compile app JS with babel
gulp.task('js', function() {
  const presets = ['es2015', 'react'];

  gulp.src('app/*.js')
    .pipe(babel({
      presets: presets,
    }))
    .pipe(gulp.dest('dist'));

  gulp.src('app/js/*.js')
    .pipe(babel({
      presets: presets,
    }))
    .pipe(gulp.dest('dist/js'));
});

// Batch every 500ms since switching between code and browser takes at least that long, save a few
// saves.
const WATCH_OPTIONS = {timeout: 500};

// Watch and re-compile when in development.
gulp.task('watch', function() {
  watch('app/**/!(*.js)', batch(WATCH_OPTIONS, function(events, done) {
    gulp.start('cp', done);
  }));

  watch([
    'app/*.js',
    'app/js/*.js',
  ], batch(WATCH_OPTIONS, function(events, done) {
    gulp.start('js', done);
  }));

  gulp.start('default');
});

gulp.task('default', ['cp', 'cp-lib', 'js']);
<|endoftext|>


<commit_before>var cadence = require('cadence')
var Dispatcher = require('inlet/dispatcher')

function Service (interface) {
    this._interface = interface
    var dispatcher = new Dispatcher(this)
    dispatcher.dispatch('GET /', 'index')
    dispatcher.dispatch('PUT /v2/keys/(.+)', 'set')
    dispatcher.dispatch('GET /v2/keys/(.+)', 'get')
    dispatcher.dispatch('DELETE /v2/keys/(.+)', 'remove')
    this.dispatcher = dispatcher
}

Service.prototype.index = cadence(function (async) {
    return 'Memento API\n'
})

Service.prototype.set = cadence(function (async, request, path) {
    var value = request.body.value
    this._interface.set({ path: path, value: value }, async())
})

Service.prototype.get = cadence(function (async, request, path) {
    var got = this._interface.get(path)
    if (got == null) {
        request.raise(404)
    }
    return got
})

Service.prototype.remove = cadence(function (async, request, path) {
    var value = request.body.value
    this._interface.remove({ path: path }, async())
})

module.exports = Service
<commit_msg>Rename `inquisitor`.<commit_after>var cadence = require('cadence')
var Dispatcher = require('inlet/dispatcher')

function Service (inquisitor) {
    this._inquisitor = inquisitor
    var dispatcher = new Dispatcher(this)
    dispatcher.dispatch('GET /', 'index')
    dispatcher.dispatch('PUT /v2/keys/(.+)', 'set')
    dispatcher.dispatch('GET /v2/keys/(.+)', 'get')
    dispatcher.dispatch('DELETE /v2/keys/(.+)', 'remove')
    this.dispatcher = dispatcher
}

Service.prototype.index = cadence(function (async) {
    return 'Memento API\n'
})

Service.prototype.set = cadence(function (async, request, path) {
    var value = request.body.value
    this._inquisitor.set({ path: path, value: value }, async())
})

Service.prototype.get = cadence(function (async, request, path) {
    var got = this._inquisitor.get(path)
    if (got == null) {
        request.raise(404)
    }
    return got
})

Service.prototype.remove = cadence(function (async, request, path) {
    var value = request.body.value
    this._inquisitor.remove({ path: path }, async())
})

module.exports = Service
<|endoftext|>


<commit_before>/**
 * @author dmarcos / https://github.com/dmarcos
 * @author mrdoob / http://mrdoob.com
 *
 * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
 *
 * Firefox: http://mozvr.com/downloads/
 * Chromium: https://drive.google.com/folderview?id=0BzudLt22BqGRbW9WTHMtOWMzNjQ&usp=sharing#list
 *
 */

THREE.VREffect = function ( renderer, onError, camera ) {

	var vrHMD;
	var eyeTranslationL, eyeFOVL;
	var eyeTranslationR, eyeFOVR;
	var stereoTransformL = new THREE.Matrix4(),
		stereoTransformR = new THREE.Matrix4();

	function gotVRDevices( devices ) {

		for ( var i = 0; i < devices.length; i ++ ) {

			if ( devices[ i ] instanceof HMDVRDevice ) {

				vrHMD = devices[ i ];

				if ( vrHMD.getEyeParameters !== undefined ) {

					var eyeParamsL = vrHMD.getEyeParameters( 'left' );
					var eyeParamsR = vrHMD.getEyeParameters( 'right' );

					eyeTranslationL = eyeParamsL.eyeTranslation;
					eyeTranslationR = eyeParamsR.eyeTranslation;
					eyeFOVL = eyeParamsL.recommendedFieldOfView;
					eyeFOVR = eyeParamsR.recommendedFieldOfView;

				} else {

					// TODO: This is an older code path and not spec compliant.
					// It should be removed at some point in the near future.
					eyeTranslationL = vrHMD.getEyeTranslation( 'left' );
					eyeTranslationR = vrHMD.getEyeTranslation( 'right' );
					eyeFOVL = vrHMD.getRecommendedEyeFieldOfView( 'left' );
					eyeFOVR = vrHMD.getRecommendedEyeFieldOfView( 'right' );

				}

				var zNear = camera !== undefined ? camera.near : 0.1;
				var zFar = camera !== undefined ? camera.far : 1000;
				cameraL.projectionMatrix.copy( fovToProjection( eyeFOVL, true, zNear, zFar ) );
				cameraR.projectionMatrix.copy( fovToProjection( eyeFOVR, true, zNear, zFar ) );

				stereoTransformL.makeTranslation( eyeTranslationL.x, eyeTranslationL.y, eyeTranslationL.z );
				stereoTransformR.makeTranslation( eyeTranslationR.x, eyeTranslationR.y, eyeTranslationR.z );

				break; // We keep the first we encounter

			}

		}

		if ( vrHMD === undefined ) {

			if ( onError ) onError( 'HMD not available' );

		}

	}

	if ( navigator.getVRDevices ) {

		navigator.getVRDevices().then( gotVRDevices );

	}

	//

	this.scale = 1;

	this.setSize = function( width, height ) {

		renderer.setSize( width, height );

	};

	// fullscreen

	var isFullscreen = false;

	var canvas = renderer.domElement;
	var fullscreenchange = canvas.mozRequestFullScreen ? 'mozfullscreenchange' : 'webkitfullscreenchange';

	document.addEventListener( fullscreenchange, function ( event ) {

		isFullscreen = document.mozFullScreenElement || document.webkitFullscreenElement;

	}, false );

	this.setFullScreen = function ( boolean ) {

		if ( vrHMD === undefined ) return;
		if ( isFullscreen === boolean ) return;

		if ( canvas.mozRequestFullScreen ) {

			canvas.mozRequestFullScreen( { vrDisplay: vrHMD } );

		} else if ( canvas.webkitRequestFullscreen ) {

			canvas.webkitRequestFullscreen( { vrDisplay: vrHMD } );

		}

	};

	// render

	var cameraL = new THREE.PerspectiveCamera();
	var cameraR = new THREE.PerspectiveCamera();

	cameraL.matrixAutoUpdate = false;
	cameraR.matrixAutoUpdate = false;

	this.render = function ( scene, camera ) {

		if ( vrHMD ) {

			var sceneL, sceneR;
			var autoUpdate;
			if ( Array.isArray( scene ) ) {

				sceneL = scene[ 0 ];
				sceneR = scene[ 1 ];

			} else {

				sceneL = scene;
				sceneR = scene;
				autoUpdate = scene.autoUpdate;

				if ( autoUpdate === true ) {

					scene.updateMatrixWorld();
					scene.autoUpdate = false;

				}

			}

			var size = renderer.getSize();
			size.width /= 2;

			renderer.enableScissorTest( true );
			renderer.clear();

			if ( camera.parent === null ) camera.updateMatrixWorld();

			// render left eye
			renderer.setViewport( 0, 0, size.width, size.height );
			renderer.setScissor( 0, 0, size.width, size.height );
			cameraL.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformL );
			renderer.render( sceneL, cameraL );

			// render right eye
			renderer.setViewport( size.width, 0, size.width, size.height );
			renderer.setScissor( size.width, 0, size.width, size.height );
			cameraR.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformR );
			renderer.render( sceneR, cameraR );

			renderer.enableScissorTest( false );

			if ( autoUpdate === true ) {

				scene.autoUpdate = autoUpdate;

			}

			return;

		}

		// Regular render mode if not HMD

		if ( Array.isArray( scene ) ) scene = scene[ 0 ];

		renderer.render( scene, camera );

	};

	//

	function fovToNDCScaleOffset( fov ) {

		var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
		var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
		var pyscale = 2.0 / ( fov.upTan + fov.downTan );
		var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
		return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };

	}

	function fovPortToProjection( fov, rightHanded, zNear, zFar ) {

		rightHanded = rightHanded === undefined ? true : rightHanded;
		zNear = zNear === undefined ? 0.01 : zNear;
		zFar = zFar === undefined ? 10000.0 : zFar;

		var handednessScale = rightHanded ? - 1.0 : 1.0;

		// start with an identity matrix
		var mobj = new THREE.Matrix4();
		var m = mobj.elements;

		// and with scale/offset info for normalized device coords
		var scaleAndOffset = fovToNDCScaleOffset( fov );

		// X result, map clip edges to [-w,+w]
		m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
		m[ 0 * 4 + 1 ] = 0.0;
		m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
		m[ 0 * 4 + 3 ] = 0.0;

		// Y result, map clip edges to [-w,+w]
		// Y offset is negated because this proj matrix transforms from world coords with Y=up,
		// but the NDC scaling has Y=down (thanks D3D?)
		m[ 1 * 4 + 0 ] = 0.0;
		m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
		m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
		m[ 1 * 4 + 3 ] = 0.0;

		// Z result (up to the app)
		m[ 2 * 4 + 0 ] = 0.0;
		m[ 2 * 4 + 1 ] = 0.0;
		m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
		m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );

		// W result (= Z in)
		m[ 3 * 4 + 0 ] = 0.0;
		m[ 3 * 4 + 1 ] = 0.0;
		m[ 3 * 4 + 2 ] = handednessScale;
		m[ 3 * 4 + 3 ] = 0.0;

		mobj.transpose();

		return mobj;

	}

	function fovToProjection( fov, rightHanded, zNear, zFar ) {

		var DEG2RAD = Math.PI / 180.0;

		var fovPort = {
			upTan: Math.tan( fov.upDegrees * DEG2RAD ),
			downTan: Math.tan( fov.downDegrees * DEG2RAD ),
			leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
			rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
		};

		return fovPortToProjection( fovPort, rightHanded, zNear, zFar );

	}

};
<commit_msg>reincorporate vreffect scale<commit_after>/**
 * @author dmarcos / https://github.com/dmarcos
 * @author mrdoob / http://mrdoob.com
 *
 * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
 *
 * Firefox: http://mozvr.com/downloads/
 * Chromium: https://drive.google.com/folderview?id=0BzudLt22BqGRbW9WTHMtOWMzNjQ&usp=sharing#list
 *
 */

THREE.VREffect = function ( renderer, onError, camera ) {

	var vrHMD;
	var eyeTranslationL, eyeFOVL;
	var eyeTranslationR, eyeFOVR;
	var stereoTransformL = new THREE.Matrix4(),
		stereoTransformR = new THREE.Matrix4();

	function gotVRDevices( devices ) {

		for ( var i = 0; i < devices.length; i ++ ) {

			if ( devices[ i ] instanceof HMDVRDevice ) {

				vrHMD = devices[ i ];

				if ( vrHMD.getEyeParameters !== undefined ) {

					var eyeParamsL = vrHMD.getEyeParameters( 'left' );
					var eyeParamsR = vrHMD.getEyeParameters( 'right' );

					eyeTranslationL = eyeParamsL.eyeTranslation;
					eyeTranslationR = eyeParamsR.eyeTranslation;
					eyeFOVL = eyeParamsL.recommendedFieldOfView;
					eyeFOVR = eyeParamsR.recommendedFieldOfView;

				} else {

					// TODO: This is an older code path and not spec compliant.
					// It should be removed at some point in the near future.
					eyeTranslationL = vrHMD.getEyeTranslation( 'left' );
					eyeTranslationR = vrHMD.getEyeTranslation( 'right' );
					eyeFOVL = vrHMD.getRecommendedEyeFieldOfView( 'left' );
					eyeFOVR = vrHMD.getRecommendedEyeFieldOfView( 'right' );

				}

				var zNear = camera !== undefined ? camera.near : 0.1;
				var zFar = camera !== undefined ? camera.far : 1000;
				cameraL.projectionMatrix.copy( fovToProjection( eyeFOVL, true, zNear, zFar ) );
				cameraR.projectionMatrix.copy( fovToProjection( eyeFOVR, true, zNear, zFar ) );

				stereoTransformL.makeTranslation( this.scale * eyeTranslationL.x, this.scale * eyeTranslationL.y, this.scale * eyeTranslationL.z );
				stereoTransformR.makeTranslation( this.scale * eyeTranslationR.x, this.scale * eyeTranslationR.y, this.scale * eyeTranslationR.z );

				break; // We keep the first we encounter

			}

		}

		if ( vrHMD === undefined ) {

			if ( onError ) onError( 'HMD not available' );

		}

	}

	if ( navigator.getVRDevices ) {

		navigator.getVRDevices().then( gotVRDevices.bind(this) );

	}

	//

	this.scale = 1;

	this.setSize = function( width, height ) {

		renderer.setSize( width, height );

	};

	// fullscreen

	var isFullscreen = false;

	var canvas = renderer.domElement;
	var fullscreenchange = canvas.mozRequestFullScreen ? 'mozfullscreenchange' : 'webkitfullscreenchange';

	document.addEventListener( fullscreenchange, function ( event ) {

		isFullscreen = document.mozFullScreenElement || document.webkitFullscreenElement;

	}, false );

	this.setFullScreen = function ( boolean ) {

		if ( vrHMD === undefined ) return;
		if ( isFullscreen === boolean ) return;

		if ( canvas.mozRequestFullScreen ) {

			canvas.mozRequestFullScreen( { vrDisplay: vrHMD } );

		} else if ( canvas.webkitRequestFullscreen ) {

			canvas.webkitRequestFullscreen( { vrDisplay: vrHMD } );

		}

	};

	// render

	var cameraL = new THREE.PerspectiveCamera();
	var cameraR = new THREE.PerspectiveCamera();

	cameraL.matrixAutoUpdate = false;
	cameraR.matrixAutoUpdate = false;

	this.render = function ( scene, camera ) {

		if ( vrHMD ) {

			var sceneL, sceneR;
			var autoUpdate;
			if ( Array.isArray( scene ) ) {

				sceneL = scene[ 0 ];
				sceneR = scene[ 1 ];

			} else {

				sceneL = scene;
				sceneR = scene;
				autoUpdate = scene.autoUpdate;

				if ( autoUpdate === true ) {

					scene.updateMatrixWorld();
					scene.autoUpdate = false;

				}

			}

			var size = renderer.getSize();
			size.width /= 2;

			renderer.enableScissorTest( true );
			renderer.clear();

			if ( camera.parent === null ) camera.updateMatrixWorld();

			// render left eye
			renderer.setViewport( 0, 0, size.width, size.height );
			renderer.setScissor( 0, 0, size.width, size.height );
			cameraL.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformL );
			renderer.render( sceneL, cameraL );

			// render right eye
			renderer.setViewport( size.width, 0, size.width, size.height );
			renderer.setScissor( size.width, 0, size.width, size.height );
			cameraR.matrixWorld.multiplyMatrices( camera.matrixWorld, stereoTransformR );
			renderer.render( sceneR, cameraR );

			renderer.enableScissorTest( false );

			if ( autoUpdate === true ) {

				scene.autoUpdate = autoUpdate;

			}

			return;

		}

		// Regular render mode if not HMD

		if ( Array.isArray( scene ) ) scene = scene[ 0 ];

		renderer.render( scene, camera );

	};

	//

	function fovToNDCScaleOffset( fov ) {

		var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
		var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
		var pyscale = 2.0 / ( fov.upTan + fov.downTan );
		var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
		return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };

	}

	function fovPortToProjection( fov, rightHanded, zNear, zFar ) {

		rightHanded = rightHanded === undefined ? true : rightHanded;
		zNear = zNear === undefined ? 0.01 : zNear;
		zFar = zFar === undefined ? 10000.0 : zFar;

		var handednessScale = rightHanded ? - 1.0 : 1.0;

		// start with an identity matrix
		var mobj = new THREE.Matrix4();
		var m = mobj.elements;

		// and with scale/offset info for normalized device coords
		var scaleAndOffset = fovToNDCScaleOffset( fov );

		// X result, map clip edges to [-w,+w]
		m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
		m[ 0 * 4 + 1 ] = 0.0;
		m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
		m[ 0 * 4 + 3 ] = 0.0;

		// Y result, map clip edges to [-w,+w]
		// Y offset is negated because this proj matrix transforms from world coords with Y=up,
		// but the NDC scaling has Y=down (thanks D3D?)
		m[ 1 * 4 + 0 ] = 0.0;
		m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
		m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
		m[ 1 * 4 + 3 ] = 0.0;

		// Z result (up to the app)
		m[ 2 * 4 + 0 ] = 0.0;
		m[ 2 * 4 + 1 ] = 0.0;
		m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
		m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );

		// W result (= Z in)
		m[ 3 * 4 + 0 ] = 0.0;
		m[ 3 * 4 + 1 ] = 0.0;
		m[ 3 * 4 + 2 ] = handednessScale;
		m[ 3 * 4 + 3 ] = 0.0;

		mobj.transpose();

		return mobj;

	}

	function fovToProjection( fov, rightHanded, zNear, zFar ) {

		var DEG2RAD = Math.PI / 180.0;

		var fovPort = {
			upTan: Math.tan( fov.upDegrees * DEG2RAD ),
			downTan: Math.tan( fov.downDegrees * DEG2RAD ),
			leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
			rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
		};

		return fovPortToProjection( fovPort, rightHanded, zNear, zFar );

	}

};
<|endoftext|>


<commit_before>'use strict';
describe('faApp', function() {
  var element, $compile, $scope, $famous;

  beforeEach(module('famous.angular'));

  beforeEach(inject(function(_$compile_, _$rootScope_, _$famous_) {
    $compile = _$compile_;
    $scope = _$rootScope_.$new();
    $famous = _$famous_;
    element = $compile('

')($scope);
  }));

  it('should append a div.famous-angular-container pre-compilation', function() {
    expect(element[0].querySelector('.famous-angular-container')).toBeNull();
    element.append($compile("<fa-app></fa-app>")($scope));
    expect(element[0].querySelector('.famous-angular-container')).not.toBeNull();
  });

  it('should work as an element', function() {
    element.append($compile("<fa-app></fa-app>")($scope));
    expect(element[0].querySelector('.famous-angular-container')).not.toBeNull();
  });

  it('should work as an attirbute', function() {
    element.append($compile("

")($scope));
    expect(element[0].querySelector('.famous-angular-container')).not.toBeNull();
  });

  it('should unregister its context when recieving a "$destroy" event', function() {
    // Not implemented yet due to a Famo.us Engine limitation
  });

  it('should add a node to its view when receiving a "registerChild" event', function() {
    var faApp = $compile("<fa-app></fa-app>")($scope);
    document.body.appendChild(faApp[0]);
    // Get fa-app's newly created scope
    var faAppScope = angular.element(document.querySelector('fa-app')).scope();

    // Spy on isolate.view.add();
    var isolateView = faAppScope.isolate[faAppScope.$id].view;
    spyOn(isolateView, 'add');

    // Create a child scope of that, so that we can emit events up to fa-app
    var secondScope = faAppScope.$new();
    var mockData = { renderNode: 1 };

    secondScope.$emit('registerChild', mockData);
    expect(isolateView.add).toHaveBeenCalled();
  });

  it('should transclude content', function() {
    expect(element.find('span').length).toEqual(0);
    element.append($compile("<fa-app></fa-app>")($scope));
    expect(element.find('span').length).toEqual(1);
  });

});
<commit_msg>Clean up faApp spec typos.<commit_after>'use strict';
describe('faApp', function() {
  var element, $compile, $scope, $famous;

  beforeEach(module('famous.angular'));

  beforeEach(inject(function(_$compile_, _$rootScope_, _$famous_) {
    $compile = _$compile_;
    $scope = _$rootScope_.$new();
    $famous = _$famous_;
    element = $compile('

')($scope);
  }));

  it('should append a div.famous-angular-container pre-compilation', function() {
    expect(element[0].querySelector('.famous-angular-container')).toBeNull();
    element.append($compile("<fa-app></fa-app>")($scope));
    expect(element[0].querySelector('.famous-angular-container')).not.toBeNull();
  });

  it('should work as an element', function() {
    element.append($compile("<fa-app></fa-app>")($scope));
    expect(element[0].querySelector('.famous-angular-container')).not.toBeNull();
  });

  it('should work as an attribute', function() {
    element.append($compile("

")($scope));
    expect(element[0].querySelector('.famous-angular-container')).not.toBeNull();
  });

  it('should unregister its context when receiving a "$destroy" event', function() {
    // Not implemented yet due to a Famo.us Engine limitation
  });

  it('should add a node to its view when receiving a "registerChild" event', function() {
    var faApp = $compile("<fa-app></fa-app>")($scope);
    document.body.appendChild(faApp[0]);
    // Get fa-app's newly created scope
    var faAppScope = angular.element(document.querySelector('fa-app')).scope();

    // Spy on isolate.view.add();
    var isolateView = faAppScope.isolate[faAppScope.$id].view;
    spyOn(isolateView, 'add');

    // Create a child scope of that, so that we can emit events up to fa-app
    var childScope = faAppScope.$new();
    var mockData = { renderNode: 1 };

    childScope.$emit('registerChild', mockData);
    expect(isolateView.add).toHaveBeenCalled();
  });

  it('should transclude content', function() {
    expect(element.find('span').length).toEqual(0);
    element.append($compile("<fa-app></fa-app>")($scope));
    expect(element.find('span').length).toEqual(1);
  });

});
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/tap:i18n';
import { Session } from 'meteor/session';
import { Contracts } from '/imports/api/contracts/Contracts';

import { setVote, getTickValue, candidateBallot, executeVote } from '/imports/ui/modules/ballot';
import { Wallet } from '/imports/ui/modules/Wallet';
import './fork.html';

Template.fork.helpers({
  length() {
    if (this.label !== undefined) {
      if (this.label.length > 51) {
        return 'option-link option-long option-longest';
      } else if (this.label.length > 37) {
        return 'option-link option-long';
      }
    }
    return '';
  },
  dragMode() {
    if (Session.get('contract').stage === 'DRAFT' || this.mini === true) {
      return '';
    }
    return 'vote-nondrag';
  },
  tickStyle() {
    if (this.mode === 'REJECT') {
      return 'unauthorized';
    }
    return '';
  },
  checkbox(mode) {
    switch (mode) {
      case 'AUTHORIZE':
        return 'vote-authorize nondraggable';
      case 'REJECT':
        return 'vote-authorize unauthorized nondraggable';
      case 'FORK':
      default:
        return 'vote vote-alternative';
    }
  },
  action() {
    if (this.authorized === false) {
      return 'undefined';
    }
    return '';
  },
  option(mode) {
    if (Session.get('contract').stage === 'DRAFT' || (Session.get('rightToVote') === false && Session.get('contract').stage !== 'DRAFT')) {
      return 'disabled';
    }
    switch (mode) {
      case 'AUTHORIZE':
        return '';
      case 'REJECT':
        if (this.mini) {
          return 'unauthorized';
        }
        return 'option-link unauthorized';
      default:
        return '';
    }
  },
  decision(mode) {
    switch (mode) {
      case 'REJECT':
        return 'option-link unauthorized';
      default:
        return '';
    }
  },
  caption(mode) {
    if (mode !== 'FORK') {
      return TAPi18n.__(mode);
    }
    return this.label;
  },
  tick() {
    if (Session.get('contract').stage === 'DRAFT') {
      return 'disabled';
    }
    return '';
  },
  tickStatus() {
    this.tick = getTickValue(Session.get('contract')._id, this);
    if (Session.get('candidateBallot') || (this.tick)) {
      if (this.tick) {
        if (this.mode === 'REJECT') {
          return 'tick-active-unauthorized';
        }
        return 'tick-active';
      }
    // already voted
    } else if (Session.get('rightToVote') === false && Session.get('contract').stage !== 'DRAFT') {
      if (this.tick) {
        return 'tick-disabled';
      }
    }
    return '';
  },
  style(className) {
    let final = className;
    if (this.mini === true) {
      final += ` ${final}-mini`;
    }
    return final;
  },
  isReject() {
    return (this.mode === 'REJECT');
  },
});

Template.fork.events({
  'click #ballotCheckbox'() {
    if (!Session.get('showModal')) {
      switch (Session.get('contract').stage) {
        case 'DRAFT':
        case 'FINISH':
          Session.set('disabledCheckboxes', true);
          break;
        case 'LIVE':
        default:
          if (Session.get('rightToVote')) {
            if (Session.get('candidateBallot') === undefined) {
              candidateBallot(Meteor.userId());
            }
            this.tick = setVote(Session.get('contract')._id, this);
            if (this.tick === true) {
              Session.set('noSelectedOption', false);
            }
            if (Session.get(`vote-${Session.get('contract')._id}`).inBallot > 0) {
              const wallet = new Wallet(Session.get(`vote-${Session.get('contract')._id}`));
              const cancel = () => {
                console.log('hello');
              };
              executeVote(wallet, cancel);
            }
            break;
          }
      }
    }
  },
  'click #remove-fork'() {
    // Meteor.call('removeFork', Session.get('contract')._id, this._id);
    Contracts.update(Session.get('contract')._id, { $pull: {
      ballot:
        { _id: this._id },
    } });
  },
});
<commit_msg>change of ballot restored if canceled<commit_after>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/tap:i18n';
import { Session } from 'meteor/session';
import { Contracts } from '/imports/api/contracts/Contracts';

import { setVote, getTickValue, candidateBallot, executeVote } from '/imports/ui/modules/ballot';
import { Wallet } from '/imports/ui/modules/Wallet';
import './fork.html';

Template.fork.helpers({
  length() {
    if (this.label !== undefined) {
      if (this.label.length > 51) {
        return 'option-link option-long option-longest';
      } else if (this.label.length > 37) {
        return 'option-link option-long';
      }
    }
    return '';
  },
  dragMode() {
    if (Session.get('contract').stage === 'DRAFT' || this.mini === true) {
      return '';
    }
    return 'vote-nondrag';
  },
  tickStyle() {
    if (this.mode === 'REJECT') {
      return 'unauthorized';
    }
    return '';
  },
  checkbox(mode) {
    switch (mode) {
      case 'AUTHORIZE':
        return 'vote-authorize nondraggable';
      case 'REJECT':
        return 'vote-authorize unauthorized nondraggable';
      case 'FORK':
      default:
        return 'vote vote-alternative';
    }
  },
  action() {
    if (this.authorized === false) {
      return 'undefined';
    }
    return '';
  },
  option(mode) {
    if (Session.get('contract').stage === 'DRAFT' || (Session.get('rightToVote') === false && Session.get('contract').stage !== 'DRAFT')) {
      return 'disabled';
    }
    switch (mode) {
      case 'AUTHORIZE':
        return '';
      case 'REJECT':
        if (this.mini) {
          return 'unauthorized';
        }
        return 'option-link unauthorized';
      default:
        return '';
    }
  },
  decision(mode) {
    switch (mode) {
      case 'REJECT':
        return 'option-link unauthorized';
      default:
        return '';
    }
  },
  caption(mode) {
    if (mode !== 'FORK') {
      return TAPi18n.__(mode);
    }
    return this.label;
  },
  tick() {
    if (Session.get('contract').stage === 'DRAFT') {
      return 'disabled';
    }
    return '';
  },
  tickStatus() {
    this.tick = getTickValue(Session.get('contract')._id, this);
    if (Session.get('candidateBallot') || (this.tick)) {
      if (this.tick) {
        if (this.mode === 'REJECT') {
          return 'tick-active-unauthorized';
        }
        return 'tick-active';
      }
    // already voted
    } else if (Session.get('rightToVote') === false && Session.get('contract').stage !== 'DRAFT') {
      if (this.tick) {
        return 'tick-disabled';
      }
    }
    return '';
  },
  style(className) {
    let final = className;
    if (this.mini === true) {
      final += ` ${final}-mini`;
    }
    return final;
  },
  isReject() {
    return (this.mode === 'REJECT');
  },
});

Template.fork.events({
  'click #ballotCheckbox'() {
    if (!Session.get('showModal')) {
      switch (Session.get('contract').stage) {
        case 'DRAFT':
        case 'FINISH':
          Session.set('disabledCheckboxes', true);
          break;
        case 'LIVE':
        default:
          if (Session.get('rightToVote')) {
            if (Session.get('candidateBallot') === undefined) {
              candidateBallot(Meteor.userId());
            }
            const previous = Session.get('candidateBallot');
            this.tick = setVote(Session.get('contract')._id, this);
            if (this.tick === true) {
              Session.set('noSelectedOption', false);
            }
            if (Session.get(`vote-${Session.get('contract')._id}`).inBallot > 0) {
              const wallet = new Wallet(Session.get(`vote-${Session.get('contract')._id}`));
              const cancel = () => {
                Session.set('candidateBallot', previous);
              };
              executeVote(wallet, cancel);
            }
            break;
          }
      }
    }
  },
  'click #remove-fork'() {
    // Meteor.call('removeFork', Session.get('contract')._id, this._id);
    Contracts.update(Session.get('contract')._id, { $pull: {
      ballot:
        { _id: this._id },
    } });
  },
});
<|endoftext|>


<commit_before>/**
 * workers.js - worker processes for bcoin
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * https://github.com/indutny/bcoin
 */

var bcoin = require('../bcoin');
var bn = require('bn.js');
var constants = bcoin.protocol.constants;
var utils = require('./utils');
var assert = utils.assert;
var BufferWriter = require('./writer');
var BufferReader = require('./reader');
var cp = require('child_process');
var workers = exports;

var HEADER_SIZE = 12;

/**
 * Master
 */

workers.MAX_WORKERS = +process.env.BCOIN_WORKERS || 30;
workers.TIMEOUT = 10000;
workers.children = {};
workers.uid = 0;

workers.spawn = function spawn(index) {
  var child;

  utils.debug('Spawning worker process: %d', index);

  child = cp.spawn(process.argv[0], [__filename], {
    stdio: ['pipe', 'pipe', 'inherit'],
    env: utils.merge({}, process.env, {
      BCOIN_WORKER: index + ''
    })
  });

  child.on('error', function(err) {
    utils.debug('Worker %d error: %s', index, err.message);
  });

  child.on('exit', function(code) {
    utils.debug('Worker %d exited: %s', index, code);
    if (workers.children[index] === child)
      delete workers.children[index];
  });

  child.on('close', function() {
    utils.debug('Worker %d closed', index);
    if (workers.children[index] === child)
      delete workers.children[index];
  });

  child.stdout.on('data', parser(function(id, body) {
    child.emit('completed ' + id, body.items[0], body.items[1]);
  }));

  return child;
};

// Load balance the workers based on job ID.
workers.alloc = function alloc(id) {
  var index = id % workers.MAX_WORKERS;
  if (!workers.children[index])
    workers.children[index] = workers.spawn(index);
  return workers.children[index];
};

workers.call = function call(method, args, callback) {
  var id = workers.uid++;
  var event, child, timeout;

  if (id > 0xffffffff) {
    workers.uid = 0;
    id = workers.uid++;
  }

  event = 'completed ' + id;
  child = workers.alloc(id);

  function listener(err, result) {
    clearTimeout(timeout);
    timeout = null;
    callback(err, result);
  }

  child.once(event, listener);

  timeout = setTimeout(function() {
    child.removeListener(event, listener);
    return callback(new Error('Worker timed out.'));
  }, workers.TIMEOUT);

  child.stdin.write(createPacket(id, method, args));
};

/**
 * Calls
 */

bcoin.tx.prototype.verifyAsync = function verifyAsync(index, force, flags, callback) {
  var tx;

  callback = utils.asyncify(callback);

  if (!force && this.ts !== 0)
    return callback(null, true);

  if (this.inputs.length === 0)
    return callback(null, false);

  if (this.isCoinbase())
    return callback(null, true);

  // Important: we need to serialize
  // the coins for the worker.
  tx = this.toExtended(true);

  return workers.call('verify', [tx, index, force, flags], callback);
};

/**
 * Child
 */

workers.listen = function listen() {
  bcoin.debug = function debug() {
    process.stderr.write('Worker %s: ', process.env.BCOIN_WORKER);
    return console.error.apply(console.error, arguments);
  };

  utils.debug = bcoin.debug;
  utils.print = bcoin.debug;

  process.stdin.on('data', parser(function(id, body) {
    var res;

    try {
      res = workers[body.name].apply(workers[body.name], body.items);
    } catch (e) {
      utils.debug(e.stack + '');
      return process.stdout.write(createPacket(id, null, [{
        message: e.message,
        stack: e.stack + ''
      }]));
    }

    return process.stdout.write(createPacket(id, null, [null, res]));
  }));
};

/**
 * Calls
 * The actual calls that are run
 * in a separate worker process.
 */

workers.verify = function verify(tx, index, force, flags) {
  tx = bcoin.tx.fromExtended(tx, true);
  return tx.verify(index, force, flags);
};

/**
 * Helpers
 */

/*
function createPacket(id, name, items) {
  var p, i;

  for (i = 0; i < items.length; i++) {
    if (Buffer.isBuffer(items[i]))
      items[i] = [0, items[i].toString('hex')];
  }

  items = JSON.stringify({ name: name, items: items });
  items = new Buffer(items, 'utf8');

  p = new BufferWriter();
  p.writeU32(0xdeadbeef);
  p.writeU32(id);
  p.writeU32(items.length + 1);
  p.writeBytes(items);
  p.writeU8(0x0a);

  return p.render();
}

function parseBody(data) {
  data = JSON.parse(data.toString('utf8'));
  for (var i = 0; i < data.items.length; i++) {
    if (data.items[i] && data.items[i][0] === 0 && data.items[i].length === 2)
      data.items[i] = new Buffer(data.items[i][1], 'hex');
  }
  return data;
}
*/

function createPacket(id, name, items) {
  var p = new BufferWriter();
  var payload = createBody(name, items);
  p.writeU32(0xdeadbeef);
  p.writeU32(id);
  p.writeU32(payload.length);
  p.writeBytes(payload);
  return p.render();
}

function createBody(name, items) {
  var p = new BufferWriter();
  var i;

  if (name)
    p.writeVarString(name, 'ascii');
  else
    p.writeUIntv(0);

  p.writeUIntv(items.length);

  for (i = 0; i < items.length; i++) {
    switch (typeof items[i]) {
      case 'string':
        p.writeU8(1);
        p.writeVarString(items[i], 'utf8');
        break;
      case 'number':
        p.writeU8(2);
        p.write32(items[i]);
        break;
      case 'boolean':
        p.writeU8(3);
        p.writeU8(items[i] ? 1 : 0);
        break;
      case 'object':
      case 'undefined':
        if (items[i] == null) {
          p.writeU8(0);
        } else if (Buffer.isBuffer(items[i])) {
          p.writeU8(5);
          p.writeVarBytes(items[i]);
        } else {
          p.writeU8(4);
          p.writeVarString(JSON.stringify(items[i]), 'utf8');
        }
        break;
      default:
        assert(false, 'Bad type: ' + (typeof items[i]));
    }
  }

  p.writeU8(0x0a);

  return p.render();
}

function parseBody(data) {
  var p = new BufferReader(data, true);
  var name, count, i;
  var items = [];

  p.start();

  name = p.readVarString('ascii');
  count = p.readUIntv();

  for (i = 0; i < count; i++) {
    switch (p.readU8()) {
      case 0:
        items.push(null);
        break;
      case 1:
        items.push(p.readVarString('utf8'));
        break;
      case 2:
        items.push(p.read32());
        break;
      case 3:
        items.push(p.readU8() === 1);
        break;
      case 4:
        items.push(items.parse(p.readVarString('utf8')));
        break;
      case 5:
        items.push(p.readVarBytes());
        break;
    }
  }

  assert(p.readU8() === 0x0a);

  p.end();

  return {
    name: name || null,
    items: items
  };
}

function parseHeader(data) {
  return {
    magic: utils.readU32(data, 0),
    id: utils.readU32(data, 4),
    size: utils.readU32(data, 8)
  };
}

function parser(onPacket) {
  var waiting = HEADER_SIZE;
  var wait = 0;
  var buf = [];
  var read = 0;
  var header = null;

  return function parse(data) {
    var packet, rest;

    read += data.length;
    buf.push(data);

    if (read < waiting)
      return;

    buf = Buffer.concat(buf);

    if (buf.length > waiting) {
      packet = buf.slice(0, waiting);
      rest = buf.slice(waiting);
    } else {
      packet = buf;
    }

    if (!header) {
      header = parseHeader(packet);

      if (header.magic !== 0xdeadbeef) {
        buf = [];
        waiting = HEADER_SIZE;
        read = 0;
        utils.debug('Bad magic number: %d', header.magic);
        return;
      }

      buf = [];
      waiting = header.size;
      read = 0;

      if (rest)
        parse(rest);

      return;
    }

    try {
      packet = parseBody(packet);
    } catch (e) {
      utils.debug(e.stack + '');
      return;
    }

    onPacket(header.id, packet);

    buf = [];
    waiting = HEADER_SIZE;
    read = 0;
    header = null;

    if (rest)
      parse(rest);
  };
}

if (process.env.BCOIN_WORKER)
  workers.listen();
<commit_msg>remove json parsing.<commit_after>/**
 * workers.js - worker processes for bcoin
 * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
 * https://github.com/indutny/bcoin
 */

var bcoin = require('../bcoin');
var bn = require('bn.js');
var constants = bcoin.protocol.constants;
var utils = require('./utils');
var assert = utils.assert;
var BufferWriter = require('./writer');
var BufferReader = require('./reader');
var cp = require('child_process');
var workers = exports;

var HEADER_SIZE = 12;

/**
 * Master
 */

workers.MAX_WORKERS = +process.env.BCOIN_WORKERS || 30;
workers.TIMEOUT = 10000;
workers.children = {};
workers.uid = 0;

workers.spawn = function spawn(index) {
  var child;

  utils.debug('Spawning worker process: %d', index);

  child = cp.spawn(process.argv[0], [__filename], {
    stdio: ['pipe', 'pipe', 'inherit'],
    env: utils.merge({}, process.env, {
      BCOIN_WORKER: index + ''
    })
  });

  child.on('error', function(err) {
    utils.debug('Worker %d error: %s', index, err.message);
  });

  child.on('exit', function(code) {
    utils.debug('Worker %d exited: %s', index, code);
    if (workers.children[index] === child)
      delete workers.children[index];
  });

  child.on('close', function() {
    utils.debug('Worker %d closed', index);
    if (workers.children[index] === child)
      delete workers.children[index];
  });

  child.stdout.on('data', parser(function(id, body) {
    child.emit('completed ' + id, body.items[0], body.items[1]);
  }));

  return child;
};

// Load balance the workers based on job ID.
workers.alloc = function alloc(id) {
  var index = id % workers.MAX_WORKERS;
  if (!workers.children[index])
    workers.children[index] = workers.spawn(index);
  return workers.children[index];
};

workers.call = function call(method, args, callback) {
  var id = workers.uid++;
  var event, child, timeout;

  if (id > 0xffffffff) {
    workers.uid = 0;
    id = workers.uid++;
  }

  event = 'completed ' + id;
  child = workers.alloc(id);

  function listener(err, result) {
    clearTimeout(timeout);
    timeout = null;
    callback(err, result);
  }

  child.once(event, listener);

  timeout = setTimeout(function() {
    child.removeListener(event, listener);
    return callback(new Error('Worker timed out.'));
  }, workers.TIMEOUT);

  child.stdin.write(createPacket(id, method, args));
};

/**
 * Calls
 */

bcoin.tx.prototype.verifyAsync = function verifyAsync(index, force, flags, callback) {
  var tx;

  callback = utils.asyncify(callback);

  if (!force && this.ts !== 0)
    return callback(null, true);

  if (this.inputs.length === 0)
    return callback(null, false);

  if (this.isCoinbase())
    return callback(null, true);

  // Important: we need to serialize
  // the coins for the worker.
  tx = this.toExtended(true);

  return workers.call('verify', [tx, index, force, flags], callback);
};

/**
 * Child
 */

workers.listen = function listen() {
  bcoin.debug = function debug() {
    process.stderr.write('Worker %s: ', process.env.BCOIN_WORKER);
    return console.error.apply(console.error, arguments);
  };

  utils.debug = bcoin.debug;
  utils.print = bcoin.debug;

  process.stdin.on('data', parser(function(id, body) {
    var res;

    try {
      res = workers[body.name].apply(workers[body.name], body.items);
    } catch (e) {
      utils.debug(e.stack + '');
      return process.stdout.write(createPacket(id, null, [{
        message: e.message,
        stack: e.stack + ''
      }]));
    }

    return process.stdout.write(createPacket(id, null, [null, res]));
  }));
};

/**
 * Calls
 * The actual calls that are run
 * in a separate worker process.
 */

workers.verify = function verify(tx, index, force, flags) {
  tx = bcoin.tx.fromExtended(tx, true);
  return tx.verify(index, force, flags);
};

/**
 * Helpers
 */

function createPacket(id, name, items) {
  var p = new BufferWriter();
  var payload = createBody(name, items);
  p.writeU32(0xdeadbeef);
  p.writeU32(id);
  p.writeU32(payload.length);
  p.writeBytes(payload);
  return p.render();
}

function createBody(name, items) {
  var p = new BufferWriter();
  var i;

  if (name)
    p.writeVarString(name, 'ascii');
  else
    p.writeUIntv(0);

  p.writeUIntv(items.length);

  for (i = 0; i < items.length; i++) {
    switch (typeof items[i]) {
      case 'string':
        p.writeU8(1);
        p.writeVarString(items[i], 'utf8');
        break;
      case 'number':
        p.writeU8(2);
        p.write32(items[i]);
        break;
      case 'boolean':
        p.writeU8(3);
        p.writeU8(items[i] ? 1 : 0);
        break;
      case 'object':
      case 'undefined':
        if (items[i] == null) {
          p.writeU8(0);
        } else if (Buffer.isBuffer(items[i])) {
          p.writeU8(5);
          p.writeVarBytes(items[i]);
        } else {
          p.writeU8(4);
          p.writeVarString(JSON.stringify(items[i]), 'utf8');
        }
        break;
      default:
        assert(false, 'Bad type: ' + (typeof items[i]));
    }
  }

  p.writeU8(0x0a);

  return p.render();
}

function parseBody(data) {
  var p = new BufferReader(data, true);
  var name, count, i;
  var items = [];

  p.start();

  name = p.readVarString('ascii');
  count = p.readUIntv();

  for (i = 0; i < count; i++) {
    switch (p.readU8()) {
      case 0:
        items.push(null);
        break;
      case 1:
        items.push(p.readVarString('utf8'));
        break;
      case 2:
        items.push(p.read32());
        break;
      case 3:
        items.push(p.readU8() === 1);
        break;
      case 4:
        items.push(items.parse(p.readVarString('utf8')));
        break;
      case 5:
        items.push(p.readVarBytes());
        break;
    }
  }

  assert(p.readU8() === 0x0a);

  p.end();

  return {
    name: name || null,
    items: items
  };
}

function parseHeader(data) {
  return {
    magic: utils.readU32(data, 0),
    id: utils.readU32(data, 4),
    size: utils.readU32(data, 8)
  };
}

function parser(onPacket) {
  var waiting = HEADER_SIZE;
  var wait = 0;
  var buf = [];
  var read = 0;
  var header = null;

  return function parse(data) {
    var packet, rest;

    read += data.length;
    buf.push(data);

    if (read < waiting)
      return;

    buf = Buffer.concat(buf);

    if (buf.length > waiting) {
      packet = buf.slice(0, waiting);
      rest = buf.slice(waiting);
    } else {
      packet = buf;
    }

    if (!header) {
      header = parseHeader(packet);

      if (header.magic !== 0xdeadbeef) {
        buf = [];
        waiting = HEADER_SIZE;
        read = 0;
        utils.debug('Bad magic number: %d', header.magic);
        return;
      }

      buf = [];
      waiting = header.size;
      read = 0;

      if (rest)
        parse(rest);

      return;
    }

    try {
      packet = parseBody(packet);
    } catch (e) {
      utils.debug(e.stack + '');
      return;
    }

    onPacket(header.id, packet);

    buf = [];
    waiting = HEADER_SIZE;
    read = 0;
    header = null;

    if (rest)
      parse(rest);
  };
}

if (process.env.BCOIN_WORKER)
  workers.listen();
<|endoftext|>


<commit_before>"use strict";

module.exports = function (t, a) {
	var el;

	if (typeof document === "undefined") return;
	if (document.body == null) return;
	if (typeof document.body.offsetWidth !== "number") return;

	el = document.createElement("p");
	el.appendChild(document.createElement("div"));

	if ((el.onmousewheel === undefined) && (el.onwheel === undefined)) return;
	a(t.call(el, { width: 1000, height: 1000 }), el);
};
<commit_msg>style: prettier<commit_after>"use strict";

module.exports = function (t, a) {
	var el;

	if (typeof document === "undefined") return;
	if (document.body == null) return;
	if (typeof document.body.offsetWidth !== "number") return;

	el = document.createElement("p");
	el.appendChild(document.createElement("div"));

	if (el.onmousewheel === undefined && el.onwheel === undefined) return;
	a(t.call(el, { width: 1000, height: 1000 }), el);
};
<|endoftext|>


<commit_before>var enemy;

var enemyImg =  new Image();
enemyImg.onload = function(){
	  for (var i = 0; i < enemies.length; i++) {
        drawEnemy(enemies[i]);
    }
}

var ENEMY_WIDTH = 40;

var ENEMY_HEIGHT = 40;

var STARTING_ENEMY_HEALTH = 10;

var enemies = [];

var MULTIPLIER = 5;

function Enemy(xLocation, yLocation, width, height, startingHealth) {
    this.X = xLocation;
    this.Y = yLocation;
    this.Width = width;
    this.Height = height;
    this.StartingHealth = startingHealth;
    this.Health = this.StartingHealth;
    this.Alive = true;
}

function drawEnemies() {
    //console.log(enemies.length);
    for (var i = 0; i < enemies.length; i++) {
        drawEnemy(enemies[i]);
    }
}

function drawEnemy(enemy) {
    if (!enemy.Alive)
        return
    //console.log(enemy);
    //ctx.fillStyle = "#0000FF";
    //ctx.fillRect(enemy.X, enemy.Y, enemy.Width, enemy.Height);
	ctx.drawImage(enemyImg, enemy.X, enemy.Y, enemy.Width, enemy.Height);
	enemyImg.src = "img/enemy.png";
}

function createEnemies() {
    for (var i = 0; i < level; i++) {
        for (var j = 0; j < MULTIPLIER; j++) {
            createEnemyInSection(j, i);
        }
    }
}

function createEnemyInSection(section, row) {
    var xLoc = (section + 1) * sectionWidth;
    var yLoc = 0 - ((ENEMY_HEIGHT + 10) * row);
    var enemy = new Enemy(xLoc, yLoc, ENEMY_WIDTH, ENEMY_HEIGHT, STARTING_ENEMY_HEALTH);
    enemies.push(enemy);
}

function advanceEnemies() {
    for (var i = 0; i < enemies.length; i++) {
        enemies[i].Y = enemies[i].Y + 1;
    }
}

function decreaseEnemyHealth(i) {
    //console.log("hit");

    var enemy = enemies[i];
    enemy.Health = enemy.Health - 1;
    if (enemy.Health <= 0) {
        //console.log("Killed");
        enemies.splice(i, 1);

        if(enemies.length == 0){
            levelUp();
        }
    }
}
<commit_msg>third commit<commit_after>var enemy;

var enemyImg =  new Image();
enemyImg.onload = function(){
	  for (var i = 0; i < enemies.length; i++) {
        drawEnemy(enemies[i]);
    }
}

var ENEMY_WIDTH = 40;

var ENEMY_HEIGHT = 40;

var STARTING_ENEMY_HEALTH = 10;

var enemies = [];

var MULTIPLIER = 5;

function Enemy(xLocation, yLocation, width, height, startingHealth) {
    this.X = xLocation;
    this.Y = yLocation;
    this.Width = width;
    this.Height = height;
    this.StartingHealth = startingHealth;
    this.Health = this.StartingHealth;
    this.Alive = true;
}

function drawEnemies() {
    //console.log(enemies.length);
    for (var i = 0; i < enemies.length; i++) {
        drawEnemy(enemies[i]);
    }
}

function drawEnemy(enemy) {
    if (!enemy.Alive)
        return
    //console.log(enemy);
    //ctx.fillStyle = "#0000FF";
    //ctx.fillRect(enemy.X, enemy.Y, enemy.Width, enemy.Height);
	ctx.drawImage(enemyImg, enemy.X, enemy.Y, enemy.Width, enemy.Height);
	enemyImg.src = "img/enemy.png";
}

function createEnemies() {
    for (var i = 0; i < level; i++) {
        for (var j = 0; j < MULTIPLIER; j++) {
            createEnemyInSection(j, i);
        }
    }
}

function createEnemyInSection(section, row) {
    var xLoc = (section + 1) * sectionWidth;
    var yLoc = 0 - ((ENEMY_HEIGHT + 10) * row);
    var enemy = new Enemy(xLoc, yLoc, ENEMY_WIDTH, ENEMY_HEIGHT, STARTING_ENEMY_HEALTH);
    enemies.push(enemy);
}

function advanceEnemies() {
    for (var i = 0; i < enemies.length; i++) {
        enemies[i].Y = enemies[i].Y + 1;
    }
}

function decreaseEnemyHealth(i) {
    //console.log("hit");

    var enemy = enemies[i];
    enemy.Health = enemy.Health - 1;
    if (enemy.Health <= 0) {
        //console.log("Killed");
        enemies.splice(i, 1);
        makeStars(enemy.X, enemy.Y);
        if(enemies.length == 0){
            levelUp();
        }
    }
}
<|endoftext|>