<commit_before>var _              = require('lodash');
var async            = require('async');
var paths          = require('../../conf/paths');
var netConf        = require(paths.confdir + '/network');
var process_events = require(paths.libdir + '/process-events');
var storage        = require(paths.libdir + '/storage');

var modulerequest  = require(paths.libdir + '/server/modulerequest');
var modulecollector  = require(paths.libdir + '/server/modulecollector');
var modulepackager  = require(paths.libdir + '/server/modulepackager');
var modulecache  = require(paths.libdir + '/server/modulecache');

var log = function (msg) {
	process_events.send(process_events.LOG, msg, 'worker');
}

/**
 *
 * @param {ClientRequest} request
 * @param {ServerResponse} response
 */
module.exports = function (request, response) {

	var modulereq = modulerequest(request);

	async.waterfall([
		modulecollector.bind(null, modulereq),
		modulepackager.bind(null, modulereq),
		modulecache.bind(null, modulereq)
	], function (err, source, byteLength, lastModified) {

		if (err) {
			// handle errors

			log(['Error', err].join(' '));

			if (err.statusCode) {
				response.writeHead(err.statusCode, {'Content-Type': 'text/plain'});
				response.end(err.message, 'utf8')
			} else {
				response.writeHead(500, {'Content-Type': 'text/plain'});
				response.end('Internal server error', 'utf8');
			}
			return;
		}

		var responseStatus = 200;

		if (request.headers['if-modified-since']) {
			var ifModifiedSince = new Date(request.headers['if-modified-since']);

			if (+lastModified <= +ifModifiedSince) {
				responseStatus = 304;
				byteLength = 0;
				source = '';
			}
		}

		// serve content
		response.writeHead(responseStatus, {
			'Content-Type': 'application/x-javascript;charset=UTF-8',
			'Content-Length': byteLength,
			'Last-Modified': lastModified.toUTCString(),
			'Cache-Control': 'must-revalidate',
			'X-JMS-Cache': 'MISS'
		});

		response.end(source, 'utf8');

		//_.pluck(result, 'source');

	});

}<commit_msg>moduleserver response structure<commit_after>var _              = require('lodash');
var async            = require('async');
var paths          = require('../../conf/paths');
var netConf        = require(paths.confdir + '/network');
var process_events = require(paths.libdir + '/process-events');
var storage        = require(paths.libdir + '/storage');

var modulerequest  = require(paths.libdir + '/server/modulerequest');
var modulecollector  = require(paths.libdir + '/server/modulecollector');
var modulepackager  = require(paths.libdir + '/server/modulepackager');
var modulecache  = require(paths.libdir + '/server/modulecache');

var log = function (msg) {
	process_events.send(process_events.LOG, msg, 'worker');
}

/**
 *
 * @param {ClientRequest} request
 * @param {ServerResponse} response
 */
module.exports = function (request, response) {

	var modulereq = modulerequest(request);

	async.waterfall([
		modulecollector.bind(null, modulereq),
		modulepackager.bind(null, modulereq),
		modulecache.bind(null, modulereq)
	], function (err, source, byteLength, lastModified) {

		if (err) {
			// handle errors

			log(['Error', err].join(' '));

			if (err.statusCode) {
				response.writeHead(err.statusCode, {'Content-Type': 'text/plain'});
				response.end(err.message, 'utf8')
			} else {
				response.writeHead(500, {'Content-Type': 'text/plain'});
				response.end('Internal server error', 'utf8');
			}
			return;
		}

		var responseStatus = 200;

		if (request.headers['if-modified-since']) {
			var ifModifiedSince = new Date(request.headers['if-modified-since']);

			if (+lastModified <= +ifModifiedSince) {
				responseStatus = 304;
				byteLength = 0;
				source = '';
			}
		}

		// serve content
		response.writeHead(responseStatus, {
			'Content-Type': 'application/x-javascript;charset=UTF-8',
			'Content-Length': byteLength,
			'Last-Modified': lastModified.toUTCString(),
			'Cache-Control': 'must-revalidate',
			'X-JMS-Cache': 'MISS'
		});

		response.end(source, 'utf8');

	});

}<|endoftext|>


<commit_before>"use strict";
var crypto = require('crypto');

function generateUniqueId(len, cb) {
    var id = "";
    try {
        id = crypto.randomBytes(len).toString('hex');
        cb(null, id);
    } catch (err) {
        cb(err);
    }
}

function getDeployer(config) {
    var deployerDriver = require("./" + config.driver.type + "/" + config.driver.driver + ".js");
    return deployerDriver;
}

var deployer = {
    "createContainer": function (deployerConfig, params, mongo, cb) {
        var name = params.name;
        var environment = params.env;
        var dockerImage = params.image;
        //var profile = params.profile;
        var links = params.links;

        generateUniqueId(8, function (err, uid) {
            if (err) {
                return cb(err);
            }

            var containerName = name + "_" + uid + "_" + environment;

            var env = [
                "SOAJS_ENV=" + environment
            ];

            //used by gc service to pass new env params
            if (params.variables && Array.isArray(params.variables) && params.variables.length > 0) {
                env = env.concat(params.variables);
            }

            var port = null;
            if (params.port) {
                port = {};
                port["" + params.port + "/tcp"] = [{"HostPort": "" + params.port}];
            }

            deployerConfig.envCode = environment;

            var deployer = getDeployer(deployerConfig);
            var options = {
                Image: dockerImage,
                name: containerName,
                "Env": env,
                "Tty": false,
                "Hostname": containerName,
                "HostConfig": {
	                "PortBindings": port,
                    "PublishAllPorts": true
                }
            };

            if (deployerConfig.config && deployerConfig.config.HostConfig && deployerConfig.config.HostConfig.NetworkMode) {
                options.HostConfig.NetworkMode = deployerConfig.config.HostConfig.NetworkMode;
            }

            if (deployerConfig.config && deployerConfig.config.MachineName) {
                options.Env.concat("constraint:node==" + deployerConfig.config.MachineName);
            }

	        if(links && Array.isArray(links) && links.length > 0){
		        options.HostConfig.Links = links;
	        }

            if (params.Cmd) {
                options.Cmd = params.Cmd;
            }
            deployer.createContainer(deployerConfig, options, mongo, cb);
        });
    },

    "start": function (deployerConfig, cid, mongo, cb) {
        var deployer = getDeployer(deployerConfig);
        deployer.start(deployerConfig, cid, mongo, cb);
    },

    "remove": function (deployerConfig, cid, mongo, cb) {
        var deployer = getDeployer(deployerConfig);
        deployer.remove(deployerConfig, cid, mongo, cb);
    },

    "info": function (deployerConfig, cid, req, res, mongo) {
        var deployer = getDeployer(deployerConfig);
        deployer.info(deployerConfig, cid, req, res, mongo);
    }
};
module.exports = deployer;<commit_msg>exposed port 443<commit_after>"use strict";
var crypto = require('crypto');

function generateUniqueId(len, cb) {
    var id = "";
    try {
        id = crypto.randomBytes(len).toString('hex');
        cb(null, id);
    } catch (err) {
        cb(err);
    }
}

function getDeployer(config) {
    var deployerDriver = require("./" + config.driver.type + "/" + config.driver.driver + ".js");
    return deployerDriver;
}

var deployer = {
    "createContainer": function (deployerConfig, params, mongo, cb) {
        var name = params.name;
        var environment = params.env;
        var dockerImage = params.image;
        //var profile = params.profile;
        var links = params.links;

        generateUniqueId(8, function (err, uid) {
            if (err) {
                return cb(err);
            }

            var containerName = name + "_" + uid + "_" + environment;

            var env = [
                "SOAJS_ENV=" + environment
            ];

            //used by gc service to pass new env params
            if (params.variables && Array.isArray(params.variables) && params.variables.length > 0) {
                env = env.concat(params.variables);
            }

            var port = null;
            if (params.port) {
                port = {};
                port["" + params.port + "/tcp"] = [{"HostPort": "" + params.port}];
	            port["443/tcp"] = [{"HostPort": "443"}];
            }

            deployerConfig.envCode = environment;

            var deployer = getDeployer(deployerConfig);
            var options = {
                Image: dockerImage,
                name: containerName,
                "Env": env,
                "Tty": false,
                "Hostname": containerName,
                "HostConfig": {
	                "PortBindings": port,
                    "PublishAllPorts": true
                }
            };

            if (deployerConfig.config && deployerConfig.config.HostConfig && deployerConfig.config.HostConfig.NetworkMode) {
                options.HostConfig.NetworkMode = deployerConfig.config.HostConfig.NetworkMode;
            }

            if (deployerConfig.config && deployerConfig.config.MachineName) {
                options.Env.concat("constraint:node==" + deployerConfig.config.MachineName);
            }

	        if(links && Array.isArray(links) && links.length > 0){
		        options.HostConfig.Links = links;
	        }

            if (params.Cmd) {
                options.Cmd = params.Cmd;
            }
            deployer.createContainer(deployerConfig, options, mongo, cb);
        });
    },

    "start": function (deployerConfig, cid, mongo, cb) {
        var deployer = getDeployer(deployerConfig);
        deployer.start(deployerConfig, cid, mongo, cb);
    },

    "remove": function (deployerConfig, cid, mongo, cb) {
        var deployer = getDeployer(deployerConfig);
        deployer.remove(deployerConfig, cid, mongo, cb);
    },

    "info": function (deployerConfig, cid, req, res, mongo) {
        var deployer = getDeployer(deployerConfig);
        deployer.info(deployerConfig, cid, req, res, mongo);
    }
};
module.exports = deployer;<|endoftext|>


<commit_before>/*
 * Copyright 2015 the Mimu Authors (Dan Bornstein et alia).
 * Licensed AS IS and WITHOUT WARRANTY under the Apache License,
 * Version 2.0. Details: <http://www.apache.org/licenses/LICENSE-2.0>
 */

"use strict";

// The following repos were used as reference while implementing this class:
// * https://github.com/dfcreative/color-name
// * https://github.com/MoOx/color-string
// * https://github.com/MoOx/color

// Map of by-name colors.
var NAMED_COLORS = {
    aliceblue:            "#f0f8ff",
    antiquewhite:         "#faebd7",
    aqua:                 "#00ffff",
    aquamarine:           "#7fffd4",
    azure:                "#f0ffff",
    beige:                "#f5f5dc",
    bisque:               "#ffe4c4",
    black:                "#000000",
    blanchedalmond:       "#ffebcd",
    blue:                 "#0000ff",
    blueviolet:           "#8a2be2",
    brown:                "#a52a2a",
    burlywood:            "#deb887",
    cadetblue:            "#5f9ea0",
    chartreuse:           "#7fff00",
    chocolate:            "#d2691e",
    coral:                "#ff7f50",
    cornflowerblue:       "#6495ed",
    cornsilk:             "#fff8dc",
    crimson:              "#dc143c",
    cyan:                 "#00ffff",
    darkblue:             "#00008b",
    darkcyan:             "#008b8b",
    darkgoldenrod:        "#b8860b",
    darkgray:             "#a9a9a9",
    darkgreen:            "#006400",
    darkgrey:             "#a9a9a9",
    darkkhaki:            "#bdb76b",
    darkmagenta:          "#8b008b",
    darkolivegreen:       "#556b2f",
    darkorange:           "#ff8c00",
    darkorchid:           "#9932cc",
    darkred:              "#8b0000",
    darksalmon:           "#e9967a",
    darkseagreen:         "#8fbc8f",
    darkslateblue:        "#483d8b",
    darkslategray:        "#2f4f4f",
    darkslategrey:        "#2f4f4f",
    darkturquoise:        "#00ced1",
    darkviolet:           "#9400d3",
    deeppink:             "#ff1493",
    deepskyblue:          "#00bfff",
    dimgray:              "#696969",
    dimgrey:              "#696969",
    dodgerblue:           "#1e90ff",
    firebrick:            "#b22222",
    floralwhite:          "#fffaf0",
    forestgreen:          "#228b22",
    fuchsia:              "#ff00ff",
    gainsboro:            "#dcdcdc",
    ghostwhite:           "#f8f8ff",
    gold:                 "#ffd700",
    goldenrod:            "#daa520",
    gray:                 "#808080",
    green:                "#008000",
    greenyellow:          "#adff2f",
    grey:                 "#808080",
    honeydew:             "#f0fff0",
    hotpink:              "#ff69b4",
    indianred:            "#cd5c5c",
    indigo:               "#4b0082",
    ivory:                "#fffff0",
    khaki:                "#f0e68c",
    lavender:             "#e6e6fa",
    lavenderblush:        "#fff0f5",
    lawngreen:            "#7cfc00",
    lemonchiffon:         "#fffacd",
    lightblue:            "#add8e6",
    lightcoral:           "#f08080",
    lightcyan:            "#e0ffff",
    lightgoldenrodyellow: "#fafad2",
    lightgray:            "#d3d3d3",
    lightgreen:           "#90ee90",
    lightgrey:            "#d3d3d3",
    lightpink:            "#ffb6c1",
    lightsalmon:          "#ffa07a",
    lightseagreen:        "#20b2aa",
    lightskyblue:         "#87cefa",
    lightslategray:       "#778899",
    lightslategrey:       "#778899",
    lightsteelblue:       "#b0c4de",
    lightyellow:          "#ffffe0",
    lime:                 "#00ff00",
    limegreen:            "#32cd32",
    linen:                "#faf0e6",
    magenta:              "#ff00ff",
    maroon:               "#800000",
    mediumaquamarine:     "#66cdaa",
    mediumblue:           "#0000cd",
    mediumorchid:         "#ba55d3",
    mediumpurple:         "#9370db",
    mediumseagreen:       "#3cb371",
    mediumslateblue:      "#7b68ee",
    mediumspringgreen:    "#00fa9a",
    mediumturquoise:      "#48d1cc",
    mediumvioletred:      "#c71585",
    midnightblue:         "#191970",
    mintcream:            "#f5fffa",
    mistyrose:            "#ffe4e1",
    moccasin:             "#ffe4b5",
    navajowhite:          "#ffdead",
    navy:                 "#000080",
    oldlace:              "#fdf5e6",
    olive:                "#808000",
    olivedrab:            "#6b8e23",
    orange:               "#ffa500",
    orangered:            "#ff4500",
    orchid:               "#da70d6",
    palegoldenrod:        "#eee8aa",
    palegreen:            "#98fb98",
    paleturquoise:        "#afeeee",
    palevioletred:        "#db7093",
    papayawhip:           "#ffefd5",
    peachpuff:            "#ffdab9",
    peru:                 "#cd853f",
    pink:                 "#ffc0cb",
    plum:                 "#dda0dd",
    powderblue:           "#b0e0e6",
    purple:               "#800080",
    rebeccapurple:        "#663399",
    red:                  "#ff0000",
    rosybrown:            "#bc8f8f",
    royalblue:            "#4169e1",
    saddlebrown:          "#8b4513",
    salmon:               "#fa8072",
    sandybrown:           "#f4a460",
    seagreen:             "#2e8b57",
    seashell:             "#fff5ee",
    sienna:               "#a0522d",
    silver:               "#c0c0c0",
    skyblue:              "#87ceeb",
    slateblue:            "#6a5acd",
    slategray:            "#708090",
    slategrey:            "#708090",
    snow:                 "#fffafa",
    springgreen:          "#00ff7f",
    steelblue:            "#4682b4",
    tan:                  "#d2b48c",
    teal:                 "#008080",
    thistle:              "#d8bfd8",
    tomato:               "#ff6347",
    transparent:          "#00000000",
    turquoise:            "#40e0d0",
    violet:               "#ee82ee",
    wheat:                "#f5deb3",
    white:                "#ffffff",
    whitesmoke:           "#f5f5f5",
    yellow:               "#ffff00",
    yellowgreen:          "#9acd32"
}

// Simple color container and manipulator.
class Color {
    constructor() {
        this._red = 0;
        this._green = 0;
        this._blue = 0;
        this._alpha = 0;
    }

    // Clone an instance.
    clone() {
        var c = new Color();

        c._red   = this._red;
        c._green = this._green;
        c._blue  = this._blue;
        c._alpha = this._alpha;
        return c;
    }

    // Gets the color as a CSS string.
    toCss() {
        var rgb = this._red + ", " + this._green + ", " + this._blue;

        if (this._alpha == 1) {
            return "rgb(" + rgb + ")";
        } else {
            return "rgba(" + rgb + ", " + this._alpha + ")";
        }
    }

    // Mixes in the given color at the given weight (defaults to 0.5). Returns
    // a new color representing the combination.
    mix(other, weight) {
        // Adapted from MoOx's color module, which in turn is an adaptation
        // from Sass.
        if (weight === undefined) { weight = 0.5; }

        var p = weight;
        var w = 2 * p - 1;
        var a = this._alpha - other._alpha;
        var w1 = (((w*a == -1) ? w : (w+a)/(1 + w*a)) + 1) / 2.0;
        var w2 = 1 - w1;

        var result = new Color();
        result._setNums(
            (w1 * this._red)   + (w2 * other._red),
            (w1 * this._green) + (w2 * other._green),
            (w1 * this._blue)  + (w2 * other._blue),
            (p  * this._alpha) + ((1-p) * other._alpha));
        return result;
    }

    // Sets the four values (with alpha optional) given one- or two-character
    // hex strings.
    _setHex(r, g, b, a) {
        if (!a) {
            a = "ff";
        }

        if (r.length === 1) { r = r + r; }
        if (g.length === 1) { g = g + g; }
        if (b.length === 1) { b = b + b; }
        if (a.length === 1) { a = a + a; }

        this._setNums(
            parseInt(r, 16),
            parseInt(g, 16),
            parseInt(b, 16),
            (parseInt(a, 16) / 255));
    }

    // Sets the four values (with alpha optional) given in-range numeric
    // values.
    _setNums(r, g, b, a) {
        if (!a) {
            a = 1;
        }

        this._red   = Math.trunc(r);
        this._green = Math.trunc(g);
        this._blue  = Math.trunc(b);
        this._alpha = a;
    }

    // Parse an instance out of a string in some of the standard CSS formats.
    // Currently supported are 3, 4, 6, and 8 digit hex forms; and `rgb` and
    // `rgba` function forms.
    static parse(cssString) {
        var result = NAMED_COLORS[cssString];
        if (result) {
            if (typeof result === "string") {
                result = Color.parse(result);
                NAMED_COLORS[cssString] = result;
            }
            return result.clone();
        }

        result = new Color();
        var match;

        if (match = cssString.match(/^#([a-fA-F0-9]{3,8})$/)) {
            match = match[1]; // The parenthesized part.
            switch (match.length) {
                case 3: {
                    result._setHex(match[0], match[1], match[2]);
                    break;
                }
                case 4: {
                    result._setHex(match[0], match[1], match[2], match[3]);
                    break;
                }
                case 6: {
                    result._setHex(match[0] + match[1], match[2] + match[3],
                        match[4] + match[5]);
                    break;
                }
                case 8: {
                    result._setHex(match[0] + match[1], match[2] + match[3],
                        match[4] + match[5], match[6] + match[7]);
                    break;
                }
                default: {
                    return undefined;
                }
            }
        } else if (match = Color._parseFunc(cssString)) {
            switch(match[0]) {
                case "rgb": {
                    if (match.length !== 4) {
                        return undefined;
                    }
                    var r = Color._parseNum(match[1], 255, true);
                    var g = Color._parseNum(match[2], 255, true);
                    var b = Color._parseNum(match[3], 255, true);
                    if (isNaN(r + g + b)) {
                        return undefined;
                    }
                    result._setNums(r, g, b);
                    break;
                }
                case "rgba": {
                    if (match.length !== 5) {
                        return undefined;
                    }
                    var r = Color._parseNum(match[1], 255, true);
                    var g = Color._parseNum(match[2], 255, true);
                    var b = Color._parseNum(match[3], 255, true);
                    var a = Color._parseNum(match[4], 1);
                    if (isNaN(r + g + b + a)) {
                        return undefined;
                    }
                    result._setNums(r, g, b, a);
                    break;
                }
                default: {
                    return undefined;
                }
            }
        } else {
            return undefined;
        }

        return result;
    }

    // Parses a function form with up to four arguments. Returns the array
    // of name followed by arguments if matched or `undefined` if there was
    // no match.
    static _parseFunc(cssString) {
        // Match the name and outer parens.
        var match = cssString.match(/^([a-z]+)\s*\(\s*(.*)\s*\)$/);
        if (!match) {
            return undefined;
        }

        var result = [match[1]];
        var argString = "," + match[2];

        if (argString === ",") {
            return result;
        }

        while (argString !== "") {
            match = argString.match(/^,\s*([^, ]+)\s*(.*)$/);
            if (!match) {
                return undefined;
            }
            result.push(match[1]);
            argString = match[2];
        }

        return result;
    }

    // Parses a numeric value, with percent-scaling, clamping, and optional
    // truncation. If parsing fails, returns NaN.
    static _parseNum(s, max, trunc) {
        var match = s.match(/^([-+]?[0-9]*\.?[0-9]*)(%?)$/);
        if (!match) {
            return NaN;
        }

        var isPercent = (match[2] == "%");
        var result = parseFloat(match[1]);

        if (isNaN(result)) {
            return result;
        }

        if (isPercent) {
            result = Color._clamp(result, 100);
            result = (result / 100) * max;
        } else {
            result = Color._clamp(result, max);
        }

        if (trunc) {
            result = Math.trunc(result);
        }

        return result;
    }

    // Clamps a value to be between 0 and a given maximum.
    static _clamp(n, max) {
        if (n < 0) {
            return 0;
        } else if (n > max) {
            return max;
        }

        return n;
    }
}
<commit_msg>Minor clarity.<commit_after>/*
 * Copyright 2015 the Mimu Authors (Dan Bornstein et alia).
 * Licensed AS IS and WITHOUT WARRANTY under the Apache License,
 * Version 2.0. Details: <http://www.apache.org/licenses/LICENSE-2.0>
 */

"use strict";

// The following repos were used as reference while implementing this class:
// * https://github.com/dfcreative/color-name
// * https://github.com/MoOx/color-string
// * https://github.com/MoOx/color

// Map of by-name colors.
var NAMED_COLORS = {
    aliceblue:            "#f0f8ff",
    antiquewhite:         "#faebd7",
    aqua:                 "#00ffff",
    aquamarine:           "#7fffd4",
    azure:                "#f0ffff",
    beige:                "#f5f5dc",
    bisque:               "#ffe4c4",
    black:                "#000000",
    blanchedalmond:       "#ffebcd",
    blue:                 "#0000ff",
    blueviolet:           "#8a2be2",
    brown:                "#a52a2a",
    burlywood:            "#deb887",
    cadetblue:            "#5f9ea0",
    chartreuse:           "#7fff00",
    chocolate:            "#d2691e",
    coral:                "#ff7f50",
    cornflowerblue:       "#6495ed",
    cornsilk:             "#fff8dc",
    crimson:              "#dc143c",
    cyan:                 "#00ffff",
    darkblue:             "#00008b",
    darkcyan:             "#008b8b",
    darkgoldenrod:        "#b8860b",
    darkgray:             "#a9a9a9",
    darkgreen:            "#006400",
    darkgrey:             "#a9a9a9",
    darkkhaki:            "#bdb76b",
    darkmagenta:          "#8b008b",
    darkolivegreen:       "#556b2f",
    darkorange:           "#ff8c00",
    darkorchid:           "#9932cc",
    darkred:              "#8b0000",
    darksalmon:           "#e9967a",
    darkseagreen:         "#8fbc8f",
    darkslateblue:        "#483d8b",
    darkslategray:        "#2f4f4f",
    darkslategrey:        "#2f4f4f",
    darkturquoise:        "#00ced1",
    darkviolet:           "#9400d3",
    deeppink:             "#ff1493",
    deepskyblue:          "#00bfff",
    dimgray:              "#696969",
    dimgrey:              "#696969",
    dodgerblue:           "#1e90ff",
    firebrick:            "#b22222",
    floralwhite:          "#fffaf0",
    forestgreen:          "#228b22",
    fuchsia:              "#ff00ff",
    gainsboro:            "#dcdcdc",
    ghostwhite:           "#f8f8ff",
    gold:                 "#ffd700",
    goldenrod:            "#daa520",
    gray:                 "#808080",
    green:                "#008000",
    greenyellow:          "#adff2f",
    grey:                 "#808080",
    honeydew:             "#f0fff0",
    hotpink:              "#ff69b4",
    indianred:            "#cd5c5c",
    indigo:               "#4b0082",
    ivory:                "#fffff0",
    khaki:                "#f0e68c",
    lavender:             "#e6e6fa",
    lavenderblush:        "#fff0f5",
    lawngreen:            "#7cfc00",
    lemonchiffon:         "#fffacd",
    lightblue:            "#add8e6",
    lightcoral:           "#f08080",
    lightcyan:            "#e0ffff",
    lightgoldenrodyellow: "#fafad2",
    lightgray:            "#d3d3d3",
    lightgreen:           "#90ee90",
    lightgrey:            "#d3d3d3",
    lightpink:            "#ffb6c1",
    lightsalmon:          "#ffa07a",
    lightseagreen:        "#20b2aa",
    lightskyblue:         "#87cefa",
    lightslategray:       "#778899",
    lightslategrey:       "#778899",
    lightsteelblue:       "#b0c4de",
    lightyellow:          "#ffffe0",
    lime:                 "#00ff00",
    limegreen:            "#32cd32",
    linen:                "#faf0e6",
    magenta:              "#ff00ff",
    maroon:               "#800000",
    mediumaquamarine:     "#66cdaa",
    mediumblue:           "#0000cd",
    mediumorchid:         "#ba55d3",
    mediumpurple:         "#9370db",
    mediumseagreen:       "#3cb371",
    mediumslateblue:      "#7b68ee",
    mediumspringgreen:    "#00fa9a",
    mediumturquoise:      "#48d1cc",
    mediumvioletred:      "#c71585",
    midnightblue:         "#191970",
    mintcream:            "#f5fffa",
    mistyrose:            "#ffe4e1",
    moccasin:             "#ffe4b5",
    navajowhite:          "#ffdead",
    navy:                 "#000080",
    oldlace:              "#fdf5e6",
    olive:                "#808000",
    olivedrab:            "#6b8e23",
    orange:               "#ffa500",
    orangered:            "#ff4500",
    orchid:               "#da70d6",
    palegoldenrod:        "#eee8aa",
    palegreen:            "#98fb98",
    paleturquoise:        "#afeeee",
    palevioletred:        "#db7093",
    papayawhip:           "#ffefd5",
    peachpuff:            "#ffdab9",
    peru:                 "#cd853f",
    pink:                 "#ffc0cb",
    plum:                 "#dda0dd",
    powderblue:           "#b0e0e6",
    purple:               "#800080",
    rebeccapurple:        "#663399",
    red:                  "#ff0000",
    rosybrown:            "#bc8f8f",
    royalblue:            "#4169e1",
    saddlebrown:          "#8b4513",
    salmon:               "#fa8072",
    sandybrown:           "#f4a460",
    seagreen:             "#2e8b57",
    seashell:             "#fff5ee",
    sienna:               "#a0522d",
    silver:               "#c0c0c0",
    skyblue:              "#87ceeb",
    slateblue:            "#6a5acd",
    slategray:            "#708090",
    slategrey:            "#708090",
    snow:                 "#fffafa",
    springgreen:          "#00ff7f",
    steelblue:            "#4682b4",
    tan:                  "#d2b48c",
    teal:                 "#008080",
    thistle:              "#d8bfd8",
    tomato:               "#ff6347",
    transparent:          "#00000000",
    turquoise:            "#40e0d0",
    violet:               "#ee82ee",
    wheat:                "#f5deb3",
    white:                "#ffffff",
    whitesmoke:           "#f5f5f5",
    yellow:               "#ffff00",
    yellowgreen:          "#9acd32"
}

// Simple color container and manipulator.
class Color {
    constructor() {
        this._red = 0;
        this._green = 0;
        this._blue = 0;
        this._alpha = 0;
    }

    // Clone an instance.
    clone() {
        var c = new Color();

        c._red   = this._red;
        c._green = this._green;
        c._blue  = this._blue;
        c._alpha = this._alpha;
        return c;
    }

    // Gets the color as a CSS string.
    toCss() {
        var rgb = this._red + ", " + this._green + ", " + this._blue;

        if (this._alpha == 1) {
            return "rgb(" + rgb + ")";
        } else {
            return "rgba(" + rgb + ", " + this._alpha + ")";
        }
    }

    // Mixes in the given color at the given weight (defaults to 0.5). Returns
    // a new color representing the combination.
    mix(other, weight) {
        // Adapted from MoOx's color module, which in turn is an adaptation
        // from Sass.
        if (weight === undefined) { weight = 0.5; }

        var p = weight;
        var w = (2 * p) - 1;
        var a = this._alpha - other._alpha;
        var w1 = (((w*a == -1) ? w : (w+a)/(1 + w*a)) + 1) / 2.0;
        var w2 = 1 - w1;

        var result = new Color();
        result._setNums(
            (w1 * this._red)   + (w2 * other._red),
            (w1 * this._green) + (w2 * other._green),
            (w1 * this._blue)  + (w2 * other._blue),
            (p  * this._alpha) + ((1-p) * other._alpha));
        return result;
    }

    // Sets the four values (with alpha optional) given one- or two-character
    // hex strings.
    _setHex(r, g, b, a) {
        if (!a) {
            a = "ff";
        }

        if (r.length === 1) { r = r + r; }
        if (g.length === 1) { g = g + g; }
        if (b.length === 1) { b = b + b; }
        if (a.length === 1) { a = a + a; }

        this._setNums(
            parseInt(r, 16),
            parseInt(g, 16),
            parseInt(b, 16),
            (parseInt(a, 16) / 255));
    }

    // Sets the four values (with alpha optional) given in-range numeric
    // values.
    _setNums(r, g, b, a) {
        if (!a) {
            a = 1;
        }

        this._red   = Math.trunc(r);
        this._green = Math.trunc(g);
        this._blue  = Math.trunc(b);
        this._alpha = a;
    }

    // Parse an instance out of a string in some of the standard CSS formats.
    // Currently supported are 3, 4, 6, and 8 digit hex forms; and `rgb` and
    // `rgba` function forms.
    static parse(cssString) {
        var result = NAMED_COLORS[cssString];
        if (result) {
            if (typeof result === "string") {
                result = Color.parse(result);
                NAMED_COLORS[cssString] = result;
            }
            return result.clone();
        }

        result = new Color();
        var match;

        if (match = cssString.match(/^#([a-fA-F0-9]{3,8})$/)) {
            match = match[1]; // The parenthesized part.
            switch (match.length) {
                case 3: {
                    result._setHex(match[0], match[1], match[2]);
                    break;
                }
                case 4: {
                    result._setHex(match[0], match[1], match[2], match[3]);
                    break;
                }
                case 6: {
                    result._setHex(match[0] + match[1], match[2] + match[3],
                        match[4] + match[5]);
                    break;
                }
                case 8: {
                    result._setHex(match[0] + match[1], match[2] + match[3],
                        match[4] + match[5], match[6] + match[7]);
                    break;
                }
                default: {
                    return undefined;
                }
            }
        } else if (match = Color._parseFunc(cssString)) {
            switch(match[0]) {
                case "rgb": {
                    if (match.length !== 4) {
                        return undefined;
                    }
                    var r = Color._parseNum(match[1], 255, true);
                    var g = Color._parseNum(match[2], 255, true);
                    var b = Color._parseNum(match[3], 255, true);
                    if (isNaN(r + g + b)) {
                        return undefined;
                    }
                    result._setNums(r, g, b);
                    break;
                }
                case "rgba": {
                    if (match.length !== 5) {
                        return undefined;
                    }
                    var r = Color._parseNum(match[1], 255, true);
                    var g = Color._parseNum(match[2], 255, true);
                    var b = Color._parseNum(match[3], 255, true);
                    var a = Color._parseNum(match[4], 1);
                    if (isNaN(r + g + b + a)) {
                        return undefined;
                    }
                    result._setNums(r, g, b, a);
                    break;
                }
                default: {
                    return undefined;
                }
            }
        } else {
            return undefined;
        }

        return result;
    }

    // Parses a function form with up to four arguments. Returns the array
    // of name followed by arguments if matched or `undefined` if there was
    // no match.
    static _parseFunc(cssString) {
        // Match the name and outer parens.
        var match = cssString.match(/^([a-z]+)\s*\(\s*(.*)\s*\)$/);
        if (!match) {
            return undefined;
        }

        var result = [match[1]];
        var argString = "," + match[2];

        if (argString === ",") {
            return result;
        }

        while (argString !== "") {
            match = argString.match(/^,\s*([^, ]+)\s*(.*)$/);
            if (!match) {
                return undefined;
            }
            result.push(match[1]);
            argString = match[2];
        }

        return result;
    }

    // Parses a numeric value, with percent-scaling, clamping, and optional
    // truncation. If parsing fails, returns NaN.
    static _parseNum(s, max, trunc) {
        var match = s.match(/^([-+]?[0-9]*\.?[0-9]*)(%?)$/);
        if (!match) {
            return NaN;
        }

        var isPercent = (match[2] == "%");
        var result = parseFloat(match[1]);

        if (isNaN(result)) {
            return result;
        }

        if (isPercent) {
            result = Color._clamp(result, 100);
            result = (result / 100) * max;
        } else {
            result = Color._clamp(result, max);
        }

        if (trunc) {
            result = Math.trunc(result);
        }

        return result;
    }

    // Clamps a value to be between 0 and a given maximum.
    static _clamp(n, max) {
        if (n < 0) {
            return 0;
        } else if (n > max) {
            return max;
        }

        return n;
    }
}
<|endoftext|>


<commit_before><commit_msg>Logging requestData for put and post requests<commit_after><|endoftext|>


<commit_before>// npm build command

// everything about the installation after the creation of
// the .npm/{name}/{version}/package folder.
// linking the modules into the npm.root,
// resolving dependencies, etc.

// This runs AFTER install or link are completed.

var npm = require("./npm.js")
  , log = require("npmlog")
  , chain = require("slide").chain
  , fs = require("graceful-fs")
  , path = require("path")
  , lifecycle = require("./utils/lifecycle.js")
  , readJson = require("read-package-json")
  , link = require("./utils/link.js")
  , linkIfExists = link.ifExists
  , cmdShim = require("cmd-shim")
  , cmdShimIfExists = cmdShim.ifExists
  , asyncMap = require("slide").asyncMap

module.exports = build
build.usage = "npm build <folder>\n(this is plumbing)"

build._didBuild = {}
build._noLC = {}
function build (args, global, didPre, didRB, cb) {
  if (typeof cb !== "function") cb = didRB, didRB = false
  if (typeof cb !== "function") cb = didPre, didPre = false
  if (typeof cb !== "function") {
    cb = global, global = npm.config.get("global")
  }
  // it'd be nice to asyncMap these, but actually, doing them
  // in parallel generally munges up the output from node-waf
  var builder = build_(global, didPre, didRB)
  chain(args.map(function (arg) { return function (cb) {
    builder(arg, cb)
  }}), cb)
}

function build_ (global, didPre, didRB) { return function (folder, cb) {
  folder = path.resolve(folder)
  build._didBuild[folder] = true
  log.info("build", folder)
  readJson(path.resolve(folder, "package.json"), function (er, pkg) {
    if (er) return cb(er)
    chain
      ( [ !didPre && [lifecycle, pkg, "preinstall", folder]
        , [linkStuff, pkg, folder, global, didRB]
        , pkg.name === "npm" && [writeBuiltinConf, folder]
        , didPre !== build._noLC && [lifecycle, pkg, "install", folder]
        , didPre !== build._noLC && [lifecycle, pkg, "postinstall", folder]
        , didPre !== build._noLC
          && npm.config.get("npat")
          && [lifecycle, pkg, "test", folder] ]
      , cb )
  })
}}

function writeBuiltinConf (folder, cb) {
  // the builtin config is "sticky". Any time npm installs itself,
  // it puts its builtin config file there, as well.
  if (!npm.config.usingBuiltin
      || folder !== path.dirname(__dirname)) {
    return cb()
  }
  npm.config.save("builtin", cb)
}

function linkStuff (pkg, folder, global, didRB, cb) {
  // allow to opt out of linking binaries.
  if (npm.config.get("bin-links") === false) return cb()

  // if it's global, and folder is in {prefix}/node_modules,
  // then bins are in {prefix}/bin
  // otherwise, then bins are in folder/../.bin
  var parent = path.dirname(folder)
    , gnm = global && npm.globalDir
    , top = parent === npm.dir
    , gtop = parent === gnm

  log.verbose("linkStuff", [global, gnm, gtop, parent])
  log.info("linkStuff", pkg._id)

  shouldWarn(pkg, folder, global, function() {
    asyncMap( [linkBins, linkMans, !didRB && rebuildBundles]
            , function (fn, cb) {
      if (!fn) return cb()
      log.verbose(fn.name, pkg._id)
      fn(pkg, folder, parent, gtop, cb)
    }, cb)
  })
}

function shouldWarn(pkg, folder, global, cb) {
  var parent = path.dirname(folder)
    , top = parent === npm.dir
    , cwd = process.cwd()

  readJson(path.resolve(cwd, "package.json"), function(er, topPkg) {
    if (er) return cb(er)

    var linkedPkg = path.basename(cwd)
      , currentPkg = path.basename(folder)

    // current searched package is the linked package on first call
    if (linkedPkg !== currentPkg) {

      if (!topPkg.dependencies) return

      // don't generate a warning if it's listed in dependencies
      if (Object.keys(topPkg.dependencies).indexOf(currentPkg) === -1) {

        if (top && pkg.preferGlobal && !global) {
          log.warn("prefer global", pkg._id + " should be installed with -g")
        }
      }
    }

    cb()
  })
}

function rebuildBundles (pkg, folder, parent, gtop, cb) {
  if (!npm.config.get("rebuild-bundle")) return cb()

  var deps = Object.keys(pkg.dependencies || {})
             .concat(Object.keys(pkg.devDependencies || {}))
    , bundles = pkg.bundleDependencies || pkg.bundledDependencies || []

  fs.readdir(path.resolve(folder, "node_modules"), function (er, files) {
    // error means no bundles
    if (er) return cb()

    log.verbose("rebuildBundles", files)
    // don't asyncMap these, because otherwise build script output
    // gets interleaved and is impossible to read
    chain(files.filter(function (file) {
      // rebuild if:
      // not a .folder, like .bin or .hooks
      return !file.match(/^[\._-]/)
          // not some old 0.x style bundle
          && file.indexOf("@") === -1
          // either not a dep, or explicitly bundled
          && (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1)
    }).map(function (file) {
      file = path.resolve(folder, "node_modules", file)
      return function (cb) {
        if (build._didBuild[file]) return cb()
        log.verbose("rebuild bundle", file)
        // if file is not a package dir, then don't do it.
        fs.lstat(path.resolve(file, "package.json"), function (er, st) {
          if (er) return cb()
          build_(false)(file, cb)
        })
    }}), cb)
  })
}

function linkBins (pkg, folder, parent, gtop, cb) {
  if (!pkg.bin || !gtop && path.basename(parent) !== "node_modules") {
    return cb()
  }
  var binRoot = gtop ? npm.globalBin
                     : path.resolve(parent, ".bin")
  log.verbose("link bins", [pkg.bin, binRoot, gtop])

  asyncMap(Object.keys(pkg.bin), function (b, cb) {
    linkBin( path.resolve(folder, pkg.bin[b])
           , path.resolve(binRoot, b)
           , gtop && folder
           , function (er) {
      if (er) return cb(er)
      // bins should always be executable.
      // XXX skip chmod on windows?
      fs.chmod(path.resolve(folder, pkg.bin[b]), npm.modes.exec, function (er) {
        if (er || !gtop) return cb(er)
        var dest = path.resolve(binRoot, b)
          , src = path.resolve(folder, pkg.bin[b])
          , out = npm.config.get("parseable")
                ? dest + "::" + src + ":BINFILE"
                : dest + " -> " + src
        console.log(out)
        cb()
      })
    })
  }, cb)
}

function linkBin (from, to, gently, cb) {
  if (process.platform !== "win32") {
    return linkIfExists(from, to, gently, cb)
  } else {
    return cmdShimIfExists(from, to, cb)
  }
}

function linkMans (pkg, folder, parent, gtop, cb) {
  if (!pkg.man || !gtop || process.platform === "win32") return cb()

  var manRoot = path.resolve(npm.config.get("prefix"), "share", "man")
  asyncMap(pkg.man, function (man, cb) {
    if (typeof man !== "string") return cb()
    var parseMan = man.match(/(.*)\.([0-9]+)(\.gz)?$/)
      , stem = parseMan[1]
      , sxn = parseMan[2]
      , gz = parseMan[3] || ""
      , bn = path.basename(stem)
      , manDest = path.join( manRoot
                           , "man"+sxn
                           , (bn.indexOf(pkg.name) === 0 ? bn
                             : pkg.name + "-" + bn)
                             + "." + sxn + gz
                           )

    linkIfExists(man, manDest, gtop && folder, cb)
  }, cb)
}
<commit_msg>call the cb if topPackage doesn't have dependencies<commit_after>// npm build command

// everything about the installation after the creation of
// the .npm/{name}/{version}/package folder.
// linking the modules into the npm.root,
// resolving dependencies, etc.

// This runs AFTER install or link are completed.

var npm = require("./npm.js")
  , log = require("npmlog")
  , chain = require("slide").chain
  , fs = require("graceful-fs")
  , path = require("path")
  , lifecycle = require("./utils/lifecycle.js")
  , readJson = require("read-package-json")
  , link = require("./utils/link.js")
  , linkIfExists = link.ifExists
  , cmdShim = require("cmd-shim")
  , cmdShimIfExists = cmdShim.ifExists
  , asyncMap = require("slide").asyncMap

module.exports = build
build.usage = "npm build <folder>\n(this is plumbing)"

build._didBuild = {}
build._noLC = {}
function build (args, global, didPre, didRB, cb) {
  if (typeof cb !== "function") cb = didRB, didRB = false
  if (typeof cb !== "function") cb = didPre, didPre = false
  if (typeof cb !== "function") {
    cb = global, global = npm.config.get("global")
  }
  // it'd be nice to asyncMap these, but actually, doing them
  // in parallel generally munges up the output from node-waf
  var builder = build_(global, didPre, didRB)
  chain(args.map(function (arg) { return function (cb) {
    builder(arg, cb)
  }}), cb)
}

function build_ (global, didPre, didRB) { return function (folder, cb) {
  folder = path.resolve(folder)
  build._didBuild[folder] = true
  log.info("build", folder)
  readJson(path.resolve(folder, "package.json"), function (er, pkg) {
    if (er) return cb(er)
    chain
      ( [ !didPre && [lifecycle, pkg, "preinstall", folder]
        , [linkStuff, pkg, folder, global, didRB]
        , pkg.name === "npm" && [writeBuiltinConf, folder]
        , didPre !== build._noLC && [lifecycle, pkg, "install", folder]
        , didPre !== build._noLC && [lifecycle, pkg, "postinstall", folder]
        , didPre !== build._noLC
          && npm.config.get("npat")
          && [lifecycle, pkg, "test", folder] ]
      , cb )
  })
}}

function writeBuiltinConf (folder, cb) {
  // the builtin config is "sticky". Any time npm installs itself,
  // it puts its builtin config file there, as well.
  if (!npm.config.usingBuiltin
      || folder !== path.dirname(__dirname)) {
    return cb()
  }
  npm.config.save("builtin", cb)
}

function linkStuff (pkg, folder, global, didRB, cb) {
  // allow to opt out of linking binaries.
  if (npm.config.get("bin-links") === false) return cb()

  // if it's global, and folder is in {prefix}/node_modules,
  // then bins are in {prefix}/bin
  // otherwise, then bins are in folder/../.bin
  var parent = path.dirname(folder)
    , gnm = global && npm.globalDir
    , top = parent === npm.dir
    , gtop = parent === gnm

  log.verbose("linkStuff", [global, gnm, gtop, parent])
  log.info("linkStuff", pkg._id)

  shouldWarn(pkg, folder, global, function() {
    asyncMap( [linkBins, linkMans, !didRB && rebuildBundles]
            , function (fn, cb) {
      if (!fn) return cb()
      log.verbose(fn.name, pkg._id)
      fn(pkg, folder, parent, gtop, cb)
    }, cb)
  })
}

function shouldWarn(pkg, folder, global, cb) {
  var parent = path.dirname(folder)
    , top = parent === npm.dir
    , cwd = process.cwd()

  readJson(path.resolve(cwd, "package.json"), function(er, topPkg) {
    if (er) return cb(er)

    var linkedPkg = path.basename(cwd)
      , currentPkg = path.basename(folder)

    // current searched package is the linked package on first call
    if (linkedPkg !== currentPkg) {

      if (!topPkg.dependencies) return cb()

      // don't generate a warning if it's listed in dependencies
      if (Object.keys(topPkg.dependencies).indexOf(currentPkg) === -1) {

        if (top && pkg.preferGlobal && !global) {
          log.warn("prefer global", pkg._id + " should be installed with -g")
        }
      }
    }

    cb()
  })
}

function rebuildBundles (pkg, folder, parent, gtop, cb) {
  if (!npm.config.get("rebuild-bundle")) return cb()

  var deps = Object.keys(pkg.dependencies || {})
             .concat(Object.keys(pkg.devDependencies || {}))
    , bundles = pkg.bundleDependencies || pkg.bundledDependencies || []

  fs.readdir(path.resolve(folder, "node_modules"), function (er, files) {
    // error means no bundles
    if (er) return cb()

    log.verbose("rebuildBundles", files)
    // don't asyncMap these, because otherwise build script output
    // gets interleaved and is impossible to read
    chain(files.filter(function (file) {
      // rebuild if:
      // not a .folder, like .bin or .hooks
      return !file.match(/^[\._-]/)
          // not some old 0.x style bundle
          && file.indexOf("@") === -1
          // either not a dep, or explicitly bundled
          && (deps.indexOf(file) === -1 || bundles.indexOf(file) !== -1)
    }).map(function (file) {
      file = path.resolve(folder, "node_modules", file)
      return function (cb) {
        if (build._didBuild[file]) return cb()
        log.verbose("rebuild bundle", file)
        // if file is not a package dir, then don't do it.
        fs.lstat(path.resolve(file, "package.json"), function (er, st) {
          if (er) return cb()
          build_(false)(file, cb)
        })
    }}), cb)
  })
}

function linkBins (pkg, folder, parent, gtop, cb) {
  if (!pkg.bin || !gtop && path.basename(parent) !== "node_modules") {
    return cb()
  }
  var binRoot = gtop ? npm.globalBin
                     : path.resolve(parent, ".bin")
  log.verbose("link bins", [pkg.bin, binRoot, gtop])

  asyncMap(Object.keys(pkg.bin), function (b, cb) {
    linkBin( path.resolve(folder, pkg.bin[b])
           , path.resolve(binRoot, b)
           , gtop && folder
           , function (er) {
      if (er) return cb(er)
      // bins should always be executable.
      // XXX skip chmod on windows?
      fs.chmod(path.resolve(folder, pkg.bin[b]), npm.modes.exec, function (er) {
        if (er || !gtop) return cb(er)
        var dest = path.resolve(binRoot, b)
          , src = path.resolve(folder, pkg.bin[b])
          , out = npm.config.get("parseable")
                ? dest + "::" + src + ":BINFILE"
                : dest + " -> " + src
        console.log(out)
        cb()
      })
    })
  }, cb)
}

function linkBin (from, to, gently, cb) {
  if (process.platform !== "win32") {
    return linkIfExists(from, to, gently, cb)
  } else {
    return cmdShimIfExists(from, to, cb)
  }
}

function linkMans (pkg, folder, parent, gtop, cb) {
  if (!pkg.man || !gtop || process.platform === "win32") return cb()

  var manRoot = path.resolve(npm.config.get("prefix"), "share", "man")
  asyncMap(pkg.man, function (man, cb) {
    if (typeof man !== "string") return cb()
    var parseMan = man.match(/(.*)\.([0-9]+)(\.gz)?$/)
      , stem = parseMan[1]
      , sxn = parseMan[2]
      , gz = parseMan[3] || ""
      , bn = path.basename(stem)
      , manDest = path.join( manRoot
                           , "man"+sxn
                           , (bn.indexOf(pkg.name) === 0 ? bn
                             : pkg.name + "-" + bn)
                             + "." + sxn + gz
                           )

    linkIfExists(man, manDest, gtop && folder, cb)
  }, cb)
}
<|endoftext|>


<commit_before>var async    = require('async');
var cron     = require('cron');
var fetcher  = require('./fetcher');
var levelup  = require('level');
var levelttl = require('level-ttl');

const MAX_FETCH        = 5;
const REFRESH_SCHEDULE = '0 0 */1 * * *';

function Cache(categoryList, urlLookup, opts) {
  this.categoryList = categoryList;
  this.urlLookup    = urlLookup;

  this.db = levelttl(levelup(opts.dbDir), {
    defaultTTL: opts.defaultTtl,
    checkFrequency: opts.checkFrequency
  });
}

Cache.prototype.build = function (cb) {
  var self = this;
  console.log('[i] Building cache at ' + new Date());

  var feedTasks = [];
  this.categoryList.forEach(function (category) {
    category.feeds.forEach(function (feed) {
      function feedTask(cb) {
        self.setFeed(feed.url, cb);
      }
      feedTasks.push(feedTask);
    });
  });
  async.parallelLimit(feedTasks, MAX_FETCH, function (err, articlesLists) {
    if (err) {
      cb(err);
    } else {

      var articleTasks = [];
      articlesLists.forEach(function (articlesList) {

        if (Array.isArray(articlesList)) {
          articlesList.forEach(function (article) {
            function articleTask(cb) {
              self.setArticle(article.url, cb);
            }
            articleTasks.push(articleTask);
          });
        } else {
          console.error('[x] Unexpected articlesList: ' + articlesList);
        }

      });
      async.parallelLimit(articleTasks, MAX_FETCH, function (err, results) {
        if (!err) {
          console.log('[v] Cache build done');
        }
        cb(err, results);
      });
    }
  });
};

Cache.prototype.refresh = function () {
  var self = this;
  console.log('[i] Scheduling cache refresh with ' + REFRESH_SCHEDULE);

  var CronJob = cron.CronJob;
  var job     = new CronJob(
    REFRESH_SCHEDULE,
    function () {
      console.log('[i] Refreshing cache at ' + new Date());
      self.build(function (err) {
        if (err) {
          console.error(err);
        }
      });
    },
    function () {
      console.log('[v] Cache refresh done');
    },
    true
  );
};

Cache.prototype.setFeed = function (feedUrl, cb) {
  var self = this;
  fetcher.fetchFeed(feedUrl, function (err, articlesList) {
    if (err) {
      cb();
    } else {
      self.db.put(feedUrl, JSON.stringify(articlesList), function (err) {
        cb(err, articlesList);
      });
    }
  });
};

Cache.prototype.setArticle = function (articleUrl, cb) {
  var self = this;
  this.getArticle(articleUrl, function (err, article) {
    if (err) {
      // an error could mean either the article doesn't yet exist or a genuine error
      fetcher.fetchArticle(articleUrl, function (article) {
        if (article.url === undefined) {
          console.error(new Error('[x] Unable to fetch article ' + articleUrl));
          cb();
        } else {
          // strip fragment identifier from article URL
          // fragment identifier is only available on the client browser and not on the server
          // some feeds, e.g. BBC's contain links with fragment identifier
          self.db.put(articleUrl.replace(/#.*$/, ''), JSON.stringify(article), cb);
        }
      });
    } else {
      console.log('[!] Article already fetched ' + articleUrl);
      // re-add article in order to refresh TTL
      self.db.put(articleUrl, JSON.stringify(article), cb);
    }
  });
};

Cache.prototype.getFeed = function (feedId, cb) {
  var url = this.urlLookup[feedId];
  this.db.get(url, function (err, result) {
    if (err) {
      cb(err);
    } else {
      cb(null, JSON.parse(result));
    }
  });
};

Cache.prototype.getArticle = function (url, cb) {
  this.db.get(url, function (err, result) {
    if (err) {
      cb(err);
    } else {
      console.log(url);
      cb(null, JSON.parse(result));
    }
  });
};

module.exports = Cache;<commit_msg>Minor logging cleanup.<commit_after>var async    = require('async');
var cron     = require('cron');
var fetcher  = require('./fetcher');
var levelup  = require('level');
var levelttl = require('level-ttl');

const MAX_FETCH        = 5;
const REFRESH_SCHEDULE = '0 0 */1 * * *';

function Cache(categoryList, urlLookup, opts) {
  this.categoryList = categoryList;
  this.urlLookup    = urlLookup;

  this.db = levelttl(levelup(opts.dbDir), {
    defaultTTL: opts.defaultTtl,
    checkFrequency: opts.checkFrequency
  });
}

Cache.prototype.build = function (cb) {
  var self = this;
  console.log('[i] Building cache at ' + new Date());

  var feedTasks = [];
  this.categoryList.forEach(function (category) {
    category.feeds.forEach(function (feed) {
      function feedTask(cb) {
        self.setFeed(feed.url, cb);
      }
      feedTasks.push(feedTask);
    });
  });
  async.parallelLimit(feedTasks, MAX_FETCH, function (err, articlesLists) {
    if (err) {
      cb(err);
    } else {

      var articleTasks = [];
      articlesLists.forEach(function (articlesList) {

        if (Array.isArray(articlesList)) {
          articlesList.forEach(function (article) {
            function articleTask(cb) {
              self.setArticle(article.url, cb);
            }
            articleTasks.push(articleTask);
          });
        } else {
          console.error('[x] Unexpected articlesList: ' + articlesList);
        }

      });
      async.parallelLimit(articleTasks, MAX_FETCH, function (err, results) {
        if (!err) {
          console.log('[v] Cache build done');
        }
        cb(err, results);
      });
    }
  });
};

Cache.prototype.refresh = function () {
  var self = this;
  console.log('[i] Scheduling cache refresh with ' + REFRESH_SCHEDULE);

  var CronJob = cron.CronJob;
  var job     = new CronJob(
    REFRESH_SCHEDULE,
    function () {
      console.log('[i] Refreshing cache at ' + new Date());
      self.build(function (err) {
        if (err) {
          console.error(err);
        }
      });
    },
    function () {
      console.log('[v] Cache refresh done');
    },
    true
  );
};

Cache.prototype.setFeed = function (feedUrl, cb) {
  var self = this;
  fetcher.fetchFeed(feedUrl, function (err, articlesList) {
    if (err) {
      cb();
    } else {
      self.db.put(feedUrl, JSON.stringify(articlesList), function (err) {
        cb(err, articlesList);
      });
    }
  });
};

Cache.prototype.setArticle = function (articleUrl, cb) {
  var self = this;
  this.getArticle(articleUrl, function (err, article) {
    if (err) {
      // an error could mean either the article doesn't yet exist or a genuine error
      fetcher.fetchArticle(articleUrl, function (article) {
        if (article.url === undefined) {
          console.error(new Error('[x] Unable to fetch article ' + articleUrl));
          cb();
        } else {
          // strip fragment identifier from article URL
          // fragment identifier is only available on the client browser and not on the server
          // some feeds, e.g. BBC's contain links with fragment identifier
          self.db.put(articleUrl.replace(/#.*$/, ''), JSON.stringify(article), cb);
        }
      });
    } else {
      console.log('[i] Article already fetched ' + articleUrl);
      // re-add article in order to refresh TTL
      self.db.put(articleUrl, JSON.stringify(article), cb);
    }
  });
};

Cache.prototype.getFeed = function (feedId, cb) {
  var url = this.urlLookup[feedId];
  this.db.get(url, function (err, result) {
    if (err) {
      cb(err);
    } else {
      cb(null, JSON.parse(result));
    }
  });
};

Cache.prototype.getArticle = function (url, cb) {
  this.db.get(url, function (err, result) {
    if (err) {
      cb(err);
    } else {
      cb(null, JSON.parse(result));
    }
  });
};

module.exports = Cache;<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Client library for the SDC Compute Node API (CNAPI)
 */

var util = require('util');
var format = util.format;

var RestifyClient = require('./restifyclient');

// --- Exported Client

/**
 * Constructor
 *
 * See the RestifyClient constructor for details
 */
function CNAPI(options) {
    RestifyClient.call(this, options);
}

util.inherits(CNAPI, RestifyClient);

/**
 * Gets boot params for the given CN
 *
 * @param {String} uuid : CN UUID to get
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getBootParams = function (uuid, callback) {
    if (!uuid)
        throw new TypeError('uuid is required (string)');
    return this.get(format('/boot/%s', uuid), callback);
};

/**
 * Lists all servers
 *
 * @param {Object} params : Filter params.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.listServers = function (params, callback) {
    if (typeof (params) === 'function') {
        callback = params;
        params = {};
    }
    return this.get('/servers', params, callback);
};

/**
 * Gets a server by UUID
 *
 * @param {String} uuid : the UUID of the server.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getServer = function (uuid, callback) {
    if (!uuid)
        throw new TypeError('UUID is required');

    return this.get(format('/servers/%s', uuid), callback);
};

/**
 * Setup a server by UUID
 *
 * @param {String} uuid : the UUID of the server.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.setupServer = function (uuid, callback) {
    if (!uuid)
        throw new TypeError('UUID is required');

    return this.post(format('/servers/%s/setup', uuid), {}, callback);
};

/**
 * Gets a task
 *
 * @param {String} id : the task id.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getTask = function (id, callback) {
    if (!id)
        throw new TypeError('Task Id is required');

    return this.get(format('/tasks/%s', id), callback);
};

/**
 * Creates a vm
 *
 * @param {String} server : the UUID of the server.
 * @param {Object} params : attributes of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.createVm = function (server, params, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!params || typeof (params) !== 'object')
        throw new TypeError('params is required (object)');

    return this.post(format('/servers/%s/vms', server), params, callback);
};

/**
 * Gets a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.get(format('/servers/%s/vms/%s', server, uuid), callback);
};

/**
 * Stops a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.stopVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.post(format('/servers/%s/vms/%s/stop', server, uuid),
                     {}, callback);
};

/**
 * Starts a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.startVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.post(format('/servers/%s/vms/%s/start', server, uuid),
                     {}, callback);
};

/**
 * Reboots a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.rebootVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.post(format('/servers/%s/vms/%s/reboot', server, uuid),
                     {}, callback);
};

/**
 * Deletes a vm from a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.deleteVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.del(format('/servers/%s/vms/%s', server, uuid), callback);
};

module.exports = CNAPI;
<commit_msg>TOOLS-146 node-sdc-clients cnapi setupServer -> PUT<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Client library for the SDC Compute Node API (CNAPI)
 */

var util = require('util');
var format = util.format;

var RestifyClient = require('./restifyclient');

// --- Exported Client

/**
 * Constructor
 *
 * See the RestifyClient constructor for details
 */
function CNAPI(options) {
    RestifyClient.call(this, options);
}

util.inherits(CNAPI, RestifyClient);

/**
 * Gets boot params for the given CN
 *
 * @param {String} uuid : CN UUID to get
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getBootParams = function (uuid, callback) {
    if (!uuid)
        throw new TypeError('uuid is required (string)');
    return this.get(format('/boot/%s', uuid), callback);
};

/**
 * Lists all servers
 *
 * @param {Object} params : Filter params.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.listServers = function (params, callback) {
    if (typeof (params) === 'function') {
        callback = params;
        params = {};
    }
    return this.get('/servers', params, callback);
};

/**
 * Gets a server by UUID
 *
 * @param {String} uuid : the UUID of the server.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getServer = function (uuid, callback) {
    if (!uuid)
        throw new TypeError('UUID is required');

    return this.get(format('/servers/%s', uuid), callback);
};

/**
 * Setup a server by UUID
 *
 * @param {String} uuid : the UUID of the server.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.setupServer = function (uuid, callback) {
    if (!uuid)
        throw new TypeError('UUID is required');

    return this.put(format('/servers/%s/setup', uuid), {}, callback);
};

/**
 * Gets a task
 *
 * @param {String} id : the task id.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getTask = function (id, callback) {
    if (!id)
        throw new TypeError('Task Id is required');

    return this.get(format('/tasks/%s', id), callback);
};

/**
 * Creates a vm
 *
 * @param {String} server : the UUID of the server.
 * @param {Object} params : attributes of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.createVm = function (server, params, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!params || typeof (params) !== 'object')
        throw new TypeError('params is required (object)');

    return this.post(format('/servers/%s/vms', server), params, callback);
};

/**
 * Gets a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.getVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.get(format('/servers/%s/vms/%s', server, uuid), callback);
};

/**
 * Stops a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.stopVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.post(format('/servers/%s/vms/%s/stop', server, uuid),
                     {}, callback);
};

/**
 * Starts a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.startVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.post(format('/servers/%s/vms/%s/start', server, uuid),
                     {}, callback);
};

/**
 * Reboots a vm on a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.rebootVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.post(format('/servers/%s/vms/%s/reboot', server, uuid),
                     {}, callback);
};

/**
 * Deletes a vm from a server
 *
 * @param {String} server : the UUID of the server.
 * @param {String} uuid : the UUID of the vm.
 * @param {Function} callback : of the form f(err, res).
 */
CNAPI.prototype.deleteVm = function (server, uuid, callback) {
    if (!server)
        throw new TypeError('Server UUID is required');
    if (!uuid)
        throw new TypeError('VM UUID is required');

    return this.del(format('/servers/%s/vms/%s', server, uuid), callback);
};

module.exports = CNAPI;
<|endoftext|>


<commit_before>/*jshint evil:true, onevar:false*/
/*global define*/
var installedColorSpaces = [],
    namedColors = {},
    undef = function (obj) {
        return typeof obj === 'undefined';
    },
    channelRegExp = /\s*(\.\d+|\d+(?:\.\d+)?)(%)?\s*/,
    alphaChannelRegExp = /\s*(\.\d+|\d+(?:\.\d+)?)\s*/,
    cssColorRegExp = new RegExp(
                         "^(rgb|hsl|hsv)a?" +
                         "\\(" +
                             channelRegExp.source + "," +
                             channelRegExp.source + "," +
                             channelRegExp.source +
                             "(?:," + alphaChannelRegExp.source + ")?" +
                         "\\)$", "i");

function ONECOLOR(obj) {
    if (Object.prototype.toString.apply(obj) === '[object Array]') {
        if (typeof obj[0] === 'string' && typeof ONECOLOR[obj[0]] === 'function') {
            // Assumed array from .toJSON()
            return new ONECOLOR[obj[0]](obj.slice(1, obj.length));
        } else if (obj.length === 4) {
            // Assumed 4 element int RGB array from canvas with all channels [0;255]
            return new ONECOLOR.RGB(obj[0] / 255, obj[1] / 255, obj[2] / 255, obj[3] / 255);
        }
    } else if (typeof obj === 'string') {
        var lowerCased = obj.toLowerCase();
        if (namedColors[lowerCased]) {
            obj = '#' + namedColors[lowerCased];
        }
        // Test for CSS rgb(....) string
        var matchCssSyntax = obj.match(cssColorRegExp);
        if (matchCssSyntax) {
            var colorSpaceName = matchCssSyntax[1].toUpperCase(),
                alpha = undef(matchCssSyntax[8]) ? matchCssSyntax[8] : parseFloat(matchCssSyntax[8]),
                hasHue = colorSpaceName[0] === 'H',
                firstChannelDivisor = matchCssSyntax[3] ? 100 : (hasHue ? 360 : 255),
                secondChannelDivisor = (matchCssSyntax[5] || hasHue) ? 100 : 255,
                thirdChannelDivisor = (matchCssSyntax[7] || hasHue) ? 100 : 255;
            if (undef(ONECOLOR[colorSpaceName])) {
                throw new Error("one.color." + colorSpaceName + " is not installed.");
            }
            return new ONECOLOR[colorSpaceName](
                parseFloat(matchCssSyntax[2]) / firstChannelDivisor,
                parseFloat(matchCssSyntax[4]) / secondChannelDivisor,
                parseFloat(matchCssSyntax[6]) / thirdChannelDivisor,
                alpha
            );
        }
        // Assume hex syntax
        if (obj.length < 6) {
            // Allow CSS shorthand
            obj = obj.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, '$1$1$2$2$3$3');
        }
        // Split obj into red, green, and blue components
        var hexMatch = obj.match(/^#?([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/i);
        if (hexMatch) {
            return new ONECOLOR.RGB(
                parseInt(hexMatch[1], 16) / 255,
                parseInt(hexMatch[2], 16) / 255,
                parseInt(hexMatch[3], 16) / 255
            );
        }
    } else if (typeof obj === 'object' && obj.isColor) {
        return obj;
    } else if (!isNaN(obj)) {
        // Strange integer representation sometimes returned by document.queryCommandValue in some browser...
        return new ONECOLOR.RGB((obj & 0xFF) / 255, ((obj & 0xFF00) >> 8) / 255, ((obj & 0xFF0000) >> 16) / 255);
    }
    return false;
}

function installColorSpace(colorSpaceName, propertyNames, config) {
    ONECOLOR[colorSpaceName] = new Function(propertyNames.join(","),
        // Allow passing an array to the constructor:
        "if (Object.prototype.toString.apply(" + propertyNames[0] + ") === '[object Array]') {" +
            propertyNames.map(function (propertyName, i) {
                return propertyName + "=" + propertyNames[0] + "[" + i + "];";
            }).reverse().join("") +
        "}" +
        "if (" + propertyNames.filter(function (propertyName) {
            return propertyName !== 'alpha';
        }).map(function (propertyName) {
            return "isNaN(" + propertyName + ")";
        }).join("||") + "){" + "throw new Error(\"[" + colorSpaceName + "]: Invalid color: (\"+" + propertyNames.join("+\",\"+") + "+\")\");}" +
        propertyNames.map(function (propertyName) {
            if (propertyName === 'hue') {
                return "this._hue=hue<0?hue-Math.floor(hue):hue%1"; // Wrap
            } else if (propertyName === 'alpha') {
                return "this._alpha=(isNaN(alpha)||alpha>1)?1:(alpha<0?0:alpha);";
            } else {
                return "this._" + propertyName + "=" + propertyName + "<0?0:(" + propertyName + ">1?1:" + propertyName + ")";
            }
        }).join(";") + ";"
    );
    ONECOLOR[colorSpaceName].propertyNames = propertyNames;

    var prototype = ONECOLOR[colorSpaceName].prototype;

    ['valueOf', 'hex', 'hexa', 'css', 'cssa'].forEach(function (methodName) {
        prototype[methodName] = prototype[methodName] || (colorSpaceName === 'RGB' ? prototype.hex : new Function("return this.rgb()." + methodName + "();"));
    });

    prototype.isColor = true;

    prototype.equals = function (otherColor, epsilon) {
        if (undef(epsilon)) {
            epsilon = 1e-10;
        }

        otherColor = otherColor[colorSpaceName.toLowerCase()]();

        for (var i = 0; i < propertyNames.length; i = i + 1) {
            if (Math.abs(this['_' + propertyNames[i]] - otherColor['_' + propertyNames[i]]) > epsilon) {
                return false;
            }
        }

        return true;
    };

    prototype.toJSON = new Function(
        "return ['" + colorSpaceName + "', " +
            propertyNames.map(function (propertyName) {
                return "this._" + propertyName;
            }, this).join(", ") +
        "];"
    );

    for (var propertyName in config) {
        if (config.hasOwnProperty(propertyName)) {
            var matchFromColorSpace = propertyName.match(/^from(.*)$/);
            if (matchFromColorSpace) {
                ONECOLOR[matchFromColorSpace[1].toUpperCase()].prototype[colorSpaceName.toLowerCase()] = config[propertyName];
            } else {
                prototype[propertyName] = config[propertyName];
            }
        }
    }

    // It is pretty easy to implement the conversion to the same color space:
    prototype[colorSpaceName.toLowerCase()] = function () {
        return this;
    };
    prototype.toString = new Function("return \"[one.color." + colorSpaceName + ":\"+" + propertyNames.map(function (propertyName, i) {
        return "\" " + propertyNames[i] + "=\"+this._" + propertyName;
    }).join("+") + "+\"]\";");

    // Generate getters and setters
    propertyNames.forEach(function (propertyName, i) {
        prototype[propertyName] = prototype[propertyName === 'black' ? 'k' : propertyName[0]] = new Function("value", "isDelta",
            // Simple getter mode: color.red()
            "if (typeof value === 'undefined') {" +
                "return this._" + propertyName + ";" +
            "}" +
            // Adjuster: color.red(+.2, true)
            "if (isDelta) {" +
                "return new this.constructor(" + propertyNames.map(function (otherPropertyName, i) {
                    return "this._" + otherPropertyName + (propertyName === otherPropertyName ? "+value" : "");
                }).join(", ") + ");" +
            "}" +
            // Setter: color.red(.2);
            "return new this.constructor(" + propertyNames.map(function (otherPropertyName, i) {
                return propertyName === otherPropertyName ? "value" : "this._" + otherPropertyName;
            }).join(", ") + ");");
    });

    function installForeignMethods(targetColorSpaceName, sourceColorSpaceName) {
        var obj = {};
        obj[sourceColorSpaceName.toLowerCase()] = new Function("return this.rgb()." + sourceColorSpaceName.toLowerCase() + "();"); // Fallback
        ONECOLOR[sourceColorSpaceName].propertyNames.forEach(function (propertyName, i) {
            obj[propertyName] = obj[propertyName === 'black' ? 'k' : propertyName[0]] = new Function("value", "isDelta", "return this." + sourceColorSpaceName.toLowerCase() + "()." + propertyName + "(value, isDelta);");
        });
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop) && ONECOLOR[targetColorSpaceName].prototype[prop] === undefined) {
                ONECOLOR[targetColorSpaceName].prototype[prop] = obj[prop];
            }
        }
    }

    installedColorSpaces.forEach(function (otherColorSpaceName) {
        installForeignMethods(colorSpaceName, otherColorSpaceName);
        installForeignMethods(otherColorSpaceName, colorSpaceName);
    });

    installedColorSpaces.push(colorSpaceName);
}

ONECOLOR.installMethod = function (name, fn) {
    installedColorSpaces.forEach(function (colorSpace) {
        ONECOLOR[colorSpace].prototype[name] = fn;
    });
};

installColorSpace('RGB', ['red', 'green', 'blue', 'alpha'], {
    hex: function () {
        var hexString = (Math.round(255 * this._red) * 0x10000 + Math.round(255 * this._green) * 0x100 + Math.round(255 * this._blue)).toString(16);
        return '#' + ('00000'.substr(0, 6 - hexString.length)) + hexString;
    },

    hexa: function () {
        var alphaString = Math.round(this._alpha * 255).toString(16);
        return '#' + '00'.substr(0, 2 - alphaString.length) + alphaString + this.hex().substr(1, 6);
    },

    css: function () {
        return "rgb(" + Math.round(255 * this._red) + "," + Math.round(255 * this._green) + "," + Math.round(255 * this._blue) + ")";
    },

    cssa: function () {
        return "rgba(" + Math.round(255 * this._red) + "," + Math.round(255 * this._green) + "," + Math.round(255 * this._blue) + "," + this._alpha + ")";
    }
});

if (typeof module !== 'undefined') {
    // Node module export
    module.exports = ONECOLOR;
} else if (typeof define === 'function' && !undef(define.amd)) {
    define([], function () {
        return ONECOLOR;
    });
} else if (typeof jQuery !== 'undefined' && undef(jQuery.color)) {
    jQuery.color = ONECOLOR;
} else {
    one = window.one || {};
    one.color = ONECOLOR;
}
<commit_msg>Adding support for 'transparent'<commit_after>/*jshint evil:true, onevar:false*/
/*global define*/
var installedColorSpaces = [],
    namedColors = {},
    undef = function (obj) {
        return typeof obj === 'undefined';
    },
    channelRegExp = /\s*(\.\d+|\d+(?:\.\d+)?)(%)?\s*/,
    alphaChannelRegExp = /\s*(\.\d+|\d+(?:\.\d+)?)\s*/,
    cssColorRegExp = new RegExp(
                         "^(rgb|hsl|hsv)a?" +
                         "\\(" +
                             channelRegExp.source + "," +
                             channelRegExp.source + "," +
                             channelRegExp.source +
                             "(?:," + alphaChannelRegExp.source + ")?" +
                         "\\)$", "i");

function ONECOLOR(obj) {
    if (Object.prototype.toString.apply(obj) === '[object Array]') {
        if (typeof obj[0] === 'string' && typeof ONECOLOR[obj[0]] === 'function') {
            // Assumed array from .toJSON()
            return new ONECOLOR[obj[0]](obj.slice(1, obj.length));
        } else if (obj.length === 4) {
            // Assumed 4 element int RGB array from canvas with all channels [0;255]
            return new ONECOLOR.RGB(obj[0] / 255, obj[1] / 255, obj[2] / 255, obj[3] / 255);
        }
    } else if (typeof obj === 'string') {
        var lowerCased = obj.toLowerCase();
        if (namedColors[lowerCased]) {
            obj = '#' + namedColors[lowerCased];
        }
        if (lowerCased === 'transparent') {
            obj = 'rgba(0,0,0,0)';
        }
        // Test for CSS rgb(....) string
        var matchCssSyntax = obj.match(cssColorRegExp);
        if (matchCssSyntax) {
            var colorSpaceName = matchCssSyntax[1].toUpperCase(),
                alpha = undef(matchCssSyntax[8]) ? matchCssSyntax[8] : parseFloat(matchCssSyntax[8]),
                hasHue = colorSpaceName[0] === 'H',
                firstChannelDivisor = matchCssSyntax[3] ? 100 : (hasHue ? 360 : 255),
                secondChannelDivisor = (matchCssSyntax[5] || hasHue) ? 100 : 255,
                thirdChannelDivisor = (matchCssSyntax[7] || hasHue) ? 100 : 255;
            if (undef(ONECOLOR[colorSpaceName])) {
                throw new Error("one.color." + colorSpaceName + " is not installed.");
            }
            return new ONECOLOR[colorSpaceName](
                parseFloat(matchCssSyntax[2]) / firstChannelDivisor,
                parseFloat(matchCssSyntax[4]) / secondChannelDivisor,
                parseFloat(matchCssSyntax[6]) / thirdChannelDivisor,
                alpha
            );
        }
        // Assume hex syntax
        if (obj.length < 6) {
            // Allow CSS shorthand
            obj = obj.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, '$1$1$2$2$3$3');
        }
        // Split obj into red, green, and blue components
        var hexMatch = obj.match(/^#?([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/i);
        if (hexMatch) {
            return new ONECOLOR.RGB(
                parseInt(hexMatch[1], 16) / 255,
                parseInt(hexMatch[2], 16) / 255,
                parseInt(hexMatch[3], 16) / 255
            );
        }
    } else if (typeof obj === 'object' && obj.isColor) {
        return obj;
    } else if (!isNaN(obj)) {
        // Strange integer representation sometimes returned by document.queryCommandValue in some browser...
        return new ONECOLOR.RGB((obj & 0xFF) / 255, ((obj & 0xFF00) >> 8) / 255, ((obj & 0xFF0000) >> 16) / 255);
    }
    return false;
}

function installColorSpace(colorSpaceName, propertyNames, config) {
    ONECOLOR[colorSpaceName] = new Function(propertyNames.join(","),
        // Allow passing an array to the constructor:
        "if (Object.prototype.toString.apply(" + propertyNames[0] + ") === '[object Array]') {" +
            propertyNames.map(function (propertyName, i) {
                return propertyName + "=" + propertyNames[0] + "[" + i + "];";
            }).reverse().join("") +
        "}" +
        "if (" + propertyNames.filter(function (propertyName) {
            return propertyName !== 'alpha';
        }).map(function (propertyName) {
            return "isNaN(" + propertyName + ")";
        }).join("||") + "){" + "throw new Error(\"[" + colorSpaceName + "]: Invalid color: (\"+" + propertyNames.join("+\",\"+") + "+\")\");}" +
        propertyNames.map(function (propertyName) {
            if (propertyName === 'hue') {
                return "this._hue=hue<0?hue-Math.floor(hue):hue%1"; // Wrap
            } else if (propertyName === 'alpha') {
                return "this._alpha=(isNaN(alpha)||alpha>1)?1:(alpha<0?0:alpha);";
            } else {
                return "this._" + propertyName + "=" + propertyName + "<0?0:(" + propertyName + ">1?1:" + propertyName + ")";
            }
        }).join(";") + ";"
    );
    ONECOLOR[colorSpaceName].propertyNames = propertyNames;

    var prototype = ONECOLOR[colorSpaceName].prototype;

    ['valueOf', 'hex', 'hexa', 'css', 'cssa'].forEach(function (methodName) {
        prototype[methodName] = prototype[methodName] || (colorSpaceName === 'RGB' ? prototype.hex : new Function("return this.rgb()." + methodName + "();"));
    });

    prototype.isColor = true;

    prototype.equals = function (otherColor, epsilon) {
        if (undef(epsilon)) {
            epsilon = 1e-10;
        }

        otherColor = otherColor[colorSpaceName.toLowerCase()]();

        for (var i = 0; i < propertyNames.length; i = i + 1) {
            if (Math.abs(this['_' + propertyNames[i]] - otherColor['_' + propertyNames[i]]) > epsilon) {
                return false;
            }
        }

        return true;
    };

    prototype.toJSON = new Function(
        "return ['" + colorSpaceName + "', " +
            propertyNames.map(function (propertyName) {
                return "this._" + propertyName;
            }, this).join(", ") +
        "];"
    );

    for (var propertyName in config) {
        if (config.hasOwnProperty(propertyName)) {
            var matchFromColorSpace = propertyName.match(/^from(.*)$/);
            if (matchFromColorSpace) {
                ONECOLOR[matchFromColorSpace[1].toUpperCase()].prototype[colorSpaceName.toLowerCase()] = config[propertyName];
            } else {
                prototype[propertyName] = config[propertyName];
            }
        }
    }

    // It is pretty easy to implement the conversion to the same color space:
    prototype[colorSpaceName.toLowerCase()] = function () {
        return this;
    };
    prototype.toString = new Function("return \"[one.color." + colorSpaceName + ":\"+" + propertyNames.map(function (propertyName, i) {
        return "\" " + propertyNames[i] + "=\"+this._" + propertyName;
    }).join("+") + "+\"]\";");

    // Generate getters and setters
    propertyNames.forEach(function (propertyName, i) {
        prototype[propertyName] = prototype[propertyName === 'black' ? 'k' : propertyName[0]] = new Function("value", "isDelta",
            // Simple getter mode: color.red()
            "if (typeof value === 'undefined') {" +
                "return this._" + propertyName + ";" +
            "}" +
            // Adjuster: color.red(+.2, true)
            "if (isDelta) {" +
                "return new this.constructor(" + propertyNames.map(function (otherPropertyName, i) {
                    return "this._" + otherPropertyName + (propertyName === otherPropertyName ? "+value" : "");
                }).join(", ") + ");" +
            "}" +
            // Setter: color.red(.2);
            "return new this.constructor(" + propertyNames.map(function (otherPropertyName, i) {
                return propertyName === otherPropertyName ? "value" : "this._" + otherPropertyName;
            }).join(", ") + ");");
    });

    function installForeignMethods(targetColorSpaceName, sourceColorSpaceName) {
        var obj = {};
        obj[sourceColorSpaceName.toLowerCase()] = new Function("return this.rgb()." + sourceColorSpaceName.toLowerCase() + "();"); // Fallback
        ONECOLOR[sourceColorSpaceName].propertyNames.forEach(function (propertyName, i) {
            obj[propertyName] = obj[propertyName === 'black' ? 'k' : propertyName[0]] = new Function("value", "isDelta", "return this." + sourceColorSpaceName.toLowerCase() + "()." + propertyName + "(value, isDelta);");
        });
        for (var prop in obj) {
            if (obj.hasOwnProperty(prop) && ONECOLOR[targetColorSpaceName].prototype[prop] === undefined) {
                ONECOLOR[targetColorSpaceName].prototype[prop] = obj[prop];
            }
        }
    }

    installedColorSpaces.forEach(function (otherColorSpaceName) {
        installForeignMethods(colorSpaceName, otherColorSpaceName);
        installForeignMethods(otherColorSpaceName, colorSpaceName);
    });

    installedColorSpaces.push(colorSpaceName);
}

ONECOLOR.installMethod = function (name, fn) {
    installedColorSpaces.forEach(function (colorSpace) {
        ONECOLOR[colorSpace].prototype[name] = fn;
    });
};

installColorSpace('RGB', ['red', 'green', 'blue', 'alpha'], {
    hex: function () {
        var hexString = (Math.round(255 * this._red) * 0x10000 + Math.round(255 * this._green) * 0x100 + Math.round(255 * this._blue)).toString(16);
        return '#' + ('00000'.substr(0, 6 - hexString.length)) + hexString;
    },

    hexa: function () {
        var alphaString = Math.round(this._alpha * 255).toString(16);
        return '#' + '00'.substr(0, 2 - alphaString.length) + alphaString + this.hex().substr(1, 6);
    },

    css: function () {
        return "rgb(" + Math.round(255 * this._red) + "," + Math.round(255 * this._green) + "," + Math.round(255 * this._blue) + ")";
    },

    cssa: function () {
        return "rgba(" + Math.round(255 * this._red) + "," + Math.round(255 * this._green) + "," + Math.round(255 * this._blue) + "," + this._alpha + ")";
    }
});

if (typeof module !== 'undefined') {
    // Node module export
    module.exports = ONECOLOR;
} else if (typeof define === 'function' && !undef(define.amd)) {
    define([], function () {
        return ONECOLOR;
    });
} else if (typeof jQuery !== 'undefined' && undef(jQuery.color)) {
    jQuery.color = ONECOLOR;
} else {
    one = window.one || {};
    one.color = ONECOLOR;
}
<|endoftext|>


<commit_before><commit_msg>Use local npm version of react and webpack transforms, falling back to included version when needed<commit_after><|endoftext|>


<commit_before>var Frog = require('./frog.js')
var Cars = require('./cars.js')
var Logs = require('./logs.js')
var Turtles = require('./turtles.js')
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var frog = new Frog(280, 560, 40, 40, context);
var frogger = document.getElementById('frog')
var carArrayOne = [];
var carArrayTwo = [];
var carArrayThree = [];
var carArrayFour = [];
var carArrayFive = [];
var logArrayOne = [];
var turtleArrayOne = [];
var logArrayTwo = [];
var turtleArrayTwo = [];
var logArrayThree = [];

carArrayOne.push(new Cars(0, 520, 60, 40, context));
carArrayOne.push(new Cars(-180, 520, 60, 40, context));
carArrayOne.push(new Cars(-360, 520, 60, 40, context));
carArrayTwo.push(new Cars(600, 480, 40, 40, context));
carArrayTwo.push(new Cars(760, 480, 40, 40, context));
carArrayTwo.push(new Cars(920, 480, 40, 40, context));
carArrayThree.push(new Cars(80, 440, 60, 40, context));
carArrayThree.push(new Cars(-80, 440, 60, 40, context));
carArrayThree.push(new Cars(-240, 440, 60, 40, context));
carArrayFour.push(new Cars(540, 400, 80, 40, context));
carArrayFour.push(new Cars(400, 400, 80, 40, context));
carArrayFour.push(new Cars(260, 400, 80, 40, context));
carArrayFive.push(new Cars(20, 360, 60, 40, context));
carArrayFive.push(new Cars(-160, 360, 60, 40, context));
carArrayFive.push(new Cars(-340, 360, 60, 40, context));
logArrayOne.push(new Logs(0, 240, 100, 35, context));
logArrayOne.push(new Logs(-200, 240, 100, 35, context));
logArrayOne.push(new Logs(-400, 240, 100, 35, context));
turtleArrayOne.push(new Turtles(600, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(660, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(720, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(900, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(960, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(1020, 200, 50, 35, context));
logArrayTwo.push(new Logs(0, 160, 300, 35, context));
turtleArrayTwo.push(new Turtles(690, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(750, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(810, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(990, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(1050, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(1120, 120, 50, 35, context));
logArrayThree.push(new Logs(-100, 80, 100, 35, context));
logArrayThree.push(new Logs(-360, 80, 100, 35, context));
logArrayThree.push(new Logs(-560, 80, 100, 35, context));

requestAnimationFrame(function gameLoop() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  frog.draw();
  carArrayOne.forEach(function (car) {
    car.draw().driveRight();
  });
  carArrayTwo.forEach(function (car) {
    car.drawLaneTwo().driveLeft();
  });
  carArrayThree.forEach(function (car) {
    car.drawLaneThree().driveRight();
  });
  carArrayFour.forEach(function (car) {
      car.drawLaneFour().driveLeft();
  });
  carArrayFive.forEach(function (car) {
      car.drawLaneFive().driveRight();
  });
  logArrayOne.forEach(function (log) {
      log.draw().floatRight();
  });
  turtleArrayOne.forEach(function (turtle){
      turtle.draw().swimLeft();
  });
  logArrayTwo.forEach(function (log){
      log.draw().floatRight();
  });
  turtleArrayTwo.forEach(function (turtle){
      turtle.draw().swimLeft();
  });
  logArrayThree.forEach(function (log){
      log.draw().floatRight();
  });
  requestAnimationFrame(gameLoop);
});

  window.addEventListener('keydown', function(event){
      if (event.keyCode === 38){
          frog.moveUp();
        } else if (event.keyCode === 40){
          frog.moveDown();
        } else if (event.keyCode === 37){
          frog.moveLeft();
        } else if (event.keyCode === 39){
          frog.moveRight();
        }
    });
<commit_msg>add collision funcitonality to the first lane, still has issues with other lanes<commit_after>var Frog = require('./frog.js')
var Cars = require('./cars.js')
var Logs = require('./logs.js')
var Turtles = require('./turtles.js')
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');
var frog = new Frog(280, 560, 40, 40, context);
var frogger = document.getElementById('frog')
var carArrayOne = [];
var carArrayTwo = [];
var carArrayThree = [];
var carArrayFour = [];
var carArrayFive = [];
var logArrayOne = [];
var turtleArrayOne = [];
var logArrayTwo = [];
var turtleArrayTwo = [];
var logArrayThree = [];

function collide(car) {
  if (frog.x < car.x + car.width &&
    frog.x + frog.width > car.x &&
    frog.y < car.y + car.height &&
    frog.height + frog.y > car.y){
      window.alert("ahhh!!!!")
      window.location.reload();
    }

carArrayOne.push(new Cars(0, 520, 60, 40, context));
carArrayOne.push(new Cars(-180, 520, 60, 40, context));
carArrayOne.push(new Cars(-360, 520, 60, 40, context));
carArrayTwo.push(new Cars(600, 480, 40, 40, context));
carArrayTwo.push(new Cars(760, 480, 40, 40, context));
carArrayTwo.push(new Cars(920, 480, 40, 40, context));
carArrayThree.push(new Cars(80, 440, 60, 40, context));
carArrayThree.push(new Cars(-80, 440, 60, 40, context));
carArrayThree.push(new Cars(-240, 440, 60, 40, context));
carArrayFour.push(new Cars(540, 400, 80, 40, context));
carArrayFour.push(new Cars(400, 400, 80, 40, context));
carArrayFour.push(new Cars(260, 400, 80, 40, context));
carArrayFive.push(new Cars(20, 360, 60, 40, context));
carArrayFive.push(new Cars(-160, 360, 60, 40, context));
carArrayFive.push(new Cars(-340, 360, 60, 40, context));
logArrayOne.push(new Logs(0, 240, 100, 35, context));
logArrayOne.push(new Logs(-200, 240, 100, 35, context));
logArrayOne.push(new Logs(-400, 240, 100, 35, context));
turtleArrayOne.push(new Turtles(600, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(660, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(720, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(900, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(960, 200, 50, 35, context));
turtleArrayOne.push(new Turtles(1020, 200, 50, 35, context));
logArrayTwo.push(new Logs(0, 160, 300, 35, context));
turtleArrayTwo.push(new Turtles(690, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(750, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(810, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(990, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(1050, 120, 50, 35, context));
turtleArrayTwo.push(new Turtles(1120, 120, 50, 35, context));
logArrayThree.push(new Logs(-100, 80, 100, 35, context));
logArrayThree.push(new Logs(-360, 80, 100, 35, context));
logArrayThree.push(new Logs(-560, 80, 100, 35, context));

requestAnimationFrame(function gameLoop() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  frog.draw();
  carArrayOne.forEach(function (car) {
    car.draw().driveRight()
    collide(car);
      });
  carArrayTwo.forEach(function (car) {
    car.drawLaneTwo().driveLeft();
    collide(car);
  });
  carArrayThree.forEach(function (car) {
    car.drawLaneThree().driveRight()
    collide(car);
  });
  carArrayFour.forEach(function (car) {
      car.drawLaneFour().driveLeft();
  });
  carArrayFive.forEach(function (car) {
      car.drawLaneFive().driveRight();
  });
  logArrayOne.forEach(function (log) {
      log.draw().floatRight();
  });
  turtleArrayOne.forEach(function (turtle){
      turtle.draw().swimLeft();
  });
  logArrayTwo.forEach(function (log){
      log.draw().floatRight();
  });
  turtleArrayTwo.forEach(function (turtle){
      turtle.draw().swimLeft();
  });
  logArrayThree.forEach(function (log){
      log.draw().floatRight();
  });
  requestAnimationFrame(gameLoop);
});

  window.addEventListener('keydown', function(event){
      if (event.keyCode === 38){
          frog.moveUp();
        } else if (event.keyCode === 40){
          frog.moveDown();
        } else if (event.keyCode === 37){
          frog.moveLeft();
        } else if (event.keyCode === 39){
          frog.moveRight();
        }
    });
<|endoftext|>