<commit_before>(function (clique, _, Backbone, $) {
    "use strict";

    clique.adapter = {};

    clique.Adapter = function (options) {
        var accessors,
            defaultNeighborhood;

        // A default neighborhood computation function, to be used when the
        // concrete adapter doesn't supply its own.
        defaultNeighborhood = _.bind(function (node, radius) {
            var step,
                chain,
                result = {
                    nodes: {},
                    links: {}
                };

            step = _.bind(function (frontier) {
                // Get neighbor links of all nodes in the frontier.
                return $.when.apply($, _.map(frontier, _.partial(this.getNeighbors, _, undefined), this)).then(function () {
                    var args = _.toArray(arguments),
                        nodes = [];

                    _.each(args, function (neighbors) {
                        _.each(neighbors.nodes, function (node) {
                            if (!_.has(result.nodes, node.key())) {
                                nodes.push(node);
                            }
                            result.nodes[node.key()] = node;
                        });

                        _.each(neighbors.links, function (link) {
                            result.links[link.key()] = link;
                        });
                    });

                    return nodes;
                });
            }, this);

            // Initialize the chain with the node we're expanding from.
            result.nodes[node.key()] = node;
            chain = $.when([node]);

            // Expand the chain enough times to reach the specified radius.
            _.each(_.range(radius), function () {
                chain = chain.then(step);
            });

            // Compute the neighboring links on the final frontier.
            return chain.then(_.bind(function (frontier) {
                return $.when.apply($, _.map(frontier, _.partial(this.getNeighborLinks, _, undefined), this)).then(function () {
                    _.each(_.toArray(arguments), function (links) {
                        _.each(links, function (link) {
                            if (!_.has(result.links, link.key())) {
                                result.links[link.key()] = link;
                            }
                        });
                    });

                    result.nodes = _.values(result.nodes);
                    result.links = _.values(result.links);

                    return result;
                });
            }, this));
        }, this);

        // Keep track of accessors.
        this.accessors = accessors = {};
        this.onNewAccessor = this.onNewAccessor || _.noop;
        this.addAccessor = function (blob) {
            var mut;

            if (!_.has(accessors, blob.key)) {
                accessors[blob.key] = new clique.util.Accessor(blob);
                this.onNewAccessor(mut);
            }

            mut = accessors[blob.key];

            return mut;
        };

        // Define methods.
        this.getAccessor = _.propertyOf(accessors);

        this.findNodes = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findNode = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findNodeByKey = function (key) {
            return this.findNode({
                key: key
            });
        };

        this.findLinks = function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                undirected = _.isUndefined(spec.undirected) ? true : spec.undirected,
                directed = _.isUndefined(spec.directed) ? true : spec.directed,
                source = spec.source,
                target = spec.target;

            delete spec.undirected;
            delete spec.directed;
            delete spec.source;
            delete spec.target;

            return $.when(this.findLinksImpl(spec, source, target, undirected, directed)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findLink = function (spec) {
            return $.when(this.findLinksImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findLinkByKey = function (key) {
            return this.findLink({
                key: key
            });
        };

        this.getNeighborLinks = function (node, opts) {
            var reqs = [];

            opts = opts || {};
            _.each(["outgoing", "incoming", "undirected"], function (mode) {
                opts[mode] = _.isUndefined(opts[mode]) ? true : opts[mode];
            });

            if (opts.outgoing) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    undirected: false
                }));
            }

            if (opts.incoming) {
                reqs.push(this.findLinks({
                    target: node.key(),
                    undirected: false
                }));
            }

            if (opts.undirected) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    undirected: true
                }));

                reqs.push(this.findLinks({
                    target: node.key(),
                    undirected: true
                }));
            }

            return $.when.apply($, reqs).then(function () {
                return _.reduce(_.toArray(arguments), function (memo, item) {
                    return memo.concat(item);
                }, []);
            });
        };

        this.getOutgoingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.getNeighbors = function (node, opts) {
            var key = node.key(),
                links;

            return this.getNeighborLinks(node, opts).then(_.bind(function (links_) {
                var neighborKeys,
                    muts;

                links = links_;

                neighborKeys = _.map(links, function (link) {
                    return key === link.source() ? link.target() : link.source();
                });

                // Attempt to retrieve the accessors.  The ones we don't have
                // yet will show up as undefined in this array.
                muts = _.map(neighborKeys, this.getAccessor, this);

                _.each(muts, function (mut, i) {
                    if (_.isUndefined(mut)) {
                        muts[i] = this.findNodeByKey(neighborKeys[i]);
                    } else {
                        muts[i] = $.when(muts[i]);
                    }
                }, this);

                return $.when.apply($, muts);
            }, this)).then(function () {
                return {
                    nodes: _.toArray(arguments),
                    links: links
                };
            });
        };

        this.getOutgoingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.neighborhood = function (node, radius) {
            if (this.neighborhoodImpl) {
                return this.neighborhoodImpl.apply(this, arguments).then(_.bind(function (nbd) {
                    return {
                        nodes: _.map(nbd.nodes, this.addAccessor, this),
                        links: _.map(nbd.links, this.addAccessor, this)
                    };
                }, this));
            } else {
                return defaultNeighborhood(node, radius);
            }
        };

        this.createNode = function (data) {
            return $.when(this.createNodeImpl(data || {}))
                .then(_.bind(this.addAccessor, this));
        };

        this.createLink = function (source, target, _data, undirected) {
            var data;

            // If source/target is a accessor, call its key method to get the
            // key; otherwise, assume it is a string describing the key already.
            source = _.result(source, "key", source);
            target = _.result(target, "key", target);

            data = _data || {};
            undirected = _.isUndefined(undirected) ? false : undirected;

            return $.when(this.createLinkImpl(source, target, data, undirected))
                .then(_.bind(this.addAccessor, this));
        };

        this.destroyNode = function (node) {
            var key = node.key();
            return this.destroyNodeImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        this.destroyLink = function (link) {
            var key = link.key();
            return this.destroyLinkImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        options = options || {};
        this.initialize.apply(this, arguments);
    };

    clique.Adapter.extend = Backbone.Model.extend;

    clique.adapter.NodeLinkList = clique.Adapter.extend({
        initialize: function (options) {
            var table = {};

            this.nodes = clique.util.deepCopy(options.nodes);
            this.links = clique.util.deepCopy(options.links);

            _.each(this.nodes, function (node, i) {
                var tmpNs = "datax",
                    ns;

                // Promote the data elements into a dedicated namespace.
                //
                // First figure out a suitable temporary name to use for the
                // namespace.
                while (_.has(node, tmpNs)) {
                    tmpNs += "x";
                }

                // Create the namespace.
                ns = node[tmpNs] = {};

                // Move all top-level properties into the namespace.
                _.each(node, function (v, k) {
                    if (k !== tmpNs) {
                        ns[k] = v;
                        delete node[k];
                    }
                });

                // Rename the temporary namespace as "data".
                if (tmpNs !== "data") {
                    node.data = ns;
                    delete node[tmpNs];
                }

                table[i] = node;

                // Assign a unique key to this node.
                node.key = _.uniqueId("node_");
            });

            _.each(this.links, function (link) {
                link.key = _.uniqueId("link_");

                link.source = table[link.source];
                link.target = table[link.target];
            }, this);
        },

        findNodesImpl: function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                searchspace = this.nodes,
                result;

            if (spec.key) {
                searchspace = _.filter(searchspace, function (node) {
                    return node.key === spec.key;
                });

                delete spec.key;
            }

            result = _.filter(searchspace, function (node) {
                return _.isMatch(node.data, spec);
            });

            return result;
        },

        findLinksImpl: function (spec, source, target, undirected, directed) {
            return _.filter(this.links, function (link) {
                var undirectedMatch = (link.undirected || false) === undirected,
                    directedMatch = (_.isUndefined(link.undirected) || !link.undirected) === directed,
                    sourceMatch = _.isUndefined(source) || (link.source.key === source),
                    targetMatch = _.isUndefined(target) || (link.target.key === target),
                    dataMatch = _.isMatch(spec, link.data);

                return _.every([sourceMatch, targetMatch, dataMatch, undirectedMatch || directedMatch]);
            });
        },

        newNode: _.noop,
        newLink: _.noop,
        destroyNode: _.noop,
        destroyLink: _.noop
    });
}(window.clique, window._, window.Backbone, window.jQuery));
<commit_msg>Fix bug in searching for directed vs. undirected links<commit_after>(function (clique, _, Backbone, $) {
    "use strict";

    clique.adapter = {};

    clique.Adapter = function (options) {
        var accessors,
            defaultNeighborhood;

        // A default neighborhood computation function, to be used when the
        // concrete adapter doesn't supply its own.
        defaultNeighborhood = _.bind(function (node, radius) {
            var step,
                chain,
                result = {
                    nodes: {},
                    links: {}
                };

            step = _.bind(function (frontier) {
                // Get neighbor links of all nodes in the frontier.
                return $.when.apply($, _.map(frontier, _.partial(this.getNeighbors, _, undefined), this)).then(function () {
                    var args = _.toArray(arguments),
                        nodes = [];

                    _.each(args, function (neighbors) {
                        _.each(neighbors.nodes, function (node) {
                            if (!_.has(result.nodes, node.key())) {
                                nodes.push(node);
                            }
                            result.nodes[node.key()] = node;
                        });

                        _.each(neighbors.links, function (link) {
                            result.links[link.key()] = link;
                        });
                    });

                    return nodes;
                });
            }, this);

            // Initialize the chain with the node we're expanding from.
            result.nodes[node.key()] = node;
            chain = $.when([node]);

            // Expand the chain enough times to reach the specified radius.
            _.each(_.range(radius), function () {
                chain = chain.then(step);
            });

            // Compute the neighboring links on the final frontier.
            return chain.then(_.bind(function (frontier) {
                return $.when.apply($, _.map(frontier, _.partial(this.getNeighborLinks, _, undefined), this)).then(function () {
                    _.each(_.toArray(arguments), function (links) {
                        _.each(links, function (link) {
                            if (!_.has(result.links, link.key())) {
                                result.links[link.key()] = link;
                            }
                        });
                    });

                    result.nodes = _.values(result.nodes);
                    result.links = _.values(result.links);

                    return result;
                });
            }, this));
        }, this);

        // Keep track of accessors.
        this.accessors = accessors = {};
        this.onNewAccessor = this.onNewAccessor || _.noop;
        this.addAccessor = function (blob) {
            var mut;

            if (!_.has(accessors, blob.key)) {
                accessors[blob.key] = new clique.util.Accessor(blob);
                this.onNewAccessor(mut);
            }

            mut = accessors[blob.key];

            return mut;
        };

        // Define methods.
        this.getAccessor = _.propertyOf(accessors);

        this.findNodes = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findNode = function (spec) {
            return $.when(this.findNodesImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findNodeByKey = function (key) {
            return this.findNode({
                key: key
            });
        };

        this.findLinks = function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                directed = spec.directed,
                source = spec.source,
                target = spec.target;

            delete spec.directed;
            delete spec.source;
            delete spec.target;

            return $.when(this.findLinksImpl(spec, source, target, directed)).then(_.partial(_.map, _, this.addAccessor, this));
        };

        this.findLink = function (spec) {
            return $.when(this.findLinksImpl(spec)).then(_.bind(function (results) {
                if (_.isEmpty(results)) {
                    return undefined;
                }

                return this.addAccessor(results[0]);
            }, this));
        };

        this.findLinkByKey = function (key) {
            return this.findLink({
                key: key
            });
        };

        this.getNeighborLinks = function (node, opts) {
            var reqs = [];

            opts = opts || {};
            _.each(["outgoing", "incoming", "undirected"], function (mode) {
                opts[mode] = _.isUndefined(opts[mode]) ? true : opts[mode];
            });

            if (opts.outgoing) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    directed: true
                }));
            }

            if (opts.incoming) {
                reqs.push(this.findLinks({
                    target: node.key(),
                    directed: true
                }));
            }

            if (opts.undirected) {
                reqs.push(this.findLinks({
                    source: node.key(),
                    directed: false
                }));

                reqs.push(this.findLinks({
                    target: node.key(),
                    directed: false
                }));
            }

            return $.when.apply($, reqs).then(function () {
                return _.reduce(_.toArray(arguments), function (memo, item) {
                    return memo.concat(item);
                }, []);
            });
        };

        this.getOutgoingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedLinks = function (node) {
            return this.getNeighborLinks(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.getNeighbors = function (node, opts) {
            var key = node.key(),
                links;

            return this.getNeighborLinks(node, opts).then(_.bind(function (links_) {
                var neighborKeys,
                    muts;

                links = links_;

                neighborKeys = _.map(links, function (link) {
                    return key === link.source() ? link.target() : link.source();
                });

                // Attempt to retrieve the accessors.  The ones we don't have
                // yet will show up as undefined in this array.
                muts = _.map(neighborKeys, this.getAccessor, this);

                _.each(muts, function (mut, i) {
                    if (_.isUndefined(mut)) {
                        muts[i] = this.findNodeByKey(neighborKeys[i]);
                    } else {
                        muts[i] = $.when(muts[i]);
                    }
                }, this);

                return $.when.apply($, muts);
            }, this)).then(function () {
                return {
                    nodes: _.toArray(arguments),
                    links: links
                };
            });
        };

        this.getOutgoingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: false
            });
        };

        this.getOutflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: false,
                undirected: true
            });
        };

        this.getIncomingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: false
            });
        };

        this.getInflowingNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: true,
                undirected: true
            });
        };

        this.getUndirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: false,
                incoming: false,
                undirected: true
            });
        };

        this.getDirectedNeighbors = function (node) {
            return this.getNeighbors(node, {
                outgoing: true,
                incoming: true,
                undirected: false
            });
        };

        this.neighborhood = function (node, radius) {
            if (this.neighborhoodImpl) {
                return this.neighborhoodImpl.apply(this, arguments).then(_.bind(function (nbd) {
                    return {
                        nodes: _.map(nbd.nodes, this.addAccessor, this),
                        links: _.map(nbd.links, this.addAccessor, this)
                    };
                }, this));
            } else {
                return defaultNeighborhood(node, radius);
            }
        };

        this.createNode = function (data) {
            return $.when(this.createNodeImpl(data || {}))
                .then(_.bind(this.addAccessor, this));
        };

        this.createLink = function (source, target, _data, undirected) {
            var data;

            // If source/target is a accessor, call its key method to get the
            // key; otherwise, assume it is a string describing the key already.
            source = _.result(source, "key", source);
            target = _.result(target, "key", target);

            data = _data || {};
            undirected = _.isUndefined(undirected) ? false : undirected;

            return $.when(this.createLinkImpl(source, target, data, undirected))
                .then(_.bind(this.addAccessor, this));
        };

        this.destroyNode = function (node) {
            var key = node.key();
            return this.destroyNodeImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        this.destroyLink = function (link) {
            var key = link.key();
            return this.destroyLinkImpl(key).then(function (response) {
                return {
                    key: key,
                    response: response
                };
            });
        };

        options = options || {};
        this.initialize.apply(this, arguments);
    };

    clique.Adapter.extend = Backbone.Model.extend;

    clique.adapter.NodeLinkList = clique.Adapter.extend({
        initialize: function (options) {
            var table = {};

            this.nodes = clique.util.deepCopy(options.nodes);
            this.links = clique.util.deepCopy(options.links);

            _.each(this.nodes, function (node, i) {
                var tmpNs = "datax",
                    ns;

                // Promote the data elements into a dedicated namespace.
                //
                // First figure out a suitable temporary name to use for the
                // namespace.
                while (_.has(node, tmpNs)) {
                    tmpNs += "x";
                }

                // Create the namespace.
                ns = node[tmpNs] = {};

                // Move all top-level properties into the namespace.
                _.each(node, function (v, k) {
                    if (k !== tmpNs) {
                        ns[k] = v;
                        delete node[k];
                    }
                });

                // Rename the temporary namespace as "data".
                if (tmpNs !== "data") {
                    node.data = ns;
                    delete node[tmpNs];
                }

                table[i] = node;

                // Assign a unique key to this node.
                node.key = _.uniqueId("node_");
            });

            _.each(this.links, function (link) {
                link.key = _.uniqueId("link_");

                link.source = table[link.source];
                link.target = table[link.target];
            }, this);
        },

        findNodesImpl: function (_spec) {
            var spec = clique.util.deepCopy(_spec),
                searchspace = this.nodes,
                result;

            if (spec.key) {
                searchspace = _.filter(searchspace, function (node) {
                    return node.key === spec.key;
                });

                delete spec.key;
            }

            result = _.filter(searchspace, function (node) {
                return _.isMatch(node.data, spec);
            });

            return result;
        },

        findLinksImpl: function (spec, source, target, directed) {
            return _.filter(this.links, function (link) {
                var directedMatch,
                    sourceMatch = _.isUndefined(source) || (link.source.key === source),
                    targetMatch = _.isUndefined(target) || (link.target.key === target),
                    dataMatch = _.isMatch(spec, link.data);

                if (_.isUndefined(directed) || _.isNull(directed)) {
                    directedMatch = true;
                } else if (directed) {
                    directedMatch = !link.undirected;
                } else {
                    directedMatch = link.undirected;
                }

                return _.every([sourceMatch, targetMatch, dataMatch, directedMatch]);
            });
        },

        newNode: _.noop,
        newLink: _.noop,
        destroyNode: _.noop,
        destroyLink: _.noop
    });
}(window.clique, window._, window.Backbone, window.jQuery));
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Guiferviz
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * MysteryGame class.
 *
 * Creates a game similar to the one showed in the Reinforcement Learning
 * MOOC (Udacity) by Georgia Tech.
 * The games appears in "Lesson 2 - Reinforcement Learning Basics".
 *
 * Container: DOM element where the game will be inyected. The game will
 *          adapt to the container size.
 * Map: bidimensional array with numbers from 0 to 5.
 *          0 - Wall
 *          1 - Empty cell
 *          2,3,4,5 - Red, Green, Blue, Yellow cell
 * Player: Array with the x and y origin coordinates of the player.
 * Obj: Array with the x and y circle position.
 * Actions: Array with the actions in the order you want.
 *          The first element corresponds with the key number 1 and so on.
 *          ["up", "down", "left", "right", "catch", "release"]
 *          If not array is given random actions will be choosen.
 */
MysteryGame = function (container, map, player, circle, actions)
{
    this.w = container.offsetWidth;
    this.h = container.offsetHeight;
    if (!this.h)
    {
        this.h = this.w;
        container.style.height = this.h + "px";
    }
    this.tiles_x = map[0].length;
    this.tiles_y = map.length;
    this.size_x = this.w / this.tiles_x;
    this.size_y = this.h / this.tiles_y;
    this.endColor = Math.floor(Math.random() * 4 + 2);
    this.svg = this.createSvg(this.w, this.h);
    this.catched = false;
    this.actions = actions || ["up", "down", "left", "right",
    		"catch", "release"];
    if (!actions)
        this.shuffle(this.actions);

    this.map = this.createMap(map);
    this.player = this.createPlayer(player);
    this.obj = this.createObject(circle);
    this.goodtext = this.createText(this.w / 2, this.h / 2, "+1");
    this.goodtext.classList.add("hide");
    this.badtext = this.createText(this.w / 2, this.h / 2, "-1");
    this.badtext.classList.add("hide");
    this.badtext.classList.add("bad");

    container.innerHTML = "";  // Deletes all in container
    container.appendChild(this.svg);

    var this_ = this;
    window.addEventListener("keypress", function(e)
    {
        this_.doAction(e.charCode);
    });
};

MysteryGame.SVG_URL = "http://www.w3.org/2000/svg";

MysteryGame.prototype.shuffle = function (o)
{
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

MysteryGame.prototype.createSvg = function (w, h)
{
    var svg = document.createElementNS(MysteryGame.SVG_URL, "svg");
    svg.setAttribute('width', w);
    svg.setAttribute('height', h);
    svg.classList.add("mystery");

    return svg;
};

MysteryGame.prototype.createRect = function (x, y, w, h)
{
    var rect = document.createElementNS(MysteryGame.SVG_URL, 'rect');
    rect.setAttribute('x', x);
    rect.setAttribute('y', y);
    rect.setAttribute('width', w);
    rect.setAttribute('height', h);

    return rect;
};

MysteryGame.prototype.createCircle = function (x, y, r)
{
    var circle = document.createElementNS(MysteryGame.SVG_URL, 'circle');
    circle.setAttribute('cx', x);
    circle.setAttribute('cy', y);
    circle.setAttribute('r', r);

    return circle;
};

MysteryGame.prototype.createMap = function (colors)
{
    var map = [];
    for (var i = 0; i < this.tiles_y; ++i)
    {
    	var row = [];
        for (var j = 0; j < this.tiles_x; ++j)
        {
            var rect = this.createRect(j * this.size_x, i * this.size_y,
                this.size_x, this.size_y);
            rect.classList.add("c" + colors[i][j]);
            rect.color = colors[i][j];
            row.push(rect);
            this.svg.appendChild(rect);
        }
        map.push(row);
    }

    return map;
};

MysteryGame.prototype.createText = function (x, y, txt)
{
    var text = document.createElementNS(MysteryGame.SVG_URL, 'text');
    text.setAttribute('x', x);
    text.setAttribute('y', y);
    text.innerHTML = txt;
    this.svg.appendChild(text);

    return text;
};

MysteryGame.prototype.createPlayer = function (origin)
{
    var player = this.createRect(origin[0] * this.size_x + this.size_x * 0.2,
        origin[1] * this.size_y + this.size_y * 0.2,
        this.size_x * 0.6, this.size_y * 0.6);
    player.classList.add("c" + this.endColor);
    player.wx = origin[0];
    player.wy = origin[1];
    this.svg.appendChild(player);

    return player;
};

MysteryGame.prototype.createObject = function (origin)
{
    var obj = this.createCircle(origin[0] * this.size_x + this.size_x * 0.5,
        origin[1] * this.size_y + this.size_y * 0.5,
        this.size_x * 0.3);
    obj.classList.add("c" + this.endColor);
    obj.wx = origin[0];
    obj.wy = origin[1];
    this.svg.appendChild(obj);

    return obj;
};

MysteryGame.prototype.showText = function (domText)
{
    domText.classList.remove("hide");
    setTimeout(function () { domText.classList.add("hide"); }, 1500);
};

MysteryGame.prototype.doAction = function (charCode)
{
    var action = charCode - '1'.charCodeAt(0);
	if (action >= 0 && action <= 5)
	{
		var actionName = this.actions[action];
		var dx = 0, dy = 0;
		if (actionName == "up")
		{
			dy = -1;
		}
		else if (actionName == "down")
		{
			dy = 1;
		}
		else if (actionName == "left")
		{
			dx = -1;
		}
		else if (actionName == "right")
		{
			dx = 1;
		}
		else if (actionName == "catch")
		{
			if (this.player.wx == this.obj.wx &&
				this.player.wy == this.obj.wy)
			{
                this.showText(this.goodtext);
				this.catched = true;
			}
		}
		else if (actionName == "release")
		{
			if (this.catched)
			{
				this.catched = false;
				if (this.map[this.obj.wy][this.obj.wx].color == this.endColor)
				{
					this.createText(this.w / 2, this.h / 2, "You Win :)");
				}
                else
                {
                    this.showText(this.badtext);
                }
			}
		}

		// If not a wall.
		if (this.player.wy + dy >= 0 && this.player.wx + dx < this.tiles_x &&
			this.player.wx + dx >= 0 && this.player.wy + dy < this.tiles_y &&
			this.map[this.player.wy + dy][this.player.wx + dx].color > 0)
		{
            // Move player.
			this.player.wx += dx;
			this.player.wy += dy;
			this.player.setAttribute('x',
                    this.player.wx * this.size_x + this.size_x * 0.2);
			this.player.setAttribute('y',
                    this.player.wy * this.size_y + this.size_y * 0.2);

            // Move circle if catched.
			if (this.catched)
			{
				this.obj.wx += dx;
				this.obj.wy += dy;
				this.obj.setAttribute('cx',
                        this.obj.wx * this.size_x + this.size_x * 0.5);
				this.obj.setAttribute('cy',
                        this.obj.wy * this.size_y + this.size_y * 0.5);

                if (this.map[this.obj.wy][this.obj.wx].color == this.endColor
                    && !this.firstTimeIn)
                {
                    this.firstTimeIn = true;
                    this.showText(this.goodtext);
                }
			}
		}
	}
};
<commit_msg>Catching reward only if the object is not catched.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Guiferviz
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * MysteryGame class.
 *
 * Creates a game similar to the one showed in the Reinforcement Learning
 * MOOC (Udacity) by Georgia Tech.
 * The games appears in "Lesson 2 - Reinforcement Learning Basics".
 *
 * Container: DOM element where the game will be inyected. The game will
 *          adapt to the container size.
 * Map: bidimensional array with numbers from 0 to 5.
 *          0 - Wall
 *          1 - Empty cell
 *          2,3,4,5 - Red, Green, Blue, Yellow cell
 * Player: Array with the x and y origin coordinates of the player.
 * Obj: Array with the x and y circle position.
 * Actions: Array with the actions in the order you want.
 *          The first element corresponds with the key number 1 and so on.
 *          ["up", "down", "left", "right", "catch", "release"]
 *          If not array is given random actions will be choosen.
 */
MysteryGame = function (container, map, player, circle, actions)
{
    this.w = container.offsetWidth;
    this.h = container.offsetHeight;
    if (!this.h)
    {
        this.h = this.w;
        container.style.height = this.h + "px";
    }
    this.tiles_x = map[0].length;
    this.tiles_y = map.length;
    this.size_x = this.w / this.tiles_x;
    this.size_y = this.h / this.tiles_y;
    this.endColor = Math.floor(Math.random() * 4 + 2);
    this.svg = this.createSvg(this.w, this.h);
    this.catched = false;
    this.actions = actions || ["up", "down", "left", "right",
    		"catch", "release"];
    if (!actions)
        this.shuffle(this.actions);

    this.map = this.createMap(map);
    this.player = this.createPlayer(player);
    this.obj = this.createObject(circle);
    this.goodtext = this.createText(this.w / 2, this.h / 2, "+1");
    this.goodtext.classList.add("hide");
    this.badtext = this.createText(this.w / 2, this.h / 2, "-1");
    this.badtext.classList.add("hide");
    this.badtext.classList.add("bad");

    container.innerHTML = "";  // Deletes all in container
    container.appendChild(this.svg);

    var this_ = this;
    window.addEventListener("keypress", function(e)
    {
        this_.doAction(e.charCode);
    });
};

MysteryGame.SVG_URL = "http://www.w3.org/2000/svg";

MysteryGame.prototype.shuffle = function (o)
{
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

MysteryGame.prototype.createSvg = function (w, h)
{
    var svg = document.createElementNS(MysteryGame.SVG_URL, "svg");
    svg.setAttribute('width', w);
    svg.setAttribute('height', h);
    svg.classList.add("mystery");

    return svg;
};

MysteryGame.prototype.createRect = function (x, y, w, h)
{
    var rect = document.createElementNS(MysteryGame.SVG_URL, 'rect');
    rect.setAttribute('x', x);
    rect.setAttribute('y', y);
    rect.setAttribute('width', w);
    rect.setAttribute('height', h);

    return rect;
};

MysteryGame.prototype.createCircle = function (x, y, r)
{
    var circle = document.createElementNS(MysteryGame.SVG_URL, 'circle');
    circle.setAttribute('cx', x);
    circle.setAttribute('cy', y);
    circle.setAttribute('r', r);

    return circle;
};

MysteryGame.prototype.createMap = function (colors)
{
    var map = [];
    for (var i = 0; i < this.tiles_y; ++i)
    {
    	var row = [];
        for (var j = 0; j < this.tiles_x; ++j)
        {
            var rect = this.createRect(j * this.size_x, i * this.size_y,
                this.size_x, this.size_y);
            rect.classList.add("c" + colors[i][j]);
            rect.color = colors[i][j];
            row.push(rect);
            this.svg.appendChild(rect);
        }
        map.push(row);
    }

    return map;
};

MysteryGame.prototype.createText = function (x, y, txt)
{
    var text = document.createElementNS(MysteryGame.SVG_URL, 'text');
    text.setAttribute('x', x);
    text.setAttribute('y', y);
    text.innerHTML = txt;
    this.svg.appendChild(text);

    return text;
};

MysteryGame.prototype.createPlayer = function (origin)
{
    var player = this.createRect(origin[0] * this.size_x + this.size_x * 0.2,
        origin[1] * this.size_y + this.size_y * 0.2,
        this.size_x * 0.6, this.size_y * 0.6);
    player.classList.add("c" + this.endColor);
    player.wx = origin[0];
    player.wy = origin[1];
    this.svg.appendChild(player);

    return player;
};

MysteryGame.prototype.createObject = function (origin)
{
    var obj = this.createCircle(origin[0] * this.size_x + this.size_x * 0.5,
        origin[1] * this.size_y + this.size_y * 0.5,
        this.size_x * 0.3);
    obj.classList.add("c" + this.endColor);
    obj.wx = origin[0];
    obj.wy = origin[1];
    this.svg.appendChild(obj);

    return obj;
};

MysteryGame.prototype.showText = function (domText)
{
    domText.classList.remove("hide");
    setTimeout(function () { domText.classList.add("hide"); }, 1500);
};

MysteryGame.prototype.doAction = function (charCode)
{
    var action = charCode - '1'.charCodeAt(0);
	if (action >= 0 && action <= 5)
	{
		var actionName = this.actions[action];
		var dx = 0, dy = 0;
		if (actionName == "up")
		{
			dy = -1;
		}
		else if (actionName == "down")
		{
			dy = 1;
		}
		else if (actionName == "left")
		{
			dx = -1;
		}
		else if (actionName == "right")
		{
			dx = 1;
		}
		else if (actionName == "catch")
		{
			if (this.player.wx == this.obj.wx &&
				this.player.wy == this.obj.wy &&
                !this.catched)
			{
                this.showText(this.goodtext);
				this.catched = true;
			}
		}
		else if (actionName == "release")
		{
			if (this.catched)
			{
				this.catched = false;
				if (this.map[this.obj.wy][this.obj.wx].color == this.endColor)
				{
					this.createText(this.w / 2, this.h / 2, "You Win :)");
				}
                else
                {
                    this.showText(this.badtext);
                }
			}
		}

		// If not a wall.
		if (this.player.wy + dy >= 0 && this.player.wx + dx < this.tiles_x &&
			this.player.wx + dx >= 0 && this.player.wy + dy < this.tiles_y &&
			this.map[this.player.wy + dy][this.player.wx + dx].color > 0)
		{
            // Move player.
			this.player.wx += dx;
			this.player.wy += dy;
			this.player.setAttribute('x',
                    this.player.wx * this.size_x + this.size_x * 0.2);
			this.player.setAttribute('y',
                    this.player.wy * this.size_y + this.size_y * 0.2);

            // Move circle if catched.
			if (this.catched)
			{
				this.obj.wx += dx;
				this.obj.wy += dy;
				this.obj.setAttribute('cx',
                        this.obj.wx * this.size_x + this.size_x * 0.5);
				this.obj.setAttribute('cy',
                        this.obj.wy * this.size_y + this.size_y * 0.5);

                if (this.map[this.obj.wy][this.obj.wx].color == this.endColor
                    && !this.firstTimeIn)
                {
                    this.firstTimeIn = true;
                    this.showText(this.goodtext);
                }
			}
		}
	}
};
<|endoftext|>


<commit_before>var negateHostsByCIDR = function () {
    // Generate a list of hostname[string_addr] targets which do not exist in CIDR range
    //
    // Created by: Matt Burch
    // Usage: negateHostsByCIDR("x.x.x.x/x") or negateHostsByCIDR("x.x.x.x/x","y.y.y.y/y");
    //
    var hostTargets = [];
    var nets = Array.prototype.slice.call(arguments, 0);
    var hosts = Hosts.find({
        project_id: Session.get('projectId')
    }).fetch();
    var hostip = {};

    function dec2Bin(octet, cidr) {
        var pad = '00000000';
        var bin = parseInt(octet[0], 10).toString(2);
        bincidr = (bin.length >= pad.length ? bin : pad.slice(0, pad.length - bin.length) + bin);

        for (i = 1; i <= octet.length; i++) {
            bin = parseInt(octet[i], 10).toString(2);
            bincidr += (bin.length >= pad.length ? bin : pad.slice(0, pad.length - bin.length) + bin);
        }

        return bincidr.slice(0, parseInt(cidr, 10));
    }

    hosts.forEach(function (host) {
        var ip = host.string_addr.split(".");
        hostip[dec2Bin(ip, 32)] = host.string_addr;
    });

    nets.forEach(function (cidr) {
        cidr = cidr.split("/");
        var net = cidr[0].split(".");
        var netbin = dec2Bin(net, cidr[1]);

        for (var key in hostip) {
            if ((key.slice(0, parseInt(cidr[1], 10))) == netbin) {
                delete hostip[key];
            }
        }
    });

    for (var key in hostip) {
        console.log(hostip[key]);
    }
}<commit_msg>remove unused variable and add declaration<commit_after>var negateHostsByCIDR = function () {
    // Generate a list of hostname[string_addr] targets which do not exist in CIDR range
    //
    // Created by: Matt Burch
    // Usage: negateHostsByCIDR('x.x.x.x/x') or negateHostsByCIDR('x.x.x.x/x','y.y.y.y/y');
    //
    var nets = Array.prototype.slice.call(arguments, 0);
    var hosts = Hosts.find({
        project_id: Session.get('projectId')
    }).fetch();
    var hostip = {};

    function dec2Bin(octet, cidr) {
        var pad = '00000000';
        var bin = parseInt(octet[0], 10).toString(2);
        var bincidr = (bin.length >= pad.length ? bin : pad.slice(0, pad.length - bin.length) + bin);

        for (i = 1; i <= octet.length; i++) {
            bin = parseInt(octet[i], 10).toString(2);
            bincidr += (bin.length >= pad.length ? bin : pad.slice(0, pad.length - bin.length) + bin);
        }

        return bincidr.slice(0, parseInt(cidr, 10));
    }

    hosts.forEach(function (host) {
        var ip = host.string_addr.split('.');
        hostip[dec2Bin(ip, 32)] = host.string_addr;
    });

    nets.forEach(function (cidr) {
        cidr = cidr.split('/');
        var net = cidr[0].split('.');
        var netbin = dec2Bin(net, cidr[1]);

        for (var key in hostip) {
            if ((key.slice(0, parseInt(cidr[1], 10))) == netbin) {
                delete hostip[key];
            }
        }
    });

    for (var key in hostip) {
        console.log(hostip[key]);
    }
};<|endoftext|>


<commit_before>var math = require('../math'),
    utils = require('../utils'),
    DisplayObjectContainer = require('./DisplayObjectContainer'),
    InteractionManager = require('../interaction/InteractionManager');

/**
 * A Stage represents the root of the display tree. Everything connected to the stage is rendered, but
 * the stage itself cannot be transformed. If you want to transform everything within a stage use a single
 * DOC as a child of the stage and transform that one.
 *
 * Creating a stage is a mandatory process when you use Pixi, which is as simple as this:
 *
 * ```js
 * var stage = new Stage(0xFFFFFF);
 * ```
 *
 * Where the parameter given is the background colour of the stage. You will use this stage instance to
 * add your sprites to it and therefore to the renderer. Here is how to add a sprite to the stage:
 *
 * ```js
 * stage.addChild(sprite);
 * ```
 *
 * @class
 * @extends DisplayObjectContainer
 * @namespace PIXI
 * @param backgroundColor {number} the background color of the stage, e.g.: 0xFFFFFF for white
 */
function Stage(backgroundColor) {
    DisplayObjectContainer.call( this );

    /**
     * [read-only] Current transform of the object based on world (parent) factors
     *
     * @member {Matrix}
     * @readonly
     * @private
     */
    this.worldTransform = new math.Matrix();

    /**
     * Whether or not the stage is interactive
     *
     * @member {boolean}
     */
    this.interactive = true;

    /**
     * The interaction manage for this stage, manages all interactive activity on the stage
     *
     * @member {InteractionManager}
     */
    this.interactionManager = new InteractionManager(this);

    /**
     * Whether the stage is dirty and needs to have interactions updated
     *
     * @member {boolean}
     * @private
     */
    this.dirty = true;

    //the stage is its own stage
    this.stage = this;

    //optimize hit detection a bit
    this.stage.hitArea = new math.Rectangle(0, 0, 100000, 100000);

    this.setBackgroundColor(backgroundColor);
};

// constructor
Stage.prototype = Object.create(DisplayObjectContainer.prototype);
Stage.prototype.constructor = Stage;

/**
 * Sets another DOM element which can receive mouse/touch interactions instead of the default Canvas element.
 * This is useful for when you have other DOM elements on top of the Canvas element.
 *
 * @param domElement {DOMElement} This new domElement which will receive mouse/touch events
 */
Stage.prototype.setInteractionDelegate = function (domElement) {
    this.interactionManager.setTargetDomElement(domElement);
};

/*
 * Updates the object transform for rendering
 *
 * @method updateTransform
 * @private
 */
Stage.prototype.updateTransform = function () {
    this.worldAlpha = 1;

    for (var i = 0, j = this.children.length; i < j; ++i) {
        this.children[i].updateTransform();
    }

    if (this.dirty) {
        this.dirty = false;

        // update interactive!
        this.interactionManager.dirty = true;
    }

    if (this.interactive) {
        this.interactionManager.update();
    }
};

/**
 * Sets the background color for the stage
 *
 * @param backgroundColor {number} The color of the background, e.g.: 0xFFFFFF for white
 */
Stage.prototype.setBackgroundColor = function (backgroundColor) {
    this.backgroundColor = backgroundColor || 0x000000;
    this.backgroundColorSplit = utils.hex2rgb(this.backgroundColor);

    var hex = this.backgroundColor.toString(16);
    hex = '000000'.substr(0, 6 - hex.length) + hex;

    this.backgroundColorString = '#' + hex;
};

/**
 * This will return the point containing global coordinates of the mouse.
 *
 * @return {Point} A point containing the coordinates of the global InteractionData position.
 */
Stage.prototype.getMousePosition = function () {
    return this.interactionManager.mouse.global;
};
<commit_msg>fix some docs<commit_after>var math = require('../math'),
    utils = require('../utils'),
    DisplayObjectContainer = require('./DisplayObjectContainer'),
    InteractionManager = require('../interaction/InteractionManager');

/**
 * A Stage represents the root of the display tree. Everything connected to the stage is rendered, but
 * the stage itself cannot be transformed. If you want to transform everything within a stage use a single
 * DOC as a child of the stage and transform that one.
 *
 * Creating a stage is a mandatory process when you use Pixi, which is as simple as this:
 *
 * ```js
 * var stage = new Stage(0xFFFFFF);
 * ```
 *
 * Where the parameter given is the background colour of the stage. You will use this stage instance to
 * add your sprites to it and therefore to the renderer. Here is how to add a sprite to the stage:
 *
 * ```js
 * stage.addChild(sprite);
 * ```
 *
 * @class
 * @extends DisplayObjectContainer
 * @namespace PIXI
 * @param backgroundColor {number} the background color of the stage, e.g.: 0xFFFFFF for white
 */
function Stage(backgroundColor) {
    DisplayObjectContainer.call(this);

    /**
     * Current transform of the object based on world (parent) factors
     *
     * @member {Matrix}
     * @readonly
     * @private
     */
    this.worldTransform = new math.Matrix();

    /**
     * Whether or not the stage is interactive
     *
     * @member {boolean}
     */
    this.interactive = true;

    /**
     * The interaction manage for this stage, manages all interactive activity on the stage
     *
     * @member {InteractionManager}
     */
    this.interactionManager = new InteractionManager(this);

    /**
     * Whether the stage is dirty and needs to have interactions updated
     *
     * @member {boolean}
     * @private
     */
    this.dirty = true;

    //the stage is its own stage
    this.stage = this;

    //optimize hit detection a bit
    this.stage.hitArea = new math.Rectangle(0, 0, 100000, 100000);

    this.setBackgroundColor(backgroundColor);
};

// constructor
Stage.prototype = Object.create(DisplayObjectContainer.prototype);
Stage.prototype.constructor = Stage;

/**
 * Sets another DOM element which can receive mouse/touch interactions instead of the default Canvas element.
 * This is useful for when you have other DOM elements on top of the Canvas element.
 *
 * @param domElement {DOMElement} This new domElement which will receive mouse/touch events
 */
Stage.prototype.setInteractionDelegate = function (domElement) {
    this.interactionManager.setTargetDomElement(domElement);
};

/*
 * Updates the object transform for rendering
 *
 * @method updateTransform
 * @private
 */
Stage.prototype.updateTransform = function () {
    this.worldAlpha = 1;

    for (var i = 0, j = this.children.length; i < j; ++i) {
        this.children[i].updateTransform();
    }

    if (this.dirty) {
        this.dirty = false;

        // update interactive!
        this.interactionManager.dirty = true;
    }

    if (this.interactive) {
        this.interactionManager.update();
    }
};

/**
 * Sets the background color for the stage
 *
 * @param backgroundColor {number} The color of the background, e.g.: 0xFFFFFF for white
 */
Stage.prototype.setBackgroundColor = function (backgroundColor) {
    this.backgroundColor = backgroundColor || 0x000000;
    this.backgroundColorSplit = utils.hex2rgb(this.backgroundColor);

    var hex = this.backgroundColor.toString(16);
    hex = '000000'.substr(0, 6 - hex.length) + hex;

    this.backgroundColorString = '#' + hex;
};

/**
 * This will return the point containing global coordinates of the mouse.
 *
 * @return {Point} A point containing the coordinates of the global InteractionData position.
 */
Stage.prototype.getMousePosition = function () {
    return this.interactionManager.mouse.global;
};
<|endoftext|>


<commit_before>/*
 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
 */

L.Draggable = L.Class.extend({
	includes: L.Mixin.Events,

	statics: {
		START: L.Browser.touch ? 'touchstart' : 'mousedown',
		END: L.Browser.touch ? 'touchend' : 'mouseup',
		MOVE: L.Browser.touch ? 'touchmove' : 'mousemove',
		TAP_TOLERANCE: 15
	},

	initialize: function (element, dragStartTarget) {
		this._element = element;
		this._dragStartTarget = dragStartTarget || element;
	},

	enable: function () {
		if (this._enabled) {
			return;
		}
		L.DomEvent.addListener(this._dragStartTarget, L.Draggable.START, this._onDown, this);
		this._enabled = true;
	},

	disable: function () {
		if (!this._enabled) {
			return;
		}
		L.DomEvent.removeListener(this._dragStartTarget, L.Draggable.START, this._onDown);
		this._enabled = false;
		this._moved = false;
	},

	_onDown: function (e) {
		if ((!L.Browser.touch && e.shiftKey) || ((e.which !== 1) && (e.button !== 1) && !e.touches)) {
			return;
		}

		this._simulateClick = true;

		if (e.touches && e.touches.length > 1) {
			this._simulateClick = false;
			return;
		}

		var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
			el = first.target;

		L.DomEvent.preventDefault(e);

		if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
			el.className += ' leaflet-active';
		}

		this._moved = false;
		if (this._moving) {
			return;
		}

		if (!L.Browser.touch) {
			L.DomUtil.disableTextSelection();
			this._setMovingCursor();
		}

		this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
		this._startPoint = new L.Point(first.clientX, first.clientY);

		L.DomEvent.addListener(document, L.Draggable.MOVE, this._onMove, this);
		L.DomEvent.addListener(document, L.Draggable.END, this._onUp, this);
	},

	_onMove: function (e) {
		if (e.touches && e.touches.length > 1) {
			return;
		}

		L.DomEvent.preventDefault(e);

		var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e);

		if (!this._moved) {
			this.fire('dragstart');
			this._moved = true;
		}
		this._moving = true;

		var newPoint = new L.Point(first.clientX, first.clientY);
		this._newPos = this._startPos.add(newPoint).subtract(this._startPoint);

		L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
	},

	_updatePosition: function () {
		this.fire('predrag');
		L.DomUtil.setPosition(this._element, this._newPos);
		this.fire('drag');
	},

	_onUp: function (e) {
		if (this._simulateClick && e.changedTouches) {
			var first = e.changedTouches[0],
				el = first.target,
				dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;

			if (el.tagName.toLowerCase() === 'a') {
				el.className = el.className.replace(' leaflet-active', '');
			}

			if (dist < L.Draggable.TAP_TOLERANCE) {
				this._simulateEvent('click', first);
			}
		}

		if (!L.Browser.touch) {
			L.DomUtil.enableTextSelection();
			this._restoreCursor();
		}

		L.DomEvent.removeListener(document, L.Draggable.MOVE, this._onMove);
		L.DomEvent.removeListener(document, L.Draggable.END, this._onUp);

		if (this._moved) {
			this.fire('dragend');
		}
		this._moving = false;
	},

	_setMovingCursor: function () {
		document.body.className += ' leaflet-dragging';
	},

	_restoreCursor: function () {
		document.body.className = document.body.className.replace(/ leaflet-dragging/g, '');
	},

	_simulateEvent: function (type, e) {
		var simulatedEvent = document.createEvent('MouseEvents');

		simulatedEvent.initMouseEvent(
				type, true, true, window, 1,
				e.screenX, e.screenY,
				e.clientX, e.clientY,
				false, false, false, false, 0, null);

		e.target.dispatchEvent(simulatedEvent);
	}
});
<commit_msg>make panning even more smooth<commit_after>/*
 * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
 */

L.Draggable = L.Class.extend({
	includes: L.Mixin.Events,

	statics: {
		START: L.Browser.touch ? 'touchstart' : 'mousedown',
		END: L.Browser.touch ? 'touchend' : 'mouseup',
		MOVE: L.Browser.touch ? 'touchmove' : 'mousemove',
		TAP_TOLERANCE: 15
	},

	initialize: function (element, dragStartTarget) {
		this._element = element;
		this._dragStartTarget = dragStartTarget || element;
	},

	enable: function () {
		if (this._enabled) {
			return;
		}
		L.DomEvent.addListener(this._dragStartTarget, L.Draggable.START, this._onDown, this);
		this._enabled = true;
	},

	disable: function () {
		if (!this._enabled) {
			return;
		}
		L.DomEvent.removeListener(this._dragStartTarget, L.Draggable.START, this._onDown);
		this._enabled = false;
		this._moved = false;
	},

	_onDown: function (e) {
		if ((!L.Browser.touch && e.shiftKey) || ((e.which !== 1) && (e.button !== 1) && !e.touches)) {
			return;
		}

		this._simulateClick = true;

		if (e.touches && e.touches.length > 1) {
			this._simulateClick = false;
			return;
		}

		var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
			el = first.target;

		L.DomEvent.preventDefault(e);

		if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
			el.className += ' leaflet-active';
		}

		this._moved = false;
		if (this._moving) {
			return;
		}

		if (!L.Browser.touch) {
			L.DomUtil.disableTextSelection();
			this._setMovingCursor();
		}

		this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
		this._startPoint = new L.Point(first.clientX, first.clientY);

		L.DomEvent.addListener(document, L.Draggable.MOVE, this._onMove, this);
		L.DomEvent.addListener(document, L.Draggable.END, this._onUp, this);
	},

	_onMove: function (e) {
		if (e.touches && e.touches.length > 1) {
			return;
		}

		L.DomEvent.preventDefault(e);

		var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e);

		if (!this._moved) {
			this.fire('dragstart');
			this._moved = true;
		}
		this._moving = true;

		var newPoint = new L.Point(first.clientX, first.clientY);
		this._newPos = this._startPos.add(newPoint).subtract(this._startPoint);

		L.Util.cancelAnimFrame(this._animRequest);
		this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
	},

	_updatePosition: function () {
		this.fire('predrag');
		L.DomUtil.setPosition(this._element, this._newPos);
		this.fire('drag');
	},

	_onUp: function (e) {
		if (this._simulateClick && e.changedTouches) {
			var first = e.changedTouches[0],
				el = first.target,
				dist = (this._newPos && this._newPos.distanceTo(this._startPos)) || 0;

			if (el.tagName.toLowerCase() === 'a') {
				el.className = el.className.replace(' leaflet-active', '');
			}

			if (dist < L.Draggable.TAP_TOLERANCE) {
				this._simulateEvent('click', first);
			}
		}

		if (!L.Browser.touch) {
			L.DomUtil.enableTextSelection();
			this._restoreCursor();
		}

		L.DomEvent.removeListener(document, L.Draggable.MOVE, this._onMove);
		L.DomEvent.removeListener(document, L.Draggable.END, this._onUp);

		if (this._moved) {
			this.fire('dragend');
		}
		this._moving = false;
	},

	_setMovingCursor: function () {
		document.body.className += ' leaflet-dragging';
	},

	_restoreCursor: function () {
		document.body.className = document.body.className.replace(/ leaflet-dragging/g, '');
	},

	_simulateEvent: function (type, e) {
		var simulatedEvent = document.createEvent('MouseEvents');

		simulatedEvent.initMouseEvent(
				type, true, true, window, 1,
				e.screenX, e.screenY,
				e.clientX, e.clientY,
				false, false, false, false, 0, null);

		e.target.dispatchEvent(simulatedEvent);
	}
});
<|endoftext|>


<commit_before>const uuid = require("uuid");
const ENTITY_FILENAME = "entity.json";

const entity = (fileAdapter, serializer) => {

  const validateName = (resourceName) => {
    if(resourceName !== null && resourceName !== undefined && fileAdapter.validate(resourceName)) {
      return Promise.resolve();
    }
    else {
      return Promise.reject(Error(`Invalid identifier: ${resourceName}`));
    }
  };

  return {
    read: () => {
      return fileAdapter.readFile(ENTITY_FILENAME)
        .then((content) => {
          return serializer.deserialize(content);
        });
    },
    write: (content) => {
      const serializedContent = serializer.serialize(content);
      return fileAdapter.writeFile(ENTITY_FILENAME, serializedContent);
    },
    listResources: () => {
      return fileAdapter.listDirectories();
    },
    listResourceEntities: (resourceName) => {
      return validateName(resourceName)
        .then(() => fileAdapter.getDirectoryProvider(resourceName))
        .then((subfolderProvider) => subfolderProvider.listDirectories());
    },
    createResourceEntity: (resourceName, id) => {
      if (!id) {
        id = uuid() + "-" + uuid();
      }
      return validateName(resourceName)
        .then(() => validateName(id))
        .then(() => fileAdapter.createDirectory(resourceName))
        .then(() => fileAdapter.getDirectoryProvider(resourceName))
        .then((subFolderProvider) => subFolderProvider.createDirectory(id))
        .then(() => id);
    },
    getResourceEntity: (resourceName, id) => {
      return validateName(resourceName)
        .then(() => validateName(id))
        .then(() => fileAdapter.getDirectoryProvider(resourceName))
        .then((resourceFsProvider) => resourceFsProvider.getDirectoryProvider(id))
        .then((entityFsProvider) => entity(entityFsProvider, serializer));
    }
  };
};

module.exports = entity;<commit_msg>Renamed read to load and also validating resources and ids<commit_after>const uuid = require("uuid");
const ENTITY_FILENAME = "entity.json";

const entity = (fileAdapter, serializer) => {

  const validateName = (resourceName) => {
    if(resourceName !== null && resourceName !== undefined && fileAdapter.validate(resourceName)) {
      return Promise.resolve();
    }
    else {
      return Promise.reject(Error(`Invalid identifier: ${resourceName}`));
    }
  };

  return {
    load: () => {
      return fileAdapter.readFile(ENTITY_FILENAME)
        .then((content) => {
          return serializer.deserialize(content);
        });
    },
    write: (content) => {
      const serializedContent = serializer.serialize(content);
      return fileAdapter.writeFile(ENTITY_FILENAME, serializedContent);
    },
    listResources: () => {
      return fileAdapter.listDirectories();
    },
    listResourceEntities: (resourceName) => {
      return validateName(resourceName)
        .then(() => fileAdapter.getDirectoryProvider(resourceName))
        .then((subfolderProvider) => subfolderProvider.listDirectories());
    },
    createResourceEntity: (resourceName, id) => {
      if (!id) {
        id = uuid() + "-" + uuid();
      }
      return validateName(resourceName)
        .then(() => validateName(id))
        .then(() => fileAdapter.createDirectory(resourceName))
        .then(() => fileAdapter.getDirectoryProvider(resourceName))
        .then((subFolderProvider) => subFolderProvider.createDirectory(id))
        .then(() => id);
    },
    getResourceEntity: (resourceName, id) => {
      return validateName(resourceName)
        .then(() => validateName(id))
        .then(() => fileAdapter.getDirectoryProvider(resourceName))
        .then((resourceFsProvider) => resourceFsProvider.getDirectoryProvider(id))
        .then((entityFsProvider) => entity(entityFsProvider, serializer));
    }
  };
};

module.exports = entity;<|endoftext|>


<commit_before>import optionsStorage from '../options';
import ContextExtractor from '../ContextExtractor';

const IFRAME_ID = 'leoTranslateIFrame';

let mouseX = 0;
let mouseY = 0;
let options = {};

// Fetch options from local storage
optionsStorage.getAllOptions().then(data => options = data);

document.body.addEventListener('mousedown', e => {
  if (e.button === 0) {
    hideIFrame();
  }

  if (e.button === 2 || e.button === 0) {
    mouseX = e.pageX;
    mouseY = e.pageY;
  }
});

document.body.addEventListener('dblclick', e => {
  if (options['double-click']) {
    // If there's a key constraint.
    if (options['double-click-ctrl'] || options['double-click-alt']) {

      // If there's no a condition that has passed a check.
      if (! (isAltClick() || isCtrlClick())) {
        return;
      }
    }

    callTranslatePopup();

    function isAltClick () {
      return options['double-click-alt'] && e.altKey;
    }

    function isCtrlClick () {
      return options['double-click-ctrl'] && e.ctrlKey;
    }
  }
});

// Listen for messages from the iFrame
window.addEventListener('message', e => {
  if (chrome.extension.getURL('') === e.origin+'/') {
    const iFrame = getIFrame();

    if (e.data.id === 'vue-popup-resized') {
      iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
      iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
    } else if (e.data.id === 'vue-popup-get-data') {
      sendDataToIFrame(iFrame);
    } else if (e.data.id === 'vue-translate-close') {
      hideIFrame();
    }
  }
});

chrome.runtime.onMessage.addListener(message => {
  if (message.id === 'context-menu-clicked') {
    callTranslatePopup();
  }
});

function callTranslatePopup () {
  const maxLength = ContextExtractor.LIMIT * 2;

  if (getSelection().toString().length > maxLength) {
    chrome.runtime.sendMessage({
      id: 'show-notification',
      text: 'The selection is too long! It must be less than '+maxLength+' characters.'
    });
  } else {
    const iFrame = getIFrame();

    showIFrame(iFrame);
    sendDataToIFrame(iFrame);
  }
}

function getIFrame () {
  let container = document.getElementById(IFRAME_ID);

  if (container === null) {
    container = document.createElement('iframe');

    const defaultStyles = {
      position: 'absolute',
      display: 'none',
      border: 'none',
      zIndex: 10000,
      boxShadow: '0 0 1px 0'
    };

    container.id = IFRAME_ID;

    for (const styleName in defaultStyles) {
      container.style[styleName] = defaultStyles[styleName];
    }

    document.body.appendChild(container);

    container.src = chrome.extension.getURL('/templates/context-popup.html');
  }

  return container;
}

function showIFrame (iFrame = null) {
  const container = iFrame || getIFrame();

  container.style.display = 'block';
  container.style.top = mouseY+'px';
  container.style.left = mouseX+'px';
}

function hideIFrame() {
  const container = document.getElementById(IFRAME_ID);

  if (container !== null) {
    container.style.display = 'none';
  }
}

function sendDataToIFrame (iFrame) {
  const selection = getSelection();

  const message = {
    id: 'content-data',
    url: document.URL,
    text: selection.toString(),
    title: document.title,
    context: ''
  };

  if (options['context-capturing']) {
    message['context'] = new ContextExtractor(selection).getContext().getSentence();
  }

  iFrame.contentWindow.postMessage(message, chrome.extension.getURL(''));
}
<commit_msg>fix getting out of the window boundaries.<commit_after>import optionsStorage from '../options';
import ContextExtractor from '../ContextExtractor';

const IFRAME_WIDTH = 250;
const IFRAME_ID = 'leoTranslateIFrame';

let mouseX = 0;
let mouseY = 0;
let options = {};

// Fetch options from local storage
optionsStorage.getAllOptions().then(data => options = data);

document.body.addEventListener('mousedown', e => {
  if (e.button === 0) {
    hideIFrame();
  }

  if (e.button === 2 || e.button === 0) {
    mouseX = e.pageX + IFRAME_WIDTH > window.document.body.clientWidth ? window.document.body.clientWidth - IFRAME_WIDTH : e.pageX;
    mouseY = e.pageY;
  }
});

document.body.addEventListener('dblclick', e => {
  if (options['double-click']) {
    // If there's a key constraint.
    if (options['double-click-ctrl'] || options['double-click-alt']) {

      // If there's no a condition that has passed a check.
      if (! (isAltClick() || isCtrlClick())) {
        return;
      }
    }

    callTranslatePopup();

    function isAltClick () {
      return options['double-click-alt'] && e.altKey;
    }

    function isCtrlClick () {
      return options['double-click-ctrl'] && e.ctrlKey;
    }
  }
});

// Listen for messages from the iFrame
window.addEventListener('message', e => {
  if (chrome.extension.getURL('') === e.origin+'/') {
    const iFrame = getIFrame();

    if (e.data.id === 'vue-popup-resized') {
      iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
      iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
    } else if (e.data.id === 'vue-popup-get-data') {
      sendDataToIFrame(iFrame);
    } else if (e.data.id === 'vue-translate-close') {
      hideIFrame();
    }
  }
});

chrome.runtime.onMessage.addListener(message => {
  if (message.id === 'context-menu-clicked') {
    callTranslatePopup();
  }
});

function callTranslatePopup () {
  const maxLength = ContextExtractor.LIMIT * 2;

  if (getSelection().toString().length > maxLength) {
    chrome.runtime.sendMessage({
      id: 'show-notification',
      text: 'The selection is too long! It must be less than '+maxLength+' characters.'
    });
  } else {
    const iFrame = getIFrame();

    showIFrame(iFrame);
    sendDataToIFrame(iFrame);
  }
}

function getIFrame () {
  let container = document.getElementById(IFRAME_ID);

  if (container === null) {
    container = document.createElement('iframe');

    const defaultStyles = {
      position: 'absolute',
      display: 'none',
      border: 'none',
      zIndex: 10000,
      boxShadow: '0 0 1px 0',
      width: IFRAME_WIDTH
    };

    container.id = IFRAME_ID;

    for (const styleName in defaultStyles) {
      container.style[styleName] = defaultStyles[styleName];
    }

    document.body.appendChild(container);

    container.src = chrome.extension.getURL('/templates/context-popup.html');
  }

  return container;
}

function showIFrame (iFrame = null) {
  const container = iFrame || getIFrame();

  container.style.display = 'block';
  container.style.top = mouseY+'px';
  container.style.left = mouseX+'px';
}

function hideIFrame() {
  const container = document.getElementById(IFRAME_ID);

  if (container !== null) {
    container.style.display = 'none';
  }
}

function sendDataToIFrame (iFrame) {
  const selection = getSelection();

  const message = {
    id: 'content-data',
    url: document.URL,
    text: selection.toString(),
    title: document.title,
    context: ''
  };

  if (options['context-capturing']) {
    message['context'] = new ContextExtractor(selection).getContext().getSentence();
  }

  iFrame.contentWindow.postMessage(message, chrome.extension.getURL(''));
}
<|endoftext|>


<commit_before>
  var ns=$.fn.wipeImages,factory=ns.wipeFactory;

  //Diagonal Fade Animations
  function diagonals(){
    var opts={
      cols:8,rows:4
    },wipe;
    function _run(rev1,rev2){
      wipe.isGrouped=true;
      wipe.groups=wipe.groupDiagonally(opts.rows,opts.cols,rev1);
      if(rev2) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      diagTopLeft:function(el){
        wipe=new factory(el,opts);
        _run();
      },
      diagTopRight:function(el){
        wipe=new factory(el,opts);
        _run(true,true);
      },
      diagBottomRight:function(el){
        wipe=new factory(el,opts);
        _run(false,true);
      },
      diagBottomLeft:function(el){
        wipe=new factory(el,opts);
        _run(true,false);
      }
    };
  }

  //From Center Fade Animations
  function fromCenters(){
    var opts={
      cols:10,rows:1
    },wipe;
    function _run(rev){
      wipe.isGrouped=true;
      wipe.groups=wipe.groupCentrally(opts.rows,opts.cols);
      if(rev) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      fromCenter:function(el){
        wipe=new factory(el,opts);
        _run();
      },
      toCenter:function(el){
        opts.cols=9;
        wipe=new factory(el,opts);
        _run(true);
      }
    };
  }

  //pyramid animations
  function pyramids(){
    var opts={
      cols:19,rows:1,
      from:{
        height:"0px"
      }
    },wipe;
    function _run(rev){
      wipe.isGrouped=true;
      wipe.groups=wipe.groupCentrally(opts.rows,opts.cols);
      if(rev) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      pyramidInvertedCollapse:function(el){
        var endHeight=el.height();
        opts.to={height:endHeight + "px"};
        wipe=new factory(el,opts);
        _run();
      },
      pyramidCollapse:function(el){
        var endHeight=el.height();
        opts.to={height:endHeight + "px"};
        wipe=new factory(el,opts);
        _run(true);
      },
      pyramidInvertedGrow:function(el){
        var endHeight=el.height();
        opts=$.extend({
          from:{
            bottom:"0px",
            top:"auto"
          },
          to:{
            height:endHeight + "px"
          }
        },opts);
        wipe=new factory(el,opts);
        _run(true);
      },
      pyramidGrow:function(el){
        var endHeight=el.height();
        opts=$.extend({
          from:{
            bottom:"0px",
            top:"auto"
          },
          to:{
            height:endHeight + "px"
          }
        },opts);
        wipe=new factory(el,opts);
        _run();
      }
    };
  }

  //CSS3 animations - Experimental
  function css3s(){
    var opts={
      cols:4,rows:4,
      isCss3:true,
    },wipe;
    function _run(shfl,rev){
      if(rev) {wipe.groups.reverse();}
      if(shfl) {wipe.groups.shuffle();}
      wipe.run();
    }
    return{
      css3_ZoomIn:function(el){
        opts.from=$.extend({"opacity":0},ns.prefixize("transform","scale(0.1)"));
        opts.to=$.extend({"opacity":1},ns.prefixize("transform","scale(1)"));
        wipe=new factory(el,opts);
        _run();
      },
      css3_ZoomOut:function(el){
        opts.from=$.extend({"opacity":0},ns.prefixize("transform","scale(1.5)"));
        opts.to=$.extend({"opacity":1},ns.prefixize("transform","scale(1)"));
        wipe=new factory(el,opts);
        _run();
      },
      css3_rotate:function(el){
        opts.from=$.extend({"opacity":0},ns.prefixize("transform","rotate(90deg)"));
        opts.to=$.extend({"opacity":1},ns.prefixize("transform","rotate(0)"));
        opts.cols=6;opts.rows=6;
        wipe=new factory(el,opts);
        _run();
      }
    }
  }

  ns.wipes=$.extend(ns.wipes,pyramids(),fromCenters(),diagonals(),css3s());
<commit_msg>check if browser supports css3 transitions before exporting the animations<commit_after>
  var ns=$.fn.wipeImages,factory=ns.wipeFactory;

  //Diagonal Fade Animations
  function diagonals(){
    var opts={
      cols:8,rows:4
    },wipe;
    function _run(rev1,rev2){
      wipe.isGrouped=true;
      wipe.groups=wipe.groupDiagonally(opts.rows,opts.cols,rev1);
      if(rev2) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      diagTopLeft:function(el){
        wipe=new factory(el,opts);
        _run();
      },
      diagTopRight:function(el){
        wipe=new factory(el,opts);
        _run(true,true);
      },
      diagBottomRight:function(el){
        wipe=new factory(el,opts);
        _run(false,true);
      },
      diagBottomLeft:function(el){
        wipe=new factory(el,opts);
        _run(true,false);
      }
    };
  }

  //From Center Fade Animations
  function fromCenters(){
    var opts={
      cols:10,rows:1
    },wipe;
    function _run(rev){
      wipe.isGrouped=true;
      wipe.groups=wipe.groupCentrally(opts.rows,opts.cols);
      if(rev) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      fromCenter:function(el){
        wipe=new factory(el,opts);
        _run();
      },
      toCenter:function(el){
        opts.cols=9;
        wipe=new factory(el,opts);
        _run(true);
      }
    };
  }

  //pyramid animations
  function pyramids(){
    var opts={
      cols:19,rows:1,
      from:{
        height:"0px"
      }
    },wipe;
    function _run(rev){
      wipe.isGrouped=true;
      wipe.groups=wipe.groupCentrally(opts.rows,opts.cols);
      if(rev) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      pyramidInvertedCollapse:function(el){
        var endHeight=el.height();
        opts.to={height:endHeight + "px"};
        wipe=new factory(el,opts);
        _run();
      },
      pyramidCollapse:function(el){
        var endHeight=el.height();
        opts.to={height:endHeight + "px"};
        wipe=new factory(el,opts);
        _run(true);
      },
      pyramidInvertedGrow:function(el){
        var endHeight=el.height();
        opts=$.extend({
          from:{
            bottom:"0px",
            top:"auto"
          },
          to:{
            height:endHeight + "px"
          }
        },opts);
        wipe=new factory(el,opts);
        _run(true);
      },
      pyramidGrow:function(el){
        var endHeight=el.height();
        opts=$.extend({
          from:{
            bottom:"0px",
            top:"auto"
          },
          to:{
            height:endHeight + "px"
          }
        },opts);
        wipe=new factory(el,opts);
        _run();
      }
    };
  }

  //CSS3 animations - Experimental
  function css3s(){
    //check support first
    var thisBody = document.body || document.documentElement,
    thisStyle = thisBody.style,
    support=false;
    for (var i = ns.prefixes.length - 1; i >= 0; i--){
      var pf=ns.prefixes[i].charAt(0).toUpperCase() + ns.prefixes[i].substr(1);
      if(thisStyle[pf+(pf!=""?"T":"t")+"ransition"]!== undefined ){
        support=true;
        break;
      }
    };
    if(support) return {};
    //end support
    var opts={
      cols:4,rows:4,
      isCss3:true,
    },wipe;
    function _run(shfl,rev){
      if(rev) {wipe.groups.reverse();}
      if(shfl) {wipe.groups.shuffle();}
      wipe.run();
    }
    return{
      css3_ZoomIn:function(el){
        opts.from=$.extend({"opacity":0},ns.prefixize("transform","scale(0.1)"));
        opts.to=$.extend({"opacity":1},ns.prefixize("transform","scale(1)"));
        wipe=new factory(el,opts);
        _run();
      },
      css3_ZoomOut:function(el){
        opts.from=$.extend({"opacity":0},ns.prefixize("transform","scale(1.5)"));
        opts.to=$.extend({"opacity":1},ns.prefixize("transform","scale(1)"));
        wipe=new factory(el,opts);
        _run();
      },
      css3_rotate:function(el){
        opts.from=$.extend({"opacity":0},ns.prefixize("transform","rotate(90deg)"));
        opts.to=$.extend({"opacity":1},ns.prefixize("transform","rotate(0)"));
        opts.cols=6;opts.rows=6;
        wipe=new factory(el,opts);
        _run();
      }
    }
  }

  ns.wipes=$.extend(ns.wipes,pyramids(),fromCenters(),diagonals(),css3s());
<|endoftext|>


<commit_before>"use strict";

const fs        = require('fs');
const path      = require('path');
const _         = require('lodash');

const extractor = require('./extractor');
const utl       = require('../utl');

function getAllJSFilesFromDir (pDirName, pOptions) {
    return fs.readdirSync(pDirName)
        .filter(pFileInDir => utl.ignore(pFileInDir, pOptions.exclude))
        .reduce((pSum, pFileName) => {
            if (fs.statSync(path.join(pDirName, pFileName)).isDirectory()){
                return pSum.concat(getAllJSFilesFromDir(path.join(pDirName, pFileName), pOptions));
            }
            if (path.extname(pFileName) === ".js"){
                return pSum.concat(path.join(pDirName, pFileName));
            }
            return pSum;
        }, []);
}

function extractRecursive (pFileName, pOptions, pVisited) {
    pOptions = pOptions || {};
    pVisited = pVisited || new Set();
    pVisited.add(pFileName);

    let lRetval = [];
    const lDependencies = extractor(pFileName, pOptions);

    lRetval.push({
        source: pFileName,
        dependencies: lDependencies
    });

    lDependencies
        .filter(pDep => pDep.followable && !pVisited.has(pDep.resolved))
        .forEach(
            pDep => {
                if (!pVisited.has(pDep.resolved)){
                    lRetval = lRetval.concat(
                        extractRecursive(pDep.resolved, pOptions, pVisited)
                    );
                }
            }
        );
    return lRetval;
}

function extractRecursiveDir(pDirName, pOptions) {
    let lVisited = new Set();

    return _.spread(_.concat)(
        getAllJSFilesFromDir(pDirName, pOptions)
            .reduce((pDependencies, pFilename) => {
                if (!lVisited.has(pFilename)){
                    lVisited.add(pFilename);
                    return pDependencies.concat(
                        extractRecursive(pFilename, pOptions, lVisited)
                    );
                }
                return pDependencies;
            }, [])
    );
}

function isNotFollowable(pToDependency) {
    return !(pToDependency.followable);
}

function notInFromListAlready(pFromList) {
    return pToListItem =>
        !pFromList.some(pFromListItem => pFromListItem.source === pToListItem.resolved);
}

function toDependencyToSource(pToListItem) {
    return {
        source: pToListItem.resolved,
        followable: pToListItem.followable,
        coreModule: pToListItem.coreModule,
        couldNotResolve: pToListItem.couldNotResolve,
        dependencies: []
    };
}

function complete(pAll, pFromListItem) {
    return pAll
        .concat(pFromListItem)
        .concat(
            pFromListItem.dependencies
                .filter(isNotFollowable)
                .filter(notInFromListAlready(pAll))
                .map(toDependencyToSource)
        );
}

function extract(pDirOrFile, pOptions, pCallback) {
    let lRetvalToTransform = {};
    let lCallback = pCallback ? pCallback : pInput => pInput;

    if (fs.statSync(pDirOrFile).isDirectory()) {
        lRetvalToTransform = extractRecursiveDir(pDirOrFile, pOptions);
    } else {
        lRetvalToTransform = extractRecursive(pDirOrFile, pOptions);
    }
    return lCallback(lRetvalToTransform.reduce(complete, []));
}

module.exports = extract;
<commit_msg>:wrench: :nail_care: removes a superfluous condition<commit_after>"use strict";

const fs        = require('fs');
const path      = require('path');
const _         = require('lodash');

const extractor = require('./extractor');
const utl       = require('../utl');

function getAllJSFilesFromDir (pDirName, pOptions) {
    return fs.readdirSync(pDirName)
        .filter(pFileInDir => utl.ignore(pFileInDir, pOptions.exclude))
        .reduce((pSum, pFileName) => {
            if (fs.statSync(path.join(pDirName, pFileName)).isDirectory()){
                return pSum.concat(getAllJSFilesFromDir(path.join(pDirName, pFileName), pOptions));
            }
            if (path.extname(pFileName) === ".js"){
                return pSum.concat(path.join(pDirName, pFileName));
            }
            return pSum;
        }, []);
}

function extractRecursive (pFileName, pOptions, pVisited) {
    pOptions = pOptions || {};
    pVisited = pVisited || new Set();
    pVisited.add(pFileName);

    let lRetval = [];
    const lDependencies = extractor(pFileName, pOptions);

    lRetval.push({
        source: pFileName,
        dependencies: lDependencies
    });

    lDependencies
        .filter(pDep => pDep.followable)
        .forEach(
            pDep => {
                if (!pVisited.has(pDep.resolved)){
                    lRetval = lRetval.concat(
                        extractRecursive(pDep.resolved, pOptions, pVisited)
                    );
                }
            }
        );
    return lRetval;
}

function extractRecursiveDir(pDirName, pOptions) {
    let lVisited = new Set();

    return _.spread(_.concat)(
        getAllJSFilesFromDir(pDirName, pOptions)
            .reduce((pDependencies, pFilename) => {
                if (!lVisited.has(pFilename)){
                    lVisited.add(pFilename);
                    return pDependencies.concat(
                        extractRecursive(pFilename, pOptions, lVisited)
                    );
                }
                return pDependencies;
            }, [])
    );
}

function isNotFollowable(pToDependency) {
    return !(pToDependency.followable);
}

function notInFromListAlready(pFromList) {
    return pToListItem =>
        !pFromList.some(pFromListItem => pFromListItem.source === pToListItem.resolved);
}

function toDependencyToSource(pToListItem) {
    return {
        source          : pToListItem.resolved,
        followable      : pToListItem.followable,
        coreModule      : pToListItem.coreModule,
        couldNotResolve : pToListItem.couldNotResolve,
        dependencies    : []
    };
}

function complete(pAll, pFromListItem) {
    return pAll
        .concat(pFromListItem)
        .concat(
            pFromListItem.dependencies
                .filter(isNotFollowable)
                .filter(notInFromListAlready(pAll))
                .map(toDependencyToSource)
        );
}

function extract(pDirOrFile, pOptions, pCallback) {
    let lRetvalToTransform = {};
    let lCallback = pCallback ? pCallback : pInput => pInput;

    if (fs.statSync(pDirOrFile).isDirectory()) {
        lRetvalToTransform = extractRecursiveDir(pDirOrFile, pOptions);
    } else {
        lRetvalToTransform = extractRecursive(pDirOrFile, pOptions);
    }
    return lCallback(lRetvalToTransform.reduce(complete, []));
}

module.exports = extract;
<|endoftext|>


<commit_before>// AJAX CSRF setup. Source: http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax

jQuery.ajaxSetup({
    beforeSend: function(xhr, settings) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                    var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        function sameOrigin(url) {
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
        }
        function safeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
            var cookieName = $('#nexus-constants').data('csrfCookieName');
            xhr.setRequestHeader("X-CSRFToken", getCookie(cookieName));
        }
    }
});
<commit_msg>Fix bug in CSRF cookie extraction<commit_after>// AJAX CSRF setup. Source: http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax

jQuery.ajaxSetup({
    beforeSend: function(xhr, settings) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                    var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        function sameOrigin(url) {
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
        }
        function safeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
            var cookieName = $('#nexus-constants').attr('data-csrf-cookie-name');
            xhr.setRequestHeader("X-CSRFToken", getCookie(cookieName));
        }
    }
});
<|endoftext|>