<commit_before>'use strict';

/*global cytoscape*/

cytoscape('layout', 'fruchterman', FruchtermanLayout);

function FruchtermanLayout(options) {
    let defaults = {
        fit: true
    };

    for (let key of Object.keys(defaults)) {
        if (options.hasOwnProperty(key)) {
            this.options[key] = options[key];
        } else {
            this.options[key] = defaults[key];
        }
    }
}

FruchtermanLayout.prototype.run = function () {
    let options = this.options;
    let cy = options.cy;
    let width = cy.width();
    let height = cy.height();
    let graph = new Graph();
    let vertices = new Map();

    cy.nodes().forEach(function (node) {
        let v = new Vertex(Math.random() * width, Math.random() * height);

        vertices.set(node.id(), v);
        graph.insertVertex(v);
    });

    cy.edges().forEach(function (edge) {
        graph.insertEdge(vertices.get(edge.source().id()), vertices.get(edge.target().id()));
    });

    let layoutManager = new ForceDirectedVertexLayout(width, height, 100);

    layoutManager.layout(graph);

    cy.nodes().layoutPositions(this, options, function (i, node) {
        let vertex = vertices.get(node.id());

        return {
            x: vertex.x,
            y: vertex.y
        };
    });

    if (options.fit) {
        cy.fit();
    }

    return this;
};

function Graph() {
    this.vertices = [];
    this.vertexCount = 0;
}

Graph.prototype.insertEdge = function (vertex1, vertex2) {
    let e1 = new Edge(vertex2);
    let e2 = new Edge(vertex1);

    vertex1.edges.push(e1);
    vertex2.reverseEdges.push(e2);

    return e1;
};

Graph.prototype.removeEdge = function (vertex1, vertex2) {
    for (let i = vertex1.edges.length - 1; i >= 0; i--) {
        if (vertex1.edges[i].endVertex == vertex2) {
            vertex1.edges.splice(i, 1);
            break;
        }
    }

    for (let i = vertex2.reverseEdges.length - 1; i >= 0; i--) {
        if (vertex2.reverseEdges[i].endVertex == vertex1) {
            vertex2.reverseEdges.splice(i, 1);
            break;
        }
    }
};

Graph.prototype.insertVertex = function (vertex) {
    this.vertices.push(vertex);
    this.vertexCount++;
};

Graph.prototype.removeVertex = function (vertex) {
    for (let i = vertex.edges.length - 1; i >= 0; i--) {
        this.removeEdge(vertex, vertex.edges[i].endVertex);
    }

    for (let i = vertex.reverseEdges.length - 1; i >= 0; i--) {
        this.removeEdge(vertex.reverseEdges[i].endVertex, vertex);
    }

    for (let i = this.vertices.length - 1; i >= 0; i--) {
        if (this.vertices[i] == vertex) {
            this.vertices.splice(i, 1);
            break;
        }
    }

    this.vertexCount--;
};

function Vertex(x, y) {
    this.edges = [];
    this.reverseEdges = [];
    this.x = x;
    this.y = y;
    this.dx = 0;
    this.dy = 0;
    this.fixed = false;
}

function Edge(endVertex) {
    this.endVertex = endVertex;
}

function ForceDirectedVertexLayout(width, height, iterations) {
    this.width = width;
    this.height = height;
    this.iterations = iterations;
}

ForceDirectedVertexLayout.prototype.identifyComponents = function (graph) {
    let componentCenters = [];
    let components = [];

    // Depth first search
    function dfs(vertex) {
        let stack = [];
        let component = [];

        componentCenters.push(new Vertex(-1, -1));
        components.push(component);

        function visitVertex(v) {
            component.push(v);
            v.__dfsVisited = true;

            for (let e of v.edges) {
                stack.push(e.endVertex);
            }

            for (let e of v.reverseEdges) {
                stack.push(e.endVertex);
            }
        }

        visitVertex(vertex);
        while (stack.length > 0) {
            let u = stack.pop();

            if (!u.__dfsVisited) {
                visitVertex(u);
            }
        }
    }

    // Clear DFS visited flag
    for (let v of graph.vertices) {
        v.__dfsVisited = false;
    }

    // Iterate through all vertices starting DFS from each vertex
    // that hasn't been visited yet.
    for (let v of graph.vertices) {
        if (!v.__dfsVisited)
            dfs(v);
    }

    // Interconnect all center vertices
    if (componentCenters.length > 1) {
        for (let c of componentCenters) {
            graph.insertVertex(c);
        }
        for (let i in components) {
            for (let v of components[i]) {
                // Connect visited vertex to "central" component vertex
                graph.insertEdge(v, componentCenters[i]);
            }
        }

        for (let c1 of componentCenters) {
            for (let c2 of componentCenters) {
                if (c1 !== c2) {
                    graph.insertEdge(c1, c2);
                }
            }
        }
    }
};

ForceDirectedVertexLayout.prototype.layout = function (graph) {
    let area = this.width * this.height;
    let k = Math.sqrt(area / graph.vertexCount);

    let t = this.width / 10; // Temperature.
    let dt = t / (this.iterations + 1);

    let eps = 20; // Minimum vertex distance.
    let A = 1.5; // Fine tune attraction.
    let R = 0.5; // Fine tune repulsion.

    // Initiate component identification and virtual vertex creation
    // to prevent disconnected graph components from drifting too far apart
    this.identifyComponents(graph);

    // Run through some iterations
    for (let q = 0; q < this.iterations; q++) {

        /* Calculate repulsive forces. */
        for (let v of graph.vertices) {
            v.dx = 0;
            v.dy = 0;
            // Do not move fixed vertices
            if (!v.fixed) {
                for (let u of graph.vertices) {
                    if (v != u && !u.fixed) {
                        /* Difference vector between the two vertices. */
                        let difx = v.x - u.x;
                        let dify = v.y - u.y;

                        /* Length of the dif vector. */
                        let d = Math.max(eps, Math.sqrt(difx * difx + dify * dify));
                        let force = R * k * k / d;
                        v.dx = v.dx + (difx / d) * force;
                        v.dy = v.dy + (dify / d) * force;
                    }
                }
            }
        }

        /* Calculate attractive forces. */
        for (let v of graph.vertices) {
            // Do not move fixed vertices
            if (!v.fixed) {
                for (let e of v.edges) {
                    let u = e.endVertex;
                    let difx = v.x - u.x;
                    let dify = v.y - u.y;
                    let d = Math.max(eps, Math.sqrt(difx * difx + dify * dify));
                    let force = A * d * d / k;

                    v.dx = v.dx - (difx / d) * force;
                    v.dy = v.dy - (dify / d) * force;

                    u.dx = u.dx + (difx / d) * force;
                    u.dy = u.dy + (dify / d) * force;
                }
            }
        }

        /* Limit the maximum displacement to the temperature t
         and prevent from being displaced outside frame.     */
        for (let v of graph.vertices) {
            if (!v.fixed) {
                /* Length of the displacement vector. */
                let d = Math.max(eps, Math.sqrt(v.dx * v.dx + v.dy * v.dy));

                /* Limit to the temperature t. */
                v.x = v.x + (v.dx / d) * Math.min(d, t);
                v.y = v.y + (v.dy / d) * Math.min(d, t);

                v.x = Math.round(v.x);
                v.y = Math.round(v.y);
            }
        }

        /* Cool. */
        t -= dt;
    }
};
<commit_msg>unused code in fruchterman_reingold removed<commit_after>'use strict';

/*global cytoscape*/

cytoscape('layout', 'fruchterman', FruchtermanLayout);

function FruchtermanLayout(options) {
    let defaults = {
        fit: true
    };

    for (let key of Object.keys(defaults)) {
        if (options.hasOwnProperty(key)) {
            this.options[key] = options[key];
        } else {
            this.options[key] = defaults[key];
        }
    }
}

FruchtermanLayout.prototype.run = function () {
    let options = this.options;
    let cy = options.cy;
    let width = cy.width();
    let height = cy.height();
    let graph = new Graph();
    let vertices = new Map();

    cy.nodes().forEach(function (node) {
        let v = new Vertex(Math.random() * width, Math.random() * height);

        vertices.set(node.id(), v);
        graph.insertVertex(v);
    });

    cy.edges().forEach(function (edge) {
        graph.insertEdge(vertices.get(edge.source().id()), vertices.get(edge.target().id()));
    });

    let layoutManager = new ForceDirectedVertexLayout(width, height, 100);

    layoutManager.layout(graph);

    cy.nodes().layoutPositions(this, options, function (i, node) {
        let vertex = vertices.get(node.id());

        return {
            x: vertex.x,
            y: vertex.y
        };
    });

    if (options.fit) {
        cy.fit();
    }

    return this;
};

function Graph() {
    this.vertices = [];
}

Graph.prototype.insertVertex = function (vertex) {
    this.vertices.push(vertex);
};

Graph.prototype.insertEdge = function (vertex1, vertex2) {
    let e1 = new Edge(vertex2);
    let e2 = new Edge(vertex1);

    vertex1.edges.push(e1);
    vertex2.reverseEdges.push(e2);

    return e1;
};

function Vertex(x, y) {
    this.edges = [];
    this.reverseEdges = [];
    this.x = x;
    this.y = y;
    this.dx = 0;
    this.dy = 0;
    this.fixed = false;
}

function Edge(endVertex) {
    this.endVertex = endVertex;
}

function ForceDirectedVertexLayout(width, height, iterations) {
    this.width = width;
    this.height = height;
    this.iterations = iterations;
}

ForceDirectedVertexLayout.prototype.identifyComponents = function (graph) {
    let components = [];

    // Depth first search
    function dfs(vertex) {
        let stack = [];
        let component = [];

        components.push(component);

        function visitVertex(v) {
            component.push(v);
            v.__dfsVisited = true;

            for (let e of v.edges) {
                stack.push(e.endVertex);
            }

            for (let e of v.reverseEdges) {
                stack.push(e.endVertex);
            }
        }

        visitVertex(vertex);
        while (stack.length > 0) {
            let u = stack.pop();

            if (!u.__dfsVisited) {
                visitVertex(u);
            }
        }
    }

    // Clear DFS visited flag
    for (let v of graph.vertices) {
        v.__dfsVisited = false;
    }

    // Iterate through all vertices starting DFS from each vertex
    // that hasn't been visited yet.
    for (let v of graph.vertices) {
        if (!v.__dfsVisited)
            dfs(v);
    }

    // Interconnect all center vertices
    if (components.length > 1) {
        let componentCenters = [];

        for (let component of components) {
            let center = new Vertex(-1, -1);

            graph.insertVertex(center);

            for (let otherCenter of componentCenters) {
                graph.insertEdge(center, otherCenter);
            }

            componentCenters.push(center);

            for (let v of component) {
                graph.insertEdge(v, center);
            }
        }
    }
};

ForceDirectedVertexLayout.prototype.layout = function (graph) {
    let area = this.width * this.height;
    let k = Math.sqrt(area / graph.vertices.length);

    let t = this.width / 10; // Temperature.
    let dt = t / (this.iterations + 1);

    let eps = 20; // Minimum vertex distance.
    let A = 1.5; // Fine tune attraction.
    let R = 0.5; // Fine tune repulsion.

    // Initiate component identification and virtual vertex creation
    // to prevent disconnected graph components from drifting too far apart
    this.identifyComponents(graph);

    // Run through some iterations
    for (let q = 0; q < this.iterations; q++) {

        /* Calculate repulsive forces. */
        for (let v of graph.vertices) {
            v.dx = 0;
            v.dy = 0;
            // Do not move fixed vertices
            if (!v.fixed) {
                for (let u of graph.vertices) {
                    if (v != u && !u.fixed) {
                        /* Difference vector between the two vertices. */
                        let difx = v.x - u.x;
                        let dify = v.y - u.y;

                        /* Length of the dif vector. */
                        let d = Math.max(eps, Math.sqrt(difx * difx + dify * dify));
                        let force = R * k * k / d;
                        v.dx = v.dx + (difx / d) * force;
                        v.dy = v.dy + (dify / d) * force;
                    }
                }
            }
        }

        /* Calculate attractive forces. */
        for (let v of graph.vertices) {
            // Do not move fixed vertices
            if (!v.fixed) {
                for (let e of v.edges) {
                    let u = e.endVertex;
                    let difx = v.x - u.x;
                    let dify = v.y - u.y;
                    let d = Math.max(eps, Math.sqrt(difx * difx + dify * dify));
                    let force = A * d * d / k;

                    v.dx = v.dx - (difx / d) * force;
                    v.dy = v.dy - (dify / d) * force;

                    u.dx = u.dx + (difx / d) * force;
                    u.dy = u.dy + (dify / d) * force;
                }
            }
        }

        /* Limit the maximum displacement to the temperature t
         and prevent from being displaced outside frame.     */
        for (let v of graph.vertices) {
            if (!v.fixed) {
                /* Length of the displacement vector. */
                let d = Math.max(eps, Math.sqrt(v.dx * v.dx + v.dy * v.dy));

                /* Limit to the temperature t. */
                v.x = v.x + (v.dx / d) * Math.min(d, t);
                v.y = v.y + (v.dy / d) * Math.min(d, t);

                v.x = Math.round(v.x);
                v.y = Math.round(v.y);
            }
        }

        /* Cool. */
        t -= dt;
    }
};
<|endoftext|>


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

/**
 * A service that keeps track of the last page we visited.
 */
angular.module('sb.util')
    .factory('LastLocation', function ($rootScope, localStorageService) {
        'use strict';

        /**
         * The last detected length of the history
         */

        // When the location changes, store the new one. Since the $location
        // object changes too quickly, we instead extract the hash manually.
        function onLocationChange(event, toLocation) {
            var url = new URL(toLocation);
            var hash = url.hash || '#!/';
            var trimmed_hash = hash.slice(2);
            if (trimmed_hash.indexOf('/auth') === -1) {
                localStorageService.set('lastLocation', trimmed_hash);
            }

        }

        // The published API.
        return {

            /**
             * Get the recorded history path at the provided index.
             */
            get: function () {
                return localStorageService.get('lastLocation');
            },

            /**
             * Initialize this service.
             */
            initialize: function () {
                // Register (and disconnect) our listener.
                $rootScope.$on('$destroy',
                    $rootScope.$on('$locationChangeStart', onLocationChange)
                );
            }
        };
    })
    .run(function (LastLocation) {
        'use strict';

        // Initialize this service.
        LastLocation.initialize();
    });
<commit_msg>Fixed reference to experimental API<commit_after>/*
 * Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

/**
 * A service that keeps track of the last page we visited.
 */
angular.module('sb.util')
    .factory('LastLocation',
    function ($rootScope, localStorageService, $location) {
        'use strict';

        /**
         * The last detected length of the history
         */

            // When the location changes, store the new one. Since the $location
            // object changes too quickly, we instead extract the hash manually.
        function onLocationChange() {
            var path = $location.path();
            if (!!path && path.indexOf('/auth') === -1) {
                localStorageService.set('lastLocation', path);
            }

        }

        // The published API.
        return {

            /**
             * Get the recorded history path at the provided index.
             */
            get: function () {
                return localStorageService.get('lastLocation');
            },

            /**
             * Initialize this service.
             */
            initialize: function () {
                // Register (and disconnect) our listener.
                $rootScope.$on('$destroy',
                    $rootScope.$on('$locationChangeStart', onLocationChange)
                );
            }
        };
    })
    .run(function (LastLocation) {
        'use strict';

        // Initialize this service.
        LastLocation.initialize();
    });
<|endoftext|>


<commit_before>import http from '../http';
import { store } from '../../config/store';
import { userLoggedIn, userLoggedOut } from '../../config/actions';

export default class user {

    static get(email) {
        return http.get(`/zebedee/users?email=${email}`)
            .then(response => {
                return response;
            }).catch(error => {
                console.error(`Error getting user details for ${email} \n${error}`);
            })
    }

    static getAll() {
        return http.get(`/zebedee/users`)
            .then(response => {
                return response;
            }).catch(error => {
                console.error(`Error getting all users \n${error}`)
            })
    }

    static getPermissions(email) {
        return http.get(`/zebedee/permission?email=${email}`)
            .then(response => {
                return response;
            }).catch(error => {
                console.error(`Error getting user permissions for ${email} \n${error}`);
        });
    }

    static getOldUserType(user) {
        // TAKEN FROM OLD FLORENCE
        if (user.admin) {
            return "PUBLISHING_SUPPORT";
        } else if (user.editor && !user.dataVisPublisher) {
            return "PUBLISHING_SUPPORT";
        } else if (user.editor && user.dataVisPublisher) {
            return "DATA_VISUALISATION";
        } else if (!user.admin && !user.editor && !user.dataVisPublisher) {
            return "VIEWER";
        }
    }

    static setUserState(user) {
        const email = user.email;
        let userType = '';
        if (user.editor) { userType = 'EDITOR'}
        if (user.admin) { userType = 'ADMIN'}
        if (!user.editor && !user.admin) { userType = 'VIEWER'}
        const isAdmin = !!user.admin;
        store.dispatch(userLoggedIn(email, userType, isAdmin));
        localStorage.setItem("loggedInAs", email);

        // Store the user type in localStorage. Used in old Florence
        // where views can depend on user type. e.g. Browse tree
        localStorage.setItem("userType", this.getOldUserType(user));
    }

    static logOut() {
        store.dispatch(userLoggedOut());
    }

    static updatePassword(body) {
        return http.post('/zebedee/password', body)
            .then(response => {
                return response;
            })
    }

}<commit_msg>Fix error message not showing properly in console for user requests<commit_after>import http from '../http';
import { store } from '../../config/store';
import { userLoggedIn, userLoggedOut } from '../../config/actions';

export default class user {

    static get(email) {
        return http.get(`/zebedee/users?email=${email}`)
            .then(response => {
                return response;
            }).catch(error => {
                console.error(`Error getting user details for ${email}`, error);
            })
    }

    static getAll() {
        return http.get(`/zebedee/users`)
            .then(response => {
                return response;
            }).catch(error => {
                console.error(`Error getting all users`, error)
            })
    }

    static getPermissions(email) {
        return http.get(`/zebedee/permission?email=${email}`)
            .then(response => {
                return response;
            }).catch(error => {
                console.error(`Error getting user permissions for ${email}`, error);
        });
    }

    static getOldUserType(user) {
        // TAKEN FROM OLD FLORENCE
        if (user.admin) {
            return "PUBLISHING_SUPPORT";
        } else if (user.editor && !user.dataVisPublisher) {
            return "PUBLISHING_SUPPORT";
        } else if (user.editor && user.dataVisPublisher) {
            return "DATA_VISUALISATION";
        } else if (!user.admin && !user.editor && !user.dataVisPublisher) {
            return "VIEWER";
        }
    }

    static setUserState(user) {
        const email = user.email;
        let userType = '';
        if (user.editor) { userType = 'EDITOR'}
        if (user.admin) { userType = 'ADMIN'}
        if (!user.editor && !user.admin) { userType = 'VIEWER'}
        const isAdmin = !!user.admin;
        store.dispatch(userLoggedIn(email, userType, isAdmin));
        localStorage.setItem("loggedInAs", email);

        // Store the user type in localStorage. Used in old Florence
        // where views can depend on user type. e.g. Browse tree
        localStorage.setItem("userType", this.getOldUserType(user));
    }

    static logOut() {
        store.dispatch(userLoggedOut());
    }

    static updatePassword(body) {
        return http.post('/zebedee/password', body)
            .then(response => {
                return response;
            })
    }

}<|endoftext|>


<commit_before>YUI.add('aui-button-tests', function(Y) {

    var suite = new Y.Test.Suite('aui-button'),
        searchButtonCancel;

    function assertPosition(input) {
        var inputRegion = input.get('region'),
            iconClose = input.next('.btn-search-cancel'),
            iconCloseRegion = iconClose.get('region'),

            xpos = inputRegion.right -
                searchButtonCancel.get('iconWidth') +
                searchButtonCancel.get('gutter.0'),

            ypos = inputRegion.top +
                inputRegion.height / 2 -
                searchButtonCancel.get('iconHeight') / 2 +
                searchButtonCancel.get('gutter.1');

        Y.Assert.areSame(
            Math.round(iconClose.getY()), Math.round(ypos),
            'Y-Position of input and search-btn-cancel should be the same.');

        Y.Assert.areSame(
            iconClose.getX(), xpos, 'X-Position of input and search-btn-cancel should be the same.');
    }

    function fillInput(input) {
        input.focus().val('This is a test!');
        input.simulate('click');

        // TODO: Remove this when yeti is fixed to stop stealing focus from the test.
        searchButtonCancel._syncButtonUI(input);
    }

    suite.add(new Y.Test.Case({
        name: 'Search Button Cancel',

        '#1: Focusing first input should position .btn-search-cancel on the right.': function() {
            var test = this,
                inputNode = Y.all('input.clearable').item(0);

            searchButtonCancel = new Y.ButtonSearchCancel({
                trigger: '.clearable'
            });

            inputNode.once('click', function() {
                setTimeout(function() {
                    test.resume(function() {
                        assertPosition(inputNode);
                    });
                }, 800);
            });

            Y.soon(function() {
                fillInput(inputNode);
            });

            test.wait(1000);
        },

        '#2: Focusing second input should position .btn-search-cancel on the right.': function() {
            var test = this,
                inputNode = Y.all('input.clearable').item(1);

            searchButtonCancel = new Y.ButtonSearchCancel({
                trigger: '.clearable'
            });

            inputNode.once('click', function() {
                setTimeout(function() {
                    test.resume(function() {
                        assertPosition(inputNode);
                    });
                }, 800);
            });

            Y.soon(function() {
                fillInput(inputNode);
            });

            test.wait(1000);
        },

        '#3: .btn-search-cancel should be positioned correctly when input is moved by removing from dom and placing in a different area': function() {
            searchButtonCancel = new Y.ButtonSearchCancel({
                trigger: '.clearable'
            });

            Y.one('#search-btn-cancel-heading').insert(
                Y.one('#search-btn-cancel-demo'), 'before');

            Y.all('input.clearable').each(function(input) {
                assertPosition(input);
            });
        }
    }));

    Y.Test.Runner.add(suite);

}, '', {
    requires: ['aui-button', 'aui-button-search-cancel', 'aui-node', 'node-event-simulate', 'test']
});
<commit_msg>AUI-1281 Fixing test for Firefox<commit_after>YUI.add('aui-button-tests', function(Y) {

    var suite = new Y.Test.Suite('aui-button'),
        searchButtonCancel;

    function assertPosition(input) {
        var inputRegion = input.get('region'),
            iconClose = input.next('.btn-search-cancel'),
            iconCloseRegion = iconClose.get('region'),

            xpos = inputRegion.right -
                searchButtonCancel.get('iconWidth') +
                searchButtonCancel.get('gutter.0'),

            ypos = inputRegion.top +
                inputRegion.height / 2 -
                searchButtonCancel.get('iconHeight') / 2 +
                searchButtonCancel.get('gutter.1');

        Y.Assert.areSame(
            Math.round(iconClose.getY()), Math.round(ypos), 'Y-Position of input and search-btn-cancel should be the same.');
        Y.Assert.areSame(
            iconClose.getX(), xpos, 'X-Position of input and search-btn-cancel should be the same.');
    }

    function fillInput(input) {
        input.val('This is a test!');

        // TODO: Remove this when yeti is fixed to stop stealing focus from the test.
        searchButtonCancel._syncButtonUI(input);
    }

    suite.add(new Y.Test.Case({
        name: 'Search Button Cancel',

        '#1: Focusing first input should position .btn-search-cancel on the right.': function() {
            var test = this,
                inputNode = Y.all('input.clearable').item(0);

            searchButtonCancel = new Y.ButtonSearchCancel({
                trigger: '.clearable'
            });

            setTimeout(function() {
                test.resume(function() {
                    assertPosition(inputNode);
                });
            }, 800);

            Y.soon(function() {
                fillInput(inputNode);
            });

            test.wait(1000);
        },

        '#2: Focusing second input should position .btn-search-cancel on the right.': function() {
            var test = this,
                inputNode = Y.all('input.clearable').item(1);

            searchButtonCancel = new Y.ButtonSearchCancel({
                trigger: '.clearable'
            });

            setTimeout(function() {
                test.resume(function() {
                    assertPosition(inputNode);
                });
            }, 800);

            Y.soon(function() {
                fillInput(inputNode);
            });

            test.wait(1000);
        },

        '#3: .btn-search-cancel should be positioned correctly when input is moved by removing from dom and placing in a different area': function() {
            searchButtonCancel = new Y.ButtonSearchCancel({
                trigger: '.clearable'
            });

            Y.one('#search-btn-cancel-heading').insert(
                Y.one('#search-btn-cancel-demo'), 'before');

            Y.all('input.clearable').each(function(input) {
                assertPosition(input);
            });
        }
    }));

    Y.Test.Runner.add(suite);

}, '', {
    requires: ['aui-button', 'aui-button-search-cancel', 'aui-node', 'node-event-simulate', 'test']
});
<|endoftext|>


<commit_before>'use strict'

// should this just be declared in FB bot module?
// const token = process.env.FB_PAGE_ACCESS_TOKEN

// need to examine the request coming from Facebook for what distinguishes it
// basically returns False now
function isHandlerForRequest(platformRequestContext) {
  var responseUrl = platformRequestContext.userRequest.response_url || '';
  return (responseUrl && responseUrl.includes('facebook')) ? true : false;
}

function getResponsePayload() {

}

function sendResponseToPlatform() {

}

module.exports = {
  getResponsePayload: getResponsePayload,
  sendResponseToPlatform: sendResponseToPlatform,
  isHandlerForRequest: isHandlerForRequest
}<commit_msg>debug<commit_after>'use strict'

// should this just be declared in FB bot module?
// const token = process.env.FB_PAGE_ACCESS_TOKEN

// need to examine the request coming from Facebook for what distinguishes it
// basically returns False now
function isHandlerForRequest(platformRequestContext) {
  var object = platformRequestContext.userRequest.object || '';
  return (object === 'page') ? true : false;
}

function getResponsePayload() {

}

function sendResponseToPlatform() {

}

module.exports = {
  getResponsePayload: getResponsePayload,
  sendResponseToPlatform: sendResponseToPlatform,
  isHandlerForRequest: isHandlerForRequest
}<|endoftext|>


<commit_before>var jsonfile = require('jsonfile');
var filter = require('lodash.filter');
var pluck = require('lodash.pluck');

var args = process.argv;

if (!args[2] || !args[3]) {
  console.error('\nUsage: node bpmn-jsonator.js /path/to/bpmn.json element');
  return;
}

var file = args[2];
var elementName = args[3];

jsonfile.readFile(file, function(err, obj) {
  var elements = filter(obj.types, function(type) {
    if (type.superClass) {
      return type.superClass.indexOf(elementName) !== -1;
    } else {
      return false;
    }
  });
  console.log(pluck(elements, 'name'));
});
<commit_msg>feat: show all hierarchical child classes<commit_after>var jsonfile = require('jsonfile');
var filter = require('lodash.filter');
var pluck = require('lodash.pluck');

var args = process.argv;

if (!args[2] || !args[3]) {
  console.error('\nUsage: node bpmn-jsonator.js /path/to/bpmn.json element');
  return;
}

var file = args[2];
var elementName = args[3];

jsonfile.readFile(file, function(err, obj) {

  function getChildren(elementName) {
    var elements = filter(obj.types, function(type) {
      return type.superClass ? type.superClass.indexOf(elementName) !== -1 : false;
    });

    var children = pluck(elements, 'name');

    if(children.length !== 0) {
      console.log(elementName +": "+ children);
    }

    for (var i=0; i<elements.length; i++) {
      getChildren(elements[i].name);
    }

    return pluck(elements, 'name');
  }

  getChildren(elementName);
});
<|endoftext|>


<commit_before>// Config ===============================================

var Q                    = require('q');
var moment               = require('moment');
var Botkit               = require('botkit');
var responses            = require('./responses.js');

var whitelistedUsers     = ['tyler shambora (4merly six-p-tdrop)', 'daniel lerman', 'ryan little', 'cory cummings'];
var readOnlyChannels     = ['C1317518C', 'C3G3Y7RFX'];

// Init ===============================================

if (!process.env.BOT_TOKEN) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
  debug: true,
  logLevel: 6
});

controller.configureSlackApp({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  scopes: ['bot', 'chat:write:user', 'chat:write:bot', 'channels:read', 'channels:write', 'groups:write']
});

controller.setupWebserver(process.env.PORT, function(err, webserver) {
  if (err) {
    throw new Error(err);
  }
  controller.createWebhookEndpoints(controller.webserver);
  controller.createHomepageEndpoint(controller.webserver);
  controller.createOauthEndpoints(controller.webserver, function(err, req, res) {
    if (err) {
      res.status(500).send('ERROR: ' + err);
    } else {
      res.send('Great Success!');
    }
  });
});

var bot = controller.spawn({
  token: process.env.BOT_TOKEN
});

bot.startRTM(function(err) {
  if (err) {
    console.log('Even if you fall on your face, you\'re still moving forward.');
    throw new Error(err);
  }
});

// USED TO GET THE MEGA ADMIN TOKEN
controller.on('create_user',function(bot, user) {
  console.log('USED TO GET THE MEGA ADMIN TOKEN');
  console.log('-----');
  console.log('USER TOKEN:');
  console.log(user.access_token);
  console.log('-----');
});

var _bots = {};
var trackBot = function(bot) {
  _bots[bot.config.token] = bot;
};

controller.on('create_bot',function(bot, config) {
  if (_bots[bot.config.token]) {
    // already online! do nothing.
  } else {
    bot.startRTM(function(err, bot, payload) {
      if (err) {
        console.log('Even if you fall on your face, you\'re still moving forward.');
        throw new Error(err);
      } else {
        trackBot(bot);
      }
    });
  }
});

controller.storage.teams.all(function(err, teams) {
  if (err) {
    throw new Error(err);
  }
  for (var t in teams) {
    if (teams[t].bot) {
      controller.spawn(teams[t]).startRTM(function(err, bot) {
        if (err) {
          console.log('Error connecting bot to Slack:',err);
        } else {
          trackBot(bot);
        }
      });
    }
  }
});

// Helper Functions ===============================================

var getRealNameFromId = function(bot, userId) {
  var deferred = Q.defer();
  var realName = '';
  bot.api.users.info({user: userId}, function(err, response) {
    realName = response.user.real_name.toLowerCase();
    deferred.resolve(realName);
  });
  return deferred.promise;
};

var isValidChannelName = function(bot, channelName) {
  var deferred = Q.defer();
  bot.api.channels.list({}, function(err, response) {
    deferred.resolve(response.channels.some(function(channel) {
      return channel.name === channelName;
    }));
  });
  return deferred.promise;
};

var isValidUser = function(realName) {
  var deferred = Q.defer();
  deferred.resolve(whitelistedUsers.some(function(userName) {
    return userName === realName;
  }));
  return deferred.promise;
};

// Listeners  ===============================================

controller.hears([/post to (\S+)\n([\s\S]*)/], 'direct_message', function(bot, message) {
  var channelName = message.match[1];
  var update = message.match[2];

  var parsedMessages = update.split('\n\n\n').map(function(block) {
    var messageParts = block.split('\n___\n');
    return {
      fallback: messageParts[1],
      title: messageParts[0],
      text: messageParts[1],
      color: 'danger',
      mrkdwn_in: ['fallback', 'text']
    };
  });

  var validateChannel = isValidChannelName(bot, channelName);
  var validateName = getRealNameFromId(bot, message.user).then(isValidUser);
  var isValidated = Q.all([validateChannel, validateName]);

  isValidated.spread(function(validChannel, validUser) {
    if (!validUser) {
      return bot.reply(message, 'Sorry, you\'re not authenticated to post.');
    } else if (!validChannel) {
      return bot.reply(message, 'Sorry, I can\'t post to the channel: ' + channelName + '.');
    } else if (validUser && validChannel) {
      var theDate = moment().format('dddd, MMMM Do YYYY');
      bot.startConversation(message, function(err, convo) {
        convo.say('*I\'m about to post the following:*');
        convo.say({
          username: 'Brian Williams: Dev Team News Anchor',
          icon_url: 'http://dev.tylershambora.com/images/father-williams.jpg',
          text: '<!channel>\n\n*Updates for ' + theDate + ':*',
          attachments: parsedMessages
        });
        convo.ask(responses.confirm(bot, channelName, parsedMessages, theDate), [
          responses.yes(bot, 'post', {channel:channelName, message:parsedMessages, date:theDate}),
          responses.no(bot),
          responses.default()
        ]);
      });
    }
  });
});

controller.hears(['hey mister'], ['direct_message', 'mention', 'direct_mention'], function(bot, message) {
  getRealNameFromId(bot, message.user)
    .then(isValidUser)
    .then(function(result) {
      bot.reply(message, 'Hello!');
      if (result) {
        bot.reply(message, 'Hey! You\'re pretty valid!');
      }
    });
});

controller.hears([/delete (\S+) from (\S+)/], ['direct_message'], function(bot, message) {
  var channelOptions = {
    token: bot.config.token,
    channel: message.match[2],
  };

  var deleteOptions = {
    token: process.env.MEGA_TOKEN,
    ts: message.match[1],
    channel: message.match[2],
    as_user: true
  };

  bot.api.channels.info(channelOptions, function (err, response) {
    if (!response.ok) {
      console.log(response);
      bot.reply(message, 'incorrect channel id');
    } else if (message.match[1][9] !== '.') {
      bot.reply(message, 'incorrect time stamp');
    } else {
      bot.startConversation(message, function(err, convo) {
        convo.say('*I\'m about to delete:*');
        convo.say(`https://bva.slack.com/archives/${response.channel.name}/p${message.match[1].replace('.', '')}`);
        convo.ask(responses.confirm(bot, deleteOptions), [
          responses.yes(bot, 'delete', deleteOptions),
          responses.no(bot),
          responses.default()
        ]);
      });
    }
  });
});

controller.on('direct_message, mention, direct_mention', function(bot, message) {
  bot.api.reactions.add({
    timestamp: message.ts,
    channel: message.channel,
    name: 'jesus',
  }, function(err) {
    if (err) {
      console.log(err);
    } else {
      bot.reply(message, 'go with christ brah.');
    }
  });
});

controller.hears([/[\s\S]*/], ['direct_message', 'direct_mention', 'mention', 'ambient'], function(bot, message) {
  if (readOnlyChannels.indexOf(message.channel) !== -1) {
    getRealNameFromId(bot, message.user).then(function(realName) {
      var options = {
        token: process.env.MEGA_TOKEN,
        ts: message.ts,
        channel: message.channel,
        as_user: true
      };

      console.log(options);

      console.log('%s said: "%s"', realName, message.text);
      console.log('Attempting to delete the message.' );

      // this whole block looks pretty ripe for some abstraction and recursion (tsham)
      bot.api.chat.delete(options, function(err, response) {
        if (!response.ok) {
          console.log('Unable to delete due to error: ' + err);
          console.log('Trying one more time in 2 seconds');
          setTimeout(function() {
            bot.api.chat.delete(options, function(err, response) {
              if (!response.ok) {
                console.log('Unable to delete after a second attempt due to error: ' + err);
              }
            });
          }, 2000);
        } else {
          console.log('Message successfully deleted!');
        }
      });
    });
  }
});

controller.on('rtm_open', function(bot) {
  console.log('** The RTM api just connected: ' + bot.identity.name);
});

controller.on('rtm_close', function() {
  console.log('** The RTM api just closed');
});
<commit_msg>add lynwhel to whitelist<commit_after>// Config ===============================================

var Q                    = require('q');
var moment               = require('moment');
var Botkit               = require('botkit');
var responses            = require('./responses.js');

var whitelistedUsers     = ['tyler shambora (4merly six-p-tdrop)', 'daniel lerman', 'ryan little', 'cory cummings', 'lynwhel claricia'];
var readOnlyChannels     = ['C1317518C', 'C3G3Y7RFX'];

// Init ===============================================

if (!process.env.BOT_TOKEN) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
  debug: true,
  logLevel: 6
});

controller.configureSlackApp({
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  scopes: ['bot', 'chat:write:user', 'chat:write:bot', 'channels:read', 'channels:write', 'groups:write']
});

controller.setupWebserver(process.env.PORT, function(err, webserver) {
  if (err) {
    throw new Error(err);
  }
  controller.createWebhookEndpoints(controller.webserver);
  controller.createHomepageEndpoint(controller.webserver);
  controller.createOauthEndpoints(controller.webserver, function(err, req, res) {
    if (err) {
      res.status(500).send('ERROR: ' + err);
    } else {
      res.send('Great Success!');
    }
  });
});

var bot = controller.spawn({
  token: process.env.BOT_TOKEN
});

bot.startRTM(function(err) {
  if (err) {
    console.log('Even if you fall on your face, you\'re still moving forward.');
    throw new Error(err);
  }
});

// USED TO GET THE MEGA ADMIN TOKEN
controller.on('create_user',function(bot, user) {
  console.log('USED TO GET THE MEGA ADMIN TOKEN');
  console.log('-----');
  console.log('USER TOKEN:');
  console.log(user.access_token);
  console.log('-----');
});

var _bots = {};
var trackBot = function(bot) {
  _bots[bot.config.token] = bot;
};

controller.on('create_bot',function(bot, config) {
  if (_bots[bot.config.token]) {
    // already online! do nothing.
  } else {
    bot.startRTM(function(err, bot, payload) {
      if (err) {
        console.log('Even if you fall on your face, you\'re still moving forward.');
        throw new Error(err);
      } else {
        trackBot(bot);
      }
    });
  }
});

controller.storage.teams.all(function(err, teams) {
  if (err) {
    throw new Error(err);
  }
  for (var t in teams) {
    if (teams[t].bot) {
      controller.spawn(teams[t]).startRTM(function(err, bot) {
        if (err) {
          console.log('Error connecting bot to Slack:',err);
        } else {
          trackBot(bot);
        }
      });
    }
  }
});

// Helper Functions ===============================================

var getRealNameFromId = function(bot, userId) {
  var deferred = Q.defer();
  var realName = '';
  bot.api.users.info({user: userId}, function(err, response) {
    realName = response.user.real_name.toLowerCase();
    deferred.resolve(realName);
  });
  return deferred.promise;
};

var isValidChannelName = function(bot, channelName) {
  var deferred = Q.defer();
  bot.api.channels.list({}, function(err, response) {
    deferred.resolve(response.channels.some(function(channel) {
      return channel.name === channelName;
    }));
  });
  return deferred.promise;
};

var isValidUser = function(realName) {
  var deferred = Q.defer();
  deferred.resolve(whitelistedUsers.some(function(userName) {
    return userName === realName;
  }));
  return deferred.promise;
};

// Listeners  ===============================================

controller.hears([/post to (\S+)\n([\s\S]*)/], 'direct_message', function(bot, message) {
  var channelName = message.match[1];
  var update = message.match[2];

  var parsedMessages = update.split('\n\n\n').map(function(block) {
    var messageParts = block.split('\n___\n');
    return {
      fallback: messageParts[1],
      title: messageParts[0],
      text: messageParts[1],
      color: 'danger',
      mrkdwn_in: ['fallback', 'text']
    };
  });

  var validateChannel = isValidChannelName(bot, channelName);
  var validateName = getRealNameFromId(bot, message.user).then(isValidUser);
  var isValidated = Q.all([validateChannel, validateName]);

  isValidated.spread(function(validChannel, validUser) {
    if (!validUser) {
      return bot.reply(message, 'Sorry, you\'re not authenticated to post.');
    } else if (!validChannel) {
      return bot.reply(message, 'Sorry, I can\'t post to the channel: ' + channelName + '.');
    } else if (validUser && validChannel) {
      var theDate = moment().format('dddd, MMMM Do YYYY');
      bot.startConversation(message, function(err, convo) {
        convo.say('*I\'m about to post the following:*');
        convo.say({
          username: 'Brian Williams: Dev Team News Anchor',
          icon_url: 'http://dev.tylershambora.com/images/father-williams.jpg',
          text: '<!channel>\n\n*Updates for ' + theDate + ':*',
          attachments: parsedMessages
        });
        convo.ask(responses.confirm(bot, channelName, parsedMessages, theDate), [
          responses.yes(bot, 'post', {channel:channelName, message:parsedMessages, date:theDate}),
          responses.no(bot),
          responses.default()
        ]);
      });
    }
  });
});

controller.hears(['hey mister'], ['direct_message', 'mention', 'direct_mention'], function(bot, message) {
  getRealNameFromId(bot, message.user)
    .then(isValidUser)
    .then(function(result) {
      bot.reply(message, 'Hello!');
      if (result) {
        bot.reply(message, 'Hey! You\'re pretty valid!');
      }
    });
});

controller.hears([/delete (\S+) from (\S+)/], ['direct_message'], function(bot, message) {
  var channelOptions = {
    token: bot.config.token,
    channel: message.match[2],
  };

  var deleteOptions = {
    token: process.env.MEGA_TOKEN,
    ts: message.match[1],
    channel: message.match[2],
    as_user: true
  };

  bot.api.channels.info(channelOptions, function (err, response) {
    if (!response.ok) {
      console.log(response);
      bot.reply(message, 'incorrect channel id');
    } else if (message.match[1][9] !== '.') {
      bot.reply(message, 'incorrect time stamp');
    } else {
      bot.startConversation(message, function(err, convo) {
        convo.say('*I\'m about to delete:*');
        convo.say(`https://bva.slack.com/archives/${response.channel.name}/p${message.match[1].replace('.', '')}`);
        convo.ask(responses.confirm(bot, deleteOptions), [
          responses.yes(bot, 'delete', deleteOptions),
          responses.no(bot),
          responses.default()
        ]);
      });
    }
  });
});

controller.on('direct_message, mention, direct_mention', function(bot, message) {
  bot.api.reactions.add({
    timestamp: message.ts,
    channel: message.channel,
    name: 'jesus',
  }, function(err) {
    if (err) {
      console.log(err);
    } else {
      bot.reply(message, 'go with christ brah.');
    }
  });
});

controller.hears([/[\s\S]*/], ['direct_message', 'direct_mention', 'mention', 'ambient'], function(bot, message) {
  if (readOnlyChannels.indexOf(message.channel) !== -1) {
    getRealNameFromId(bot, message.user).then(function(realName) {
      var options = {
        token: process.env.MEGA_TOKEN,
        ts: message.ts,
        channel: message.channel,
        as_user: true
      };

      console.log(options);

      console.log('%s said: "%s"', realName, message.text);
      console.log('Attempting to delete the message.' );

      // this whole block looks pretty ripe for some abstraction and recursion (tsham)
      bot.api.chat.delete(options, function(err, response) {
        if (!response.ok) {
          console.log('Unable to delete due to error: ' + err);
          console.log('Trying one more time in 2 seconds');
          setTimeout(function() {
            bot.api.chat.delete(options, function(err, response) {
              if (!response.ok) {
                console.log('Unable to delete after a second attempt due to error: ' + err);
              }
            });
          }, 2000);
        } else {
          console.log('Message successfully deleted!');
        }
      });
    });
  }
});

controller.on('rtm_open', function(bot) {
  console.log('** The RTM api just connected: ' + bot.identity.name);
});

controller.on('rtm_close', function() {
  console.log('** The RTM api just closed');
});
<|endoftext|>


<commit_before>/**
 * This module takes care of loading the BridgeSupport XML files for a given
 * framework, and parsing the data into the given framework object.
 */

var fs = require('fs')
  , sax = require('sax')
  , path = require('path')
  , core = require('./core')
  , types = require('./types')
  , join = path.join
  , basename = path.basename
  , exists = path.existsSync
  , DY_SUFFIX = '.dylib'
  , BS_SUFFIX = '.bridgesupport'

function bridgesupport (fw, _global) {

  var bridgeSupportDir = join(fw.basePath, 'Resources', 'BridgeSupport')
    , bridgeSupportXML = join(bridgeSupportDir, fw.name + BS_SUFFIX)
    , bridgeSupportDylib = join(bridgeSupportDir, fw.name + DY_SUFFIX)

  // If there's no BridgeSupport file, then just return the empty object...
  if (!exists(bridgeSupportXML)) {
    console.warn('No BridgeSupport files found for framework "%s" at: %s', fw.name, bridgeSupportXML);
    return;
  }

  if (exists(bridgeSupportDylib)) {
    fw.inline = core.dlopen(bridgeSupportDylib);
  }

  var contents = fs.readFileSync(bridgeSupportXML, 'utf8')
    , parser = sax.parser(true)
    , gotEnd = false
    , classes = []
    , constants = []
    , curName
    , curRtnType
    , curArgTypes
    , isInline
  //console.error(contents);

  parser.onerror = function (e) { throw e; }
  parser.onopentag = function (node) {
    //console.log(node.name);
    switch (node.name) {
      case 'depends_on':
        bridgesupport.import(node.attributes.path);
        break;
      case 'class':
        /*currentClass = Class.getClass(node.attributes.name);
        if (!currentClass) {
          currentClass = Class.registerClass(node.attributes.name);
          framework[node.attributes.name] = currentClass;
          classes.push(currentClass);
        }*/
        break;
      case 'method':
        /*currentMethod = {
            selector: node.attributes.selector
          , args: []
        };
        if (node.attributes.class_method) {
          currentClass.__proto__[currentMethod.selector] = currentMethod;
        } else {
          currentClass.prototype[currentMethod.selector] = currentMethod;
        }*/
        break;
      case 'arg':
        if (curName) {
          // class methods also have args, we only want functions though
          curArgTypes.push(types.map(node.attributes.type));
        }
        break;
      case 'retval':
        if (curName) {
          // class methods also have retvals, we only want functions though
          curRtnType = types.map(node.attributes.type);
        }
        break;
      case 'signatures':
        // ignore
        break;
      case 'string_constant':
        _global[node.attributes.name] = node.attributes.value;
        break;
      case 'enum':
        _global[node.attributes.name] = parseInt(node.attributes.value);
        break;
      case 'struct':
        break;
      case 'field':
        //console.error(node);
        break;
      case 'cftype':
        break;
      case 'constant':
        //constants.push(node);
        break;
      case 'function':
        curName = node.attributes.name;
        curRtnType = null;
        curArgTypes = [];
        isInline = node.attributes.inline == 'true';
        // TODO: is variadic? will require a 'function generator'
        break;
      case 'args':
        break;
      case 'opaque':
        break;
      case 'informal_protocol':
        break;
      case 'function_alias':
        break;
      default:
        throw new Error('unkown tag: '+ node.name);
        break;
    }
  };
  parser.onclosetag = function (node) {
    switch (node) {
      case 'function':
        if (isInline && !fw.inline) throw new Error('declared inline but could not find inline dylib!');
        _global[curName] = core.Function(curName, curRtnType, curArgTypes, false, isInline ? fw.inline : fw.lib);
        curName = null;
        break;
    }
  };
  parser.onend = function () {
    gotEnd = true;
  };

  // Parse the contents of the file. This should happen synchronously.
  parser.write(contents).close();

  if (!gotEnd) {
    throw new Error('could not parse BridgeSupport files synchronously');
  }

  /*
  // Now time to set up the inheritance on all the Classes.
  // This has to happen after parsing has completed to ensure that all the
  // required parent classes have been parsed and loaded.
  classes.forEach(function (c) {
    Class.setupInheritance(c);
  });

  constants.forEach(function (node) {
    var sym = lib.get(node.attributes.name);
    if (node.attributes.declared_type == 'NSString*') {
      sym = Class.wrapId(sym);
      sym.__proto__ = Class.getClass('NSString').prototype;
      framework[node.attributes.name] = sym;
    }
  });
  */
}
module.exports = bridgesupport;
<commit_msg>Remove old class and method BridgeSupport parsing logic. All Obj-C classes will be introspected at runtime.<commit_after>/**
 * This module takes care of loading the BridgeSupport XML files for a given
 * framework, and parsing the data into the given framework object.
 */

var fs = require('fs')
  , sax = require('sax')
  , path = require('path')
  , core = require('./core')
  , types = require('./types')
  , join = path.join
  , basename = path.basename
  , exists = path.existsSync
  , DY_SUFFIX = '.dylib'
  , BS_SUFFIX = '.bridgesupport'

function bridgesupport (fw, _global) {

  var bridgeSupportDir = join(fw.basePath, 'Resources', 'BridgeSupport')
    , bridgeSupportXML = join(bridgeSupportDir, fw.name + BS_SUFFIX)
    , bridgeSupportDylib = join(bridgeSupportDir, fw.name + DY_SUFFIX)

  // If there's no BridgeSupport file, then just return the empty object...
  if (!exists(bridgeSupportXML)) {
    console.warn('No BridgeSupport files found for framework "%s" at: %s', fw.name, bridgeSupportXML);
    return;
  }

  if (exists(bridgeSupportDylib)) {
    fw.inline = core.dlopen(bridgeSupportDylib);
  }

  var contents = fs.readFileSync(bridgeSupportXML, 'utf8')
    , parser = sax.parser(true)
    , gotEnd = false
    , classes = []
    , constants = []
    , curName
    , curRtnType
    , curArgTypes
    , isInline
  //console.error(contents);

  parser.onerror = function (e) { throw e; }
  parser.onopentag = function (node) {
    //console.log(node.name);
    switch (node.name) {
      case 'depends_on':
        bridgesupport.import(node.attributes.path);
        break;
      case 'class':
        break;
      case 'method':
        break;
      case 'arg':
        if (curName) {
          // class methods also have args, we only want functions though
          curArgTypes.push(types.map(node.attributes.type));
        }
        break;
      case 'retval':
        if (curName) {
          // class methods also have retvals, we only want functions though
          curRtnType = types.map(node.attributes.type);
        }
        break;
      case 'signatures':
        // ignore
        break;
      case 'string_constant':
        _global[node.attributes.name] = node.attributes.value;
        break;
      case 'enum':
        _global[node.attributes.name] = parseInt(node.attributes.value);
        break;
      case 'struct':
        break;
      case 'field':
        //console.error(node);
        break;
      case 'cftype':
        break;
      case 'constant':
        //constants.push(node);
        break;
      case 'function':
        curName = node.attributes.name;
        curRtnType = null;
        curArgTypes = [];
        isInline = node.attributes.inline == 'true';
        // TODO: is variadic? will require a 'function generator'
        break;
      case 'args':
        break;
      case 'opaque':
        break;
      case 'informal_protocol':
        break;
      case 'function_alias':
        break;
      default:
        throw new Error('unkown tag: '+ node.name);
        break;
    }
  };
  parser.onclosetag = function (node) {
    switch (node) {
      case 'function':
        if (isInline && !fw.inline) throw new Error('declared inline but could not find inline dylib!');
        _global[curName] = core.Function(curName, curRtnType, curArgTypes, false, isInline ? fw.inline : fw.lib);
        curName = null;
        break;
    }
  };
  parser.onend = function () {
    gotEnd = true;
  };

  // Parse the contents of the file. This should happen synchronously.
  parser.write(contents).close();

  if (!gotEnd) {
    throw new Error('could not parse BridgeSupport files synchronously');
  }

  /*
  // Now time to set up the inheritance on all the Classes.
  // This has to happen after parsing has completed to ensure that all the
  // required parent classes have been parsed and loaded.
  classes.forEach(function (c) {
    Class.setupInheritance(c);
  });

  constants.forEach(function (node) {
    var sym = lib.get(node.attributes.name);
    if (node.attributes.declared_type == 'NSString*') {
      sym = Class.wrapId(sym);
      sym.__proto__ = Class.getClass('NSString').prototype;
      framework[node.attributes.name] = sym;
    }
  });
  */
}
module.exports = bridgesupport;
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var browserify = require('browserify');
var browserPack = require('browser-pack');
var exec = require('child_process').exec;
var sys = require('sys');
var puts = function(error, stdout, stderr) {
  if (error) console.log(error);
  //sys.puts(stdout);
  //sys.puts(stderr);
};

var pack = function (params) {
  var file = require.resolve('soop');
  var dir = file.substr(0, file.length - String('soop.js').length);
  var preludePath = dir + 'example/custom_prelude.js';
  params.raw = true;
  params.sourceMapPrefix = '//#';
  params.prelude = fs.readFileSync(preludePath, 'utf8');
  params.preludePath = preludePath;
  return browserPack(params);
};

var modules = [
  'Address',
  'Block',
  'Bloom',
  'Buffers.monkey',
  'Connection',
  'Deserialize',
  'Gruntfile',
  'Number.monkey',
  'Opcode',
  'Peer',
  'PeerManager',
  'PrivateKey',
  'RpcClient',
  'Key',
  'SIN',
  'SINKey',
  'Script',
  'ScriptInterpreter',
  'Sign',
  'Transaction',
  'Wallet',
  'WalletKey',
  'config',
  'const',
  'networks',
  'util/log',
  'util/util',
  'util/EncodedData',
  'util/VersionedData',
];

var createBitcore = function(opts) {

  opts.dir = opts.dir || '';

  // concat browser vendor files
  exec('cd ' + opts.dir + 'browser; sh concat.sh', puts);

  if (!opts.includeall && (!opts.submodules || opts.submodules.length === 0)) {
    if (!opts.stdout) console.log('Must use either -s or -a option. For more info use the --help option');
    process.exit(1);
  }

  if (opts.submodules) {
    for (var i = 0; i < opts.submodules.length; i++) {
      var sm = opts.submodules[i];
      if (modules.indexOf(sm) === -1) throw new Error('Unknown submodule ' + sm);
    }
  }

  var bopts = {
    pack: pack,
    debug: true,
    standalone: 'bitcore',
    insertGlobals: true
  };
  var b = browserify(bopts);

  b.require(opts.dir + 'browserify-bignum/bignumber.js', {
    expose: 'bignum'
  });
  b.require(opts.dir + 'browserify-buffertools/buffertools.js', {
    expose: 'buffertools'
  });
  b.require(opts.dir + 'base58-native', {
    expose: 'base58-native'
  });
  b.require('./' + opts.dir + 'bitcore', {
    expose: 'bitcore'
  });
  modules.forEach(function(m) {
    if (opts.includeall || opts.submodules.indexOf(m) > -1) {
      if (!opts.stdout) console.log('Including ' + m + ' in the browser bundle');
      b.require('./' + opts.dir + m + '.js', {
        expose: './' + m
      });
    }
  });

  if (!opts.dontminify) {
    b.transform({
      global: true
    }, 'uglifyify');
  }

  var bundle = b.bundle();
  return bundle;
};

var createTestData = function() {
  var bopts = {
    pack: pack,
    debug: true,
    standalone: 'testdata',
    insertGlobals: true
  };
  var tb = browserify(bopts);
  tb.require('./test/testdata', {
    expose: 'testdata'
  });
  tb.transform('brfs');

  return tb.bundle();
};

if (require.main === module) {
  var list = function(val) {
    return val.split(',');
  };
  var program = require('commander');
  program
    .version('0.0.1')
    .option('-a, --includeall', 'Include all submodules.')
    .option('-d, --dontminify', 'Don\'t minify the code.')
    .option('-o, --stdout', 'Specify output as stdout')
    .option('-s, --submodules <items>', 'Include the listed comma-separated submodules.', list)
    .parse(process.argv);
  var bitcoreBundle = createBitcore(program);
  var testBundle = createTestData(program);

  testBundle.pipe(fs.createWriteStream('browser/testdata.js'));
  bitcoreBundle.pipe(program.stdout ? process.stdout : fs.createWriteStream('browser/bundle.js'));
}

module.exports.createBitcore = createBitcore;
module.exports.createTestData = createTestData;
<commit_msg>muting testdata for stdout<commit_after>'use strict';

var fs = require('fs');
var browserify = require('browserify');
var browserPack = require('browser-pack');
var exec = require('child_process').exec;
var sys = require('sys');
var puts = function(error, stdout, stderr) {
  if (error) console.log(error);
  //sys.puts(stdout);
  //sys.puts(stderr);
};

var pack = function (params) {
  var file = require.resolve('soop');
  var dir = file.substr(0, file.length - String('soop.js').length);
  var preludePath = dir + 'example/custom_prelude.js';
  params.raw = true;
  params.sourceMapPrefix = '//#';
  params.prelude = fs.readFileSync(preludePath, 'utf8');
  params.preludePath = preludePath;
  return browserPack(params);
};

var modules = [
  'Address',
  'Block',
  'Bloom',
  'Buffers.monkey',
  'Connection',
  'Deserialize',
  'Gruntfile',
  'Number.monkey',
  'Opcode',
  'Peer',
  'PeerManager',
  'PrivateKey',
  'RpcClient',
  'Key',
  'SIN',
  'SINKey',
  'Script',
  'ScriptInterpreter',
  'Sign',
  'Transaction',
  'Wallet',
  'WalletKey',
  'config',
  'const',
  'networks',
  'util/log',
  'util/util',
  'util/EncodedData',
  'util/VersionedData',
];

var createBitcore = function(opts) {

  opts.dir = opts.dir || '';

  // concat browser vendor files
  exec('cd ' + opts.dir + 'browser; sh concat.sh', puts);

  if (!opts.includeall && (!opts.submodules || opts.submodules.length === 0)) {
    if (!opts.stdout) console.log('Must use either -s or -a option. For more info use the --help option');
    process.exit(1);
  }

  if (opts.submodules) {
    for (var i = 0; i < opts.submodules.length; i++) {
      var sm = opts.submodules[i];
      if (modules.indexOf(sm) === -1) throw new Error('Unknown submodule ' + sm);
    }
  }

  var bopts = {
    pack: pack,
    debug: true,
    standalone: 'bitcore',
    insertGlobals: true
  };
  var b = browserify(bopts);

  b.require(opts.dir + 'browserify-bignum/bignumber.js', {
    expose: 'bignum'
  });
  b.require(opts.dir + 'browserify-buffertools/buffertools.js', {
    expose: 'buffertools'
  });
  b.require(opts.dir + 'base58-native', {
    expose: 'base58-native'
  });
  b.require('./' + opts.dir + 'bitcore', {
    expose: 'bitcore'
  });
  modules.forEach(function(m) {
    if (opts.includeall || opts.submodules.indexOf(m) > -1) {
      if (!opts.stdout) console.log('Including ' + m + ' in the browser bundle');
      b.require('./' + opts.dir + m + '.js', {
        expose: './' + m
      });
    }
  });

  if (!opts.dontminify) {
    b.transform({
      global: true
    }, 'uglifyify');
  }

  var bundle = b.bundle();
  return bundle;
};

var createTestData = function() {
  var bopts = {
    pack: pack,
    debug: true,
    standalone: 'testdata',
    insertGlobals: true
  };
  var tb = browserify(bopts);
  tb.require('./test/testdata', {
    expose: 'testdata'
  });
  tb.transform('brfs');

  return tb.bundle();
};

if (require.main === module) {
  var list = function(val) {
    return val.split(',');
  };
  var program = require('commander');
  program
    .version('0.0.1')
    .option('-a, --includeall', 'Include all submodules.')
    .option('-d, --dontminify', 'Don\'t minify the code.')
    .option('-o, --stdout', 'Specify output as stdout')
    .option('-s, --submodules <items>', 'Include the listed comma-separated submodules.', list)
    .parse(process.argv);
  if (!program.stdout) {
    var testBundle = createTestData(program);
    testBundle.pipe(fs.createWriteStream('browser/testdata.js'));
  }
  var bitcoreBundle = createBitcore(program);
  bitcoreBundle.pipe(program.stdout ? process.stdout : fs.createWriteStream('browser/bundle.js'));
}

module.exports.createBitcore = createBitcore;
module.exports.createTestData = createTestData;
<|endoftext|>


<commit_before>
/**
 * UI Component Drag
 * @class UI.Component.Drag
 * @author Jerome D. Vial
 */
define([

], function(

) {

	var exports = new Class({
		options: {
			resizer: {
				modifier: {
					row: {
						size: 'width',
						from: 'left',
						mode: {
							y: false
						}
					},
					column: {
						size: 'height',
						from: 'top',
						mode: {
							x: false
						}
					}
				}
			}
		},

		/**
		 * Instanciate the given object comp
		 * @param  {object]} comp list component
		 * @return {[type]}      [description]
		 */
		_initComponent: function(comp) {
			//_log('_initComponent', comp.opts.name, comp);

			// shortcuts
			comp.opts.flex = comp.opts.flex || comp.flex;
			comp.opts.hide = comp.opts.hide || comp.hide;
			comp.opts.theme = comp.opts.theme || comp.theme;

			_log('comp', comp.clss);

			var name = comp.opts.name;
			var clss = mnml.strToClss(comp.clss);

			//comp.opts.container = comp.container;
			var component = this.component[name] = this[name] = new clss(comp.opts);

			//_log(component.container);

			// register component
			this._componentRegister(name, component);

			//settings
			this._initComponentSettings(component);

			// styles and size
			this._setComponentStyles(component);
			this._setComponentDisplay(component);
			this._attachComponentEvents(component);

			//

			return component;
		},

		/**
		 * [_componentRegister description]
		 * @param  {[type]} name      [description]
		 * @param  {[type]} component [description]
		 * @return {[type]}           [description]
		 */
		_componentRegister: function(name, component) {
			//_log('_componentRegister', name, component);

			this.components = this.components || [];
			this.components.push(component);
		},

		/**
		 * [_initComponentSettings description]
		 * @param  {object} name   [description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_initComponentSettings: function(component) {
			//_log('_initcompSettings', component);

			var name = component.getName();
			var element = component.element;

		},

		/**
		 * [_initComponentSettings description]
		 * @param  {object} name   [description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_setComponentStyles: function(component) {
			//_log('_setComponentStyles', component);

			if (component.options.flex) {
				//component.element.setStyle('flex', component.options.flex);
				component.element.addClass('flex-'+component.options.flex);
			}

			if (component.options.hide) {
				component.element.setStyle('display', 'none');

			}

			if (component.options.theme) {
				component.element.addClass('theme' + '-' + component.options.theme);

			}
		},

		/**
		 * [_initSize description]
		 * @param  {[type]} name   [description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_setComponentDisplay: function(component) {
			//_log('comp opts', component.options);
			var display = 'normalized';

			var name = component.getName();
			var element = component.element;

			if (this.settings[name] && this.settings[name].display) {
				display = this.settings[name].display;
			}

			component.setDisplay(display, 'width');

			if (component.options.flex) {
				//console.log('---flex', name, component.options);
			} else {

				if (this.settings[name] && this.settings[name].width) {
					//_log('settings', name, display);
					//element.setStyle('flex', 'none');
					element.addClass('flex-none');
					if (display === 'minimized') {

						element.setStyle('width', 0);
					} else {

						if (this.settings[name].width < 32)
							this.settings[name].width = 32;

						//console.log('----', name, element);
						element.setStyle('width', this.settings[name].width || 160);
					}

					component.width = this.settings[name].width || 200;
					component._modifier = 'width';
				} else if (this.settings[name] && this.settings[name].height) {
					element.setStyle('flex', 'none');
					element.setStyle('height', this.settings[name].height);
					component.height = this.settings[name].height || 160;
					component._modifier = 'height';
				}

				this._initResizer(component);
			}
		},

		/**
		 * [_attachComponentEvents description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_attachComponentEvents: function(component) {
			var self = this;
			var name = component.getName();

			component.addEvents({
				toggled:  function() {
					//console.log('toggled');
					self.fireEvent('resize');
				},
				display: function(state) {
					//_log('display', name, state);
					self.fireEvent('display', [name, state]);
				}
			});

			this.addEvents({
				resize: function() {
					component.fireEvent('resize');
				},
				drag: function() {
					component.fireEvent('resize');
				},
				normalize: function() {
					component.fireEvent('resize');
				},
				maximize: function() {
					component.fireEvent('resize');
				},
				minimize: function() {
					component.fireEvent('resize');
				},
				device: function(device) {
					//_log('device', device);
					component.fireEvent('device', device);
				}
			});
		}
	});

	return exports;
});
<commit_msg>remove log<commit_after>
/**
 * UI Component Drag
 * @class UI.Component.Drag
 * @author Jerome D. Vial
 */
define([

], function(

) {

	var exports = new Class({
		options: {
			resizer: {
				modifier: {
					row: {
						size: 'width',
						from: 'left',
						mode: {
							y: false
						}
					},
					column: {
						size: 'height',
						from: 'top',
						mode: {
							x: false
						}
					}
				}
			}
		},

		/**
		 * Instanciate the given object comp
		 * @param  {object]} comp list component
		 * @return {[type]}      [description]
		 */
		_initComponent: function(comp) {
			//_log('_initComponent', comp.opts.name, comp);

			// shortcuts
			comp.opts.flex = comp.opts.flex || comp.flex;
			comp.opts.hide = comp.opts.hide || comp.hide;
			comp.opts.theme = comp.opts.theme || comp.theme;

			//_log('comp', comp.clss);

			var name = comp.opts.name;
			var clss = mnml.strToClss(comp.clss);

			//comp.opts.container = comp.container;
			var component = this.component[name] = this[name] = new clss(comp.opts);

			//_log(component.container);

			// register component
			this._componentRegister(name, component);

			//settings
			this._initComponentSettings(component);

			// styles and size
			this._setComponentStyles(component);
			this._setComponentDisplay(component);
			this._attachComponentEvents(component);

			//

			return component;
		},

		/**
		 * [_componentRegister description]
		 * @param  {[type]} name      [description]
		 * @param  {[type]} component [description]
		 * @return {[type]}           [description]
		 */
		_componentRegister: function(name, component) {
			//_log('_componentRegister', name, component);

			this.components = this.components || [];
			this.components.push(component);
		},

		/**
		 * [_initComponentSettings description]
		 * @param  {object} name   [description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_initComponentSettings: function(component) {
			//_log('_initcompSettings', component);

			var name = component.getName();
			var element = component.element;

		},

		/**
		 * [_initComponentSettings description]
		 * @param  {object} name   [description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_setComponentStyles: function(component) {
			//_log('_setComponentStyles', component);

			if (component.options.flex) {
				//component.element.setStyle('flex', component.options.flex);
				component.element.addClass('flex-'+component.options.flex);
			}

			if (component.options.hide) {
				component.element.setStyle('display', 'none');

			}

			if (component.options.theme) {
				component.element.addClass('theme' + '-' + component.options.theme);

			}
		},

		/**
		 * [_initSize description]
		 * @param  {[type]} name   [description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_setComponentDisplay: function(component) {
			//_log('comp opts', component.options);
			var display = 'normalized';

			var name = component.getName();
			var element = component.element;

			if (this.settings[name] && this.settings[name].display) {
				display = this.settings[name].display;
			}

			component.setDisplay(display, 'width');

			if (component.options.flex) {
				//console.log('---flex', name, component.options);
			} else {

				if (this.settings[name] && this.settings[name].width) {
					//_log('settings', name, display);
					//element.setStyle('flex', 'none');
					element.addClass('flex-none');
					if (display === 'minimized') {

						element.setStyle('width', 0);
					} else {

						if (this.settings[name].width < 32)
							this.settings[name].width = 32;

						//console.log('----', name, element);
						element.setStyle('width', this.settings[name].width || 160);
					}

					component.width = this.settings[name].width || 200;
					component._modifier = 'width';
				} else if (this.settings[name] && this.settings[name].height) {
					element.setStyle('flex', 'none');
					element.setStyle('height', this.settings[name].height);
					component.height = this.settings[name].height || 160;
					component._modifier = 'height';
				}

				this._initResizer(component);
			}
		},

		/**
		 * [_attachComponentEvents description]
		 * @param  {[type]} object [description]
		 * @return {[type]}        [description]
		 */
		_attachComponentEvents: function(component) {
			var self = this;
			var name = component.getName();

			component.addEvents({
				toggled:  function() {
					//console.log('toggled');
					self.fireEvent('resize');
				},
				display: function(state) {
					//_log('display', name, state);
					self.fireEvent('display', [name, state]);
				}
			});

			this.addEvents({
				resize: function() {
					component.fireEvent('resize');
				},
				drag: function() {
					component.fireEvent('resize');
				},
				normalize: function() {
					component.fireEvent('resize');
				},
				maximize: function() {
					component.fireEvent('resize');
				},
				minimize: function() {
					component.fireEvent('resize');
				},
				device: function(device) {
					//_log('device', device);
					component.fireEvent('device', device);
				}
			});
		}
	});

	return exports;
});
<|endoftext|>


<commit_before>/**
 * Creates a regular expression object for matching text with a @pattern {String} and optional @flags {String}.
 */
core.Main.declareNamespace("RegExp", function(pattern, flags) {

});

core.Main.addMembers("RegExp", {

	/** {=Boolean} Whether to test the regular expression against all possible matches in a string, or only against the first. */
	global: null,

	/** {=Boolean} Whether to ignore case while attempting a match in a string. */
	ignoreCase: null,

	/** {=Integer} The index at which to start the next match. */
	lastIndex: null,

	/** {=Boolean} Whether or not to search in strings across multiple lines. */
	multiline: null,

	/** {=String} The text of the pattern. */
	source: null,

	/** Executes a search for a match in its @string {String} parameter. */
	exec: function(string) {},

	/** Tests for a match in its @string {String} parameter. */
	test: function(string) {},

	/** Returns an object literal representing the specified object; you can use this value to create a new object. */
	toSource: function() {},

	/** Returns a string representing the specified object. */
	toString: function() {},

});
<commit_msg>Minor bug fixes<commit_after>/**
 * Creates a regular expression object for matching text with a @pattern {String} and optional @flags {String}.
 */
core.Main.declareNamespace("RegExp", function(pattern, flags) {

});

core.Main.addMembers("RegExp", {

	/** {=Boolean} Whether to test the regular expression against all possible matches in a string, or only against the first. */
	global: null,

	/** {=Boolean} Whether to ignore case while attempting a match in a string. */
	ignoreCase: null,

	/** {=Integer} The index at which to start the next match. */
	lastIndex: null,

	/** {=Boolean} Whether or not to search in strings across multiple lines. */
	multiline: null,

	/** {=String} The text of the pattern. */
	source: null,

	/** {Object} Executes a search for a match in its @string {String} parameter. */
	exec: function(string) {},

	/** {Boolean} Tests for a match in its @string {String} parameter. */
	test: function(string) {},

	/** {Map} Returns an object literal representing the specified object; you can use this value to create a new object. */
	toSource: function() {},

	/** {String} Returns a string representing the specified object. */
	toString: function() {}

});
<|endoftext|>


<commit_before>/* @flow */
import Benchmark from 'benchmark'
import { Chance } from 'chance'
const chance = new Chance()
import type { Message } from '../lib/types.d'
import { Range } from 'atom'
import type { TextEditor } from 'atom'
import Editor from '../dist/editor'
import { writeFile as writeFileRaw } from 'fs'
import { promisify } from 'util'
const writeFile = promisify(writeFileRaw)

/* ************************************************************************* */

function getRanomPoint(parLengths: number[]): [number, number] {
  const randomRow = chance.integer({ min: 0, max: parLengths.length })
  const randomColumn = chance.integer({ min: 0, max: parLengths[randomRow] })
  return [randomRow, randomColumn]
}

function getRandomRange(parLengths: number[]) {
  const pointsSorted = [getRanomPoint(parLengths), getRanomPoint(parLengths)].sort((p1, p2) => {
    return p1[0] - p2[0]
  })
  return Range.fromObject(pointsSorted)
}

function generateRandomMessage(
  filePath: ?string,
  range: ?Range = getRandomRange(),
  severity: ?string = chance.pickone(['error', 'warning', 'info']),
): Message {
  return {
    key: chance.unique(chance.string, 1)[0],
    version: 2,
    severity,
    excerpt: String(chance.integer()),
    location: { file: filePath, position: range },
    description: chance.sentence({ words: 20 }),
  }
}

async function getTestFile(filePath: string, numParagraphs: number = 30, numSentences: number = 10) {
  let str: string = ''
  let parLengths: number[] = new Array(numParagraphs)
  for (let i = 0; i < numParagraphs; i++) {
    const par = chance.paragraph({ sentences: numSentences })
    str = str.concat(par, '\n')
    parLengths[i] = par.length
  }
  await writeFile(filePath, str)
  return { fileLegth: str.length, parLengths }
}

/* ************************************************************************* */

describe('Editor benchmark', function () {
  let editor: Editor
  let messages: Message[]
  let textEditor: TextEditor

  beforeEach(async function () {
    // parameter
    const messageNum = 1000
    const numParagraphs = 300
    const numSentences = 10
    const filePath = './benchmark/benchmarkTestFile.txt'

    // make a test file
    const { fileLegth, parLengths } = await getTestFile(filePath, numParagraphs, numSentences)

    // get linter messages
    messages = new Array(messageNum)
    for (let i = 0; i < messageNum; i++) {
      messages[i] = generateRandomMessage(filePath, getRandomRange(parLengths))
    }

    // open the test file
    await atom.workspace.open(filePath)

    // make a linter editor instance
    textEditor = atom.workspace.getActiveTextEditor()
    editor = new Editor(textEditor)

    // Activate linter-ui-default
    atom.packages.triggerDeferredActivationHooks()
    atom.packages.triggerActivationHook('core:loaded-shell-environment')

    atom.packages.loadPackage('linter-ui-default')
  })

  describe('apply benchmark', function () {
    it('applies the messages to the editor', function () {
      expect(textEditor.getBuffer().getMarkerCount()).toBe(0)

      const ti = window.performance.now()
      editor.apply(messages, [])

      const tf = window.performance.now()

      console.log(`Applying ${messages.length} took ${(tf - ti).toFixed(3)} ms`)

      expect(textEditor.getBuffer().getMarkerCount()).toBe(messages.length)
    })
  })

  afterEach(function () {
    editor.dispose()
    atom.workspace.destroyActivePaneItem()
  })
})
<commit_msg>chore: attache dom to make benchmark realistic<commit_after>/* @flow */
import Benchmark from 'benchmark'
import { Chance } from 'chance'
const chance = new Chance()
import type { Message } from '../lib/types.d'
import { Range } from 'atom'
import type { TextEditor } from 'atom'
import Editor from '../dist/editor'
import { writeFile as writeFileRaw } from 'fs'
import { promisify } from 'util'
const writeFile = promisify(writeFileRaw)

/* ************************************************************************* */

function getRanomPoint(parLengths: number[]): [number, number] {
  const randomRow = chance.integer({ min: 0, max: parLengths.length })
  const randomColumn = chance.integer({ min: 0, max: parLengths[randomRow] })
  return [randomRow, randomColumn]
}

function getRandomRange(parLengths: number[]) {
  const pointsSorted = [getRanomPoint(parLengths), getRanomPoint(parLengths)].sort((p1, p2) => {
    return p1[0] - p2[0]
  })
  return Range.fromObject(pointsSorted)
}

function generateRandomMessage(
  filePath: ?string,
  range: ?Range = getRandomRange(),
  severity: ?string = chance.pickone(['error', 'warning', 'info']),
): Message {
  return {
    key: chance.unique(chance.string, 1)[0],
    version: 2,
    severity,
    excerpt: String(chance.integer()),
    location: { file: filePath, position: range },
    description: chance.sentence({ words: 20 }),
  }
}

async function getTestFile(filePath: string, numParagraphs: number = 30, numSentences: number = 10) {
  let str: string = ''
  let parLengths: number[] = new Array(numParagraphs)
  for (let i = 0; i < numParagraphs; i++) {
    const par = chance.paragraph({ sentences: numSentences })
    str = str.concat(par, '\n')
    parLengths[i] = par.length
  }
  await writeFile(filePath, str)
  return { fileLegth: str.length, parLengths }
}

/* ************************************************************************* */

describe('Editor benchmark', function () {
  let editor: Editor
  let messages: Message[]
  let textEditor: TextEditor

  beforeEach(async function () {
    // parameter
    const messageNum = 1000
    const numParagraphs = 300
    const numSentences = 10
    const filePath = './benchmark/benchmarkTestFile.txt'

    // make a test file
    const { fileLegth, parLengths } = await getTestFile(filePath, numParagraphs, numSentences)

    // get linter messages
    messages = new Array(messageNum)
    for (let i = 0; i < messageNum; i++) {
      messages[i] = generateRandomMessage(filePath, getRandomRange(parLengths))
    }

    // open the test file
    await atom.workspace.open(filePath)

    // make a linter editor instance
    textEditor = atom.workspace.getActiveTextEditor()
    // Attache text editor
    jasmine.attachToDOM(textEditor.getElement())

    // create linter Editor instance
    editor = new Editor(textEditor)

    // Activate linter-ui-default
    atom.packages.triggerDeferredActivationHooks()
    atom.packages.triggerActivationHook('core:loaded-shell-environment')

    atom.packages.loadPackage('linter-ui-default')
  })

  describe('apply benchmark', function () {
    it('applies the messages to the editor', function () {
      expect(textEditor.getBuffer().getMarkerCount()).toBe(0)

      const ti = window.performance.now()
      editor.apply(messages, [])

      const tf = window.performance.now()

      console.log(`Applying ${messages.length} linter messages took ${(tf - ti).toFixed(3)} ms`)

      expect(textEditor.getBuffer().getMarkerCount()).toBe(messages.length)
    })
  })

  afterEach(function () {
    editor.dispose()
    atom.workspace.destroyActivePaneItem()
  })
})
<|endoftext|>


<commit_before>'use strict';

const Fidelity = require('../lib/index.js');
const Bluebird = require('bluebird');
const PromiseModule = require('promise');
const Q = require('q');

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

function newNativePromise () {
  return new Promise((resolve, reject) => {
    resolve(getRandomInt(0, 10));
  });
}

function nativePromiseResolve () {
  return Promise.resolve(getRandomInt(0,10));
}

function fidelityPromise () {
  return Fidelity.resolve(getRandomInt(0,10));
}

function bluebirdPromise () {
  return Bluebird.resolve(getRandomInt(0,10));
}

function QPromise () {
  return Q(getRandomInt(0,10));
}

function PromiseModuleResolve () {
  return PromiseModule.resolve(getRandomInt(0,10));
}

function runBenchmarks () {
  exports.compare = {
    "new Promise()" : function (done) {
      newNativePromise().then(done);
    },
    "native Promise.resolve" : function (done) {
      nativePromiseResolve().then(done);
    },
    "Fidelity.resolve" : function(done) {
      fidelityPromise().then(done);
    },
    "Bluebird.resolve" : function (done) {
      bluebirdPromise().then(done);
    },
    "Q()" : function (done) {
      QPromise().then(done);
    },
    "PromiseModule.resolve" : function (done) {
      PromiseModuleResolve().then(done);
    }
  };

  exports.time = 1000;
  require('bench').runMain();
}
runBenchmarks();

<commit_msg>Add a couple of tests to the benchmark.<commit_after>'use strict';

const Fidelity = require('../lib/index.js');
const Bluebird = require('bluebird');
const PromiseModule = require('promise');
const Q = require('q');

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

function newNativePromise () {
  return new Promise((resolve, reject) => {
    resolve(getRandomInt(0, 10));
  });
}

function nativePromiseResolve () {
  return Promise.resolve(getRandomInt(0,10));
}

function fidelityResolve () {
  return Fidelity.resolve(getRandomInt(0,10));
}

function fidelityPromise () {
  return Fidelity.promise((resolve, reject) => {
    resolve(getRandomInt(0,10));
  });
}

function bluebirdPromise () {
  return Bluebird.resolve(getRandomInt(0,10));
}

function QPromise () {
  return Q(getRandomInt(0,10));
}

function PromiseModuleResolve () {
  return PromiseModule.resolve(getRandomInt(0,10));
}

function PromiseModuleNewPromise () {
  return new PromiseModule((resolve, reject) => {
    resolve(getRandomInt(0,10));
  });
}

function runBenchmarks () {
  exports.compare = {
    "new Promise()" : function (done) {
      newNativePromise().then(done);
    },
    "native Promise.resolve" : function (done) {
      nativePromiseResolve().then(done);
    },
    "Fidelity.promise" : function(done) {
      fidelityPromise().then(done);
    },
    "Fidelity.resolve" : function(done) {
      fidelityResolve().then(done);
    },
    "Bluebird.resolve" : function (done) {
      bluebirdPromise().then(done);
    },
    "Q()" : function (done) {
      QPromise().then(done);
    },
    "PromiseModule.resolve" : function (done) {
      PromiseModuleResolve().then(done);
    },
    "new PromiseModule()" : function (done) {
      PromiseModuleNewPromise().then(done);
    }
  };

  exports.time = 1000;
  require('bench').runMain();
}
runBenchmarks();

<|endoftext|>