<commit_before>/*global module:true, require:false*/

var bane = require("bane");
var websocket = require("../lib/websocket/");
var when = require("when");

function Mopidy(settings) {
    if (!(this instanceof Mopidy)) {
        return new Mopidy(settings);
    }

    this._settings = this._configure(settings || {});
    this._console = this._getConsole();

    this._backoffDelay = this._settings.backoffDelayMin;
    this._pendingRequests = {};
    this._webSocket = null;

    bane.createEventEmitter(this);
    this._delegateEvents();

    if (this._settings.autoConnect) {
        this.connect();
    }
}

Mopidy.WebSocket = websocket.Client;

Mopidy.prototype._configure = function (settings) {
    var currentHost = (typeof document !== "undefined" &&
        document.location.host) || "localhost";
    settings.webSocketUrl = settings.webSocketUrl ||
        "ws://" + currentHost + "/mopidy/ws/";

    if (settings.autoConnect !== false) {
        settings.autoConnect = true;
    }

    settings.backoffDelayMin = settings.backoffDelayMin || 1000;
    settings.backoffDelayMax = settings.backoffDelayMax || 64000;

    return settings;
};

Mopidy.prototype._getConsole = function () {
    var console = typeof console !== "undefined" && console || {};

    console.log = console.log || function () {};
    console.warn = console.warn || function () {};
    console.error = console.error || function () {};

    return console;
};

Mopidy.prototype._delegateEvents = function () {
    // Remove existing event handlers
    this.off("websocket:close");
    this.off("websocket:error");
    this.off("websocket:incomingMessage");
    this.off("websocket:open");
    this.off("state:offline");

    // Register basic set of event handlers
    this.on("websocket:close", this._cleanup);
    this.on("websocket:error", this._handleWebSocketError);
    this.on("websocket:incomingMessage", this._handleMessage);
    this.on("websocket:open", this._resetBackoffDelay);
    this.on("websocket:open", this._getApiSpec);
    this.on("state:offline", this._reconnect);
};

Mopidy.prototype.connect = function () {
    if (this._webSocket) {
        if (this._webSocket.readyState === Mopidy.WebSocket.OPEN) {
            return;
        } else {
            this._webSocket.close();
        }
    }

    this._webSocket = this._settings.webSocket ||
        new Mopidy.WebSocket(this._settings.webSocketUrl);

    this._webSocket.onclose = function (close) {
        this.emit("websocket:close", close);
    }.bind(this);

    this._webSocket.onerror = function (error) {
        this.emit("websocket:error", error);
    }.bind(this);

    this._webSocket.onopen = function () {
        this.emit("websocket:open");
    }.bind(this);

    this._webSocket.onmessage = function (message) {
        this.emit("websocket:incomingMessage", message);
    }.bind(this);
};

Mopidy.prototype._cleanup = function (closeEvent) {
    Object.keys(this._pendingRequests).forEach(function (requestId) {
        var resolver = this._pendingRequests[requestId];
        delete this._pendingRequests[requestId];
        resolver.reject({
            message: "WebSocket closed",
            closeEvent: closeEvent
        });
    }.bind(this));

    this.emit("state:offline");
};

Mopidy.prototype._reconnect = function () {
    this.emit("reconnectionPending", {
        timeToAttempt: this._backoffDelay
    });

    setTimeout(function () {
        this.emit("reconnecting");
        this.connect();
    }.bind(this), this._backoffDelay);

    this._backoffDelay = this._backoffDelay * 2;
    if (this._backoffDelay > this._settings.backoffDelayMax) {
        this._backoffDelay = this._settings.backoffDelayMax;
    }
};

Mopidy.prototype._resetBackoffDelay = function () {
    this._backoffDelay = this._settings.backoffDelayMin;
};

Mopidy.prototype.close = function () {
    this.off("state:offline", this._reconnect);
    this._webSocket.close();
};

Mopidy.prototype._handleWebSocketError = function (error) {
    this._console.warn("WebSocket error:", error.stack || error);
};

Mopidy.prototype._send = function (message) {
    var deferred = when.defer();

    switch (this._webSocket.readyState) {
    case Mopidy.WebSocket.CONNECTING:
        deferred.resolver.reject({
            message: "WebSocket is still connecting"
        });
        break;
    case Mopidy.WebSocket.CLOSING:
        deferred.resolver.reject({
            message: "WebSocket is closing"
        });
        break;
    case Mopidy.WebSocket.CLOSED:
        deferred.resolver.reject({
            message: "WebSocket is closed"
        });
        break;
    default:
        message.jsonrpc = "2.0";
        message.id = this._nextRequestId();
        this._pendingRequests[message.id] = deferred.resolver;
        this._webSocket.send(JSON.stringify(message));
        this.emit("websocket:outgoingMessage", message);
    }

    return deferred.promise;
};

Mopidy.prototype._nextRequestId = (function () {
    var lastUsed = -1;
    return function () {
        lastUsed += 1;
        return lastUsed;
    };
}());

Mopidy.prototype._handleMessage = function (message) {
    try {
        var data = JSON.parse(message.data);
        if (data.hasOwnProperty("id")) {
            this._handleResponse(data);
        } else if (data.hasOwnProperty("event")) {
            this._handleEvent(data);
        } else {
            this._console.warn(
                "Unknown message type received. Message was: " +
                message.data);
        }
    } catch (error) {
        if (error instanceof SyntaxError) {
            this._console.warn(
                "WebSocket message parsing failed. Message was: " +
                message.data);
        } else {
            throw error;
        }
    }
};

Mopidy.prototype._handleResponse = function (responseMessage) {
    if (!this._pendingRequests.hasOwnProperty(responseMessage.id)) {
        this._console.warn(
            "Unexpected response received. Message was:", responseMessage);
        return;
    }

    var resolver = this._pendingRequests[responseMessage.id];
    delete this._pendingRequests[responseMessage.id];

    if (responseMessage.hasOwnProperty("result")) {
        resolver.resolve(responseMessage.result);
    } else if (responseMessage.hasOwnProperty("error")) {
        resolver.reject(responseMessage.error);
        this._console.warn("Server returned error:", responseMessage.error);
    } else {
        resolver.reject({
            message: "Response without 'result' or 'error' received",
            data: {response: responseMessage}
        });
        this._console.warn(
            "Response without 'result' or 'error' received. Message was:",
            responseMessage);
    }
};

Mopidy.prototype._handleEvent = function (eventMessage) {
    var type = eventMessage.event;
    var data = eventMessage;
    delete data.event;

    this.emit("event:" + this._snakeToCamel(type), data);
};

Mopidy.prototype._getApiSpec = function () {
    return this._send({method: "core.describe"})
        .then(this._createApi.bind(this), this._handleWebSocketError)
        .then(null, this._handleWebSocketError);
};

Mopidy.prototype._createApi = function (methods) {
    var caller = function (method) {
        return function () {
            var params = Array.prototype.slice.call(arguments);
            return this._send({
                method: method,
                params: params
            });
        }.bind(this);
    }.bind(this);

    var getPath = function (fullName) {
        var path = fullName.split(".");
        if (path.length >= 1 && path[0] === "core") {
            path = path.slice(1);
        }
        return path;
    };

    var createObjects = function (objPath) {
        var parentObj = this;
        objPath.forEach(function (objName) {
            objName = this._snakeToCamel(objName);
            parentObj[objName] = parentObj[objName] || {};
            parentObj = parentObj[objName];
        }.bind(this));
        return parentObj;
    }.bind(this);

    var createMethod = function (fullMethodName) {
        var methodPath = getPath(fullMethodName);
        var methodName = this._snakeToCamel(methodPath.slice(-1)[0]);
        var object = createObjects(methodPath.slice(0, -1));
        object[methodName] = caller(fullMethodName);
        object[methodName].description = methods[fullMethodName].description;
        object[methodName].params = methods[fullMethodName].params;
    }.bind(this);

    Object.keys(methods).forEach(createMethod);
    this.emit("state:online");
};

Mopidy.prototype._snakeToCamel = function (name) {
    return name.replace(/(_[a-z])/g, function (match) {
        return match.toUpperCase().replace("_", "");
    });
};

module.exports = Mopidy;
<commit_msg>js: Simplify _send() rejections<commit_after>/*global module:true, require:false*/

var bane = require("bane");
var websocket = require("../lib/websocket/");
var when = require("when");

function Mopidy(settings) {
    if (!(this instanceof Mopidy)) {
        return new Mopidy(settings);
    }

    this._settings = this._configure(settings || {});
    this._console = this._getConsole();

    this._backoffDelay = this._settings.backoffDelayMin;
    this._pendingRequests = {};
    this._webSocket = null;

    bane.createEventEmitter(this);
    this._delegateEvents();

    if (this._settings.autoConnect) {
        this.connect();
    }
}

Mopidy.WebSocket = websocket.Client;

Mopidy.prototype._configure = function (settings) {
    var currentHost = (typeof document !== "undefined" &&
        document.location.host) || "localhost";
    settings.webSocketUrl = settings.webSocketUrl ||
        "ws://" + currentHost + "/mopidy/ws/";

    if (settings.autoConnect !== false) {
        settings.autoConnect = true;
    }

    settings.backoffDelayMin = settings.backoffDelayMin || 1000;
    settings.backoffDelayMax = settings.backoffDelayMax || 64000;

    return settings;
};

Mopidy.prototype._getConsole = function () {
    var console = typeof console !== "undefined" && console || {};

    console.log = console.log || function () {};
    console.warn = console.warn || function () {};
    console.error = console.error || function () {};

    return console;
};

Mopidy.prototype._delegateEvents = function () {
    // Remove existing event handlers
    this.off("websocket:close");
    this.off("websocket:error");
    this.off("websocket:incomingMessage");
    this.off("websocket:open");
    this.off("state:offline");

    // Register basic set of event handlers
    this.on("websocket:close", this._cleanup);
    this.on("websocket:error", this._handleWebSocketError);
    this.on("websocket:incomingMessage", this._handleMessage);
    this.on("websocket:open", this._resetBackoffDelay);
    this.on("websocket:open", this._getApiSpec);
    this.on("state:offline", this._reconnect);
};

Mopidy.prototype.connect = function () {
    if (this._webSocket) {
        if (this._webSocket.readyState === Mopidy.WebSocket.OPEN) {
            return;
        } else {
            this._webSocket.close();
        }
    }

    this._webSocket = this._settings.webSocket ||
        new Mopidy.WebSocket(this._settings.webSocketUrl);

    this._webSocket.onclose = function (close) {
        this.emit("websocket:close", close);
    }.bind(this);

    this._webSocket.onerror = function (error) {
        this.emit("websocket:error", error);
    }.bind(this);

    this._webSocket.onopen = function () {
        this.emit("websocket:open");
    }.bind(this);

    this._webSocket.onmessage = function (message) {
        this.emit("websocket:incomingMessage", message);
    }.bind(this);
};

Mopidy.prototype._cleanup = function (closeEvent) {
    Object.keys(this._pendingRequests).forEach(function (requestId) {
        var resolver = this._pendingRequests[requestId];
        delete this._pendingRequests[requestId];
        resolver.reject({
            message: "WebSocket closed",
            closeEvent: closeEvent
        });
    }.bind(this));

    this.emit("state:offline");
};

Mopidy.prototype._reconnect = function () {
    this.emit("reconnectionPending", {
        timeToAttempt: this._backoffDelay
    });

    setTimeout(function () {
        this.emit("reconnecting");
        this.connect();
    }.bind(this), this._backoffDelay);

    this._backoffDelay = this._backoffDelay * 2;
    if (this._backoffDelay > this._settings.backoffDelayMax) {
        this._backoffDelay = this._settings.backoffDelayMax;
    }
};

Mopidy.prototype._resetBackoffDelay = function () {
    this._backoffDelay = this._settings.backoffDelayMin;
};

Mopidy.prototype.close = function () {
    this.off("state:offline", this._reconnect);
    this._webSocket.close();
};

Mopidy.prototype._handleWebSocketError = function (error) {
    this._console.warn("WebSocket error:", error.stack || error);
};

Mopidy.prototype._send = function (message) {
    switch (this._webSocket.readyState) {
    case Mopidy.WebSocket.CONNECTING:
        return when.reject({message: "WebSocket is still connecting"});
    case Mopidy.WebSocket.CLOSING:
        return when.reject({message: "WebSocket is closing"});
    case Mopidy.WebSocket.CLOSED:
        return when.reject({message: "WebSocket is closed"});
    default:
        var deferred = when.defer();
        message.jsonrpc = "2.0";
        message.id = this._nextRequestId();
        this._pendingRequests[message.id] = deferred.resolver;
        this._webSocket.send(JSON.stringify(message));
        this.emit("websocket:outgoingMessage", message);
        return deferred.promise;
    }
};

Mopidy.prototype._nextRequestId = (function () {
    var lastUsed = -1;
    return function () {
        lastUsed += 1;
        return lastUsed;
    };
}());

Mopidy.prototype._handleMessage = function (message) {
    try {
        var data = JSON.parse(message.data);
        if (data.hasOwnProperty("id")) {
            this._handleResponse(data);
        } else if (data.hasOwnProperty("event")) {
            this._handleEvent(data);
        } else {
            this._console.warn(
                "Unknown message type received. Message was: " +
                message.data);
        }
    } catch (error) {
        if (error instanceof SyntaxError) {
            this._console.warn(
                "WebSocket message parsing failed. Message was: " +
                message.data);
        } else {
            throw error;
        }
    }
};

Mopidy.prototype._handleResponse = function (responseMessage) {
    if (!this._pendingRequests.hasOwnProperty(responseMessage.id)) {
        this._console.warn(
            "Unexpected response received. Message was:", responseMessage);
        return;
    }

    var resolver = this._pendingRequests[responseMessage.id];
    delete this._pendingRequests[responseMessage.id];

    if (responseMessage.hasOwnProperty("result")) {
        resolver.resolve(responseMessage.result);
    } else if (responseMessage.hasOwnProperty("error")) {
        resolver.reject(responseMessage.error);
        this._console.warn("Server returned error:", responseMessage.error);
    } else {
        resolver.reject({
            message: "Response without 'result' or 'error' received",
            data: {response: responseMessage}
        });
        this._console.warn(
            "Response without 'result' or 'error' received. Message was:",
            responseMessage);
    }
};

Mopidy.prototype._handleEvent = function (eventMessage) {
    var type = eventMessage.event;
    var data = eventMessage;
    delete data.event;

    this.emit("event:" + this._snakeToCamel(type), data);
};

Mopidy.prototype._getApiSpec = function () {
    return this._send({method: "core.describe"})
        .then(this._createApi.bind(this), this._handleWebSocketError)
        .then(null, this._handleWebSocketError);
};

Mopidy.prototype._createApi = function (methods) {
    var caller = function (method) {
        return function () {
            var params = Array.prototype.slice.call(arguments);
            return this._send({
                method: method,
                params: params
            });
        }.bind(this);
    }.bind(this);

    var getPath = function (fullName) {
        var path = fullName.split(".");
        if (path.length >= 1 && path[0] === "core") {
            path = path.slice(1);
        }
        return path;
    };

    var createObjects = function (objPath) {
        var parentObj = this;
        objPath.forEach(function (objName) {
            objName = this._snakeToCamel(objName);
            parentObj[objName] = parentObj[objName] || {};
            parentObj = parentObj[objName];
        }.bind(this));
        return parentObj;
    }.bind(this);

    var createMethod = function (fullMethodName) {
        var methodPath = getPath(fullMethodName);
        var methodName = this._snakeToCamel(methodPath.slice(-1)[0]);
        var object = createObjects(methodPath.slice(0, -1));
        object[methodName] = caller(fullMethodName);
        object[methodName].description = methods[fullMethodName].description;
        object[methodName].params = methods[fullMethodName].params;
    }.bind(this);

    Object.keys(methods).forEach(createMethod);
    this.emit("state:online");
};

Mopidy.prototype._snakeToCamel = function (name) {
    return name.replace(/(_[a-z])/g, function (match) {
        return match.toUpperCase().replace("_", "");
    });
};

module.exports = Mopidy;
<|endoftext|>


<commit_before>var Controller = function (opts) {
    //Parse all the options
    this.availableOperations = opts.availableOperations || ['GET_ALL', 'GET', 'POST', 'PUT', 'DELETE'];
    this.model = opts.model || null;

    this._mongooseModel = null;
};

Controller.prototype = {
    ALL: function (req, res, next) {
        next();
    },

    GET_ALL: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        var limit = 0,
            skip = 0;

        //Limit
        if (req.query.hasOwnProperty('limit')) {
            limit = req.query['limit'];
            delete req.query['limit'];
        }

        //Skip
        if (req.query.hasOwnProperty('skip')) {
            skip = req.query['skip'];
            delete req.query['skip'];
        }

        var query = this._mongooseModel.find(req.query);

        if (limit > 0) {
            query.limit(limit);
        }

        if (skip > 0) {
            query.skip(skip);
        }

        query.exec(function (err, results) {
            if (err) {
                res.send(err);
            } else {
                res.send(results);
            }
        });
    },

    GET: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        this._mongooseModel.findById(mongoose.Types.ObjectId(req.params.id), function (err, result) {
            if (err) {
                res.send(err);
            } else {
                res.send(result);
            }
        });
    },

    POST: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        var item = new this._mongooseModel();

        for (var key in req.body) {
            item[key] = req.body[key];
        }

        item.save(function (err) {
            if (err) {
                res.send(err);
            } else {
                res.send(item);
            }
        });
    },

    PUT: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        this._mongooseModel.findById(mongoose.Types.ObjectId(req.params.id), function (err, result) {
            if (err) {
                res.send(err);
            } else {
                for (var key in req.body) {
                    result[key] = req.body[key];
                }

                result.save(function (err) {
                    if (err) {
                        res.send(err);
                    } else {
                        res.send(result);
                    }
                });
            }
        });
    },

    DELETE: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        this._mongooseModel.findById(mongoose.Types.ObjectId(req.params.id), function (err, result) {
            if (err) {
                res.send(err);
            } else {
                result.remove(function (err) {
                    if (err) {
                        res.send(err);
                    } else {
                        res.send(result);
                    }
                });
            }
        });
    },

    getBaseRoute: function () {
        return this._mongooseModel.collection.name.toLowerCase();
    },

    setMongooseInstance: function (mongoose) {
        this._mongooseModel = mongoose.model(this.model);
    }
};

module.exports.Controller = Controller;

var Morest = function (router, mongoose, opts) {
    this.controllers = opts.controllers || []; //Define the controllers
    this.baseRoute = opts.baseRoute || '/'; //Define a base router from which all routes extend, e.g. '/api/'

    if (router === null || typeof router === 'undefined') {
        throw new Error('[Morest] Router not defined');
    }

    if (mongoose === null || typeof mongoose === 'undefined') {
        throw new Error('[Morest] Mongoose not defined');
    }

    //Generate routes
    for (var c = 0; c < this.controllers.length; c++) {
        var controller = this.controllers[c];

        controller.setMongooseInstance(mongoose);

        router.all(this.baseRoute + controller.getBaseRoute(), controller.ALL.bind(controller));

        if (controller.availableOperations.indexOf('GET_ALL') > -1) {
            //GET_ALL
            router.get(this.baseRoute + controller.getBaseRoute(), controller.GET_ALL.bind(controller));
        }

        if (controller.availableOperations.indexOf('GET') > -1) {
            //GET
            router.get(this.baseRoute + controller.getBaseRoute() + '/:id', controller.GET.bind(controller));
        }

        if (controller.availableOperations.indexOf('POST') > -1) {
            //POST
            router.post(this.baseRoute + controller.getBaseRoute(), controller.POST.bind(controller));
        }

        if (controller.availableOperations.indexOf('PUT') > -1) {
            //PUT
            router.put(this.baseRoute + controller.getBaseRoute() + '/:id', controller.PUT.bind(controller));
        }

        if (controller.availableOperations.indexOf('DELETE') > -1) {
            //DELETE
            router.delete(this.baseRoute + controller.getBaseRoute() + '/:id', controller.DELETE.bind(controller));
        }
    }

    return router;
};

module.exports.Morest = Morest;<commit_msg>Fixed missing mongoose require().<commit_after>var mongoose = require('mongoose');

var Controller = function (opts) {
    //Parse all the options
    this.availableOperations = opts.availableOperations || ['GET_ALL', 'GET', 'POST', 'PUT', 'DELETE'];
    this.model = opts.model || null;

    this._mongooseModel = null;
};

Controller.prototype = {
    ALL: function (req, res, next) {
        next();
    },

    GET_ALL: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        var limit = 0,
            skip = 0;

        //Limit
        if (req.query.hasOwnProperty('limit')) {
            limit = req.query['limit'];
            delete req.query['limit'];
        }

        //Skip
        if (req.query.hasOwnProperty('skip')) {
            skip = req.query['skip'];
            delete req.query['skip'];
        }

        var query = this._mongooseModel.find(req.query);

        if (limit > 0) {
            query.limit(limit);
        }

        if (skip > 0) {
            query.skip(skip);
        }

        query.exec(function (err, results) {
            if (err) {
                res.send(err);
            } else {
                res.send(results);
            }
        });
    },

    GET: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        this._mongooseModel.findById(mongoose.Types.ObjectId(req.params.id), function (err, result) {
            if (err) {
                res.send(err);
            } else {
                res.send(result);
            }
        });
    },

    POST: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        var item = new this._mongooseModel();

        for (var key in req.body) {
            item[key] = req.body[key];
        }

        item.save(function (err) {
            if (err) {
                res.send(err);
            } else {
                res.send(item);
            }
        });
    },

    PUT: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        this._mongooseModel.findById(mongoose.Types.ObjectId(req.params.id), function (err, result) {
            if (err) {
                res.send(err);
            } else {
                for (var key in req.body) {
                    result[key] = req.body[key];
                }

                result.save(function (err) {
                    if (err) {
                        res.send(err);
                    } else {
                        res.send(result);
                    }
                });
            }
        });
    },

    DELETE: function (req, res) {
        if (this._mongooseModel === null) {
            throw new Error('[Morest] Controller does not have access to a Mongoose instance');
        }

        this._mongooseModel.findById(mongoose.Types.ObjectId(req.params.id), function (err, result) {
            if (err) {
                res.send(err);
            } else {
                result.remove(function (err) {
                    if (err) {
                        res.send(err);
                    } else {
                        res.send(result);
                    }
                });
            }
        });
    },

    getBaseRoute: function () {
        return this._mongooseModel.collection.name.toLowerCase();
    },

    setMongooseInstance: function (mongoose) {
        this._mongooseModel = mongoose.model(this.model);
    }
};

module.exports.Controller = Controller;

var Morest = function (router, mongoose, opts) {
    this.controllers = opts.controllers || []; //Define the controllers
    this.baseRoute = opts.baseRoute || '/'; //Define a base router from which all routes extend, e.g. '/api/'

    if (router === null || typeof router === 'undefined') {
        throw new Error('[Morest] Router not defined');
    }

    if (mongoose === null || typeof mongoose === 'undefined') {
        throw new Error('[Morest] Mongoose not defined');
    }

    //Generate routes
    for (var c = 0; c < this.controllers.length; c++) {
        var controller = this.controllers[c];

        controller.setMongooseInstance(mongoose);

        router.all(this.baseRoute + controller.getBaseRoute(), controller.ALL.bind(controller));

        if (controller.availableOperations.indexOf('GET_ALL') > -1) {
            //GET_ALL
            router.get(this.baseRoute + controller.getBaseRoute(), controller.GET_ALL.bind(controller));
        }

        if (controller.availableOperations.indexOf('GET') > -1) {
            //GET
            router.get(this.baseRoute + controller.getBaseRoute() + '/:id', controller.GET.bind(controller));
        }

        if (controller.availableOperations.indexOf('POST') > -1) {
            //POST
            router.post(this.baseRoute + controller.getBaseRoute(), controller.POST.bind(controller));
        }

        if (controller.availableOperations.indexOf('PUT') > -1) {
            //PUT
            router.put(this.baseRoute + controller.getBaseRoute() + '/:id', controller.PUT.bind(controller));
        }

        if (controller.availableOperations.indexOf('DELETE') > -1) {
            //DELETE
            router.delete(this.baseRoute + controller.getBaseRoute() + '/:id', controller.DELETE.bind(controller));
        }
    }

    return router;
};

module.exports.Morest = Morest;
<|endoftext|>


<commit_before>//=======================================================
//              _
//  _ __       | |_ _ __ ___  _ __  _   _   (_)___
// | '_ \ _____| __| '__/ _ \| '_ \| | | |  | / __|
// | | | |_____| |_| | | (_) | |_) | |_| |_ | \__ \
// |_| |_|      \__|_|  \___/| .__/ \__, (_)/ |___/
//                           |_|    |___/ |__/
// n-tropy.js
// Version: 2.0
// Author: Dino Paskvan
// Mail: dpaskvan@gmail.com
// Web: http://www.dinopaskvan.com
// Copyright (c) 2014 Dino Paskvan
// Licence : MIT
//=======================================================

window.ntropy = (function () {
  "use strict";
  /**
   * Calls ntropy to start the random generation process
   * @param {Object} options - Set the pool and length for the random generator
   * @param {Function} callback - Function to be exectuted after the number has been generated
   */
  return function (options, callback) {
    var pool = options.pool || "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%",
      limit = options.limit || 10,
      seed = [],
      oldMX = 0,
      oldMY = 0,
      oldX = 0,
      oldY = 0,
      oldZ = 0;

    /**
     * Compars if values have changed enough in relation to the supplied offset
     * @param {Number} oldVal - Previous value
     * @param {Number} newVal - New value
     * @param {Number} offset - The offset to compare to
     */

    function cmpValues(oldVal, newVal, offset) {
      if (oldVal > newVal) {
        if ((oldVal - newVal) > offset) {
          return true;
        }
        return false;
      }
      if ((newVal - oldVal) > offset) {
        return true;
      }
      return false;
    }

    /**
     * Checks for (compatible) mobile devices
     */

    function mobileCheck() {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    /**
     * Uses the data from motion events to create seed for the random string
     * @param {Object} e - The event
     */

    function handleMotionEvent(e) {
      var x = e.accelerationIncludingGravity.x,
        y = e.accelerationIncludingGravity.y,
        z = e.accelerationIncludingGravity.z,
        random = '',
        tSeed,
        i;
      if (cmpValues(oldX, x, 2) || cmpValues(oldY, y, 2) || cmpValues(oldZ, z, 2)) {
        tSeed = Math.abs((Math.floor(x * 100) ^ Math.floor(y * 100)) ^ Math.floor(z * 100)) % (pool.length * 3);
        if (tSeed < pool.length) {
          seed.push(tSeed);
        }
        if (seed.length === limit) {
          for (i = 0; i < seed.length; i = i + 1) {
            random += pool[seed[i]];
            if (random.length === limit) {
              window.removeEventListener('devicemotion', handleMotionEvent, true);
              callback(random);
            }
          }
        }
        oldX = x;
        oldY = y;
        oldZ = z;
      }
    }

    /**
     * Uses the data from mouse movement events to create seed for the random string
     * @param {Object} e - The event
     */

    function handleMouseEvent(e) {
      var x = e.clientX,
        y = e.clientY,
        random = '',
        tSeed,
        i;
      if (cmpValues(oldMX, x, 51) || cmpValues(oldMY, y, 51)) {
        tSeed = (x ^ y) % (pool.length * 3);
        if (tSeed < pool.length) {
          seed.push(tSeed);
        }
        if (seed.length === limit) {
          for (i = 0; i < seed.length; i = i + 1) {
            random += pool[seed[i]];
            if (random.length === limit) {
              window.removeEventListener('mousemove', handleMouseEvent, true);
              callback(random);
            }
          }
        }
        oldMX = x;
        oldMY = y;
      }
    }

    if (window.DeviceOrientationEvent && mobileCheck()) {
      window.addEventListener('devicemotion', handleMotionEvent, true);
    } else {
      window.addEventListener('mousemove', handleMouseEvent, true);
    }
  };
}());
<commit_msg>Simplified cmpValues()<commit_after>//=======================================================
//              _
//  _ __       | |_ _ __ ___  _ __  _   _   (_)___
// | '_ \ _____| __| '__/ _ \| '_ \| | | |  | / __|
// | | | |_____| |_| | | (_) | |_) | |_| |_ | \__ \
// |_| |_|      \__|_|  \___/| .__/ \__, (_)/ |___/
//                           |_|    |___/ |__/
// n-tropy.js
// Version: 2.0
// Author: Dino Paskvan
// Mail: dpaskvan@gmail.com
// Web: http://www.dinopaskvan.com
// Copyright (c) 2014 Dino Paskvan
// Licence : MIT
//=======================================================

window.ntropy = (function () {
  "use strict";
  /**
   * Calls ntropy to start the random generation process
   * @param {Object} options - Set the pool and length for the random generator
   * @param {Function} callback - Function to be exectuted after the number has been generated
   */
  return function (options, callback) {
    var pool = options.pool || "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%",
      limit = options.limit || 10,
      seed = [],
      oldMX = 0,
      oldMY = 0,
      oldX = 0,
      oldY = 0,
      oldZ = 0;

    /**
     * Compars if values have changed enough in relation to the supplied offset
     * @param {Number} oldVal - Previous value
     * @param {Number} newVal - New value
     * @param {Number} offset - The offset to compare to
     */

    function cmpValues(oldVal, newVal, offset) {
      return (oldVal > newVal) ? ((oldVal - newVal) > offset) : ((newVal - oldVal) > offset);
    }

    /**
     * Checks for (compatible) mobile devices
     */

    function mobileCheck() {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    /**
     * Uses the data from motion events to create seed for the random string
     * @param {Object} e - The event
     */

    function handleMotionEvent(e) {
      var x = e.accelerationIncludingGravity.x,
        y = e.accelerationIncludingGravity.y,
        z = e.accelerationIncludingGravity.z,
        random = '',
        tSeed,
        i;
      if (cmpValues(oldX, x, 2) || cmpValues(oldY, y, 2) || cmpValues(oldZ, z, 2)) {
        tSeed = Math.abs((Math.floor(x * 100) ^ Math.floor(y * 100)) ^ Math.floor(z * 100)) % (pool.length * 3);
        if (tSeed < pool.length) {
          seed.push(tSeed);
        }
        if (seed.length === limit) {
          for (i = 0; i < seed.length; i = i + 1) {
            random += pool[seed[i]];
            if (random.length === limit) {
              window.removeEventListener('devicemotion', handleMotionEvent, true);
              callback(random);
            }
          }
        }
        oldX = x;
        oldY = y;
        oldZ = z;
      }
    }

    /**
     * Uses the data from mouse movement events to create seed for the random string
     * @param {Object} e - The event
     */

    function handleMouseEvent(e) {
      var x = e.clientX,
        y = e.clientY,
        random = '',
        tSeed,
        i;
      if (cmpValues(oldMX, x, 51) || cmpValues(oldMY, y, 51)) {
        tSeed = (x ^ y) % (pool.length * 3);
        if (tSeed < pool.length) {
          seed.push(tSeed);
        }
        if (seed.length === limit) {
          for (i = 0; i < seed.length; i = i + 1) {
            random += pool[seed[i]];
            if (random.length === limit) {
              window.removeEventListener('mousemove', handleMouseEvent, true);
              callback(random);
            }
          }
        }
        oldMX = x;
        oldMY = y;
      }
    }

    if (window.DeviceOrientationEvent && mobileCheck()) {
      window.addEventListener('devicemotion', handleMotionEvent, true);
    } else {
      window.addEventListener('mousemove', handleMouseEvent, true);
    }
  };
}());
<|endoftext|>


<commit_before>goog.provide('ol.Loc');

goog.require('ol.Projection');

/**
 * @constructor
 * @param {number} x X.
 * @param {number} y Y.
 * @param {number=} opt_z Z.
 * @param {ol.Projection=} opt_projection Projection.
 */
ol.Loc = function(x, y, opt_z, opt_projection) {

    /**
     * @private
     * @type {number}
     */
    this.x_ = x;

    /**
     * @private
     * @type {number}
     */
    this.y_ = y;

    /**
     * @private
     * @type {number|undefined}
     */
    this.z_ = opt_z;

    /**
     * @private
     * @type {ol.Projection}
     */
    this.projection_ = goog.isDef(opt_projection) ? opt_projection : null;

};

/**
 * @return {ol.Projection|undefined} Projection.
 */
ol.Loc.prototype.getProjection = function() {
    return this.projection_;
};

/**
 * @return {number} X.
 */
ol.Loc.prototype.getX = function() {
    return this.x_;
};

/**
 * @return {number} Y.
 */
ol.Loc.prototype.getY = function() {
    return this.y_;
};

/**
 * @return {number|undefined} Z.
 */
ol.Loc.prototype.getZ = function() {
    return this.z_;
};

/**
 * @param {ol.Projection} projection Projection.
 */
ol.Loc.prototype.setProjection = function(projection) {
    this.projection_ = projection;
};

/**
 * @param {number} x X.
 */
ol.Loc.prototype.setX = function(x) {
    this.x_ = x;
};

/**
 * @param {number} y Y.
 */
ol.Loc.prototype.setY = function(y) {
    this.y_ = y;
};

/**
 * @param {number|undefined} z Z.
 */
ol.Loc.prototype.setZ = function(z) {
    this.z_ = z;
};

/**
 * Transform this location to another coordinate reference system.  This
 * requires that this location has a projection set already (if not, an error
 * will be thrown).  Returns a new location object and does not modify this
 * location.
 *
 * @param {string|!ol.Projection} proj The destination projection.  Can be
 *     supplied as a projection instance of a string identifier.
 * @returns {!ol.Loc} A new location.
 */
ol.Loc.prototype.transform = function(proj) {
    if (goog.isString(proj)) {
        proj = new ol.Projection(proj);
    }
    return this.transform_(proj);
};

/**
 * Transform this location to a new location given a projection object.
 *
 * @param {!ol.Projection} proj The destination projection.
 * @returns {!ol.Loc}
 */
ol.Loc.prototype.transform_ = function(proj) {
    var point = {x: this.x_, y: this.y_};
    var sourceProj = this.projection_;
    if (!goog.isDefAndNotNull(sourceProj)) {
        throw new Error("Cannot transform a location without a source projection.");
    }
    ol.Projection.transform(point, sourceProj, proj);
    return new ol.Loc(point['x'], point['y'], this.z_, proj);
};

/**
 * Clean up.
 */
ol.Loc.prototype.destroy = function() {
    for (var key in this) {
        delete this[key];
    }
};
<commit_msg>Quoting properties for external use.<commit_after>goog.provide('ol.Loc');

goog.require('ol.Projection');

/**
 * @constructor
 * @param {number} x X.
 * @param {number} y Y.
 * @param {number=} opt_z Z.
 * @param {ol.Projection=} opt_projection Projection.
 */
ol.Loc = function(x, y, opt_z, opt_projection) {

    /**
     * @private
     * @type {number}
     */
    this.x_ = x;

    /**
     * @private
     * @type {number}
     */
    this.y_ = y;

    /**
     * @private
     * @type {number|undefined}
     */
    this.z_ = opt_z;

    /**
     * @private
     * @type {ol.Projection}
     */
    this.projection_ = goog.isDef(opt_projection) ? opt_projection : null;

};

/**
 * @return {ol.Projection|undefined} Projection.
 */
ol.Loc.prototype.getProjection = function() {
    return this.projection_;
};

/**
 * @return {number} X.
 */
ol.Loc.prototype.getX = function() {
    return this.x_;
};

/**
 * @return {number} Y.
 */
ol.Loc.prototype.getY = function() {
    return this.y_;
};

/**
 * @return {number|undefined} Z.
 */
ol.Loc.prototype.getZ = function() {
    return this.z_;
};

/**
 * @param {ol.Projection} projection Projection.
 */
ol.Loc.prototype.setProjection = function(projection) {
    this.projection_ = projection;
};

/**
 * @param {number} x X.
 */
ol.Loc.prototype.setX = function(x) {
    this.x_ = x;
};

/**
 * @param {number} y Y.
 */
ol.Loc.prototype.setY = function(y) {
    this.y_ = y;
};

/**
 * @param {number|undefined} z Z.
 */
ol.Loc.prototype.setZ = function(z) {
    this.z_ = z;
};

/**
 * Transform this location to another coordinate reference system.  This
 * requires that this location has a projection set already (if not, an error
 * will be thrown).  Returns a new location object and does not modify this
 * location.
 *
 * @param {string|!ol.Projection} proj The destination projection.  Can be
 *     supplied as a projection instance of a string identifier.
 * @returns {!ol.Loc} A new location.
 */
ol.Loc.prototype.transform = function(proj) {
    if (goog.isString(proj)) {
        proj = new ol.Projection(proj);
    }
    return this._transform(proj);
};

/**
 * Transform this location to a new location given a projection object.
 *
 * @param {!ol.Projection} proj The destination projection.
 * @returns {!ol.Loc}
 */
ol.Loc.prototype._transform = function(proj) {
    var point = {'x': this.x_, 'y': this.y_};
    var sourceProj = this.projection_;
    if (!goog.isDefAndNotNull(sourceProj)) {
        throw new Error("Cannot transform a location without a source projection.");
    }
    ol.Projection.transform(point, sourceProj, proj);
    return new ol.Loc(point['x'], point['y'], this.z_, proj);
};

/**
 * Clean up.
 */
ol.Loc.prototype.destroy = function() {
    for (var key in this) {
        delete this[key];
    }
};
<|endoftext|>


<commit_before>const carousel = document.querySelector('.carousel'),
queries = ['sky', 'sun+mountain', 'snow', 'sun+desert', 'sun+ocean', 'sun+forest', 'sun+winter', 'sun+field', 'autumn'],
initMeasurements = window.screen.availWidth + 'x' + window.screen.availHeight,
bubbleRow = document.querySelector('.bubble-row'),
rightControl = document.querySelector('.control.-right'),
leftControl = document.querySelector('.control.-left');
let startX; // variable for touch ui

setCSSVariables();
[].forEach.call(queries, function(e) { addMarkerToHTML(); addSlideToHTML(e) });
setActive('.slide');
setActive('.bubble');

const slides = document.querySelectorAll('.slide'),
bubbles = document.querySelectorAll('.bubble');
[].forEach.call(bubbles, function(e) { e.addEventListener('click', bubbleChange, true) });

// set css variables everytime window size changes
window.addEventListener('resize', function() {
    setCSSVariables();
});

// make side arrow buttons work
rightControl.addEventListener('click', function() { moveSlide('right', slides) });
leftControl.addEventListener('click', function() { moveSlide('left', slides) });

// allow navigation with arrow keys
window.addEventListener('keydown', function(e) {
    if (e.keyCode == 39) moveSlide('right', slides);
    if (e.keyCode == 37) moveSlide('left', slides);
})

// initiate mobile UI
carousel.addEventListener("touchstart", touch2Mouse, true);
carousel.addEventListener("touchmove", touch2Mouse, true);
carousel.addEventListener("touchend", touch2Mouse, true);
carousel.addEventListener('mousedown', mousedownHandler, true);

let slideTimer = window.setInterval(function() { moveSlide('right', slides) } , 6000);

function mousedownHandler(e) {
    startX = e.clientX;
    carousel.addEventListener('mouseup', mouseupHandler, true);
}
function mouseupHandler(e) {
    if (startX > e.clientX && e.clientX < window.innerWidth/2) {
        moveSlide('right', slides);
    }
    if (startX < e.clientX && e.clientX > window.innerWidth/2) {
        moveSlide('left', slides);
    }
}
function touch2Mouse(e) {
  var theTouch = e.changedTouches[0];
  var mouseEv;

  switch(e.type)
  {
    case "touchstart": mouseEv="mousedown"; break;
    case "touchend":   mouseEv="mouseup"; break;
    case "touchmove":  mouseEv="mousemove"; break;
    default: return;
  }

  var mouseEvent = document.createEvent("MouseEvent");
  mouseEvent.initMouseEvent(
      mouseEv, true, true, window, 1,
       theTouch.screenX, theTouch.screenY, theTouch.clientX, theTouch.clientY,
      false, false, false, false, 0, null
    );
  theTouch.target.dispatchEvent(mouseEvent);

  e.preventDefault();
}
function moveSlide(direction, target) {
    for (i = 0; i < target.length; i++) {
        if (target[i].classList.contains('active')) {

            // removes active from current slide
            target[i].classList.remove('active');

            // separates between right and left control functionality
            if (direction == 'right') {
                if (i == target.length-1) {
                    target[0].classList.add('active');
                    break;
                }
                target[i+1].classList.add('active');
                break;
            } else {
                if (i == 0) {
                    target[target.length-1].classList.add('active');
                    break;
                }
                target[i-1].classList.add('active');
                break;
            }

        }
    }
    if (target == slides) {
        moveSlide(direction, bubbles);
    }

    clearInterval(slideTimer);
    slideTimer = window.setInterval(function() { moveSlide('right', slides) } , 6000);
}
function adjCSS(name, value) {
    document.documentElement.style.setProperty(`--${name}`, value + 'px');
}
function bubbleChange(e) {
    let node = e.target;
    document.querySelector('.bubble.active').classList.remove('active');
    document.querySelector('.slide.active').classList.remove('active');

    var i=0, e=node;
    while (e = e.previousSibling) { ++i;}

    node.classList.add('active');
    slides[i].classList.add('active');
}
function addSlideToHTML(query) {
    carousel.innerHTML += `<div class="slide" style="background: #222 url('http://source.unsplash.com/random/`+ initMeasurements + '?' + query + `') no-repeat center; background-size: cover;"></div>`;
}
function addMarkerToHTML() {
    bubbleRow.innerHTML += `<div class="bubble"><div class="marker"></div></div>`;
}
function setActive(selector) {
    const target = document.querySelector(selector);
    target.classList.add('active')
};
function setCSSVariables() {
    adjCSS('img-width', window.innerWidth);
    adjCSS('img-height', window.innerHeight);;
};<commit_msg>deleted old js file<commit_after><|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    gju = require('geojson-utils'),
    key = require('./lib/key.js'),
    levelup = require('levelup'),
    wellknown = require('wellknown'),
    queue = require('queue-async');

// adjusts task skipvals based on geometry, prioritizing particular areas/markets

var quickMode = true; // should we bother matching against every geometry or just quit after one hit?

if (process.stdin.isTTY) {
    if (process.argv.length < 4) {
        return console.log('file arguments are required\n`node prioritize.js [task] [geojson1 geojson2 ... ]`');
    }

    // process command line params, load geojson files
    var q = queue();
    var geojson = {};
    process.argv
        .filter(function(elem, i) { return (i>2); })
        .forEach(function(elem, i) {
            // if using overlapping geojson files, this flag might be useful.
            // otherwise, no.
            if (elem === '--slow') {
                quickMode = false;
            } else {
                q.defer(loadGeoJSON, elem);
            }
        });

    q.awaitAll(ProcessLevelDB);
}

function loadGeoJSON(elem, callback) {
    fs.readFile(elem, function(err, data) {
        if (err) console.log('# Error loading GeoJSON file ' + elem);

        var basename = path.basename(elem);
        var boundary = JSON.parse(data);
        if ((boundary === null) || !boundary.features) {
            console.log('# failed to load valid GeoJSON from ' + elem);
        } else {
            geojson[basename] = boundary;
            console.log('- loaded GeoJSON file ' + elem);
        }
        callback();
    });
}

function ProcessLevelDB(){
    console.log('- opening leveldb database ' + process.argv[2]);
    levelup('./ldb/' + process.argv[2] + '.ldb', function(err, db) {
        if (err) throw(err);

        var maxOverlaps = 0;
        console.log('- checking for geometry overlap');
        db.createReadStream()
            .on('data', function(data) {

                data.value = JSON.parse(data.value);

                // if this task is already fixed, skip it
                if (key.decompose(data.key).skipval === 0) return;

                // check if point is in any geojson geometries
                var overlapCount = 0;
                Object.keys(geojson).every(function(k) {

                    // check for valid point geometry in the task object
                    if (!data.value.st_astext) {
                        console.log('# missing geometry (st_astext) for key ' + data.key);
                        return false;
                    }

                    // test for presence of point in polygon
                    if (gju.pointInPolygon(wellknown.parse(data.value.st_astext), geojson[k].features[0].geometry)) {
                        if (!data.value.priority) data.value.priority = [];
                        data.value.priority.push(k);
                        overlapCount++;
                        if (quickMode) return false;
                    }

                    return true;
                });

                // track maximum number of overlaps
                maxOverlaps = Math.max(maxOverlaps, overlapCount);

                // record findings in the task object record
                data.value.overlapCount = overlapCount;
                db.put(data.key, JSON.stringify(data.value), function(err) {
                    if (err) console.log('# error saving key ' + data.key + '#' + overlapCount);
                });
            })
            .on('end', function(){

                // iterate through all keys, adding (maxOverlaps - overlap) to each skipval
                console.log('- reordering tasks');
                var adjustmentsMade = 0;

                var reordered = 0;
                db.createReadStream()
                    .on('data', function(data) {
                        data.value = JSON.parse(data.value);

                        // increment skipval based on number of overlaps
                        var keyComponents = key.decompose(data.key);
                        var newKey = key.compose((keyComponents.skipval + (maxOverlaps - parseInt(data.value.overlapCount))), keyComponents.hash);
                        if (parseInt(data.value.overlapCount) > 0) adjustmentsMade++;

                        // rename the task ID to reflect the new skipval
                        delete data.value.overlapCount;
                        db.del(data.key, function(err){
                            if (err) console.log('# error deleting key ' + newKey);
                            db.put(newKey, JSON.stringify(data.value), function(err) {
                                if (err) console.log('# error saving key ' + newKey);
                                reordered++;
                            });
                        });
                    })
                    .on('end', function() {
                        console.log('- finished, reprioritized ' + adjustmentsMade + '/' + reordered + ' tasks');
                    });
            });
    });
}
<commit_msg>rewritten prioritize with proper async<commit_after>var fs = require('fs'),
    path = require('path'),
    gju = require('geojson-utils'),
    key = require('./lib/key.js'),
    levelup = require('levelup'),
    wellknown = require('wellknown'),
    queue = require('queue-async');

// adjusts task skipvals based on geometry, prioritizing particular areas/markets

var quickMode = true; // should we bother matching against every geometry or just quit after one hit?
var verbose = false;
var maxOverlaps = 0;
var geojson = {};

if (require.main === module) {
    verbose = true;
    var geojsonFiles = [];

    process.argv
        .filter(function(elem, i) { return (i>2); })
        .forEach(function(elem, i) {
            // if using overlapping geojson files, this flag might be useful.
            // otherwise, no.
            if (elem === '--slow') {
                quickMode = false;
            } else {
                geojsonFiles.push(elem);
            }
        });

    prioritize(process.argv[2], geojsonFiles, function(){});
}

function prioritize(task, geojsonFiles, callback) {
    var q = queue();
    geojsonFiles.forEach(function(f) {
        q.defer(load, f);
    });
    q.awaitAll(function(err, results) {
        if (err) {
            callback(err);
        }
        else {
            processGeoJSON(task, function(err) { callback(err); });
        }
    });
}

function load(elem, callback) {
    fs.readFile(elem, function(err, data) {
        if (err) {
            if (verbose) console.log('# Error loading GeoJSON file ' + elem);
            callback(err);
        }

        var basename = path.basename(elem);
        var boundary = JSON.parse(data);
        if ((boundary === null) || !boundary.features) {
            var err = 'no valid GeoJSON in ' + elem;
            if (verbose) console.log('# ' + err);
            callback(err);
        } else {
            geojson[basename] = boundary;
            if (verbose) console.log('- loaded GeoJSON file ' + elem);
            callback(null);
        }
    });
}

function processGeoJSON(task, callback){
    if (verbose) console.log('- opening leveldb database ' + task);

    levelup('./ldb/' + task + '.ldb', function(err, db) {
        if (err) return callback(err);

        var q = queue();

        maxOverlaps = 0;
        if (verbose) console.log('- checking for geometry overlap');
        db.createReadStream()
            .on('data', function(data) {
                q.defer(checkOverlaps, db, data);
            })
            .on('end', function(){
                q.awaitAll(function(err, results) {
                    reorder(db, maxOverlaps, function(err){
                        db.close(function(err){
                            callback(err);
                        });
                    });
                });
            });
    });
}

function checkOverlaps(db, data, callback) {
    data.value = JSON.parse(data.value);

    // if this task is already fixed, skip it
    if (key.decompose(data.key).skipval === 0) return callback(null);

    // check if point is in any geojson geometries
    var overlapCount = 0;
    Object.keys(geojson).every(function(k) {

        // check for valid point geometry in the task object
        if (!data.value.st_astext) {
            if (verbose) console.log('# missing geometry (st_astext) for key ' + data.key);
            return false;
        }

        // test for presence of point in polygon
        if (gju.pointInPolygon(wellknown.parse(data.value.st_astext), geojson[k].features[0].geometry)) {
            if (!data.value.priority) data.value.priority = [];
            data.value.priority.push(k);
            overlapCount++;
            if (quickMode) return false;
        }

        return true;
    });

    // track maximum number of overlaps
    maxOverlaps = Math.max(maxOverlaps, overlapCount);

    // record findings in the task object record
    data.value.overlapCount = overlapCount;
    db.put(data.key, JSON.stringify(data.value), function(err) {
        if (verbose && err) console.log('# error saving key ' + data.key + '#' + overlapCount);
        callback(err);
    });
}

function reorder(db, maxOverlaps, callback) {
    // iterate through all keys, adding (maxOverlaps - overlap) to each skipval
    if (verbose) console.log('- reordering tasks');
    var adjustmentsMade = 0;
    var reordered = 0;
    db.createReadStream()
        .on('data', function(data) {
            data.value = JSON.parse(data.value);

            // increment skipval based on number of overlaps
            var keyComponents = key.decompose(data.key);
            var newKey = key.compose((keyComponents.skipval + (maxOverlaps - parseInt(data.value.overlapCount))), keyComponents.hash);
            if (parseInt(data.value.overlapCount) > 0) adjustmentsMade++;

            // rename the task ID to reflect the new skipval
            delete data.value.overlapCount;
            db.del(data.key, function(err){
                if (err && verbose) console.log('# error deleting key ' + newKey);
                db.put(newKey, JSON.stringify(data.value), function(err) {
                    if (err && verbose) console.log('# error saving key ' + newKey);
                    reordered++;
                });
            });
        })
        .on('end', function() {
            if (verbose) console.log('- finished, reprioritized ' + adjustmentsMade + '/' + reordered + ' tasks');
            callback(null);
        });
}

module.exports = prioritize;<|endoftext|>


<commit_before>module.exports = {
  devPort: '8000', // dev server 运行的端口
  designLayoutWidth: 750, // 设计稿的宽度 | 默认750，如果开启 Zoom 则直接按照设计稿宽度和屏幕宽度进行缩放
  designLayoutHeight: 1206, // 设计稿的高度 | 默认1206，如果开启 Zoom 则直接按照设计稿高度和屏幕高度进行缩放
  baseZoomRuler: 'width', // Zoom 缩放的基准 | 默认为 'width'，以屏幕的宽度进行缩放
  baseSize: 10, // 计算 rem 的基数，通常不用修改
  enableREM: true, // 是否用 rem 做适配
  enableZoom: true, // 是否用 zoom 做适配

  /**
   * webpack base config
   */
  entry: 'src/js/main.js',
  output: {
    path: 'dist',
    publicPath: './',
    filename: 'js/bundle.js'
  },
  outputCss: 'css/app.css',
  outputCssPublicPath: '../',
  imgLoaderQuery: {
    limit: 1000,
    name: 'img/[name].[ext]'
  },
  audioLoaderQuery: {
    name: 'plugin/[name].[ext]'
  },
  imgToBase64Dir: /src\/img-base64/,
  externals: {},
  rules: [],
  plugins: [],
  postcssPlugins: [],

  /**
   * webpack.CommonsChunkPlugin 默认配置
   * 详细描述参考：https://webpack.js.org/plugins/commons-chunk-plugin/
   */
  commonsChunkPluginOptions: null,

  /**
   * webpack.DefinePlugin 默认配置
   * 详细描述参考：https://webpack.js.org/plugins/define-plugin
   */
  definePluginOptions: {},

  /**
   * css-loader 默认配置
   * 详细描述参考：https://github.com/webpack-contrib/css-loader#options
   */
  cssLoaderOptions: {},

  /**
   * html-webpack-plugin 默认配置
   * 详细描述参考：https://github.com/jantimon/html-webpack-plugin#configuration
   */
  htmlWebpackPluginOptions: {
    template: 'src/index.html'
  },

  /**s
   * autoprefixer 默认配置
   * 详细描述参考：https://github.com/postcss/autoprefixer
   */
  autoprefixerOptions: {
    browsers: ['iOS >= 5', 'Android >= 2.3'],
    cascade: false
  },

  /**
   * postcss-assets 默认配置
   * 详细描述参考：https://github.com/assetsjs/postcss-assets
   */
  assetsOptions: {
    loadPaths: ['src/img/']
  },

  /**
   * postcss-sprites 默认配置
   * 详细描述参考：https://github.com/2createStudio/postcss-sprites
   */
  enableSpritesOnDev: false, // 是否在 dev 时合成雪碧图
  spritesOptions: {
    stylesheetPath: 'src/css/',
    spritePath: 'src/img/',
    retina: true,
    relativeTo: 'rule',
    spritesmith: {
      algorithm: 'left-right',
      padding: 2
    },
    verbose: false,
    // 将 img 目录下的子目录作为分组，子目录下的 png 图片会合成雪碧图
    groupBy: function(image) {
      var reg = /img\/(\S+)\/\S+\.png$/.exec(image.url);
      var groupName = reg ? reg[1] : reg;
      return groupName ? Promise.resolve(groupName) : Promise.reject();
    },
    // 非 img 子目录下面的 png 不合
    filterBy: function(image) {
      return /img\/\S+\/\S+\.png$/.test(image.url)
        ? Promise.resolve()
        : Promise.reject();
    }
  },

  /**
   * postcss-plugin-px2rem 默认配置
   * 详细描述参考：https://github.com/ant-tool/postcss-plugin-px2rem
   */
  px2remOptions: {
    // rootValue 由 config.designLayoutWidth / config.baseSize 而来，不用配置
    unitPrecision: 5,
    propWhiteList: [],
    propBlackList: [],
    selectorBlackList: [/.ignore-rem/],
    ignoreIdentifier: false,
    replace: true,
    mediaQuery: false,
    minPixelValue: 0
  },

  /**
   * webpack-visualizer 默认配置
   * 详细描述参考：https://github.com/chrisbateman/webpack-visualizer
   */
  enableWebpackVisualizer: false,

  /**
   * webpack development config
   *
   * 只作用于 development 模式，会覆盖 base config 中相同的配置项
   **/
  DEVELOPMENT: {
    // 配置是否在 Terminal 显示测试链接二维码
    enableDisplayQR: false
  },

  /**
   * webpack production config
   *
   * 只作用于 production 模式，会覆盖 base config 中相同的配置项
   **/
  PRODUCTION: {
    // 是否进行压缩
    enableJSCompress: true,
    enableCSSCompress: true,
    enableHTMLCompress: false, // 注意：可能会与 htmlWebpackPluginOptions.minify 冲突
    enableImageMin: false, // 用 image-webpack-loader 对图片进行压缩

    /**
     * uglifyjs-webpack-plugin 默认配置
     * 详细描述参考：https://github.com/webpack-contrib/uglifyjs-webpack-plugin#options
     */
    uglifyjsPluginOptions: {},

    /**
     * image-webpack-loader 默认配置
     * 详细描述参考：https://github.com/tcoopman/image-webpack-loader#usage
     */
    imageWebpackLoader: {
      mozjpeg: {
        quality: 65
      },
      pngquant: {
        quality: '65-90',
        speed: 4
      },
      svgo: {
        plugins: [{
          removeViewBox: false
        }, {
          removeEmptyAttrs: false
        }]
      },
      gifsicle: {
        optimizationLevel: 7,
        interlaced: false
      },
      optipng: {
        optimizationLevel: 7,
        interlaced: false
      }
    }
  }
};
<commit_msg>refactor: 修改默认配置项<commit_after>module.exports = {
  devPort: '8000', // dev server 运行的端口
  designLayoutWidth: 750, // 设计稿的宽度 | 默认750，如果开启 Zoom 则直接按照设计稿宽度和屏幕宽度进行缩放
  designLayoutHeight: 1206, // 设计稿的高度 | 默认1206，如果开启 Zoom 则直接按照设计稿高度和屏幕高度进行缩放
  baseZoomRuler: 'width', // Zoom 缩放的基准 | 默认为 'width'，以屏幕的宽度进行缩放
  baseSize: 10, // 计算 rem 的基数，通常不用修改
  enableREM: true, // 是否用 rem 做适配
  enableZoom: true, // 是否用 zoom 做适配

  /**
   * webpack base config
   */
  entry: 'src/js/main.js',
  output: {
    path: 'dist',
    publicPath: './',
    filename: 'js/bundle.js'
  },
  outputCss: 'css/app.css',
  outputCssPublicPath: '../',
  imgLoaderQuery: {
    limit: 1000,
    name: 'img/[name].[ext]'
  },
  audioLoaderQuery: {
    name: 'plugin/[name].[ext]'
  },
  imgToBase64Dir: /src\/img-base64/,
  externals: {},
  rules: [],
  plugins: [],
  postcssPlugins: [],

  /**
   * webpack.CommonsChunkPlugin 默认配置
   * 详细描述参考：https://webpack.js.org/plugins/commons-chunk-plugin/
   */
  commonsChunkPluginOptions: null,

  /**
   * webpack.DefinePlugin 默认配置
   * 详细描述参考：https://webpack.js.org/plugins/define-plugin
   */
  definePluginOptions: {},

  /**
   * css-loader 默认配置
   * 详细描述参考：https://github.com/webpack-contrib/css-loader#options
   */
  cssLoaderOptions: {},

  /**
   * html-webpack-plugin 默认配置
   * 详细描述参考：https://github.com/jantimon/html-webpack-plugin#configuration
   */
  htmlWebpackPluginOptions: {
    template: 'src/index.html'
  },

  /**s
   * autoprefixer 默认配置
   * 详细描述参考：https://github.com/postcss/autoprefixer
   */
  autoprefixerOptions: {
    browsers: ['iOS >= 5', 'Android >= 2.3'],
    cascade: false
  },

  /**
   * postcss-assets 默认配置
   * 详细描述参考：https://github.com/assetsjs/postcss-assets
   */
  assetsOptions: {
    loadPaths: ['src/img/'],
    cache: true
  },

  /**
   * postcss-sprites 默认配置
   * 详细描述参考：https://github.com/2createStudio/postcss-sprites
   */
  enableSpritesOnDev: false, // 是否在 dev 时合成雪碧图
  spritesOptions: {
    stylesheetPath: 'src/css/',
    spritePath: 'src/img/',
    retina: true,
    relativeTo: 'rule',
    spritesmith: {
      algorithm: 'left-right',
      padding: 2
    },
    verbose: false,
    // 将 img 目录下的子目录作为分组，子目录下的 png 图片会合成雪碧图
    groupBy: function(image) {
      var reg = /img\/(\S+)\/\S+\.png$/.exec(image.url);
      var groupName = reg ? reg[1] : reg;
      return groupName ? Promise.resolve(groupName) : Promise.reject();
    },
    // 非 img 子目录下面的 png 不合
    filterBy: function(image) {
      return /img\/\S+\/\S+\.png$/.test(image.url)
        ? Promise.resolve()
        : Promise.reject();
    }
  },

  /**
   * postcss-plugin-px2rem 默认配置
   * 详细描述参考：https://github.com/ant-tool/postcss-plugin-px2rem
   */
  px2remOptions: {
    // rootValue 由 config.designLayoutWidth / config.baseSize 而来，不用配置
    unitPrecision: 5,
    propWhiteList: [],
    propBlackList: [],
    selectorBlackList: [/.ignore-rem/],
    ignoreIdentifier: false,
    replace: true,
    mediaQuery: false,
    minPixelValue: 2
  },

  /**
   * webpack-visualizer 默认配置
   * 详细描述参考：https://github.com/chrisbateman/webpack-visualizer
   */
  enableWebpackVisualizer: false,

  /**
   * webpack development config
   *
   * 只作用于 development 模式，会覆盖 base config 中相同的配置项
   **/
  DEVELOPMENT: {
    // 配置是否在 Terminal 显示测试链接二维码
    enableDisplayQR: false
  },

  /**
   * webpack production config
   *
   * 只作用于 production 模式，会覆盖 base config 中相同的配置项
   **/
  PRODUCTION: {
    // 是否进行压缩
    enableJSCompress: true,
    enableCSSCompress: true,
    enableHTMLCompress: false, // 注意：可能会与 htmlWebpackPluginOptions.minify 冲突
    enableImageMin: false, // 用 image-webpack-loader 对图片进行压缩

    /**
     * uglifyjs-webpack-plugin 默认配置
     * 详细描述参考：https://github.com/webpack-contrib/uglifyjs-webpack-plugin#options
     */
    uglifyjsPluginOptions: {},

    /**
     * image-webpack-loader 默认配置
     * 详细描述参考：https://github.com/tcoopman/image-webpack-loader#usage
     */
    imageWebpackLoader: {
      mozjpeg: {
        quality: 65
      },
      pngquant: {
        quality: '65-90',
        speed: 4
      },
      svgo: {
        plugins: [{
          removeViewBox: false
        }, {
          removeEmptyAttrs: false
        }]
      },
      gifsicle: {
        optimizationLevel: 7,
        interlaced: false
      },
      optipng: {
        optimizationLevel: 7,
        interlaced: false
      }
    }
  }
};
<|endoftext|>


<commit_before>/**
   # Option

       Option a = Some a + None

   The option type encodes the presence and absence of a value. The
   `some` constructor represents a value and `none` represents the
   absence.

   * fold(a, b) - applies `a` to value if `some` or defaults to `b`
   * getOrElse(a) - default value for `none`
   * isSome - `true` iff `this` is `some`
   * isNone - `true` iff `this` is `none`
   * toLeft(r) - `left(x)` if `some(x)`, `right(r)` if none
   * toRight(l) - `right(x)` if `some(x)`, `left(l)` if none
   * flatMap(f) - monadic flatMap/bind
   * map(f) - functor map
   * ap(s) - applicative ap(ply)
   * concat(s, plus) - semigroup concat
**/

var Option = taggedSum({
    some: ['x'],
    none: []
});

Option.prototype.fold = function(f, g) {
    return this.cata({
        some: f,
        none: g
    });
};
Option.prototype.getOrElse = function(x) {
    return this.fold(
        identity,
        function() {
            return x;
        }
    );
};
Option.prototype.toLeft = function(o) {
    return this.fold(
        function(x) {
            return Either.left(x);
        },
        function() {
            return Either.right(o);
        }
    );
};
Option.prototype.toRight = function(o) {
    return this.fold(
        function(x) {
            return Either.right(x);
        },
        function() {
            return Either.left(o);
        }
    );
};
Option.prototype.flatMap = function(f) {
    return this.fold(
        function(x) {
            return f(x);
        },
        function() {
            return this;
        }
    );
};
Option.prototype.map = function(f) {
    return this.fold(
        function(x) {
            return Option.some.of(f(x));
        },
        function() {
            return this;
        }
    );
};
Option.prototype.ap = function(s) {
    return this.fold(
        function(x) {
            return s.map(x);
        },
        function() {
            return this;
        }
    );
};
Option.prototype.concat = function(s, plus) {
    return this.fold(
        function(x) {
            return s.map(function(y) {
                return plus(x, y);
            });
        },
        function() {
            return this;
        }
    );
};

/**
   ## of(x)

   Constructor `of` Monad creating `Option` with value of `x`.
**/
Option.of = function(x) {
    return Option.some(x);
};

/**
   ## some(x)

   Constructor to represent the existance of a value, `x`.
**/
Option.some.prototype.isSome = true;
Option.some.prototype.isNone = false;

/**
   ## of(x)

   Constructor `of` Monad creating `Option.some` with value of `x`.
**/
Option.some.of = function(x) {
    return Option.some(x);
};

/**
   ## none

   Represents the absence of a value.
**/
Option.none.isSome = false;
Option.none.isNone = true;

/**
   ## of(x)

   Constructor `of` Monad creating `Option.none`.
**/
Option.none.of = function(a) {
    return Option.none;
};

/**
   ## isOption(a)

   Returns `true` if `a` is a `some` or `none`.
**/
var isOption = isInstanceOf(Option);

bilby = bilby
    .property('some', Option.some)
    .property('none', Option.none)
    .property('isOption', isOption)
    .method('fold', isOption, function(a, b, c) {
        return a.fold(b, c);
    })
    .method('flatMap', isOption, function(a, b) {
        return a.flatMap(b);
    })
    .method('map', isOption, function(a, b) {
        return a.map(b);
    })
    .method('ap', isOption, function(a, b) {
        return a.ap(b);
    })
    .method('concat', isOption, function(a, b) {
        return a.concat(b, this.concat);
    });
<commit_msg>Fixing some spelling mistakes.<commit_after>/**
   # Option

       Option a = Some a + None

   The option type encodes the presence and absence of a value. The
   `some` constructor represents a value and `none` represents the
   absence.

   * fold(a, b) - applies `a` to value if `some` or defaults to `b`
   * getOrElse(a) - default value for `none`
   * isSome - `true` iff `this` is `some`
   * isNone - `true` iff `this` is `none`
   * toLeft(r) - `left(x)` if `some(x)`, `right(r)` if none
   * toRight(l) - `right(x)` if `some(x)`, `left(l)` if none
   * flatMap(f) - monadic flatMap/bind
   * map(f) - functor map
   * ap(s) - applicative ap(ply)
   * concat(s, plus) - semigroup concat
**/

var Option = taggedSum({
    some: ['x'],
    none: []
});

Option.prototype.fold = function(f, g) {
    return this.cata({
        some: f,
        none: g
    });
};
Option.prototype.getOrElse = function(x) {
    return this.fold(
        identity,
        function() {
            return x;
        }
    );
};
Option.prototype.toLeft = function(o) {
    return this.fold(
        function(x) {
            return Either.left(x);
        },
        function() {
            return Either.right(o);
        }
    );
};
Option.prototype.toRight = function(o) {
    return this.fold(
        function(x) {
            return Either.right(x);
        },
        function() {
            return Either.left(o);
        }
    );
};
Option.prototype.flatMap = function(f) {
    return this.fold(
        function(x) {
            return f(x);
        },
        function() {
            return this;
        }
    );
};
Option.prototype.map = function(f) {
    return this.fold(
        function(x) {
            return Option.some.of(f(x));
        },
        function() {
            return this;
        }
    );
};
Option.prototype.ap = function(s) {
    return this.fold(
        function(x) {
            return s.map(x);
        },
        function() {
            return this;
        }
    );
};
Option.prototype.concat = function(s, plus) {
    return this.fold(
        function(x) {
            return s.map(function(y) {
                return plus(x, y);
            });
        },
        function() {
            return this;
        }
    );
};

/**
   ## of(x)

   Constructor `of` Monad creating `Option` with value of `x`.
**/
Option.of = function(x) {
    return Option.some(x);
};

/**
   ## some(x)

   Constructor to represent the existence of a value, `x`.
**/
Option.some.prototype.isSome = true;
Option.some.prototype.isNone = false;

/**
   ## of(x)

   Constructor `of` Monad creating `Option.some` with value of `x`.
**/
Option.some.of = function(x) {
    return Option.some(x);
};

/**
   ## none

   Represents the absence of a value.
**/
Option.none.isSome = false;
Option.none.isNone = true;

/**
   ## of(x)

   Constructor `of` Monad creating `Option.none`.
**/
Option.none.of = function() {
    return Option.none;
};

/**
   ## isOption(a)

   Returns `true` if `a` is a `some` or `none`.
**/
var isOption = isInstanceOf(Option);

bilby = bilby
    .property('some', Option.some)
    .property('none', Option.none)
    .property('isOption', isOption)
    .method('fold', isOption, function(a, b, c) {
        return a.fold(b, c);
    })
    .method('flatMap', isOption, function(a, b) {
        return a.flatMap(b);
    })
    .method('map', isOption, function(a, b) {
        return a.map(b);
    })
    .method('ap', isOption, function(a, b) {
        return a.ap(b);
    })
    .method('concat', isOption, function(a, b) {
        return a.concat(b, this.concat);
    });
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    server: {
        port: process.env.PORT || 8889,
        host: "0.0.0.0"
    },
    log: {
        level: "silly",
        http: ':remote-addr [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer"'
    }
};<commit_msg>Set log level to error<commit_after>'use strict';

module.exports = {
    server: {
        port: process.env.PORT || 8889,
        host: "0.0.0.0"
    },
    log: {
        level: "error",
        http: ':remote-addr [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer"'
    }
};<|endoftext|>


<commit_before>import {PLATFORM} from 'aurelia-pal';

const originStorage = new Map();
const unknownOrigin = Object.freeze({moduleId: undefined, moduleMember: undefined});

/**
* A metadata annotation that describes the origin module of the function to which it's attached.
*/
export class Origin {
  /**
  * The id of the module from which the item originated.
  */
  moduleId: string;
  /**
  * The member name of the export on the module object from which the item originated.
  */
  moduleMember: string;

  /**
  * Creates an instance of Origin metadata.
  * @param moduleId The id of the module from which the item originated.
  * @param moduleMember The member name of the export on the module object from which the item originated.
  */
  constructor(moduleId: string, moduleMember: string) {
    this.moduleId = moduleId;
    this.moduleMember = moduleMember;
  }

  /**
  * Get the Origin metadata for the specified function.
  * @param fn The function to inspect for Origin metadata.
  * @return Returns the Origin metadata.
  */
  static get(fn: Function): Origin {
    let origin = originStorage.get(fn);

    if (origin === undefined) {
      PLATFORM.eachModule((key, value) => {
        if (typeof value === 'object') {
          for (let name in value) {
            try {
              let exp = value[name];
              if (exp === fn) {
                originStorage.set(fn, origin = new Origin(key, name));
                return true;
              }
            } catch (e) {
              // IE11 in cross origin frame fails when accessing Window['frameElement'] with Access Denied script error.
              // Window gets exported from webpack buildin/global.js.
            }
          }
        }

        if (value === fn) {
          originStorage.set(fn, origin = new Origin(key, 'default'));
          return true;
        }

        return false;
      });
    }

    return origin || unknownOrigin;
  }

  /**
  * Set the Origin metadata for the specified function.
  * @param fn The function to set the Origin metadata on.
  * @param fn The Origin metadata to store on the function.
  * @return Returns the Origin metadata.
  */
  static set(fn: Function, origin: Origin): void {
    originStorage.set(fn, origin);
  }
}
<commit_msg>fix(platform): Get rid of _'window.webkitStorageInfo' is deprecated_ warning<commit_after>import {PLATFORM} from 'aurelia-pal';

const originStorage = new Map();
const unknownOrigin = Object.freeze({moduleId: undefined, moduleMember: undefined});

/**
* A metadata annotation that describes the origin module of the function to which it's attached.
*/
export class Origin {
  /**
  * The id of the module from which the item originated.
  */
  moduleId: string;
  /**
  * The member name of the export on the module object from which the item originated.
  */
  moduleMember: string;

  /**
  * Creates an instance of Origin metadata.
  * @param moduleId The id of the module from which the item originated.
  * @param moduleMember The member name of the export on the module object from which the item originated.
  */
  constructor(moduleId: string, moduleMember: string) {
    this.moduleId = moduleId;
    this.moduleMember = moduleMember;
  }

  /**
  * Get the Origin metadata for the specified function.
  * @param fn The function to inspect for Origin metadata.
  * @return Returns the Origin metadata.
  */
  static get(fn: Function): Origin {
    let origin = originStorage.get(fn);

    if (origin === undefined) {
      PLATFORM.eachModule((key, value) => {
        if (typeof value === 'object') {
          let isBrowserWindow = typeof window !== 'undefined' && value === window;
          for (let name in value) {
            if (isBrowserWindow && name === 'webkitStorageInfo') { continue; } // Avoid warning to console
            try {
              let exp = value[name];
              if (exp === fn) {
                originStorage.set(fn, origin = new Origin(key, name));
                return true;
              }
            } catch (e) {
              // IE11 in cross origin frame fails when accessing Window['frameElement'] with Access Denied script error.
              // Window gets exported from webpack buildin/global.js.
            }
          }
        }

        if (value === fn) {
          originStorage.set(fn, origin = new Origin(key, 'default'));
          return true;
        }

        return false;
      });
    }

    return origin || unknownOrigin;
  }

  /**
  * Set the Origin metadata for the specified function.
  * @param fn The function to set the Origin metadata on.
  * @param fn The Origin metadata to store on the function.
  * @return Returns the Origin metadata.
  */
  static set(fn: Function, origin: Origin): void {
    originStorage.set(fn, origin);
  }
}
<|endoftext|>


<commit_before>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	url = require('url'),
	config = require('@v4fire/core/config/default'),
	concatUrls = require('urlconcat').concat,
	o = require('uniconf/options').option;

module.exports = config.createConfig({dirs: [__dirname, 'client']}, {
	__proto__: config,

	apiURL() {
		return this.api.proxy ? concatUrls(this.pathname(), 'api') : this.api.url;
	},

	api: {
		proxy: true,

		url: o('api-url', {
			env: true
		}),

		schema: {

		}
	},

	port: o('port', {
		env: true,
		type: 'number',
		default: 3333,
		validate(value) {
			return Number.isFinite(value) && (value > 0) && (value < 65536);
		}
	}),

	host() {
		return o('host-url', {
			env: true,
			default: `http://localhost:${this.port}/`
		});
	},

	pathname() {
		return o('base-path', {
			env: true,
			default: url.parse(this.host()).pathname || '/'
		});
	},

	build: {
		single: o('single-build', {
			env: true
		}),

		entries: o('entries', {
			env: true,
			short: 'e',
			coerce: (v) => v ? v.split(',') : []
		}),

		fast() {
			const v = o('fast-build', {
				env: true,
				type: 'boolean'
			});

			return v != null ? v : isProd;
		},

		buildGraphFromCache: o('build-graph-from-cache', {
			env: true,
			type: 'boolean'
		})
	},

	webpack: {
		externals: {
			'collection.js': '$C',
			'eventemitter2': 'EventEmitter2',
			'localforage': 'localforage',
			'sugar': 'Sugar',
			'vue': 'Vue',
			'chart.js': 'Chart',
			'ion-sound': 'ion',
			'socket.io-client': 'io',
			'setimmediate': 'setImmediate'
		},

		fatHTML: false,
		devtool: false,

		hashLength() {
			return !isProd || this.fatHTML ? false : 15;
		},

		dataURILimit() {
			return this.fatHTML ? false : 4096;
		},

		output() {
			return this.fatHTML ? '[name]' : '[hash]_[name]';
		},

		assetsJSON() {
			return 'assets.json';
		}
	},

	imageOpts: {
		mozjpeg: {
			progressive: true,
			quality: 65
		},

		optipng: {
			enabled: false,
		},

		pngquant: {
			quality: '65-90',
			speed: 4
		},

		gifsicle: {
			interlaced: false,
		},

		webp: {
			quality: 75
		},

		svgo: {

		}
	},

	html: {
		useShortDoctype: true,
		conservativeCollapse: true,
		removeAttributeQuotes: true,
		removeComments: isProd,
		collapseWhitespace: isProd
	},

	postcss: {

	},

	autoprefixer: {

	},

	uglify: {

	},

	monic() {
		return {
			stylus: {
				flags: {
					'+:*': true
				}
			}
		};
	},

	favicons() {
		return {
			appName: this.appName,
			path: this.src.assets('favicons'),
			background: '#FFF',
			display: 'standalone',
			orientation: 'portrait',
			version: 1.0,
			logging: false
		};
	},

	snakeskin() {
		function ignore(target) {
			target.ignore = true;
			return function () {
				return target.apply(this, arguments);
			};
		}

		const {
			webpack,
			src
		} = this;

		return {
			client: this.extend(super.snakeskin(), {
				adapter: 'ss2vue',
				adapterOptions: {transpiler: true},
				tagFilter: 'vueComp',
				tagNameFilter: 'vueTag',
				bemFilter: 'bem2vue',
				vars: {
					ignore
				}
			}),

			server: this.extend(super.snakeskin(), {
				vars: {
					fatHTML: webpack.fatHTML,
					hashLength: webpack.hashLength(),
					root: src.cwd(),
					output: src.clientOutput(),
					favicons: this.favicons().path,
					assets: src.assets(),
					lib: src.lib()
				}
			})
		};
	},

	typescript() {
		return {
			client: super.typescript(),
			worker: super.typescript(),
			server: super.typescript()
		};
	},

	css() {
		return {
			minimize: Boolean(isProd || Number(process.env.MINIFY_CSS))
		};
	},

	stylus() {
		return {
			preferPathResolver: 'webpack'
		};
	}
});
<commit_msg>Refactoring<commit_after>'use strict';

/*!
 * V4Fire Client Core
 * https://github.com/V4Fire/Client
 *
 * Released under the MIT license
 * https://github.com/V4Fire/Client/blob/master/LICENSE
 */

const
	url = require('url'),
	config = require('@v4fire/core/config/default'),
	concatUrls = require('urlconcat').concat,
	o = require('uniconf/options').option;

module.exports = config.createConfig({dirs: [__dirname, 'client']}, {
	__proto__: config,

	apiURL() {
		return this.api.proxy ? concatUrls(this.api.pathname(), 'api') : this.api.url;
	},

	api: {
		proxy: true,

		url: o('api-url', {
			env: true
		}),

		port: o('port', {
			env: true,
			type: 'number',
			default: 3333,
			validate(value) {
				return Number.isFinite(value) && (value > 0) && (value < 65536);
			}
		}),

		host() {
			return o('host-url', {
				env: true,
				default: `http://localhost:${this.port}/`
			});
		},

		pathname() {
			return o('base-path', {
				env: true,
				default: url.parse(this.host()).pathname || '/'
			});
		},

		schema: {

		}
	},

	build: {
		single: o('single-build', {
			env: true
		}),

		entries: o('entries', {
			env: true,
			short: 'e',
			coerce: (v) => v ? v.split(',') : []
		}),

		fast() {
			const v = o('fast-build', {
				env: true,
				type: 'boolean'
			});

			return v != null ? v : isProd;
		},

		buildGraphFromCache: o('build-graph-from-cache', {
			env: true,
			type: 'boolean'
		})
	},

	webpack: {
		externals: {
			'collection.js': '$C',
			'eventemitter2': 'EventEmitter2',
			'localforage': 'localforage',
			'sugar': 'Sugar',
			'vue': 'Vue',
			'chart.js': 'Chart',
			'ion-sound': 'ion',
			'socket.io-client': 'io',
			'setimmediate': 'setImmediate'
		},

		fatHTML: false,
		devtool: false,

		hashLength() {
			return !isProd || this.fatHTML ? false : 15;
		},

		dataURILimit() {
			return this.fatHTML ? false : 4096;
		},

		output() {
			return this.fatHTML ? '[name]' : '[hash]_[name]';
		},

		assetsJSON() {
			return 'assets.json';
		}
	},

	imageOpts: {
		mozjpeg: {
			progressive: true,
			quality: 65
		},

		optipng: {
			enabled: false,
		},

		pngquant: {
			quality: '65-90',
			speed: 4
		},

		gifsicle: {
			interlaced: false,
		},

		webp: {
			quality: 75
		},

		svgo: {

		}
	},

	html: {
		useShortDoctype: true,
		conservativeCollapse: true,
		removeAttributeQuotes: true,
		removeComments: isProd,
		collapseWhitespace: isProd
	},

	postcss: {

	},

	autoprefixer: {

	},

	uglify: {

	},

	monic() {
		return {
			stylus: {
				flags: {
					'+:*': true
				}
			}
		};
	},

	favicons() {
		return {
			appName: this.appName,
			path: this.src.assets('favicons'),
			background: '#FFF',
			display: 'standalone',
			orientation: 'portrait',
			version: 1.0,
			logging: false
		};
	},

	snakeskin() {
		function ignore(target) {
			target.ignore = true;
			return function () {
				return target.apply(this, arguments);
			};
		}

		const {
			webpack,
			src
		} = this;

		return {
			client: this.extend(super.snakeskin(), {
				adapter: 'ss2vue',
				adapterOptions: {transpiler: true},
				tagFilter: 'vueComp',
				tagNameFilter: 'vueTag',
				bemFilter: 'bem2vue',
				vars: {
					ignore
				}
			}),

			server: this.extend(super.snakeskin(), {
				vars: {
					fatHTML: webpack.fatHTML,
					hashLength: webpack.hashLength(),
					root: src.cwd(),
					output: src.clientOutput(),
					favicons: this.favicons().path,
					assets: src.assets(),
					lib: src.lib()
				}
			})
		};
	},

	typescript() {
		return {
			client: super.typescript(),
			worker: super.typescript(),
			server: super.typescript()
		};
	},

	css() {
		return {
			minimize: Boolean(isProd || Number(process.env.MINIFY_CSS))
		};
	},

	stylus() {
		return {
			preferPathResolver: 'webpack'
		};
	}
});
<|endoftext|>


<commit_before><commit_msg>用get代替post<commit_after><|endoftext|>


<commit_before>'use strict';

module.exports = {
	app: {
		title: 'xskillz',
		description: 'Manage xebians skillz',
		keywords: 'neo4J, express, angularjs, node.js'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'xskillz',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
			],
			js: [
				'public/lib/lodash/dist/lodash.min.js',
				'public/lib/jquery/dist/jquery.min.js',
				'public/lib/d3/d3.min.js',
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/bootstrap/dist/js/bootstrap.min.js',
				'public/lib/d3/d3.min.js'
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};
<commit_msg>Fix double include of d3 library<commit_after>'use strict';

module.exports = {
	app: {
		title: 'xskillz',
		description: 'Manage xebians skillz',
		keywords: 'neo4J, express, angularjs, node.js'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'xskillz',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
			],
			js: [
				'public/lib/lodash/dist/lodash.min.js',
				'public/lib/jquery/dist/jquery.min.js',
				'public/lib/d3/d3.min.js',
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/bootstrap/dist/js/bootstrap.min.js',
			]
		},
		css: [
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var express = require('express'),
    mongoStore = require('connect-mongo')(express),
    flash = require('connect-flash'),
    helpers = require('view-helpers'),
    config = require('./config');

module.exports = function(app, passport, mongoose) {
    app.set('showStackError', true);

    //Should be placed before express.static
    app.use(express.compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    //Setting the fav icon and static folder
    app.use(express.favicon());
    app.use(express.static(config.root + '/public'));

    //Don't use logger for test env
    if (process.env.NODE_ENV !== 'test') {
        app.use(express.logger('dev'));
    }

    //Set views path, template engine and default layout
    app.set('views', config.root + '/app/views');
    app.set('view engine', 'jade');

    //Enable jsonp
    app.enable("jsonp callback");

    app.configure(function() {
        //cookieParser should be above session
        app.use(express.cookieParser());

        //bodyParser should be above methodOverride
        app.use(express.bodyParser());
        app.use(express.methodOverride());

        //express/mongo session storage
        app.use(express.session({
            secret: 'MEAN',
            store: new mongoStore({
                url: config.db,
                collection: 'sessions',
                mongoose_connection: mongoose.connection
            })
        }));

        //connect flash for flash messages
        app.use(flash());

        //dynamic helpers
        app.use(helpers(config.app.name));

        //use passport session
        app.use(passport.initialize());
        app.use(passport.session());

        //routes should be at the last
        app.use(app.router);

        //Assume "not found" in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
        app.use(function(err, req, res, next) {
            //Treat as 404
            if (~err.message.indexOf('not found')) return next();

            //Log it
            console.error(err.stack);

            //Error page
            res.status(500).render('500', {
                error: err.stack
            });
        });

        //Assume 404 since no middleware responded
        app.use(function(req, res, next) {
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not found'
            });
        });

    });
};
<commit_msg>bug(fix-mongo-issues): set auto_reconnect to true in express.js file<commit_after>/**
 * Module dependencies.
 */
var express = require('express'),
    mongoStore = require('connect-mongo')(express),
    flash = require('connect-flash'),
    helpers = require('view-helpers'),
    config = require('./config');

module.exports = function(app, passport, mongoose) {
    app.set('showStackError', true);

    //Should be placed before express.static
    app.use(express.compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    //Setting the fav icon and static folder
    app.use(express.favicon());
    app.use(express.static(config.root + '/public'));

    //Don't use logger for test env
    if (process.env.NODE_ENV !== 'test') {
        app.use(express.logger('dev'));
    }

    //Set views path, template engine and default layout
    app.set('views', config.root + '/app/views');
    app.set('view engine', 'jade');

    //Enable jsonp
    app.enable("jsonp callback");

    app.configure(function() {
        //cookieParser should be above session
        app.use(express.cookieParser());

        //bodyParser should be above methodOverride
        app.use(express.bodyParser());
        app.use(express.methodOverride());

        //express/mongo session storage
        console.log("This is the mongoose connection +++++++++++++++++", mongoose.connection);
        console.log("This is the Config  database ----------------", config.db);
        app.use(express.session({
            secret: 'MEAN',
            store: new mongoStore({
                url: config.db,
                collection: 'sessions',
                mongoose_connection: mongoose.connection,
                auto_reconnect: true
            })
        }));

        //connect flash for flash messages
        app.use(flash());

        //dynamic helpers
        app.use(helpers(config.app.name));

        //use passport session
        app.use(passport.initialize());
        app.use(passport.session());

        //routes should be at the last
        app.use(app.router);

        //Assume "not found" in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
        app.use(function(err, req, res, next) {
            //Treat as 404
            if (~err.message.indexOf('not found')) return next();

            //Log it
            console.error(err.stack);

            //Error page
            res.status(500).render('500', {
                error: err.stack
            });
        });

        //Assume 404 since no middleware responded
        app.use(function(req, res, next) {
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not found'
            });
        });

    });
};
<|endoftext|>


<commit_before>/**
 * Express configuration
 */

'use strict';

var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

module.exports = function(app) {
  var env = app.get('env');

  console.log('config.root: ', config.root)

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.use(passport.initialize());

  // Persist sessions with mongoStore
  // We need to enable sessions for passport twitter because its an oauth 1.0 strategy
  app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({ mongoose_connection: mongoose.connection })
  }));

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'youka-client/public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    // app.use(require('connect-livereload')());
    // app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'youka-client/dist')));
    app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<commit_msg>Update client directory path<commit_after>/**
 * Express configuration
 */

'use strict';

var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');

module.exports = function(app) {
  var env = app.get('env');

  console.log('config.root: ', config.root)

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser());
  app.use(passport.initialize());

  // Persist sessions with mongoStore
  // We need to enable sessions for passport twitter because its an oauth 1.0 strategy
  app.use(session({
    secret: config.secrets.session,
    resave: true,
    saveUninitialized: true,
    store: new mongoStore({ mongoose_connection: mongoose.connection })
  }));

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'youka-client/dist')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    // app.use(require('connect-livereload')());
    // app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'youka-client/dist')));
    app.set('appPath', 'dist');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<|endoftext|>