<commit_before>'use strict';

const path = require('path');
const os = require('os');
const cliFormat = require('cli-format');

/**
 * Easy mode. Parses `ARGV` using the specified option schema. If any
 * arguments are missing or invalid, or if the `--help` option is
 * specified, usage will be printed and the process will exit.
 *
 * @alias parse
 * @param {object} config
 *      The parser configuration. See {@link parser}.
 *
 * @returns {object} the parsed options, keyed by option name
**/
function easyOptions(config) {
    const parser = createParser(config);
    const result = parser.parse(process.argv);
    if (result.help) {
        console.log(parser.usage());
        process.exit(0);
    } else if (result.version) {
        console.log(parser.version());
        process.exit(0);
    } else if (result.errors.length > 0) {
        console.error(result.errors[0]);
        console.error(parser.usage());
        process.exit(1);
    }
    return result.options;
}

/**
 * Creates a parser with the specified option schema.
 *
 * @alias parser
 * @param {object} config
 * @param {string} [config.info]
 *      A description of the program to be printed with the usage text.
 * @param {string} [config.version]
 *      The program version, for the `--version` option.
 * @param {object} [config.options]
 *      The options. Each key is the name of an option that will be
 *      returned in the parse result. The option names double as the
 *      long-name form of each option. Each option can have the following
 *      properties, all of which are optional:
 *
 *    - `type`: "string" or "boolean" (default: "boolean")
 *    - `short`: the short option character (default: first character of
 *      long name, if there is no conflict)
 *    - `required`: A boolean indicating the field is required. Only
 *      meaningful for strings. (default: false)
 *    - `description`: The description, which will be printed in the usage
 *      text.
 * @param {array<string>} [config.positional]
 *      The names of required positional arguments.
 * @returns {Parser} the parser
**/
function createParser({ info, version, options = {}, positional = [] }) {
    const schema = createSchema({ options, positional, version });

    /**
     * @memberof Parser
     * @instance
     *
     * Parses an `ARGV` array and returns an object representing the result
     * of parsing.
     *
     * @param {array<string>} argv
     *      The `ARGV` array, generally from `process.argv`.
     * @returns {ParsingResult} the parsing result
    **/
    function parse(argv) {
        const components = parseComponents(argv);
        return processComponents(components, schema);
    }

    /**
     * @memberof Parser
     * @instance
     *
     * Gets a human-friendly string containing the usage info, generated
     * from the option schema. You can display this with `console.error`
     * or similar method.
     * @param {string} [argv1]
     *      The name of this program to display in the usage. The default
     *      value is `process.argv[1]`, which is generally ideal.
     * @returns {string} the usage text
    **/
    function usage(argv1 = process.argv[1]) {
        const scriptName = path.basename(argv1);
        return generateUsage(info, schema, scriptName);
    }

    /**
     * @memberof Parser
     * @instance
     * @alias version
     *
     * Gets the version info string.
     * @param {string} [argv1]
     *      The script name. Defaults to the value of `process.argv[1]`.
     * @returns {string} the version text
    **/
    function formatVersion(argv1 = process.argv[1]) {
        const scriptName = path.basename(argv1);
        if (version) {
            return `${scriptName} ${version}`;
        } else {
            return scriptName;
        }
    }

    /**
     * @namespace Parser
    **/
    return {
        parse,
        usage,
        version: formatVersion
    };
}

function createSchema({ options, positional, version }) {
    const supportedTypes = [ 'string', 'boolean' ];
    const schema = { options: [], positional: [] };

    Object.keys(options).forEach(key => {
        const option = options[key];
        const type = option.type || 'boolean';
        const scheme = {
            name: key,
            type,
            description: option.description,
            long: key,
            short: option.short,
            required: Boolean(option.required)
        };

        if (!supportedTypes.includes(type)) {
            throw new Error(`Argument type for ${key} must be one of: ${supportedTypes.join(', ')}`);
        }

        if (option.short) {
            if (option.short.length > 1) {
                throw new Error(`Illegal short option -${option.short} must be 1 character.`);
            }
            if (schema.options.some(s => s.short === option.short)) {
                throw new Error(`Short option -${option.short} specified twice`);
            }
        }

        schema.options.push(scheme);
    });

    if (!schema.options.some(s => s.long === 'help')) {
        // Auto-generate a help option
        const help = {
            name: 'help',
            type: 'help',
            description: 'Show this message',
            long: 'help',
            required: false
        };
        if (!schema.options.some(s => s.short === 'h')) {
            help.short = 'h';
        }
        schema.options.push(help);
    }

    if (version && !schema.options.some(s => s.long === 'version')) {
        // Auto-generate a version option
        const version = {
            name: 'version',
            type: 'version',
            description: 'Print version and exit',
            long: 'version',
            required: false
        };
        if (!schema.options.some(s => s.short === 'v')) {
            version.short = 'v';
        }
        schema.options.push(version);
    }

    if (positional && positional.length) {
        positional.forEach(key => {
            if (schema.options.some(s => s.name === key)) {
                throw new Error(`Option name ${key} specified twice`);
            }
            schema.positional.push({
                name: key
            });
        });
    }

    // Automatically create short options where possible.
    schema.options.filter(s => !s.short).forEach(scheme => {
        const autoshort = scheme.long.charAt(0);
        if (!schema.options.some(s => s.short === autoshort)) {
            scheme.short = autoshort;
        }
    });

    return schema;
}

function parseComponents(argv) {
    if (!(argv && argv.length)) {
        return [];
    }
    const args = argv.slice(2);

    const matchers = [
        parseLongOption,
        parseShortOptionSet,
        parseShortOption,
        // TODO
        // parseOptionTerminator
        parseValue
    ];

    function parseLongOption(arg) {
        let results = [];
        const match = /^--([^=]+)(=(.*))?/.exec(arg);
        if (match) {
            results.push({
                type: 'long',
                value: match[1],
                raw: arg
            });
            if (match[3]) {
                results.push({
                    type: 'value',
                    value: match[3],
                    raw: match[3],
                    attached: true
                });
            }
        }
        return results;
    }

    function parseShortOptionSet(arg) {
        const match = /^-([^\-\s]{2,})/.exec(arg);
        if (match) {
            return match[1].split('').map(char => {
                return {
                    type: 'short',
                    value: char,
                    raw: `-${char}`
                };
            });
        }
        return [];
    }

    function parseShortOption(arg) {
        const match = /^-([^\-\s])/.exec(arg);
        if (match) {
            return [{
                type: 'short',
                value: match[1],
                raw: arg
            }];
        }
        return [];
    }

    function parseValue(arg) {
        return [{
            type: 'value',
            value: arg,
            raw: arg
        }];
    }

    function componentsFromArg(arg) {
        for (let i = 0, len = matchers.length; i < len; i++) {
            const matcher = matchers[i];
            const components = matcher(arg);
            if (components.length > 0) {
                return components;
            }
        }
    }

    const components = args.reduce((components, arg) => {
        components.push(...componentsFromArg(arg));
        return components;
    }, []);

    return components;
}

function processComponents(components, schema) {

    function findScheme(component) {
        return schema.options.find(scheme => {
            const name = scheme[component.type];
            return name && name === component.value;
        });
    }

    /**
     * @typedef ParsingResult
     *
     * @property {object} options
     *      the parsed options
     * @property {boolean} help
     *      true if the `--help` option was invoked
     * @property {boolean} version
     *      true if the `--version` option was invoked
     * @property {array<string>}
     *      contains parsing errors
    **/
    const result = {
        options: {},
        help: false,
        version: false,
        errors: []
    };

    const consumers = {
        string: function(component, scheme) {
            const next = components.shift();
            if (!(next && next.type === 'value')) {
                result.errors.push(`Argument ${component.raw} requires a string value`);
            } else {
                result.options[scheme.name] = next.value;
            }
        },

        boolean: function(component, scheme) {
            result.options[scheme.name] = !result.options[scheme.name];

            const next = components[0];
            if (next && next.attached) {
                result.errors.push(`Argument ${component.raw} is boolean and does not take a value`);
            }
        },

        help: function(component, scheme) {
            result.help = true;
        },

        version: function(component, scheme) {
            result.version = true;
        }
    };

    const positional = schema.positional.slice();

    while (components.length > 0) {
        const component = components.shift();
        if (component.type === 'value') {
            const scheme = positional.shift();
            if (!scheme) {
                result.errors.push("Unexpected extra argument");
            } else {
                result.options[scheme.name] = component.value;
            }
        } else {
            const scheme = findScheme(component);
            if (!scheme) {
                result.errors.push("Unrecognized argument: " + component.raw);
            } else {
                const consume = consumers[scheme.type];
                consume(component, scheme);
            }
        }
    }

    // Ensure booleans are present
    schema.options.filter(s => s.type === 'boolean').forEach(scheme => {
        result.options[scheme.name] = Boolean(result.options[scheme.name]);
    });

    schema.options.filter(s => s.required).forEach(scheme => {
        if (!result.options[scheme.name]) {
            result.errors.push(`Missing required option --${scheme.long}`);
        }
    });

    return result;
}

function generateUsage(info, schema, scriptName) {
    let buf = '';
    const eol = os.EOL;

    if (info) {
        buf += info;
        buf += eol;
    }

    buf += `Usage: ${scriptName} [options]`;
    buf += schema.positional.map(scheme => ` <${scheme.name}>`).join('');
    buf += eol;

    const leftColumnWidth = function() {
        const prefix = '  -X, --'.length;
        const longestOption = schema.options.reduce((max, scheme) => Math.max(max, scheme.long.length), 0);
        return prefix + longestOption;
    }();

    const leftColumn = schema.options
        .map(scheme => {
            const short = scheme.short ? `-${scheme.short}` : '  ';
            return `  ${short}, --${scheme.long}`;
        })
        .join('\n');
    const rightColumn = schema.options
        .map(scheme => scheme.description || '')
        .join('\n');
    const columns = [
        { content: leftColumn, width: leftColumnWidth },
        rightColumn
    ];
    buf += cliFormat.columns.wrap(columns, { paddingMiddle: '    ' });

    return buf;
}

module.exports = {
    parse: easyOptions,
    parser: createParser,
};
<commit_msg>remove extra comma when no short option<commit_after>'use strict';

const path = require('path');
const os = require('os');
const cliFormat = require('cli-format');

/**
 * Easy mode. Parses `ARGV` using the specified option schema. If any
 * arguments are missing or invalid, or if the `--help` option is
 * specified, usage will be printed and the process will exit.
 *
 * @alias parse
 * @param {object} config
 *      The parser configuration. See {@link parser}.
 *
 * @returns {object} the parsed options, keyed by option name
**/
function easyOptions(config) {
    const parser = createParser(config);
    const result = parser.parse(process.argv);
    if (result.help) {
        console.log(parser.usage());
        process.exit(0);
    } else if (result.version) {
        console.log(parser.version());
        process.exit(0);
    } else if (result.errors.length > 0) {
        console.error(result.errors[0]);
        console.error(parser.usage());
        process.exit(1);
    }
    return result.options;
}

/**
 * Creates a parser with the specified option schema.
 *
 * @alias parser
 * @param {object} config
 * @param {string} [config.info]
 *      A description of the program to be printed with the usage text.
 * @param {string} [config.version]
 *      The program version, for the `--version` option.
 * @param {object} [config.options]
 *      The options. Each key is the name of an option that will be
 *      returned in the parse result. The option names double as the
 *      long-name form of each option. Each option can have the following
 *      properties, all of which are optional:
 *
 *    - `type`: "string" or "boolean" (default: "boolean")
 *    - `short`: the short option character (default: first character of
 *      long name, if there is no conflict)
 *    - `required`: A boolean indicating the field is required. Only
 *      meaningful for strings. (default: false)
 *    - `description`: The description, which will be printed in the usage
 *      text.
 * @param {array<string>} [config.positional]
 *      The names of required positional arguments.
 * @returns {Parser} the parser
**/
function createParser({ info, version, options = {}, positional = [] }) {
    const schema = createSchema({ options, positional, version });

    /**
     * @memberof Parser
     * @instance
     *
     * Parses an `ARGV` array and returns an object representing the result
     * of parsing.
     *
     * @param {array<string>} argv
     *      The `ARGV` array, generally from `process.argv`.
     * @returns {ParsingResult} the parsing result
    **/
    function parse(argv) {
        const components = parseComponents(argv);
        return processComponents(components, schema);
    }

    /**
     * @memberof Parser
     * @instance
     *
     * Gets a human-friendly string containing the usage info, generated
     * from the option schema. You can display this with `console.error`
     * or similar method.
     * @param {string} [argv1]
     *      The name of this program to display in the usage. The default
     *      value is `process.argv[1]`, which is generally ideal.
     * @returns {string} the usage text
    **/
    function usage(argv1 = process.argv[1]) {
        const scriptName = path.basename(argv1);
        return generateUsage(info, schema, scriptName);
    }

    /**
     * @memberof Parser
     * @instance
     * @alias version
     *
     * Gets the version info string.
     * @param {string} [argv1]
     *      The script name. Defaults to the value of `process.argv[1]`.
     * @returns {string} the version text
    **/
    function formatVersion(argv1 = process.argv[1]) {
        const scriptName = path.basename(argv1);
        if (version) {
            return `${scriptName} ${version}`;
        } else {
            return scriptName;
        }
    }

    /**
     * @namespace Parser
    **/
    return {
        parse,
        usage,
        version: formatVersion
    };
}

function createSchema({ options, positional, version }) {
    const supportedTypes = [ 'string', 'boolean' ];
    const schema = { options: [], positional: [] };

    Object.keys(options).forEach(key => {
        const option = options[key];
        const type = option.type || 'boolean';
        const scheme = {
            name: key,
            type,
            description: option.description,
            long: key,
            short: option.short,
            required: Boolean(option.required)
        };

        if (!supportedTypes.includes(type)) {
            throw new Error(`Argument type for ${key} must be one of: ${supportedTypes.join(', ')}`);
        }

        if (option.short) {
            if (option.short.length > 1) {
                throw new Error(`Illegal short option -${option.short} must be 1 character.`);
            }
            if (schema.options.some(s => s.short === option.short)) {
                throw new Error(`Short option -${option.short} specified twice`);
            }
        }

        schema.options.push(scheme);
    });

    if (!schema.options.some(s => s.long === 'help')) {
        // Auto-generate a help option
        const help = {
            name: 'help',
            type: 'help',
            description: 'Show this message',
            long: 'help',
            required: false
        };
        if (!schema.options.some(s => s.short === 'h')) {
            help.short = 'h';
        }
        schema.options.push(help);
    }

    if (version && !schema.options.some(s => s.long === 'version')) {
        // Auto-generate a version option
        const version = {
            name: 'version',
            type: 'version',
            description: 'Print version and exit',
            long: 'version',
            required: false
        };
        if (!schema.options.some(s => s.short === 'v')) {
            version.short = 'v';
        }
        schema.options.push(version);
    }

    if (positional && positional.length) {
        positional.forEach(key => {
            if (schema.options.some(s => s.name === key)) {
                throw new Error(`Option name ${key} specified twice`);
            }
            schema.positional.push({
                name: key
            });
        });
    }

    // Automatically create short options where possible.
    schema.options.filter(s => !s.short).forEach(scheme => {
        const autoshort = scheme.long.charAt(0);
        if (!schema.options.some(s => s.short === autoshort)) {
            scheme.short = autoshort;
        }
    });

    return schema;
}

function parseComponents(argv) {
    if (!(argv && argv.length)) {
        return [];
    }
    const args = argv.slice(2);

    const matchers = [
        parseLongOption,
        parseShortOptionSet,
        parseShortOption,
        // TODO
        // parseOptionTerminator
        parseValue
    ];

    function parseLongOption(arg) {
        let results = [];
        const match = /^--([^=]+)(=(.*))?/.exec(arg);
        if (match) {
            results.push({
                type: 'long',
                value: match[1],
                raw: arg
            });
            if (match[3]) {
                results.push({
                    type: 'value',
                    value: match[3],
                    raw: match[3],
                    attached: true
                });
            }
        }
        return results;
    }

    function parseShortOptionSet(arg) {
        const match = /^-([^\-\s]{2,})/.exec(arg);
        if (match) {
            return match[1].split('').map(char => {
                return {
                    type: 'short',
                    value: char,
                    raw: `-${char}`
                };
            });
        }
        return [];
    }

    function parseShortOption(arg) {
        const match = /^-([^\-\s])/.exec(arg);
        if (match) {
            return [{
                type: 'short',
                value: match[1],
                raw: arg
            }];
        }
        return [];
    }

    function parseValue(arg) {
        return [{
            type: 'value',
            value: arg,
            raw: arg
        }];
    }

    function componentsFromArg(arg) {
        for (let i = 0, len = matchers.length; i < len; i++) {
            const matcher = matchers[i];
            const components = matcher(arg);
            if (components.length > 0) {
                return components;
            }
        }
    }

    const components = args.reduce((components, arg) => {
        components.push(...componentsFromArg(arg));
        return components;
    }, []);

    return components;
}

function processComponents(components, schema) {

    function findScheme(component) {
        return schema.options.find(scheme => {
            const name = scheme[component.type];
            return name && name === component.value;
        });
    }

    /**
     * @typedef ParsingResult
     *
     * @property {object} options
     *      the parsed options
     * @property {boolean} help
     *      true if the `--help` option was invoked
     * @property {boolean} version
     *      true if the `--version` option was invoked
     * @property {array<string>}
     *      contains parsing errors
    **/
    const result = {
        options: {},
        help: false,
        version: false,
        errors: []
    };

    const consumers = {
        string: function(component, scheme) {
            const next = components.shift();
            if (!(next && next.type === 'value')) {
                result.errors.push(`Argument ${component.raw} requires a string value`);
            } else {
                result.options[scheme.name] = next.value;
            }
        },

        boolean: function(component, scheme) {
            result.options[scheme.name] = !result.options[scheme.name];

            const next = components[0];
            if (next && next.attached) {
                result.errors.push(`Argument ${component.raw} is boolean and does not take a value`);
            }
        },

        help: function(component, scheme) {
            result.help = true;
        },

        version: function(component, scheme) {
            result.version = true;
        }
    };

    const positional = schema.positional.slice();

    while (components.length > 0) {
        const component = components.shift();
        if (component.type === 'value') {
            const scheme = positional.shift();
            if (!scheme) {
                result.errors.push("Unexpected extra argument");
            } else {
                result.options[scheme.name] = component.value;
            }
        } else {
            const scheme = findScheme(component);
            if (!scheme) {
                result.errors.push("Unrecognized argument: " + component.raw);
            } else {
                const consume = consumers[scheme.type];
                consume(component, scheme);
            }
        }
    }

    // Ensure booleans are present
    schema.options.filter(s => s.type === 'boolean').forEach(scheme => {
        result.options[scheme.name] = Boolean(result.options[scheme.name]);
    });

    schema.options.filter(s => s.required).forEach(scheme => {
        if (!result.options[scheme.name]) {
            result.errors.push(`Missing required option --${scheme.long}`);
        }
    });

    return result;
}

function generateUsage(info, schema, scriptName) {
    let buf = '';
    const eol = os.EOL;

    if (info) {
        buf += info;
        buf += eol;
    }

    buf += `Usage: ${scriptName} [options]`;
    buf += schema.positional.map(scheme => ` <${scheme.name}>`).join('');
    buf += eol;

    const leftColumnWidth = function() {
        const prefix = '  -X, --'.length;
        const longestOption = schema.options.reduce((max, scheme) => Math.max(max, scheme.long.length), 0);
        return prefix + longestOption;
    }();

    const leftColumn = schema.options
        .map(scheme => {
            const short = scheme.short ? `-${scheme.short},` : '   ';
            return `  ${short} --${scheme.long}`;
        })
        .join('\n');
    const rightColumn = schema.options
        .map(scheme => scheme.description || '')
        .join('\n');
    const columns = [
        { content: leftColumn, width: leftColumnWidth },
        rightColumn
    ];
    buf += cliFormat.columns.wrap(columns, { paddingMiddle: '    ' });

    return buf;
}

module.exports = {
    parse: easyOptions,
    parser: createParser,
};
<|endoftext|>


<commit_before>var AppBar = require('essence-appbar');
var BottomSheets = require('essence-bottomsheet');
var Btn = require('essence-button');
var Card = require('essence-card');
var Core = require('essence-core');
var DataTable = require('essence-data-table');
var Dialog = require('essence-dialog');
var Icon = require('essence-icon');
var Image = require('essence-image');
var Input = require('essence-input');
var List = require('essence-list');
var Menu = require('essence-menu');
var Navigation = require('essence-navigation');
var Paper = require('essence-paper');
var Progress = require('essence-progress');
var Slider = require('essence-slider');
var SnackBar = require('essence-snackbar');
var Stepper = require('essence-stepper');
var Switch = require('essence-switch');
var Tab = require('essence-tab');
var Toast = require('essence-toast');
var Tooltip = require('essence-tooltip');
var TouchPad = require('essence-touchpad');

exports.AppBar = AppBar;
exports.BottomSheets = BottomSheets;
exports.Btn = Btn;
exports.Card = Card.Card;
exports.CardHeader = Card.CardHeader;
exports.CardContent = Card.CardContent;
exports.CardFooter = Card.CardFooter;
exports.Dialog = Dialog.Dialog;
exports.DialogHeader = Dialog.DialogHeader;
exports.DialogContent = Dialog.DialogContent;
exports.DialogFooter = Dialog.DialogFooter;
exports.Core = Core;
exports.Block = Core.Block;
exports.Text = Core.Text;
exports.Divider = Core.Divider;
exports.Utils = Core.Utils;
exports.DataTable = DataTable;
exports.Icon = Icon;
exports.Image = Image;
exports.Input = Input;
exports.List = List.List;
exports.ListItem = List.ListItem;
exports.Menu = Menu;
exports.Navigation = Navigation;
exports.Paper = Paper;
exports.Progress = Progress;
exports.Slider = Slider;
exports.SnackBar = SnackBar;
exports.Stepper = Stepper;
exports.Switch = Switch;
exports.Tab = Tab;
exports.Toast = Toast;
exports.Tooltip = Tooltip;
exports.TouchPad = TouchPad;<commit_msg>Chip components included in react-essence<commit_after>var AppBar = require('essence-appbar');
var BottomSheets = require('essence-bottomsheet');
var Btn = require('essence-button');
var Card = require('essence-card');
var Chip = require('essence-chip');
var Core = require('essence-core');
var DataTable = require('essence-data-table');
var Dialog = require('essence-dialog');
var Icon = require('essence-icon');
var Image = require('essence-image');
var Input = require('essence-input');
var List = require('essence-list');
var Menu = require('essence-menu');
var Navigation = require('essence-navigation');
var Paper = require('essence-paper');
var Progress = require('essence-progress');
var Slider = require('essence-slider');
var SnackBar = require('essence-snackbar');
var Stepper = require('essence-stepper');
var Switch = require('essence-switch');
var Tab = require('essence-tab');
var Toast = require('essence-toast');
var Tooltip = require('essence-tooltip');
var TouchPad = require('essence-touchpad');

exports.AppBar = AppBar;
exports.BottomSheets = BottomSheets;
exports.Btn = Btn;
exports.Card = Card.Card;
exports.CardHeader = Card.CardHeader;
exports.CardContent = Card.CardContent;
exports.CardFooter = Card.CardFooter;
exports.Chip = Chip;
exports.Dialog = Dialog.Dialog;
exports.DialogHeader = Dialog.DialogHeader;
exports.DialogContent = Dialog.DialogContent;
exports.DialogFooter = Dialog.DialogFooter;
exports.Core = Core;
exports.Block = Core.Block;
exports.Text = Core.Text;
exports.Divider = Core.Divider;
exports.Utils = Core.Utils;
exports.DataTable = DataTable;
exports.Icon = Icon;
exports.Image = Image;
exports.Input = Input;
exports.List = List.List;
exports.ListItem = List.ListItem;
exports.Menu = Menu;
exports.Navigation = Navigation;
exports.Paper = Paper;
exports.Progress = Progress;
exports.Slider = Slider;
exports.SnackBar = SnackBar;
exports.Stepper = Stepper;
exports.Switch = Switch;
exports.Tab = Tab;
exports.Toast = Toast;
exports.Tooltip = Tooltip;
exports.TouchPad = TouchPad;<|endoftext|>


<commit_before><commit_msg>Stuff<commit_after>var koa = require('koa');
var Router = require('koa-router');

var app = koa();
app.listen(3000);
console.log("Listening on port 3000");<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-cli-firebase-hosting'
};
<commit_msg>Expose firebase command<commit_after>/* jshint node: true */
'use strict';

var path = require('path');
module.exports = {
  name: 'ember-cli-firebase-hosting',

  includedCommands: function() {
    return {
      'firebase': require('./lib/commands/firebase')
    }
  },

  blueprintsPath: function() {
    return path.join(__dirname, 'blueprints');
  }
}
<|endoftext|>


<commit_before>//A proof of concept.
//No code structure whatsoever applied
var http = require('http');
var NRP = require('node-redis-pubsub')
  , config = { port: 6379       // Port of your remote Redis server
             , host: '10.129.123.83' // Redis server host, defaults to 127.0.0.1
             }
  , nrp = new NRP(config);      // This is the NRP client
var uuid = require('node-uuid');

var responseObjects = {};

http.createServer(function (req, res) {
	var t1 = Date.now();
	var topicName   = req.method+':'+req.headers.host+':'+req.url;
	var requestUUID = uuid.v1();

	client.rpush('request|'+topicName, {
		requestUUID: requestUUID,
		data: 'Test!',
		method: req.method,
		host: req.headers.host,
		uri: req.url,
		timing: {
			t1: t1
		}
	}, function(err, reply){
		nrp.emit('request|'+topicName);	//Notify workers to fetch the new task/request from list
	});

	responseObjects[requestUUID] = res;
}).listen(80);

nrp.on('response|*', function (data, channel) {
	var requestUUID = data.requestUUID;

	responseObjects[requestUUID].end(data.response);
	data.timing['t5'] = Date.now();
	console.log('total:'+(data.timing['t5']-data.timing['t1'])+', transit delay: '+ ((data.timing['t5']-data.timing['t1'])-(data.timing['t4']-data.timing['t3']))+', internal request: '+ ((data.timing['t4']-data.timing['t3'])));
	//console.log(data.timing);
});
<commit_msg>Using the combination of PubSub channel, HashMap key/value and Lists to build the queue.<commit_after>//A proof of concept.
//No code structure whatsoever applied

var http = require('http');
var redis = require('redis');
var redisClient = redis.createClient(6379, '10.129.123.83');
var NRP = require('node-redis-pubsub')
  , config = { port: 6379       // Port of your remote Redis server
             , host: '10.129.123.83' // Redis server host, defaults to 127.0.0.1
             }
  , nrp = new NRP(config);      // This is the NRP client
var uuid = require('node-uuid');

var responseObjects = {};

http.createServer(function (req, res) {
	var timing      = {};
	timing['gatewayGotRequest'] = Date.now();
	var topicName   = req.method+':'+req.headers.host+':'+req.url;
	var requestUUID = uuid.v1();

	responseObjects[requestUUID] = res;

	redisClient.rpush('request|'+topicName+"-queue", requestUUID, function(err, reply){

		timing['gatewayQueuePush'] = Date.now();
		redisClient.hmset('request-'+requestUUID, {
			requestUUID: requestUUID,
			data: 'Test!',
			method: req.method,
			host: req.headers.host,
			uri: req.url
		}, function(err, reply){
			timing['gatewayHashSet'] = Date.now();
			timing['gatewaySentNotify'] = Date.now();
			nrp.emit('request|'+topicName, {timing: timing});	//Notify workers to fetch the new task/request from list
		});
	});
}).listen(80);

nrp.on('response|*', function (data, channel) {
	var requestUUID = data.requestUUID;

	if(typeof responseObjects[requestUUID] !== "undefined"){
		//console.log(data);
		//console.log('data:', data);
		//console.log('objs:', responseObjects);
		responseObjects[requestUUID].end(data.response);
		data.timing['gatewayResponseReady'] = Date.now();
		//console.log(data.timing);
	}
	else{
		//console.log(requestUUID);
		//console.log(responseObjects);
	}
	console.log('total:'+(data.timing['gatewayResponseReady']-data.timing['gatewayGotRequest'])+', transit delay: '+ ((data.timing['gatewayResponseReady']-data.timing['gatewayGotRequest'])-(data.timing['serviceGotHttp']-data.timing['serviceStartHttp']))+', internal request: '+ ((data.timing['serviceGotHttp']-data.timing['serviceStartHttp'])));
	//console.log(data.timing);
});
<|endoftext|>


<commit_before>var http = require('http');
var https = require('https');
var fs = require('fs');
var express = require('express');
//var u2f = require('node-u2f');
var u2f = require('u2f');
var session = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var TOTPStrategy = require('passport-totp').Strategy;
var LocalStrategy = require('passport-local').Strategy;
var morgan = require('morgan');
var path = require('path');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
var base32 = require('thirty-two');
var flash = require('connect-flash');

var Account = require('./models/account');
var G2FA = require('./models/g2fa');
var U2F_Reg = require('./models/u2f');

var port = (process.env.VCAP_APP_PORT || process.env.PORT ||3000);
var host = (process.env.VCAP_APP_HOST || '0.0.0.0');
var mongo_url = (process.env.MONGO_URL || 'mongodb://localhost/users');

if (process.env.VCAP_SERVICES) {
	var services = JSON.parse(process.env.VCAP_SERVICES);

	for (serviceName in services) {
		if (serviceName.match('^mongo')) {
			var creds = services[serviceName][0]['credentials'];
			mongo_url = creds.url;
		} else {
			console.log("no database found");
		}
	}
}

var app_id = 'https://localhost:' + port;

if (process.env.VCAP_APPLICATION) {
	var application = JSON.parse(process.env.VCAP_APPLICATION);

	var app_uri = application['application_uris'][0];

	app_id = 'https://' + app_uri;
}

var cookieSecret = 'zsemjy';

var app = express();

app.set('view engine', 'ejs');
app.set('trust proxy', 1);
app.use(morgan("combined"));
app.use(cookieParser(cookieSecret));
app.use(flash());
app.use(session({
  // genid: function(req) {
  //   return genuuid() // use UUIDs for session IDs
  // },
  secret: cookieSecret,
  resave: false,
  saveUninitialized: false,
  cookie: {
  	secure: true
  }
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(flash);
app.use(passport.initialize());
app.use(passport.session());

function requireHTTPS(req, res, next) {
	if (req.get('X-Forwarded-Proto') === 'http') {
        //FYI this should work for local development as well
        var url = 'https://' + req.get('host');
        if (req.get('host') === 'localhost') {
        	url += ':' + port;
        }
        url  += req.url;
        return res.redirect(url);
    }
    next();
}

app.use(requireHTTPS);

app.use('/',express.static('static'));

passport.use(new LocalStrategy(Account.authenticate()));
passport.use(new TOTPStrategy(function(user, done){
	G2FA.findOne({'username': user.username}, function(err, user){
		if (err) {
			return done(err);
		}
		return done(null, user.secret, 30);
	});
}));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

mongoose.connect(mongo_url);

app.get('/', function(req,res){
	res.render('index', { message: req.flash('info') });
});

app.get('/login', function(req,res){
	res.render('login',{ message: req.flash('info') });
});

app.post('/login', passport.authenticate('local', { failureRedirect: '/login', successRedirect: '/2faCheck', failureFlash: true }));

app.get('/2faCheck', ensureAuthenticated, function(req,res){
	res.render('check2fa',{ message: req.flash('info') });
});

app.get('/newUser', function(req,res){
	res.render('register', { message: req.flash('info') });
});

app.post('/newUser', function(req,res){
	Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
		if (err) {
			console.log(err);
			return res.status(400).send(err.message);
		}

		passport.authenticate('local')(req, res, function () {
			console.log("created new user %s", req.body.username);
            res.status(201).send();
        });

	});
});

app.get('/setup2FA', ensureAuthenticated, function(req,res){
	res.render('setup2fa',{ message: req.flash('info') });
});

app.get('/setupG2FA', ensureAuthenticated, function(req,res){
	G2FA.findOne({'username': req.user.username}, function(err,user){
		if (err) {
			res.status(400).send(err);
		} else {
			var secret;
			if (user !== null) {
				secret = user.secret;
			} else {
				//generate random key
				secret = genSecret(10);
				var newToken = new G2FA({username: req.user.username, secret: secret});
				newToken.save(function(err,tok){

				});
			}
			var encodedKey = base32.encode(secret);
			var otpUrl = 'otpauth://totp/2FADemo:' + req.user.username + '?secret=' + encodedKey + '&period=30&issuer=2FADemo';
			var qrImage = 'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=' + encodeURIComponent(otpUrl);
			res.send(qrImage);
		}
	});
});

app.post('/loginG2FA', ensureAuthenticated, passport.authenticate('totp'), function(req, res){
	req.session.secondFactor = 'g2fa';
	res.send();
});

app.get('/registerU2F', ensureAuthenticated, function(req,res){
	try{
		//var registerRequest = u2f.startRegistration(app_id);
		var registerRequest = u2f.request(app_id);
		req.session.registerRequest = registerRequest;
		res.send(registerRequest);
	} catch (err) {
		console.log(err);
		res.status(400).send();
	}

});

app.post('/registerU2F', ensureAuthenticated, function(req,res){
	var registerResponse = req.body;
	//console.log("Registration response %j", registerResponse);
	var registerRequest = req.session.registerRequest;
	//console.log("Registration request %j", registerRequest);
	var user = req.user.username;
	try {
		//var registration = u2f.finishRegistration(registerRequest,registerResponse);
		var registration = u2f.checkRegistration(registerRequest,registerResponse);
		//console.log("Processed registration %j", registration)
		var reg = new U2F_Reg({username: user, deviceRegistration: registration });
		reg.save(function(err,r){

		});
		res.send();
	} catch (err) {
		console.log(err);
		res.status(400).send();
	}
});

// function debug(req,res,next) {
// 	console.log("DEBUG-" + req.body.code);
// 	return next();
// }

app.get('/authenticateU2F', ensureAuthenticated, function(req,res){
	U2F_Reg.findOne({username: req.user.username}, function(err, reg){
		if (err) {
			res.status(400).send(err);
		} else {
			if (reg !== null) {
				//console.log("authU2F using - %j", reg.deviceRegistration);
				//var signRequest = u2f.startAuthentication(app_id, reg.deviceRegistration);
				var signRequest = u2f.request(app_id, reg.deviceRegistration.keyHandle);
				req.session.signrequest = signRequest;
				req.session.deviceRegistration = reg.deviceRegistration;
				//console.log("sending signReq %j", signRequest);
				res.send(signRequest);
			}
		}
	});
});

app.post('/authenticateU2F', ensureAuthenticated, function(req,res){
	var signResponse = req.body;
	var signRequest = req.session.signrequest;
	var deviceRegistration = req.session.deviceRegistration;
	try {
		//var result = u2f.finishAuthentication(signRequest, signResponse, deviceRegistration);
		var result = u2f.checkSignature(signRequest, signResponse, deviceRegistration.publicKey);
		if (result.successful) {
			req.session.secondFactor = 'u2f';
			res.send();
		} else {
			res.status(400).send();
		}
	} catch (err) {
		console.log(err);
		res.status(400).send();
	}
});

app.get('/logout', function(req,res){
	req.logout();
	req.session.secondFactor = undefined;
	res.redirect('/login')
});

app.get('/user', ensureAuthenticated, ensure2fa, function(req, res) {
	res.render('user',{name: req.user.username, message: req.flash('info')});
});

function ensureAuthenticated(req,res,next) {
	if (req.isAuthenticated()) {
    	return next();
	} else {
		res.redirect('/login');
	}
}

function ensure2fa(req, res, next) {
	if (req.session.secondFactor) {
		return next();
	}
	res.redirect('/2faCheck');
}

function genSecret(len) {
	var buf = []
	, chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
	, charlen = chars.length;

	for (var i = 0; i < len; ++i) {
		buf.push(chars[getRandomInt(0, charlen - 1)]);
	}

	return buf.join('');
};

function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

var server = http.Server(app);
if (app_id.match(/^https:\/\/localhost:/)) {
	var options = {
		key: fs.readFileSync('server.key'),
		cert: fs.readFileSync('server.crt')
	};
	server = https.createServer(options, app);
}

server.listen(port, host, function(){
	console.log('App listening on  %s:%d!', host, port);
	console.log("App_ID -> %s", app_id);
});

<commit_msg>Remove commented out code<commit_after>var http = require('http');
var https = require('https');
var fs = require('fs');
var express = require('express');
var u2f = require('u2f');
var session = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var TOTPStrategy = require('passport-totp').Strategy;
var LocalStrategy = require('passport-local').Strategy;
var morgan = require('morgan');
var path = require('path');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose');
var base32 = require('thirty-two');
var flash = require('connect-flash');

var Account = require('./models/account');
var G2FA = require('./models/g2fa');
var U2F_Reg = require('./models/u2f');

var port = (process.env.VCAP_APP_PORT || process.env.PORT ||3000);
var host = (process.env.VCAP_APP_HOST || '0.0.0.0');
var mongo_url = (process.env.MONGO_URL || 'mongodb://localhost/users');

if (process.env.VCAP_SERVICES) {
	var services = JSON.parse(process.env.VCAP_SERVICES);

	for (serviceName in services) {
		if (serviceName.match('^mongo')) {
			var creds = services[serviceName][0]['credentials'];
			mongo_url = creds.url;
		} else {
			console.log("no database found");
		}
	}
}

var app_id = 'https://localhost:' + port;

if (process.env.VCAP_APPLICATION) {
	var application = JSON.parse(process.env.VCAP_APPLICATION);

	var app_uri = application['application_uris'][0];

	app_id = 'https://' + app_uri;
}

var cookieSecret = 'zsemjy';

var app = express();

app.set('view engine', 'ejs');
app.set('trust proxy', 1);
app.use(morgan("combined"));
app.use(cookieParser(cookieSecret));
app.use(flash());
app.use(session({
  // genid: function(req) {
  //   return genuuid() // use UUIDs for session IDs
  // },
  secret: cookieSecret,
  resave: false,
  saveUninitialized: false,
  cookie: {
  	secure: true
  }
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(flash);
app.use(passport.initialize());
app.use(passport.session());

function requireHTTPS(req, res, next) {
	if (req.get('X-Forwarded-Proto') === 'http') {
        //FYI this should work for local development as well
        var url = 'https://' + req.get('host');
        if (req.get('host') === 'localhost') {
        	url += ':' + port;
        }
        url  += req.url;
        return res.redirect(url);
    }
    next();
}

app.use(requireHTTPS);

app.use('/',express.static('static'));

passport.use(new LocalStrategy(Account.authenticate()));
passport.use(new TOTPStrategy(function(user, done){
	G2FA.findOne({'username': user.username}, function(err, user){
		if (err) {
			return done(err);
		}
		return done(null, user.secret, 30);
	});
}));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

mongoose.connect(mongo_url);

app.get('/', function(req,res){
	res.render('index', { message: req.flash('info') });
});

app.get('/login', function(req,res){
	res.render('login',{ message: req.flash('info') });
});

app.post('/login', passport.authenticate('local', { failureRedirect: '/login', successRedirect: '/2faCheck', failureFlash: true }));

app.get('/2faCheck', ensureAuthenticated, function(req,res){
	res.render('check2fa',{ message: req.flash('info') });
});

app.get('/newUser', function(req,res){
	res.render('register', { message: req.flash('info') });
});

app.post('/newUser', function(req,res){
	Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
		if (err) {
			console.log(err);
			return res.status(400).send(err.message);
		}

		passport.authenticate('local')(req, res, function () {
			console.log("created new user %s", req.body.username);
            res.status(201).send();
        });

	});
});

app.get('/setup2FA', ensureAuthenticated, function(req,res){
	res.render('setup2fa',{ message: req.flash('info') });
});

app.get('/setupG2FA', ensureAuthenticated, function(req,res){
	G2FA.findOne({'username': req.user.username}, function(err,user){
		if (err) {
			res.status(400).send(err);
		} else {
			var secret;
			if (user !== null) {
				secret = user.secret;
			} else {
				//generate random key
				secret = genSecret(10);
				var newToken = new G2FA({username: req.user.username, secret: secret});
				newToken.save(function(err,tok){

				});
			}
			var encodedKey = base32.encode(secret);
			var otpUrl = 'otpauth://totp/2FADemo:' + req.user.username + '?secret=' + encodedKey + '&period=30&issuer=2FADemo';
			var qrImage = 'https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=' + encodeURIComponent(otpUrl);
			res.send(qrImage);
		}
	});
});

app.post('/loginG2FA', ensureAuthenticated, passport.authenticate('totp'), function(req, res){
	req.session.secondFactor = 'g2fa';
	res.send();
});

app.get('/registerU2F', ensureAuthenticated, function(req,res){
	try{
		var registerRequest = u2f.request(app_id);
		req.session.registerRequest = registerRequest;
		res.send(registerRequest);
	} catch (err) {
		console.log(err);
		res.status(400).send();
	}

});

app.post('/registerU2F', ensureAuthenticated, function(req,res){
	var registerResponse = req.body;
	var registerRequest = req.session.registerRequest;
	var user = req.user.username;
	try {
		var registration = u2f.checkRegistration(registerRequest,registerResponse);
		var reg = new U2F_Reg({username: user, deviceRegistration: registration });
		reg.save(function(err,r){

		});
		res.send();
	} catch (err) {
		console.log(err);
		res.status(400).send();
	}
});

app.get('/authenticateU2F', ensureAuthenticated, function(req,res){
	U2F_Reg.findOne({username: req.user.username}, function(err, reg){
		if (err) {
			res.status(400).send(err);
		} else {
			if (reg !== null) {
				var signRequest = u2f.request(app_id, reg.deviceRegistration.keyHandle);
				req.session.signrequest = signRequest;
				req.session.deviceRegistration = reg.deviceRegistration;
				res.send(signRequest);
			}
		}
	});
});

app.post('/authenticateU2F', ensureAuthenticated, function(req,res){
	var signResponse = req.body;
	var signRequest = req.session.signrequest;
	var deviceRegistration = req.session.deviceRegistration;
	try {
		var result = u2f.checkSignature(signRequest, signResponse, deviceRegistration.publicKey);
		if (result.successful) {
			req.session.secondFactor = 'u2f';
			res.send();
		} else {
			res.status(400).send();
		}
	} catch (err) {
		console.log(err);
		res.status(400).send();
	}
});

app.get('/logout', function(req,res){
	req.logout();
	req.session.secondFactor = undefined;
	res.redirect('/login')
});

app.get('/user', ensureAuthenticated, ensure2fa, function(req, res) {
	res.render('user',{name: req.user.username, message: req.flash('info')});
});

function ensureAuthenticated(req,res,next) {
	if (req.isAuthenticated()) {
    	return next();
	} else {
		res.redirect('/login');
	}
}

function ensure2fa(req, res, next) {
	if (req.session.secondFactor) {
		return next();
	}
	res.redirect('/2faCheck');
}

function genSecret(len) {
	var buf = []
	, chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
	, charlen = chars.length;

	for (var i = 0; i < len; ++i) {
		buf.push(chars[getRandomInt(0, charlen - 1)]);
	}

	return buf.join('');
};

function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

var server = http.Server(app);
if (app_id.match(/^https:\/\/localhost:/)) {
	var options = {
		key: fs.readFileSync('server.key'),
		cert: fs.readFileSync('server.crt')
	};
	server = https.createServer(options, app);
}

server.listen(port, host, function(){
	console.log('App listening on  %s:%d!', host, port);
	console.log("App_ID -> %s", app_id);
});

<|endoftext|>


<commit_before>'use strict';

var data = module.exports = {
  jquery: {
    versions: ['2.1.1', '2.1.0', '2.0.3', '2.0.2', '2.0.1', '2.0.0', '1.11.1', '1.11.0', '1.10.2', '1.10.1', '1.10.0', '1.9.1', '1.9.0', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.2', '1.7.1', '1.7.0', '1.6.4', '1.6.3', '1.6.2', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.2', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.6', '1.2.3'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js';
    }
  },
  'jquery-ui': {
    versions: ['1.11.0', '1.10.4', '1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.2', '1.9.1', '1.9.0', '1.8.24', '1.8.23', '1.8.22', '1.8.21', '1.8.20', '1.8.19', '1.8.18', '1.8.17', '1.8.16', '1.8.15', '1.8.14', '1.8.13', '1.8.12', '1.8.11', '1.8.10', '1.8.9', '1.8.8', '1.8.7', '1.8.6', '1.8.5', '1.8.4', '1.8.2', '1.8.1', '1.8.0', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.0', '1.5.3', '1.5.2'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jqueryui/' + version + '/jquery-ui.min.js';
    }
  },
  dojo: {
    versions: ['1.10.0', '1.9.3', '1.9.2', '1.9.1', '1.9.0', '1.8.5', '1.8.4', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.5', '1.7.4', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.3', '1.2.0', '1.1.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/dojo/' + version + '/dojo/dojo.js';
    }
  },
  swfobject: {
    versions: ['2.2', '2.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/swfobject/' + version + '/swfobject.js';
    }
  }
};

// AngularJS

var angularFiles = [
  'angular',
  'angular-animate',
  'angular-cookies',
  'angular-loader',
  'angular-resource',
  'angular-route',
  'angular-sanitize',
  'angular-touch'
];

angularFiles.forEach(function (item) {
  var stableVersions = ['1.3.6', '1.3.5', '1.3.4', '1.3.3', '1.3.2', '1.3.1', '1.3.0', '1.2.26', '1.2.25', '1.2.24', '1.2.23', '1.2.22', '1.2.21', '1.2.20', '1.2.19', '1.2.18', '1.2.17', '1.2.16', '1.2.15', '1.2.14', '1.2.13', '1.2.12', '1.2.11', '1.2.10', '1.2.9', '1.2.8', '1.2.7', '1.2.6', '1.2.5', '1.2.4', '1.2.3', '1.2.2', '1.2.1', '1.2.0', '1.0.8', '1.0.7', '1.0.6', '1.0.5', '1.0.4', '1.0.3', '1.0.2', '1.0.1'];
  var unstableVersions = ['1.3.0-rc.5', '1.3.0-rc.4', '1.3.0-rc.3', '1.3.0-rc.2', '1.3.0-rc.1', '1.3.0-rc.0', '1.3.0-beta.19', '1.3.0-beta.18', '1.3.0-beta.17', '1.3.0-beta.16', '1.3.0-beta.15', '1.3.0-beta.14', '1.3.0-beta.13', '1.3.0-beta.12', '1.3.0-beta.11', '1.3.0-beta.10', '1.3.0-beta.9', '1.3.0-beta.8', '1.3.0-beta.7', '1.3.0-beta.6', '1.3.0-beta.5', '1.3.0-beta.4', '1.3.0-beta.3', '1.3.0-beta.2', '1.3.0-beta.1'];
  data[item] = {
    versions: [].concat(stableVersions).concat(unstableVersions),
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/angularjs/' + version + '/' + item + '.min.js';
    }
  };
});
<commit_msg>Adding newer patches of all supported libraries<commit_after>'use strict';

var data = module.exports = {
  jquery: {
    versions: ['2.1.3', '2.1.2', '2.1.1', '2.1.0', '2.0.3', '2.0.2', '2.0.1', '2.0.0', '1.11.1', '1.11.0', '1.10.2', '1.10.1', '1.10.0', '1.9.1', '1.9.0', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.2', '1.7.1', '1.7.0', '1.6.4', '1.6.3', '1.6.2', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.2', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.6', '1.2.3'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js';
    }
  },
  'jquery-ui': {
    versions: ['1.11.2', '1.11.1', '1.11.0', '1.10.4', '1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.2', '1.9.1', '1.9.0', '1.8.24', '1.8.23', '1.8.22', '1.8.21', '1.8.20', '1.8.19', '1.8.18', '1.8.17', '1.8.16', '1.8.15', '1.8.14', '1.8.13', '1.8.12', '1.8.11', '1.8.10', '1.8.9', '1.8.8', '1.8.7', '1.8.6', '1.8.5', '1.8.4', '1.8.2', '1.8.1', '1.8.0', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.0', '1.5.3', '1.5.2'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jqueryui/' + version + '/jquery-ui.min.js';
    }
  },
  dojo: {
    versions: ['1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.3', '1.9.2', '1.9.1', '1.9.0', '1.8.5', '1.8.4', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.5', '1.7.4', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.3', '1.2.0', '1.1.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/dojo/' + version + '/dojo/dojo.js';
    }
  },
  swfobject: {
    versions: ['2.2', '2.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/swfobject/' + version + '/swfobject.js';
    }
  }
};

// AngularJS

var angularFiles = [
  'angular',
  'angular-animate',
  'angular-cookies',
  'angular-loader',
  'angular-resource',
  'angular-route',
  'angular-sanitize',
  'angular-touch'
];

angularFiles.forEach(function (item) {
  var stableVersions = ['1.3.8', '1.3.7', '1.3.6', '1.3.5', '1.3.4', '1.3.3', '1.3.2', '1.3.1', '1.3.0', '1.2.26', '1.2.25', '1.2.24', '1.2.23', '1.2.22', '1.2.21', '1.2.20', '1.2.19', '1.2.18', '1.2.17', '1.2.16', '1.2.15', '1.2.14', '1.2.13', '1.2.12', '1.2.11', '1.2.10', '1.2.9', '1.2.8', '1.2.7', '1.2.6', '1.2.5', '1.2.4', '1.2.3', '1.2.2', '1.2.1', '1.2.0', '1.0.8', '1.0.7', '1.0.6', '1.0.5', '1.0.4', '1.0.3', '1.0.2', '1.0.1'];
  var unstableVersions = ['1.3.0-rc.5', '1.3.0-rc.4', '1.3.0-rc.3', '1.3.0-rc.2', '1.3.0-rc.1', '1.3.0-rc.0', '1.3.0-beta.19', '1.3.0-beta.18', '1.3.0-beta.17', '1.3.0-beta.16', '1.3.0-beta.15', '1.3.0-beta.14', '1.3.0-beta.13', '1.3.0-beta.12', '1.3.0-beta.11', '1.3.0-beta.10', '1.3.0-beta.9', '1.3.0-beta.8', '1.3.0-beta.7', '1.3.0-beta.6', '1.3.0-beta.5', '1.3.0-beta.4', '1.3.0-beta.3', '1.3.0-beta.2', '1.3.0-beta.1'];
  data[item] = {
    versions: [].concat(stableVersions).concat(unstableVersions),
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/angularjs/' + version + '/' + item + '.min.js';
    }
  };
});
<|endoftext|>


<commit_before>/**
 * ////////////////////////////////////////
 * /////////// Random iterator ////////////
 * ////////////////////////////////////////
 *
 * This little component allows to randomly iterate
 * over an array using iterators and generators.
 */

 /**
  * Exporting the module appropriately given
  * the environment (AMD, Node.js and the browser).
  */
 (function (name, definition) {
    if (typeof define === 'function' && define.amd) {
        // Defining the module in an AMD fashion.
        define(definition);
    } else if (typeof module !== 'undefined' && module.exports) {
        // Exporting the module for Node.js/io.js.
        module.exports   = definition();
    } else {
        var gl       = this;
        var instance = definition();
        var old      = gl[name];

        /**
         * Allowing to scope the module
         * avoiding global namespace pollution.
         */
        instance.noConflict = function () {
            gl[name] = old;
            return instance;
        };
        // Exporting the module in the global
        // namespace in a browser context.
        gl[name] = instance;
    }
 })('Random', function () {

 	var iterator = function (array) {
        if (!Array.isArray(array)) {
		    throw new Error('Argument must be of type `Array`');
        }
        this.available = array.slice();
	};

	iterator.prototype.hasNext = function () {
        return this.available.length > 0;
	};

	iterator.prototype.next = function () {
        if (!this.hasNext()) return;
        var rand_index = (Math.floor(Math.random() * this.available.length));
        return this.available.splice(rand_index, 1)[0];
	};

	var generator = function (array) {
        var it = new iterator(array);

        return function () {
            return it.next();
        };
    };

	return {
        Iterator:  iterator,
        Generator: generator
	};
});<commit_msg>Re-indenting the code<commit_after>/**
 * ////////////////////////////////////////
 * /////////// Random iterator ////////////
 * ////////////////////////////////////////
 *
 * This little component allows to randomly iterate
 * over an array using iterators and generators.
 */

 /**
  * Exporting the module appropriately given
  * the environment (AMD, Node.js and the browser).
  */
 (function (name, definition) {
    if (typeof define === 'function' && define.amd) {
        // Defining the module in an AMD fashion.
        define(definition);
    } else if (typeof module !== 'undefined' && module.exports) {
        // Exporting the module for Node.js/io.js.
        module.exports   = definition();
    } else {
        var gl       = this;
        var instance = definition();
        var old      = gl[name];

        /**
         * Allowing to scope the module
         * avoiding global namespace pollution.
         */
        instance.noConflict = function () {
            gl[name] = old;
            return instance;
        };
        // Exporting the module in the global
        // namespace in a browser context.
        gl[name] = instance;
    }
 })('Random', function () {

     var iterator = function (array) {
        if (!Array.isArray(array)) {
		    throw new Error('Argument must be of type `Array`');
        }
        this.available = array.slice();
     };

     iterator.prototype.hasNext = function () {
         return this.available.length > 0;
     };

     iterator.prototype.next = function () {
         if (!this.hasNext()) return;
         var rand_index = (Math.floor(Math.random() * this.available.length));
         return this.available.splice(rand_index, 1)[0];
     };

     var generator = function (array) {
         var it = new iterator(array);

         return function () {
             return it.next();
         };

     };

     return {
         Iterator:  iterator,
         Generator: generator
	};
});<|endoftext|>


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

var fs = require('fs');
var path = require('path');
var parse = require('./lib/parser.js');
var assertIsString = require('./lib/util.js').assertIsString;

/**
 * Hyde's predefined constants in a Context
 *
 * @typedef {object} HydeContext
 * @property {string} targetroot
 * @property {string} sourceroot
 * @property {string} currentfile
 * @property {Date} time
 */

/**
 * The context for Hyde processing
 *
 * @typedef {object} ParseContext
 * @property {HydeContext} _hyde
 */

/** @type ParseContext */
var parseContext = {
  _hyde: {
    targetroot: '',
    sourceroot: '',
    currentfile: '',
    time: new Date(),
  },
};

/**
 * The walk function's callback
 *
 * @callback walk~callback
 * @param {Error} err error object
 * @param {string[]} results the paths of all files that were found
 */

/**
 * Walk a directory and its subdirectories, and call a method on each of the
 * files within
 *

 * Found at http://stackoverflow.com/revisions/5827895/6
 *
 * @param {string} dir the directory to walk
 * @param {walk~callback} done The function to call on each file
 */
var walk = function(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) { return done(err); }
    var pending = list.length;
    if (!pending) { return done(null, results); }
    list.forEach(function(file) {
      file = path.resolve(dir, file);
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) { done(null, results); }
          });
        } else {
          results.push(file);
          if (!--pending) { done(null, results); }
        }
      });
    });
  });
};

/**
 * Deletes a path and all its contents.
 *

 * Found at http://stackoverflow.com/revisions/12761924/4
 *
 * @param {string} dir the directory to be deleted
 */
var deleteDirectoryRecursive = function(dir) {
  var files = [];
  if (fs.existsSync(dir)) {
    files = fs.readdirSync(dir);
    files.forEach(function(file) {
      var curPath = dir + path.sep + file;
      if (fs.statSync(curPath).isDirectory()) { // Recurse
        deleteDirectoryRecursive(curPath);
      } else { // Delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(dir);
  }
};

/**
 * Processes a single file through Hyde.
 *
 * @param {string} file the path of the file to compile
 */
var processFile = function(file) {
  var suffix = /(\.html|\.css|\.md|\.markdown)$/i;
  if (!suffix.test(file)) {
    return;
  }

  var relativeFile = file.substr(parseContext._hyde.sourceroot.length);
  var targetAbsoluteFile = parseContext._hyde.targetroot + relativeFile;
  var targetDir = path.dirname(targetAbsoluteFile);

  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir);
  }

  var text = fs.readFileSync(file, {encoding: 'utf-8'});

  parseContext._hyde.currentfile = relativeFile;
  var parsed = parse(text, parseContext);

  fs.writeFileSync(targetAbsoluteFile, parsed);
};

/**
 * Entry point for starting to compile files.
 *
 * @param {string} sourcePath the source path. By default current work
 *    directory.
 * @param {string} targetPath the target path. By default sourcePath+'/_site'.
 */
var entry = function(sourcePath, targetPath) {
  if (typeof sourcePath === 'undefined' || sourcePath === null) {
    sourcePath = process.cwd();
  } else {
    assertIsString(sourcePath, 'Source path must be a string');
  }

  if (typeof targetPath === 'undefined' || targetPath === null) {
    targetPath = path.resolve(sourcePath, '_site');
  } else if (typeof targetPath !== 'string') {
    console.error('Target path must be a string');
    process.exit(1);
  }

  parseContext._hyde.sourceroot = sourcePath;
  parseContext._hyde.targetroot = targetPath;

  deleteDirectoryRecursive(targetPath);

  walk(sourcePath, function(err, files) {
    if (err) { throw err; }
    files.forEach(function(file) {
      if (file.indexOf('_') === -1) {
        processFile(file);
      }
    });
  });
};

module.exports = entry;<commit_msg>rename class-specific callback to global one<commit_after>/*
 * Copyright 2015 Henrik Paul
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var fs = require('fs');
var path = require('path');
var parse = require('./lib/parser.js');
var assertIsString = require('./lib/util.js').assertIsString;

/**
 * Hyde's predefined constants in a Context
 *
 * @typedef {object} HydeContext
 * @property {string} targetroot
 * @property {string} sourceroot
 * @property {string} currentfile
 * @property {Date} time
 */

/**
 * The context for Hyde processing
 *
 * @typedef {object} ParseContext
 * @property {HydeContext} _hyde
 */

/** @type ParseContext */
var parseContext = {
  _hyde: {
    targetroot: '',
    sourceroot: '',
    currentfile: '',
    time: new Date(),
  },
};

/**
 * The walk function's callback
 *
 * @callback WalkCallback
 * @param {Error} err error object
 * @param {string[]} results the paths of all files that were found
 */

/**
 * Walk a directory and its subdirectories, and call a method on each of the
 * files within
 *

 * Found at http://stackoverflow.com/revisions/5827895/6
 *
 * @param {string} dir the directory to walk
 * @param {WalkCallback} done The function to call on each file
 */
var walk = function(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) { return done(err); }
    var pending = list.length;
    if (!pending) { return done(null, results); }
    list.forEach(function(file) {
      file = path.resolve(dir, file);
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) { done(null, results); }
          });
        } else {
          results.push(file);
          if (!--pending) { done(null, results); }
        }
      });
    });
  });
};

/**
 * Deletes a path and all its contents.
 *

 * Found at http://stackoverflow.com/revisions/12761924/4
 *
 * @param {string} dir the directory to be deleted
 */
var deleteDirectoryRecursive = function(dir) {
  var files = [];
  if (fs.existsSync(dir)) {
    files = fs.readdirSync(dir);
    files.forEach(function(file) {
      var curPath = dir + path.sep + file;
      if (fs.statSync(curPath).isDirectory()) { // Recurse
        deleteDirectoryRecursive(curPath);
      } else { // Delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(dir);
  }
};

/**
 * Processes a single file through Hyde.
 *
 * @param {string} file the path of the file to compile
 */
var processFile = function(file) {
  var suffix = /(\.html|\.css|\.md|\.markdown)$/i;
  if (!suffix.test(file)) {
    return;
  }

  var relativeFile = file.substr(parseContext._hyde.sourceroot.length);
  var targetAbsoluteFile = parseContext._hyde.targetroot + relativeFile;
  var targetDir = path.dirname(targetAbsoluteFile);

  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir);
  }

  var text = fs.readFileSync(file, {encoding: 'utf-8'});

  parseContext._hyde.currentfile = relativeFile;
  var parsed = parse(text, parseContext);

  fs.writeFileSync(targetAbsoluteFile, parsed);
};

/**
 * Entry point for starting to compile files.
 *
 * @param {string} sourcePath the source path. By default current work
 *    directory.
 * @param {string} targetPath the target path. By default sourcePath+'/_site'.
 */
var entry = function(sourcePath, targetPath) {
  if (typeof sourcePath === 'undefined' || sourcePath === null) {
    sourcePath = process.cwd();
  } else {
    assertIsString(sourcePath, 'Source path must be a string');
  }

  if (typeof targetPath === 'undefined' || targetPath === null) {
    targetPath = path.resolve(sourcePath, '_site');
  } else if (typeof targetPath !== 'string') {
    console.error('Target path must be a string');
    process.exit(1);
  }

  parseContext._hyde.sourceroot = sourcePath;
  parseContext._hyde.targetroot = targetPath;

  deleteDirectoryRecursive(targetPath);

  walk(sourcePath, function(err, files) {
    if (err) { throw err; }
    files.forEach(function(file) {
      if (file.indexOf('_') === -1) {
        processFile(file);
      }
    });
  });
};

module.exports = entry;<|endoftext|>


<commit_before>var linalgModule = require('linalg-asm');

module.exports = function pdipQuad(n, m) {
  'use strict';

  var memory = allocate({
    Float64: {
      Q: n * n,
      A: n * m,
      b: m,
      c: n,
      w: {
        x: n,
        y: m,
        z: n
      },
      J: m * m,
      K: m * n,
      L: n * n,
      r: {
        rX: n,
        rY: m,
        rZ: n
      },
      work: n
    },
    Uint32: {
      ipiv: m
    }
  });
  var linalg = linalgModule(global, null, memory.heap);

  (function() {
    var i;
    for (i = 0; i < n; ++i) {
      memory.views.x[i] = 1;
      memory.views.y[i] = 0;
      memory.views.z[i] = 1;
    }
  })();

  return {
    q: function() {
      return memory.views.Q;
    },
    a: function() {
      return memory.views.A;
    },
    b: function() {
      return memory.views.b;
    },
    c: function() {
      return memory.views.c;
    },
    w: function() {
      return memory.views.w;
    },
    solve: solve
  };

  function solve(options) {
    options = options || {};
    var i, j,
        xFeasible = false,
        yFeasible = false;
    var A = memory.views.A,
        b = memory.views.b,
        c = memory.views.c,
        Q = memory.views.Q,
        J = memory.views.J,
        K = memory.views.K,
        L = memory.views.L,
        x = memory.views.x,
        y = memory.views.y,
        z = memory.views.z,
        r = memory.views.r,
        rX = memory.views.rX,
        rY = memory.views.rY,
        rZ = memory.views.rZ,
        work = memory.views.work,
        ipiv = memory.views.ipiv;

    var mu = options.mu || 0.8,
        muMin = options.muMin || 1e-10,
        gamma = options.gamma || 0.5,
        M = options.M || 2,
        rho = options.rho || 100,
        tau = options.tau || 0.8,
        xi = options.xi || 0.9,
        err = options.err || 1e-12;

    for (var loop = 0; mu > muMin; ++loop, mu *= gamma) {
      for (;;) {
        // r_z := mu e - X Z e
        for (i = 0; i < n; ++i) {
          rZ[i] = mu - x[i] * z[i];
        }

        if (xFeasible) {
          // r_x := O
          for (i = 0; i < n; ++i) {
            rX[i] = 0;
          }
        } else {
          // r_x := A ^ t y + z - Q x - c
          linalg.dcopy(n, z.byteOffset, 1, rX.byteOffset, 1);
          linalg.daxpy(n, -1, c.byteOffset, 1, rX.byteOffset, 1);
          linalg.dgemv(0, n, n, -1, Q.byteOffset, n, x.byteOffset, 1, 1, rX.byteOffset, 1);
          linalg.dgemv(1, m, n, 1, A.byteOffset, n, y.byteOffset, 1, 1, rX.byteOffset, 1);

          if (linalg.ddot(rX.length, rX.byteOffset, 1, rX.byteOffset, 1) < err) {
            xFeasible = true;
          }
        }

        if (yFeasible) {
          // r_y := O
          for (i = 0; i < m; ++i) {
            rY[i] = 0;
          }
        } else {
          // r_y := A x - b
          linalg.dcopy(m, b.byteOffset, 1, rY.byteOffset, 1);
          linalg.dgemv(0, m, n, 1, A.byteOffset, n, x.byteOffset, 1, -1, rY.byteOffset, 1);

          if (linalg.ddot(rY.length, rY.byteOffset, 1, rY.byteOffset, 1) < err) {
            yFeasible = true;
          }
        }

        if (linalg.ddot(r.length, r.byteOffset, 1, r.byteOffset, 1) < mu * M) {
          break;
        }

        // L := (Q + X^(-1) Z)^-1
        for (i = 0; i < n; ++i) {
          for (j = 0; j < n; ++j) {
            L[i * n + j] = Q[i * n + j];
          }
          L[i * n + i] += z[i] / x[i];
        }
        linalg.dgetrf(n, n, L.byteOffset, n, ipiv.byteOffset, n);
        linalg.dgetri(n, L.byteOffset, n, ipiv.byteOffset, work.byteOffset, n);

        // K := A L
        linalg.dgemm(0, 0, m, n, n, 1, A.byteOffset, n, L.byteOffset, n, 0, K.byteOffset, n);

        // J := K A^t
        linalg.dgemm(0, 1, m, m, n, 1, K.byteOffset, n, A.byteOffset, n, 0, J.byteOffset, m);

        // r_y := - r_y - K (r_x + X^(-1) r_z)
        for (i = 0; i < n; ++i) {
          work[i] = rX[i] + rZ[i] / x[i];
        }
        linalg.dgemv(0, m, n, -1, K.byteOffset, n, work.byteOffset, 1, -1, rY.byteOffset, 1);

        // solve J dw = r
        linalg.dgesv(m, 1, J.byteOffset, m, ipiv.byteOffset, rY.byteOffset, 1);

        // dx := L (r_x + X^-1 r_z + A^t d_y)
        linalg.dgemv(1, m, n, 1, A.byteOffset, n, rY.byteOffset, 1, 1, work.byteOffset, 1);
        linalg.dgemv(0, n, n, 1, L.byteOffset, n, work.byteOffset, 1, 0, rX.byteOffset, 1);

        // dz = X^-1 (Z dx - r_z)
        for (i = 0; i < n; ++i) {
          rZ[i] = (rZ[i] - z[i] * rX[i]) / x[i];
        }

        // Find alpha_x and alpha_z
        var alpha = 1;
        for (i = 0; i < n; ++i) {
          if (rX[i] < 0) {
            alpha = Math.min(alpha, -x[i] / rX[i]);
          }
          if (rZ[i] < 0) {
            alpha = Math.min(alpha, -z[i] / rZ[i]);
          }
        }
        alpha *= 0.99;

        // Armijo condition
        var dpx = dp(n, m, A, b, c, Q, x, rX, mu, rho);
        if (dpx > 0) {
          break;
        }
        var px = p(n, m, A, b, c, Q, x, mu, rho);
        linalg.daxpy(n, alpha, rX.byteOffset, 1, x.byteOffset, 1);
        for (var k = 1; !(p(n, m, A, b, c, Q, x, mu, rho) <= px + xi * alpha * Math.pow(tau, k) * dpx) && k < 100; ++k) {
          linalg.daxpy(n, alpha * Math.pow(tau, k) * (tau - 1), rX.byteOffset, 1, x.byteOffset, 1);
        }
        linalg.daxpy(m, alpha * Math.pow(tau, k - 1), rY.byteOffset, 1, y.byteOffset, 1);
        linalg.daxpy(n, alpha * Math.pow(tau, k - 1), rZ.byteOffset, 1, z.byteOffset, 1);
      }
    }

    return {
      x: x
    };
  }
};

function f(n, m, Q, c, x) {
  'use strict';
  var i, j, val = 0;
  for (i = 0; i < n; ++i) {
    for (j = 0; j < n; ++j) {
      val += x[i] * x[j] * Q[i * n + j];
    }
  }
  val /= 2;
  for (i = 0; i < n; ++i) {
    val += x[i] * c[i];
  }
  return val;
}

function g(n, m, A, b, x, i) {
  'use strict';
  var j, val = -b[i];
  for (j = 0; j < n; ++j) {
    val += x[j] * A[i * n + j];
  }
  return val;
}

function p(n, m, A, b, c, Q, x, mu, rho) {
  'use strict';
  var i, val;
  val = f(n, m, Q, c, x);
  for (i = 0; i < n; ++i) {
    val -= mu * Math.log(x[i]);
  }
  for (i = 0; i < m; ++i) {
    val += rho * Math.abs(g(n, m, A, b, x, i));
  }
  return val;
}

function dp(n, m, A, b, c, Q, x, rX, mu, rho) {
  'use strict';
  var i, j, val = 0, qx, gjx, ax;
  for (i = 0; i < n; ++i) {
    qx = c[i];
    for (j = 0; j < n; ++j) {
      qx += Q[i * n + j] * x[j];
    }
    val += qx * rX[i];
  }
  for (i = 0; i < n; ++i) {
    val -= mu * rX[i] / x[i];
  }
  for (i = 0; i < m; ++i) {
    gjx = g(n, m, A, b, x, i);
    ax = 0;
    for (j = 0; j < n; ++j) {
      ax += A[i * n + j] * rX[j];
    }
    val += rho * (Math.abs(gjx + ax) - Math.abs(gjx));
  }
  return val;
}

function allocate(arg) {
  'use strict';
  var totalSize = 0;

  totalSize += 8 * countLength(arg.Float64);
  totalSize += 4 * countLength(arg.Uint32);

  var heap = new ArrayBuffer(calcBufferSize(totalSize)),
      views = {};
  allocViews(arg.Uint32, 8 * allocViews(arg.Float64, 0, Float64Array), Uint32Array);

  return {
    heap: heap,
    views: views
  };

  function countLength(obj) {
    var length = 0;
    for (var name in obj) {
      if (typeof obj[name] === 'number') {
        length += obj[name];
      } else {
        length += countLength(obj[name]);
      }
    }
    return length;
  }

  function allocViews(obj, offset, TArray) {
    var length, totalLength = 0;
    for (var name in obj) {
      if (typeof obj[name] === 'number') {
        length = obj[name];
      } else {
        length = allocViews(obj[name], offset, TArray);
      }
      views[name] = new TArray(heap, offset, length);
      offset += views[name].byteLength;
      totalLength += length;
    }
    return totalLength;
  }

  function calcBufferSize(s) {
    var l = 1;
    while (l < s) {
      l <<= 1;
    }
    return l;
  }
}
<commit_msg>Enable to switch equation system<commit_after>var linalgModule = require('linalg-asm');

module.exports = function pdipQuad(n, m) {
  'use strict';

  var nm = n + m;
  var memory = allocate({
    Float64: {
      Q: n * n,
      A: n * m,
      b: m,
      c: n,
      w: {
        x: n,
        y: m,
        z: n
      },
      J: nm * nm,
      K: m * n,
      L: n * n,
      r: {
        rX: n,
        rY: m,
        rZ: n
      },
      work: n
    },
    Uint32: {
      ipiv: m
    }
  });
  var linalg = linalgModule(global, null, memory.heap);

  (function() {
    var i;
    for (i = 0; i < n; ++i) {
      memory.views.x[i] = 1;
      memory.views.y[i] = 0;
      memory.views.z[i] = 1;
    }
  })();

  return {
    q: function() {
      return memory.views.Q;
    },
    a: function() {
      return memory.views.A;
    },
    b: function() {
      return memory.views.b;
    },
    c: function() {
      return memory.views.c;
    },
    w: function() {
      return memory.views.w;
    },
    solve: solve
  };

  function solve(options) {
    options = options || {};
    var i, j,
        xFeasible = false,
        yFeasible = false;
    var A = memory.views.A,
        b = memory.views.b,
        c = memory.views.c,
        Q = memory.views.Q,
        J = memory.views.J,
        K = memory.views.K,
        L = memory.views.L,
        x = memory.views.x,
        y = memory.views.y,
        z = memory.views.z,
        r = memory.views.r,
        rX = memory.views.rX,
        rY = memory.views.rY,
        rZ = memory.views.rZ,
        work = memory.views.work,
        ipiv = memory.views.ipiv;
    var mu = options.mu || 0.8,
        muMin = options.muMin || 1e-10,
        gamma = options.gamma || 0.5,
        M = options.M || 2,
        rho = options.rho || 100,
        tau = options.tau || 0.8,
        xi = options.xi || 0.9,
        err = options.err || 1e-12;
    var reduce = options.reduce === undefined ? false : options.reduce;

    for (var loop = 0; mu > muMin; ++loop, mu *= gamma) {
      for (;;) {
        // r_z := mu e - X Z e
        for (i = 0; i < n; ++i) {
          rZ[i] = mu - x[i] * z[i];
        }

        if (xFeasible) {
          // r_x := O
          for (i = 0; i < n; ++i) {
            rX[i] = 0;
          }
        } else {
          // r_x := A ^ t y + z - Q x - c
          linalg.dcopy(n, z.byteOffset, 1, rX.byteOffset, 1);
          linalg.daxpy(n, -1, c.byteOffset, 1, rX.byteOffset, 1);
          linalg.dgemv(0, n, n, -1, Q.byteOffset, n, x.byteOffset, 1, 1, rX.byteOffset, 1);
          linalg.dgemv(1, m, n, 1, A.byteOffset, n, y.byteOffset, 1, 1, rX.byteOffset, 1);

          if (linalg.ddot(rX.length, rX.byteOffset, 1, rX.byteOffset, 1) < err) {
            xFeasible = true;
          }
        }

        if (yFeasible) {
          // r_y := O
          for (i = 0; i < m; ++i) {
            rY[i] = 0;
          }
        } else {
          // r_y := A x - b
          linalg.dcopy(m, b.byteOffset, 1, rY.byteOffset, 1);
          linalg.dgemv(0, m, n, 1, A.byteOffset, n, x.byteOffset, 1, -1, rY.byteOffset, 1);

          if (linalg.ddot(rY.length, rY.byteOffset, 1, rY.byteOffset, 1) < err) {
            yFeasible = true;
          }
        }

        if (linalg.ddot(r.length, r.byteOffset, 1, r.byteOffset, 1) < mu * M) {
          break;
        }

        if (reduce) {
          // L := (Q + X^(-1) Z)^-1
          for (i = 0; i < n; ++i) {
            for (j = 0; j < n; ++j) {
              L[i * n + j] = Q[i * n + j];
            }
            L[i * n + i] += z[i] / x[i];
          }
          linalg.dgetrf(n, n, L.byteOffset, n, ipiv.byteOffset, n);
          linalg.dgetri(n, L.byteOffset, n, ipiv.byteOffset, work.byteOffset, n);

          // K := A L
          linalg.dgemm(0, 0, m, n, n, 1, A.byteOffset, n, L.byteOffset, n, 0, K.byteOffset, n);

          // J := K A^t
          linalg.dgemm(0, 1, m, m, n, 1, K.byteOffset, n, A.byteOffset, n, 0, J.byteOffset, m);

          // r_y := - r_y - K (r_x + X^(-1) r_z)
          for (i = 0; i < n; ++i) {
            work[i] = rX[i] + rZ[i] / x[i];
          }
          linalg.dgemv(0, m, n, -1, K.byteOffset, n, work.byteOffset, 1, -1, rY.byteOffset, 1);

          // solve J dw = r
          linalg.dgesv(m, 1, J.byteOffset, m, ipiv.byteOffset, rY.byteOffset, 1);

          // dx := L (r_x + X^-1 r_z + A^t d_y)
          linalg.dgemv(1, m, n, 1, A.byteOffset, n, rY.byteOffset, 1, 1, work.byteOffset, 1);
          linalg.dgemv(0, n, n, 1, L.byteOffset, n, work.byteOffset, 1, 0, rX.byteOffset, 1);
        } else {
          // J := (  Q-X^(-1)Z  -A^t )
          //        -A           O
          // r_x := r_x - X ^ -1 r_z
          for (i = 0; i < nm; ++i) {
            for (j = 0; j < nm; ++j) {
              J[i * nm + j] = 0;
            }
          }
          for (i = 0; i < n; ++i) {
            for (j = 0; j < n; ++j) {
              J[i * nm + j] = Q[i * n + j];
            }
            for (j = 0; j < m; ++j) {
              J[(j + n) * nm + i] = J[i * nm + j + n] = -A[j * n + i];
            }
            J[i * nm + i] += z[i] / x[i];
            rX[i] += rZ[i] / x[i];
          }

          // solve J dw = r
          linalg.dgesv(nm, 1, J.byteOffset, nm, ipiv.byteOffset, r.byteOffset, 1);
        }

        // dz = X^-1 (Z dx - r_z)
        for (i = 0; i < n; ++i) {
          rZ[i] = (rZ[i] - z[i] * rX[i]) / x[i];
        }

        // Find alpha_x and alpha_z
        var alpha = 1;
        for (i = 0; i < n; ++i) {
          if (rX[i] < 0) {
            alpha = Math.min(alpha, -x[i] / rX[i]);
          }
          if (rZ[i] < 0) {
            alpha = Math.min(alpha, -z[i] / rZ[i]);
          }
        }
        alpha *= 0.99;

        // Armijo condition
        var dpx = dp(n, m, A, b, c, Q, x, rX, mu, rho);
        if (dpx > 0) {
          break;
        }
        var px = p(n, m, A, b, c, Q, x, mu, rho);
        linalg.daxpy(n, alpha, rX.byteOffset, 1, x.byteOffset, 1);
        for (var k = 1; !(p(n, m, A, b, c, Q, x, mu, rho) <= px + xi * alpha * Math.pow(tau, k) * dpx) && k < 100; ++k) {
          linalg.daxpy(n, alpha * Math.pow(tau, k) * (tau - 1), rX.byteOffset, 1, x.byteOffset, 1);
        }
        linalg.daxpy(m, alpha * Math.pow(tau, k - 1), rY.byteOffset, 1, y.byteOffset, 1);
        linalg.daxpy(n, alpha * Math.pow(tau, k - 1), rZ.byteOffset, 1, z.byteOffset, 1);
      }
    }

    return {
      x: x
    };
  }
};

function f(n, m, Q, c, x) {
  'use strict';
  var i, j, val = 0;
  for (i = 0; i < n; ++i) {
    for (j = 0; j < n; ++j) {
      val += x[i] * x[j] * Q[i * n + j];
    }
  }
  val /= 2;
  for (i = 0; i < n; ++i) {
    val += x[i] * c[i];
  }
  return val;
}

function g(n, m, A, b, x, i) {
  'use strict';
  var j, val = -b[i];
  for (j = 0; j < n; ++j) {
    val += x[j] * A[i * n + j];
  }
  return val;
}

function p(n, m, A, b, c, Q, x, mu, rho) {
  'use strict';
  var i, val;
  val = f(n, m, Q, c, x);
  for (i = 0; i < n; ++i) {
    val -= mu * Math.log(x[i]);
  }
  for (i = 0; i < m; ++i) {
    val += rho * Math.abs(g(n, m, A, b, x, i));
  }
  return val;
}

function dp(n, m, A, b, c, Q, x, rX, mu, rho) {
  'use strict';
  var i, j, val = 0, qx, gjx, ax;
  for (i = 0; i < n; ++i) {
    qx = c[i];
    for (j = 0; j < n; ++j) {
      qx += Q[i * n + j] * x[j];
    }
    val += qx * rX[i];
  }
  for (i = 0; i < n; ++i) {
    val -= mu * rX[i] / x[i];
  }
  for (i = 0; i < m; ++i) {
    gjx = g(n, m, A, b, x, i);
    ax = 0;
    for (j = 0; j < n; ++j) {
      ax += A[i * n + j] * rX[j];
    }
    val += rho * (Math.abs(gjx + ax) - Math.abs(gjx));
  }
  return val;
}

function allocate(arg) {
  'use strict';
  var totalSize = 0;

  totalSize += 8 * countLength(arg.Float64);
  totalSize += 4 * countLength(arg.Uint32);

  var heap = new ArrayBuffer(calcBufferSize(totalSize)),
      views = {};
  allocViews(arg.Uint32, 8 * allocViews(arg.Float64, 0, Float64Array), Uint32Array);

  return {
    heap: heap,
    views: views
  };

  function countLength(obj) {
    var length = 0;
    for (var name in obj) {
      if (typeof obj[name] === 'number') {
        length += obj[name];
      } else {
        length += countLength(obj[name]);
      }
    }
    return length;
  }

  function allocViews(obj, offset, TArray) {
    var length, totalLength = 0;
    for (var name in obj) {
      if (typeof obj[name] === 'number') {
        length = obj[name];
      } else {
        length = allocViews(obj[name], offset, TArray);
      }
      views[name] = new TArray(heap, offset, length);
      offset += views[name].byteLength;
      totalLength += length;
    }
    return totalLength;
  }

  function calcBufferSize(s) {
    var l = 1;
    while (l < s) {
      l <<= 1;
    }
    return l;
  }
}
<|endoftext|>


<commit_before>"use strict";

var url = require("url"),
    util = require("util");

var Bridge = require("tilelive-bridge");

var TMSource = function(uri, callback) {
  uri = url.parse(uri);

  uri.pathname += "/data.xml";

  // TODO if data.xml does not exist (but data.yml does), generate it before
  // pointing tilelive-bridge at it

  return Bridge.call(this, uri, callback);
};

util.inherits(TMSource, Bridge);

TMSource.registerProtocols = function(tilelive) {
  tilelive.protocols["tmsource:"] = this;
};

module.exports = function(tilelive, options) {
  TMSource.registerProtocols(tilelive);

  return TMSource;
};
<commit_msg>Assume this is a file:-style URI<commit_after>"use strict";

var url = require("url"),
    util = require("util");

var Bridge = require("tilelive-bridge");

var TMSource = function(uri, callback) {
  uri = url.parse(uri);

  uri.pathname = uri.hostname + uri.pathname + "/data.xml";

  // TODO if data.xml does not exist (but data.yml does), generate it before
  // pointing tilelive-bridge at it

  return Bridge.call(this, uri, callback);
};

util.inherits(TMSource, Bridge);

TMSource.registerProtocols = function(tilelive) {
  tilelive.protocols["tmsource:"] = this;
};

module.exports = function(tilelive, options) {
  TMSource.registerProtocols(tilelive);

  return TMSource;
};
<|endoftext|>