<commit_before>
var rbush = function (maxFill) {
	if (!(this instanceof rbush)) {
		return new rbush(maxFill);
	}
	this._maxFill = maxFill || 6;
};

rbush.prototype = {

	// redefine the next 3 methods to suit your data format

	// compare functions for sorting by x and y coordinate
	sortX: function (a, b) { return a[0] > b[0] ? 1 : -1; },
	sortY: function (a, b) { return a[1] > b[1] ? 1 : -1; },

	// get bounding box in the form of [minX, minY, maxX, maxY] given a data item
	toBBox: function (a) { return a; },

	// recursively search for objects in a given bbox
	search: function (bbox) {
		var result = [];
		this._search(bbox, this.data, result);
		return result;
	},

	// bulk load all data and recursively build the tree from stratch
	load: function (data) {
		this.data = {};
		this.data.children = [];

		this._buildFromTop(data);
		this._calcBBoxes(this.data);

		return this;
	},

	// bulk load data with the OMT algorithm
	_buildFromTop: function (data) {

		var N = data.length,           // number of items
		    S = this._numTopSlices(N), // number of slices for levels 0 and 1
		    N1 = Math.ceil(N / S),     // size of each root node
		    N2 = Math.ceil(N1 / S),    // size of each node of the next level after root

		    items = data.slice().sort(this.sortX),
		    i, j, slice, node;

		// create S x S nodes for the root and build the rest recursively
		for (i = 0; i < N; i += N1) {
			slice = items.slice(i, i + N1).sort(this.sortY);

			for (j = 0; j < N1; j += N2) {
				node = this._build(slice.slice(j, j + N2), 1);
				this.data.children.push(node);
			}
		}
	},

	_build: function (items, level) {

		var node = {},
		    len = items.length,
		    k = Math.ceil(len / this._maxFill), // size of each child node
		    i, childNode;

		if (k < 2) {
			node.children = items;
			node.leaf = true;
			return node;
		}

		// split by different plane each time - x, y, x, y, etc.
		items.sort(level % 2 ? this.sortX : this.sortY);

		node.children = [];

		for (i = 0; i < len; i += k) {
			childNode = this._build(items.slice(i, i + k), level + 1);
			node.children.push(childNode);
		}

		return node;
	},

	// recursively calculate all node bboxes in the tree
	_calcBBoxes: function (node) {

		node.bbox = [Infinity, Infinity, -Infinity, -Infinity];

		for (var i = 0, len = node.children.length, child; i < len; i++) {
			child = node.children[i];

			if (node.leaf) {
				this._extend(node.bbox, this.toBBox(child));
			} else {
				this._calcBBoxes(child);
				this._extend(node.bbox, child.bbox);
			}
		}
	},

	_numTopSlices: function (N) {

		var M = this._maxFill,                             // max number of branches in one node
		    h = Math.ceil(Math.log(N) / Math.log(M)),      // target height of the tree
		    Ns = Math.pow(M, h - 1),                       // max number of tree nodes
		    S = Math.floor(Math.sqrt(Math.ceil(N / Ns)));  // target number of level 0-1 branches

		return Math.max(S, 2);
	},

	_search: function (bbox, node, result) {

		if (!this._intersects(bbox, node.bbox)) { return; }

		var i, child,
		    len = node.children.length;

		for (i = 0; i < len; i++) {
			child = node.children[i];

			if (!node.leaf) {
				this._search(bbox, child, result);
			} else if (this._contains(bbox, this.toBBox(child))) {
				result.push(child);
			}
		}
	},

	_intersects: function (bbox, bbox2) {
		return bbox2[0] <= bbox[2] &&
		       bbox2[1] <= bbox[3] &&
		       bbox2[2] >= bbox[0] &&
		       bbox2[3] >= bbox[1];
	},

	_contains: function (bbox, bbox2) {
		return bbox2[0] >= bbox[0] &&
		       bbox2[1] >= bbox[1] &&
		       bbox2[2] <= bbox[2] &&
		       bbox2[3] <= bbox[3];
	},

	_extend: function (bbox, bbox2) {
		bbox[0] = Math.min(bbox[0], bbox2[0]);
		bbox[1] = Math.min(bbox[1], bbox2[1]);
		bbox[2] = Math.max(bbox[2], bbox2[2]);
		bbox[3] = Math.max(bbox[3], bbox2[3]);
	}
};

if (typeof module !== 'undefined') {
	module.exports = rbush;
}
<commit_msg>convert to spaces, add wrapper fn, use strict<commit_after>(function () { 'use strict';

var rbush = function (maxFill) {
    if (!(this instanceof rbush)) {
        // jshint newcap: false
        return new rbush(maxFill);
    }
    this._maxFill = maxFill || 6;
};

rbush.prototype = {

    // redefine the next 3 methods to suit your data format

    // compare functions for sorting by x and y coordinate
    sortX: function (a, b) { return a[0] > b[0] ? 1 : -1; },
    sortY: function (a, b) { return a[1] > b[1] ? 1 : -1; },

    // get bounding box in the form of [minX, minY, maxX, maxY] given a data item
    toBBox: function (a) { return a; },

    // recursively search for objects in a given bbox
    search: function (bbox) {
        var result = [];
        this._search(bbox, this.data, result);
        return result;
    },

    // bulk load all data and recursively build the tree from stratch
    load: function (data) {
        this.data = {};
        this.data.children = [];

        this._buildFromTop(data);
        this._calcBBoxes(this.data);

        return this;
    },

    // bulk load data with the OMT algorithm
    _buildFromTop: function (data) {

        var N = data.length,           // number of items
            S = this._numTopSlices(N), // number of slices for levels 0 and 1
            N1 = Math.ceil(N / S),     // size of each root node
            N2 = Math.ceil(N1 / S),    // size of each node of the next level after root

            items = data.slice().sort(this.sortX),
            i, j, slice, node;

        // create S x S nodes for the root and build the rest recursively
        for (i = 0; i < N; i += N1) {
            slice = items.slice(i, i + N1).sort(this.sortY);

            for (j = 0; j < N1; j += N2) {
                node = this._build(slice.slice(j, j + N2), 1);
                this.data.children.push(node);
            }
        }
    },

    _build: function (items, level) {

        var node = {},
            len = items.length,
            k = Math.ceil(len / this._maxFill), // size of each child node
            i, childNode;

        if (k < 2) {
            node.children = items;
            node.leaf = true;
            return node;
        }

        // split by different plane each time - x, y, x, y, etc.
        items.sort(level % 2 ? this.sortX : this.sortY);

        node.children = [];

        for (i = 0; i < len; i += k) {
            childNode = this._build(items.slice(i, i + k), level + 1);
            node.children.push(childNode);
        }

        return node;
    },

    // recursively calculate all node bboxes in the tree
    _calcBBoxes: function (node) {

        node.bbox = [Infinity, Infinity, -Infinity, -Infinity];

        for (var i = 0, len = node.children.length, child; i < len; i++) {
            child = node.children[i];

            if (node.leaf) {
                this._extend(node.bbox, this.toBBox(child));
            } else {
                this._calcBBoxes(child);
                this._extend(node.bbox, child.bbox);
            }
        }
    },

    _numTopSlices: function (N) {

        var M = this._maxFill,                             // max number of branches in one node
            h = Math.ceil(Math.log(N) / Math.log(M)),      // target height of the tree
            Ns = Math.pow(M, h - 1),                       // max number of tree nodes
            S = Math.floor(Math.sqrt(Math.ceil(N / Ns)));  // target number of level 0-1 branches

        return Math.max(S, 2);
    },

    _search: function (bbox, node, result) {

        if (!this._intersects(bbox, node.bbox)) { return; }

        var i, child,
            len = node.children.length;

        for (i = 0; i < len; i++) {
            child = node.children[i];

            if (!node.leaf) {
                this._search(bbox, child, result);
            } else if (this._contains(bbox, this.toBBox(child))) {
                result.push(child);
            }
        }
    },

    _intersects: function (bbox, bbox2) {
        return bbox2[0] <= bbox[2] &&
               bbox2[1] <= bbox[3] &&
               bbox2[2] >= bbox[0] &&
               bbox2[3] >= bbox[1];
    },

    _contains: function (bbox, bbox2) {
        return bbox2[0] >= bbox[0] &&
               bbox2[1] >= bbox[1] &&
               bbox2[2] <= bbox[2] &&
               bbox2[3] <= bbox[3];
    },

    _extend: function (bbox, bbox2) {
        bbox[0] = Math.min(bbox[0], bbox2[0]);
        bbox[1] = Math.min(bbox[1], bbox2[1]);
        bbox[2] = Math.max(bbox[2], bbox2[2]);
        bbox[3] = Math.max(bbox[3], bbox2[3]);
    }
};

if (typeof module !== 'undefined') {
    module.exports = rbush;
} else {
    window.rbush = rbush;
}

})();
<|endoftext|>


<commit_before>/* eslint sort-keys: ["error", "asc"], quote-props: ["error", "consistent"] */
/* eslint-disable sort-keys */

module.exports = {
    plugins: [
        "react"
    ],
    extends: [
        "plugin:import/react"
    ],
    rules: {
        /* eslint-enable sort-keys */
        "no-nested-ternary": "off", // nested ternaries can increase the readability of JSX components
        "react/display-name": "error",
        "react/forbid-component-props": "off",
        "react/jsx-boolean-value": "off",
        "react/jsx-closing-bracket-location": ["error", "line-aligned"],
        "react/jsx-curly-spacing": ["error", "never"],
        "react/jsx-equals-spacing": ["error", "never"],
        "react/jsx-filename-extension": "off",
        "react/jsx-first-prop-new-line": ["error", "multiline"],
        "react/jsx-handler-names": ["error", {
            eventHandlerPrefix: "handle",
            eventHandlerPropPrefix: "on"
        }],
        "react/jsx-indent": ["error", 4],
        "react/jsx-indent-props": ["error", 4],
        "react/jsx-key": "error",
        "react/jsx-max-props-per-line": ["error", {
            maximum: 4,
        }],
        "react/jsx-no-bind": ["error", {
            allowArrowFunctions: false,
            allowBind: false,
            ignoreRefs: false
        }],
        "react/jsx-no-comment-textnodes": "error",
        "react/jsx-no-duplicate-props": ["error", {
            ignoreCase: true,
        }],
        "react/jsx-no-target-blank": "error",
        "react/jsx-no-undef": "error",
        "react/jsx-pascal-case": "error",
        "react/jsx-sort-props": "off",
        "react/jsx-tag-spacing": ["error", {
            "afterOpening": "never",
            "beforeSelfClosing": "always",
            "closingSlash": "never",
        }],
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
        "react/jsx-wrap-multilines": "error",
        "react/no-children-prop": "error",
        "react/no-danger": "error",
        "react/no-danger-with-children": "error",
        "react/no-deprecated": "error",
        "react/no-did-mount-set-state": ["error", "disallow-in-func"],
        "react/no-did-update-set-state": ["error", "disallow-in-func"],
        "react/no-direct-mutation-state": "error",
        "react/no-find-dom-node": "error",
        "react/no-is-mounted": "error",
        'react/no-multi-comp': ["error", { ignoreStateless: true }],
        "react/no-render-return-value": "error",
        "react/no-set-state": "error",
        "react/no-string-refs": "error",
        "react/no-unescaped-entities": "error",
        "react/no-unknown-property": "error",
        "react/no-unused-prop-types": "error",
        "react/prefer-es6-class": "error",
        "react/prefer-stateless-function": "error",
        "react/prop-types": "error",
        "react/react-in-jsx-scope": "error",
        "react/require-render-return": "error",
        "react/self-closing-comp": "error",
        "react/sort-comp": "off",
        "react/sort-prop-types": "off",
        "react/style-prop-object": "off"
    }
};
<commit_msg>feat: Relax react rules<commit_after>/* eslint sort-keys: ["error", "asc"], quote-props: ["error", "consistent"] */
/* eslint-disable sort-keys */

module.exports = {
    plugins: [
        "react"
    ],
    extends: [
        "plugin:import/react"
    ],
    rules: {
        /* eslint-enable sort-keys */
        // Allow certain react methods to have no this
        // See https://github.com/peerigon/eslint-config-peerigon/issues/12
        "class-methods-use-this": ["warn", {
            "exceptMethods": [
                "render",
                "getInitialState",
                "getDefaultProps",
                "getChildContext",
                "shouldComponentUpdate",
            ],
        }],
        "no-nested-ternary": "off", // nested ternaries can increase the readability of JSX components
        "react/display-name": "error",
        "react/forbid-component-props": "off",
        "react/jsx-boolean-value": "off",
        "react/jsx-closing-bracket-location": ["error", "line-aligned"],
        "react/jsx-curly-spacing": ["error", "never"],
        "react/jsx-equals-spacing": ["error", "never"],
        "react/jsx-filename-extension": "off",
        "react/jsx-first-prop-new-line": ["error", "multiline"],
        "react/jsx-handler-names": ["error", {
            eventHandlerPrefix: "handle",
            eventHandlerPropPrefix: "on"
        }],
        "react/jsx-indent": ["error", 4],
        "react/jsx-indent-props": ["error", 4],
        "react/jsx-key": "error",
        "react/jsx-max-props-per-line": ["error", {
            maximum: 4,
        }],
        "react/jsx-no-bind": ["error", {
            allowArrowFunctions: false,
            allowBind: false,
            ignoreRefs: false
        }],
        "react/jsx-no-comment-textnodes": "error",
        "react/jsx-no-duplicate-props": ["error", {
            ignoreCase: true,
        }],
        "react/jsx-no-target-blank": "error",
        "react/jsx-no-undef": "error",
        "react/jsx-pascal-case": "error",
        "react/jsx-sort-props": "off",
        "react/jsx-tag-spacing": ["error", {
            "afterOpening": "never",
            "beforeSelfClosing": "always",
            "closingSlash": "never",
        }],
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
        "react/jsx-wrap-multilines": "error",
        "react/no-children-prop": "error",
        "react/no-danger": "error",
        "react/no-danger-with-children": "error",
        "react/no-deprecated": "error",
        "react/no-did-mount-set-state": ["error", "disallow-in-func"],
        "react/no-did-update-set-state": ["error", "disallow-in-func"],
        "react/no-direct-mutation-state": "error",
        "react/no-find-dom-node": "error",
        "react/no-is-mounted": "error",
        'react/no-multi-comp': ["error", { ignoreStateless: true }],
        "react/no-render-return-value": "error",
        "react/no-set-state": "error",
        "react/no-string-refs": "error",
        "react/no-unescaped-entities": "error",
        "react/no-unknown-property": "error",
        "react/no-unused-prop-types": "error",
        "react/prefer-es6-class": "error",
        "react/prefer-stateless-function": "warn",
        "react/prop-types": "error",
        "react/react-in-jsx-scope": "off",
        "react/require-render-return": "error",
        "react/self-closing-comp": "error",
        "react/sort-comp": "off",
        "react/sort-prop-types": "off",
        "react/style-prop-object": "off"
    }
};
<|endoftext|>


<commit_before>module.exports = {

  "extends": [
    "./browser.js"
  ],

  "plugins": [
    "react",
    "import",
    "jsx-a11y"
  ],

  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true,
      "experimentalObjectRestSpread": true
    }
  },

  // View link below for react rules documentation
  // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
  "rules": {

    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    "react/display-name": [0, { "ignoreTranspilerName": false }],
    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    "react/forbid-prop-types": [0, { "forbid": ["any", "array", "object"] }],
    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    "react/jsx-boolean-value": [2, "never"],
    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    "react/jsx-closing-bracket-location": [2, "line-aligned"],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    "react/jsx-curly-spacing": [0, "never", { "allowMultiline": true }],
    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    "react/jsx-handler-names": [0, {
      "eventHandlerPrefix": "handle",
      "eventHandlerPropPrefix": "on",
    }],
    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    "react/jsx-indent-props": [2, 2],
    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    "react/jsx-key": 0,
    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    "react/jsx-max-props-per-line": [0, { "maximum": 1 }],
    // Prevent usage of .bind() and arrow functions in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    "react/jsx-no-bind": 2,
    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    "react/jsx-no-duplicate-props": [0, { "ignoreCase": false }],
    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    "react/jsx-no-literals": 0,
    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    "react/jsx-no-undef": 2,
    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    "react/jsx-pascal-case": 0,
    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md
    "react/sort-prop-types": [0, {
      "ignoreCase": false,
      "callbacksLast": false,
    }],
    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    "react/jsx-sort-props": [0, {
      "ignoreCase": false,
      "callbacksLast": false,
    }],
    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    "react/jsx-uses-react": 2,
    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    "react/jsx-uses-vars": 2,
    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    "react/no-danger": 0,
    // Prevent usage of deprecated methods
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md
    "react/no-deprecated": 1,
    // Prevent usage of setState in componentDidMount
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
    "react/no-did-mount-set-state": 2,
    // Prevent usage of setState in componentDidUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
    "react/no-did-update-set-state": 2,
    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    "react/no-direct-mutation-state": 0,
    // Prevent usage of isMounted
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
    "react/no-is-mounted": 2,
    // Prevent multiple component definition per file
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
    "react/no-multi-comp": [2, { "ignoreStateless": true }],
    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    "react/no-set-state": 0,
    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    "react/no-string-refs": 0,
    // Prevent usage of unknown DOM property
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
    "react/no-unknown-property": 2,
    // Require ES6 class declarations over React.createClass
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
    "react/prefer-es6-class": [2, "always"],
    // Prevent missing props validation in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
    "react/prop-types": [2, { "ignore": [], "customValidators": [] }],
    // Prevent missing React when using JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
    "react/react-in-jsx-scope": 2,
    // Restrict file extensions that may be required
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-extension.md
    "react/require-extension": [0, { "extensions": [".jsx"] }],
    // Prevent extra closing tags for components without children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
    "react/self-closing-comp": 2,
    // Enforce spaces before the closing bracket of self-closing JSX elements
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md
    "react/jsx-space-before-closing": [2, "always"],

    // Prevent variables used in JSX to be incorrectly marked as unused (jsx-uses-vars)
    //
    "react/jsx-uses-vars": 2,

    // Enforce component methods order
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
    "react/sort-comp": [2, {
      "order": [
        "static-methods",
        "lifecycle",
        "/^on.+$/",
        "/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/",
        "everything-else",
        "/^render.+$/",
        "render"
      ]
    }],
    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/wrap-multilines.md
    "react/jsx-wrap-multilines": [2, {
      declaration: true,
      assignment: true,
      return: true
    }],

    // https://github.com/benmosher/eslint-plugin-import/tree/master/docs/rules
    'import/first': 'error',
    'import/no-amd': 'error',
    'import/no-webpack-loader-syntax': 'error',

    // https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules
    'jsx-a11y/accessible-emoji': 'warn',
    'jsx-a11y/alt-text': 'warn',
    'jsx-a11y/anchor-has-content': 'warn',
    'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
    'jsx-a11y/aria-props': 'warn',
    'jsx-a11y/aria-proptypes': 'warn',
    'jsx-a11y/aria-role': 'warn',
    'jsx-a11y/aria-unsupported-elements': 'warn',
    'jsx-a11y/heading-has-content': 'warn',
    'jsx-a11y/href-no-hash': 'warn',
    'jsx-a11y/iframe-has-title': 'warn',
    'jsx-a11y/img-redundant-alt': 'warn',
    'jsx-a11y/no-access-key': 'warn',
    'jsx-a11y/no-distracting-elements': 'warn',
    'jsx-a11y/no-redundant-roles': 'warn',
    'jsx-a11y/role-has-required-aria-props': 'warn',
    'jsx-a11y/role-supports-aria-props': 'warn',
    'jsx-a11y/scope': 'warn'

  }

}
<commit_msg>remove deprecated react rule<commit_after>module.exports = {

  "extends": [
    "./browser.js"
  ],

  "plugins": [
    "react",
    "import",
    "jsx-a11y"
  ],

  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true,
      "experimentalObjectRestSpread": true
    }
  },

  // View link below for react rules documentation
  // https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules
  "rules": {

    // Prevent missing displayName in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md
    "react/display-name": [0, { "ignoreTranspilerName": false }],
    // Forbid certain propTypes (any, array, object)
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md
    "react/forbid-prop-types": [0, { "forbid": ["any", "array", "object"] }],
    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    "react/jsx-boolean-value": [2, "never"],
    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    "react/jsx-closing-bracket-location": [2, "line-aligned"],
    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    "react/jsx-curly-spacing": [0, "never", { "allowMultiline": true }],
    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    "react/jsx-handler-names": [0, {
      "eventHandlerPrefix": "handle",
      "eventHandlerPropPrefix": "on",
    }],
    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    "react/jsx-indent-props": [2, 2],
    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    "react/jsx-key": 0,
    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    "react/jsx-max-props-per-line": [0, { "maximum": 1 }],
    // Prevent usage of .bind() and arrow functions in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    "react/jsx-no-bind": 2,
    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    "react/jsx-no-duplicate-props": [0, { "ignoreCase": false }],
    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    "react/jsx-no-literals": 0,
    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    "react/jsx-no-undef": 2,
    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    "react/jsx-pascal-case": 0,
    // Enforce propTypes declarations alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md
    "react/sort-prop-types": [0, {
      "ignoreCase": false,
      "callbacksLast": false,
    }],
    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    "react/jsx-sort-props": [0, {
      "ignoreCase": false,
      "callbacksLast": false,
    }],
    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    "react/jsx-uses-react": 2,
    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    "react/jsx-uses-vars": 2,
    // Prevent usage of dangerous JSX properties
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-danger.md
    "react/no-danger": 0,
    // Prevent usage of deprecated methods
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md
    "react/no-deprecated": 1,
    // Prevent usage of setState in componentDidMount
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md
    "react/no-did-mount-set-state": 2,
    // Prevent usage of setState in componentDidUpdate
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md
    "react/no-did-update-set-state": 2,
    // Prevent direct mutation of this.state
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md
    "react/no-direct-mutation-state": 0,
    // Prevent usage of isMounted
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
    "react/no-is-mounted": 2,
    // Prevent multiple component definition per file
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md
    "react/no-multi-comp": [2, { "ignoreStateless": true }],
    // Prevent usage of setState
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-set-state.md
    "react/no-set-state": 0,
    // Prevent using string references
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md
    "react/no-string-refs": 0,
    // Prevent usage of unknown DOM property
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md
    "react/no-unknown-property": 2,
    // Require ES6 class declarations over React.createClass
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md
    "react/prefer-es6-class": [2, "always"],
    // Prevent missing props validation in a React component definition
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prop-types.md
    "react/prop-types": [2, { "ignore": [], "customValidators": [] }],
    // Prevent missing React when using JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md
    "react/react-in-jsx-scope": 2,
    // Restrict file extensions that may be required
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/require-extension.md
    "react/require-extension": [0, { "extensions": [".jsx"] }],
    // Prevent extra closing tags for components without children
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md
    "react/self-closing-comp": 2,

    // Prevent variables used in JSX to be incorrectly marked as unused (jsx-uses-vars)
    //
    "react/jsx-uses-vars": 2,

    // Enforce component methods order
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/sort-comp.md
    "react/sort-comp": [2, {
      "order": [
        "static-methods",
        "lifecycle",
        "/^on.+$/",
        "/^(get|set)(?!(InitialState$|DefaultProps$|ChildContext$)).+$/",
        "everything-else",
        "/^render.+$/",
        "render"
      ]
    }],
    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/wrap-multilines.md
    "react/jsx-wrap-multilines": [2, {
      declaration: true,
      assignment: true,
      return: true
    }],

    // https://github.com/benmosher/eslint-plugin-import/tree/master/docs/rules
    'import/first': 'error',
    'import/no-amd': 'error',
    'import/no-webpack-loader-syntax': 'error',

    // https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules
    'jsx-a11y/accessible-emoji': 'warn',
    'jsx-a11y/alt-text': 'warn',
    'jsx-a11y/anchor-has-content': 'warn',
    'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
    'jsx-a11y/aria-props': 'warn',
    'jsx-a11y/aria-proptypes': 'warn',
    'jsx-a11y/aria-role': 'warn',
    'jsx-a11y/aria-unsupported-elements': 'warn',
    'jsx-a11y/heading-has-content': 'warn',
    'jsx-a11y/href-no-hash': 'warn',
    'jsx-a11y/iframe-has-title': 'warn',
    'jsx-a11y/img-redundant-alt': 'warn',
    'jsx-a11y/no-access-key': 'warn',
    'jsx-a11y/no-distracting-elements': 'warn',
    'jsx-a11y/no-redundant-roles': 'warn',
    'jsx-a11y/role-has-required-aria-props': 'warn',
    'jsx-a11y/role-supports-aria-props': 'warn',
    'jsx-a11y/scope': 'warn'

  }

}
<|endoftext|>


<commit_before>var con  = require('./database').connection;

module.exports = {
	isLoggedIn:function(req,res,next){
		if (req.isAuthenticated()){
      return next();
		}else{
      res.redirect('/login');
    }
	},

  isAdmin:function(req,res,next){
    if (req.isAuthenticated()){
      con.query("SELECT * FROM admins WHERE email=?",[req.user.email],
        function(error, row){
          if (row !== undefined && row.length > 0){
            req.user.isAdmin = true;
            req.user.isStudent = false;
            req.user.isTeacher = true;
            req.user.local = row;
            return next();
          }else{
            res.redirect('/student');
          }
        }
      );
    }else{
      res.redirect('/auth/google');
    }

  },

  isStudent:function(req,res,next){
    if (req.isAuthenticated()){
      con.query("SELECT * FROM students WHERE email=?",[req.user.email],
        function(error, row){
          if (row !== undefined && row.length > 0){
            // TODO: should run a query to verify if this student is also an admin
            req.user.isAdmin = false;
            req.user.isStudent = true;
            req.user.isTeacher = false;
            req.user.local = row;
            return next();
          }else{
            res.redirect('/teacher');
          }
        }
      );
    }else{
      res.redirect('/auth/google');
    }
  },

  isTeacher:function(req,res,next){
    console.log("TEACHER AUTH");
    if (req.isAuthenticated()){
      con.query("SELECT * FROM teachers WHERE teacher_email=?",[req.user.email],function(error,row){
        console.log("ROW");
        console.log(row);
        if (row !== undefined && row.length > 0){
          console.log("SUCCESS!");
          // TODO should run a query to verify if this teacher is also an admin
          req.user.isAdmin = false;
          req.user.isStudent = false;
          req.user.isTeacher = true;
          req.user.local = row;
          return next();
        }else{
          console.log("FAIL
          res.redirect('/student');
        }
      });
    }else{
      res.redirect('/auth/google');
    }
  }

 }
<commit_msg>testing<commit_after>var con  = require('./database').connection;

module.exports = {
	isLoggedIn:function(req,res,next){
		if (req.isAuthenticated()){
      return next();
		}else{
      res.redirect('/login');
    }
	},

  isAdmin:function(req,res,next){
    if (req.isAuthenticated()){
      con.query("SELECT * FROM admins WHERE email=?",[req.user.email],
        function(error, row){
          if (row !== undefined && row.length > 0){
            req.user.isAdmin = true;
            req.user.isStudent = false;
            req.user.isTeacher = true;
            req.user.local = row;
            return next();
          }else{
            res.redirect('/student');
          }
        }
      );
    }else{
      res.redirect('/auth/google');
    }

  },

  isStudent:function(req,res,next){
    if (req.isAuthenticated()){
      con.query("SELECT * FROM students WHERE email=?",[req.user.email],
        function(error, row){
          if (row !== undefined && row.length > 0){
            // TODO: should run a query to verify if this student is also an admin
            req.user.isAdmin = false;
            req.user.isStudent = true;
            req.user.isTeacher = false;
            req.user.local = row;
            return next();
          }else{
            res.redirect('/teacher');
          }
        }
      );
    }else{
      res.redirect('/auth/google');
    }
  },

  isTeacher:function(req,res,next){
    console.log("TEACHER AUTH");
    if (req.isAuthenticated()){
      con.query("SELECT * FROM teachers WHERE teacher_email=?",[req.user.email],function(error,row){
        console.log("ROW");
        console.log(row);
        if (row !== undefined && row.length > 0){
          console.log("SUCCESS!");
          // TODO should run a query to verify if this teacher is also an admin
          req.user.isAdmin = false;
          req.user.isStudent = false;
          req.user.isTeacher = true;
          req.user.local = row;
          return next();
        }else{
          console.log("FAIL");
          res.redirect('/student');
        }
      });
    }else{
      res.redirect('/auth/google');
    }
  }

 }
<|endoftext|>


<commit_before>var RomanNumber = function(value) {
    obj = Object.create(RomanNumber.prototype);
    obj.value = value;

    obj.decimal = null;
    obj.roman = null;

    obj.symtable = {
        'M'  : 1000,
        'CM' :  900,
        'D'  :  500,
        'CD' :  400,
        'C'  :  100,
        'XC' :   90,
        'L'  :   50,
        'XL' :   40,
        'X'  :   10,
        'IX' :    9,
        'V'  :    5,
        'IV' :    4,
        'I'  :    1
    };

    // validate the input
    obj.validateInput(value);

    return obj;
};

RomanNumber.prototype = {
    validateInput: function() {
        if (this.value == null || this.value.length === 0) {
            throw new Error("value required");
        };
        if (this.isDecimal()) {
            if (this.value < 1 || this.value > 3999) {
                throw new Error("invalid range");
            };
            // this.value is a valid decimal number
            this.decimal = this.value;
        } else if (this.isRoman()) {
            // this.value is a valid roman number
            this.roman = this.value;
        }
        else {
            throw new Error("invalid value");
        }
    },

    isDecimal: function() {
        return +this.value === +this.value;
    },

    isRoman: function() {
        if (this.isDecimal()) {
            return false;
        }

        var i = 0;
        while (i < this.value.length) {
            if (i+2 <= this.value.length &&
                this.value.substring(i, i+2) in this.symtable) {
                i += 2;
            } else if (this.value.substring(i, i+1) in this.symtable) {
                i += 1;
            } else {
                return false;
            }
        }

        // FIXME: more than three consecutive copies of the same letter are not allowed

        return true;
    },

    toInt: function() {
        if (this.decimal) {
            return this.decimal;
        };
        return 'not-implemented';
    },

    toString: function() {
        if (this.roman) {
            return this.roman;
        };
        return 'not-implemented';
    }
};

// tests
var testObjs = [
        null, '', 0, 1, 3, 4, 5,
        'I', 'III', 'IIII', 'IV', 'V',
        1968, '1473', 2999, 3000, 10000,
        'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MCMLXXX',
        'MMMMCMXCIX', 'MMMMDMXCIX'
    ],

    isEqual = function(str1, str2) {
        return str1 === str2 ? 'Yes' : 'False';
    },

    testRoman = function() {
        var romanNumber1 = new RomanNumber('XX');
        var romanNumber2 = new RomanNumber(40);

        console.log(romanNumber1.isRoman());  // => true
        console.log(romanNumber1.toInt());  // => 20
        console.log(romanNumber1.toString());  // => 'XX'
        console.log(romanNumber2.isRoman());  // => false
        console.log(romanNumber2.toInt());  // => 40
        console.log(romanNumber2.toString());  // => 'XL'

        testObjs.forEach(function(str) {
            try {
                num = new RomanNumber(str);
                if (num.isDecimal()) {
                    var d = num.toInt();
                    console.log('Is "%s" equal to "%s"?', str, d, isEqual(str, d));
                }
                else {
                    console.log('%s is not an arabic number, not yet implemented', str);
                }
            }
            catch(e) {
                console.log(e.name + ': ' + e.message + ' (%s)', str);
            }
        });
    };

testRoman();
<commit_msg>roman: implement the toString() method<commit_after>var RomanNumber = function(value) {
    obj = Object.create(RomanNumber.prototype);
    obj.value = value;

    obj.decimal = null;
    obj.roman = null;

    obj.symtable = {
        'M'  : 1000,
        'CM' :  900,
        'D'  :  500,
        'CD' :  400,
        'C'  :  100,
        'XC' :   90,
        'L'  :   50,
        'XL' :   40,
        'X'  :   10,
        'IX' :    9,
        'V'  :    5,
        'IV' :    4,
        'I'  :    1
    };

    // validate the input
    obj.validateInput(value);

    return obj;
};

RomanNumber.prototype = {
    validateInput: function() {
        if (this.value == null || this.value.length === 0) {
            throw new Error("value required");
        };
        if (this.isDecimal()) {
            if (this.value < 1 || this.value > 3999) {
                throw new Error("invalid range");
            };
            // this.value is a valid decimal number
            this.decimal = this.value;
        } else if (this.isRoman()) {
            // this.value is a valid roman number
            this.roman = this.value;
        }
        else {
            throw new Error("invalid value");
        }
    },

    isDecimal: function() {
        return +this.value === +this.value;
    },

    isRoman: function() {
        if (this.isDecimal()) {
            return false;
        }

        var i = 0;
        while (i < this.value.length) {
            if (i+2 <= this.value.length &&
                this.value.substring(i, i+2) in this.symtable) {
                i += 2;
            } else if (this.value.substring(i, i+1) in this.symtable) {
                i += 1;
            } else {
                return false;
            }
        }

        // FIXME: more than three consecutive copies of the same letter are not allowed

        return true;
    },

    toInt: function() {
        if (this.decimal) {
            return this.decimal;
        };
        return 'not-implemented';
    },

    toString: function() {
        if (this.roman) {
            return this.roman;
        };

        var residous = this.value,
            result = '';

        while (residous > 0) {
            for (var s in this.symtable) {
                if (residous >= this.symtable[s]) {
                    residous %= this.symtable[s];
                    result += s;
                    break;
                }
            }
        }

        return result;
    }
};

// tests
var testObjs = [
        null, '', 0, 1, 3, 4, 5,
        'I', 'III', 'IIII', 'IV', 'V',
        1968, '1473', 2999, 3000, 10000,
        'CDXXIX', 'CD1X', 'error', 'MCDLXXXII', 'MCMLXXX',
        'MMMMCMXCIX', 'MMMMDMXCIX'
    ],

    isEqual = function(str1, str2) {
        return str1 === str2 ? 'Yes' : 'False';
    },

    testRoman = function() {
        var romanNumber1 = new RomanNumber('XX');
        var romanNumber2 = new RomanNumber(40);
        var romanNumber3 = new RomanNumber(1995);

        console.log(romanNumber1.isRoman());  // => true
        console.log(romanNumber1.toInt());  // => 20
        console.log(romanNumber1.toString());  // => 'XX'
        console.log(romanNumber2.isRoman());  // => false
        console.log(romanNumber2.toInt());  // => 40
        console.log(romanNumber2.toString());  // => 'XL'
        console.log(romanNumber3.toString());  // => 'MCMXCV'

        testObjs.forEach(function(str) {
            try {
                num = new RomanNumber(str);
                if (num.isDecimal()) {
                    var d = num.toInt();
                    console.log('Is "%s" equal to "%s"?', str, d, isEqual(str, d));
                }
                else {
                    console.log('%s is not an arabic number, not yet implemented', str);
                }
            }
            catch(e) {
                console.log(e.name + ': ' + e.message + ' (%s)', str);
            }
        });
    };

testRoman();
<|endoftext|>


<commit_before>'use strict';

/** @module route
 */
var express = require('express'),
	favicon = require('serve-favicon'),
	cookieParser = require('cookie-parser'),
	cookieSession = require('cookie-session'),
	bodyParser = require('body-parser'),
	passport = require('passport'),
	GoogleStrategy = require('passport-google-oauth20').Strategy,
	model = require('./model');

var route = exports = module.exports = {};

var router = express.Router();

function IsAuth(app, req) {
	if(!app.locals.login.google) {
		return false;
	}

	return req.isAuthenticated();
}

function UpdateDatabaseUserFromGoogleProfile(dbuser, googleProfile) {
	dbuser.displayName = googleProfile.displayName;
	dbuser.email = googleProfile.emails[0].value;
	return dbuser;
}

route.init = function(app) {
	app.use(cookieParser());
	app.use(bodyParser.urlencoded({ extended: true }));

	if(app.locals.session.enabled) {
		app.use(cookieSession({
			name: 'session',
			secret: app.secrets.session.secret,
			keys: ['key1', 'key2']
		}))
	}

	/*router.use('/', function (req, res, next) {
		var auth = IsAuth(app, req);
		var currentUser = auth ? req.user : model.guest;
		console.log('deaguero-org: %s %s %s %d %d %s',
			req.ip, req.method, req.protocol, auth, currentUser.id, req.url);
		next();
	});*/

	if(app.locals.login.google) {
		// configure passport
		passport.use(new GoogleStrategy({
			clientID: app.secrets.login.googleId,
			clientSecret: app.secrets.login.googleSecret,
			callbackURL: (app.locals.ssl.enabled ? "https://" : "http://") + "www.deaguero.org/auth/google/callback"
		},
		function(accessToken, refreshToken, googleProfile, cb) {
			model.User.findOne({ 'id' : googleProfile.id }, function(err, dbuser) {
				if(err) {
					console.log("deaguero.org: %s", err);
					return cb(err, model.guest);
				}
				var createMode = "updated";
				if(!dbuser) {
					createMode = "created";
					dbuser = new model.User({ id : googleProfile.id });
				}
				UpdateDatabaseUserFromGoogleProfile(dbuser, googleProfile).save(function(err) {
					if(err) {
						console.log("deaguero.org: %s", err);
						return cb(err, model.guest);
					} else {
						console.log("deaguero.org: %s user %s (%d)", createMode, dbuser.email, dbuser.id);
						return cb(null, dbuser);
					}
				});
			});
		}));

		passport.serializeUser(function(user, cb) {
			console.log("s: %s", JSON.stringify(user));
			return cb(null, user._id);
		});

		passport.deserializeUser(function(dbuser_id, cb) {
			console.log("d: %s", JSON.stringify(dbuser_id));
			model.User.findById(dbuser_id, function(err, user) {
				if(err) {
					console.log("deaguero.org: %s", err);
					return cb(err, model.guest);
				}
				return cb(null, user);
			});
		});

		// add passport routes to the app
		app.use(passport.initialize());
		app.use(passport.session());

		router.get('/auth/google', passport.authenticate('google', {
			scope: [ // https://developers.google.com/+/web/api/rest/oauth#authorization-scopes
				'profile',
				'email'
			]
		}),
		function(req,res) {
			res.redirect('/'); // should not be called; the user should be redirected to google
		});

		router.get('/auth/google/callback', passport.authenticate('google', {
			successRedirect: '/',
			failureRedirect: '/',
			session: true
		}),
		function(req, res) {
			res.redirect('https://www.deaguero.org/#');
		});

		router.get('/logout', function(req, res) {
			req.logout();
			res.redirect('/');
		});
	}

	router.use('/js', express.static(__dirname + '/node_modules/jquery/dist'));
	router.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js'));
	router.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));
	router.use('/static', express.static(__dirname + '/public'));

	var _favicon = favicon(__dirname + '/public/favicon.ico');
	app.use(favicon(__dirname + '/public/favicon.ico'));

	router.get('/', function (req, res) {
		var currentUser = IsAuth(app, req) ? req.user : model.guest;
		res.render(app.secrets.view.folder + 'index.ect', { user: currentUser });
	});

	// add router to the app
	app.use("/", router);

	// add 404 handling to the app
	app.use("*", function(req,res){
		res.sendFile(app.secrets.view.folder + "404.html");
	});
};
<commit_msg>oauth20 working, remove unnecessary log lines<commit_after>'use strict';

/** @module route
 */
var express = require('express'),
	favicon = require('serve-favicon'),
	cookieParser = require('cookie-parser'),
	cookieSession = require('cookie-session'),
	bodyParser = require('body-parser'),
	passport = require('passport'),
	GoogleStrategy = require('passport-google-oauth20').Strategy,
	model = require('./model');

var route = exports = module.exports = {};

var router = express.Router();

function IsAuth(app, req) {
	if(!app.locals.login.google) {
		return false;
	}

	return req.isAuthenticated();
}

function UpdateDatabaseUserFromGoogleProfile(dbuser, googleProfile) {
	dbuser.displayName = googleProfile.displayName;
	dbuser.email = googleProfile.emails[0].value;
	return dbuser;
}

route.init = function(app) {
	app.use(cookieParser());
	app.use(bodyParser.urlencoded({ extended: true }));

	if(app.locals.session.enabled) {
		app.use(cookieSession({
			name: 'session',
			secret: app.secrets.session.secret,
			keys: ['key1', 'key2']
		}))
	}

	/*router.use('/', function (req, res, next) {
		var auth = IsAuth(app, req);
		var currentUser = auth ? req.user : model.guest;
		console.log('deaguero-org: %s %s %s %d %d %s',
			req.ip, req.method, req.protocol, auth, currentUser.id, req.url);
		next();
	});*/

	if(app.locals.login.google) {
		// configure passport
		passport.use(new GoogleStrategy({
			clientID: app.secrets.login.googleId,
			clientSecret: app.secrets.login.googleSecret,
			callbackURL: (app.locals.ssl.enabled ? "https://" : "http://") + "www.deaguero.org/auth/google/callback"
		},
		function(accessToken, refreshToken, googleProfile, cb) {
			model.User.findOne({ 'id' : googleProfile.id }, function(err, dbuser) {
				if(err) {
					console.log("deaguero.org: %s", err);
					return cb(err, model.guest);
				}
				var createMode = "updated";
				if(!dbuser) {
					createMode = "created";
					dbuser = new model.User({ id : googleProfile.id });
				}
				UpdateDatabaseUserFromGoogleProfile(dbuser, googleProfile).save(function(err) {
					if(err) {
						console.log("deaguero.org: %s", err);
						return cb(err, model.guest);
					} else {
						console.log("deaguero.org: %s user %s (%d)", createMode, dbuser.email, dbuser.id);
						return cb(null, dbuser);
					}
				});
			});
		}));

		passport.serializeUser(function(user, cb) {
			return cb(null, user._id);
		});

		passport.deserializeUser(function(dbuser_id, cb) {
			model.User.findById(dbuser_id, function(err, user) {
				if(err) {
					console.log("deaguero.org: %s", err);
					return cb(err, model.guest);
				}
				return cb(null, user);
			});
		});

		// add passport routes to the app
		app.use(passport.initialize());
		app.use(passport.session());

		router.get('/auth/google', passport.authenticate('google', {
			scope: [ // https://developers.google.com/+/web/api/rest/oauth#authorization-scopes
				'profile',
				'email'
			]
		}),
		function(req,res) {
			res.redirect('/'); // should not be called; the user should be redirected to google
		});

		router.get('/auth/google/callback', passport.authenticate('google', {
			successRedirect: '/',
			failureRedirect: '/',
			session: true
		}),
		function(req, res) {
			res.redirect('https://www.deaguero.org/#');
		});

		router.get('/logout', function(req, res) {
			req.logout();
			res.redirect('/');
		});
	}

	router.use('/js', express.static(__dirname + '/node_modules/jquery/dist'));
	router.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js'));
	router.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css'));
	router.use('/static', express.static(__dirname + '/public'));

	var _favicon = favicon(__dirname + '/public/favicon.ico');
	app.use(favicon(__dirname + '/public/favicon.ico'));

	router.get('/', function (req, res) {
		var currentUser = IsAuth(app, req) ? req.user : model.guest;
		res.render(app.secrets.view.folder + 'index.ect', { user: currentUser });
	});

	// add router to the app
	app.use("/", router);

	// add 404 handling to the app
	app.use("*", function(req,res){
		res.sendFile(app.secrets.view.folder + "404.html");
	});
};
<|endoftext|>


<commit_before>/*eslint-env node*/
var connect = require('connect');
var serveStatic = require('serve-static');
var request = require('request');
var SauceTunnel = require('sauce-tunnel');

var browserVersions = [
	['Windows 10',  'chrome',             '40'    ],
	['Mac 10.10',   'chrome',             'latest'],
	['Linux',       'chrome',             'beta'  ],
	['Windows 10',  'firefox',            '36'    ],
	['Mac 10.10',   'firefox',            'latest'],
	['Linux',       'firefox',            'beta'  ],
	['Mac 10.9',    'safari',             'latest'],
	['Mac 10.10',   'safari',             'latest'],
	['Mac 10.11',   'safari',             'latest'],
	['Windows 7',   'internet explorer',  '9'     ],
	['Windows 8',   'internet explorer',  '10'    ],
	['Windows 8.1', 'internet explorer',  '11'    ],
	['Windows 10',  'internet explorer',  'latest'],
	['Mac 10.10',   'iphone',             '7.0'   ],
	['Mac 10.10',   'iphone',             'latest'],
	['Linux',       'android',            '4.0'   ],
	['Linux',       'android',            'latest'],
];
var versionsData;

var tunnel = new SauceTunnel(process.env.SAUCE_USERNAME, process.env.SAUCE_ACCESS_KEY, 'tunnel', true);

tunnel.start(function(status) {

	if (status === false){
		throw new Error('Something went wrong with the tunnel');
	}
	console.log('Sauce tunnel started');

	connect().use(serveStatic(__dirname)).listen(8080, function() {
		console.log('Webserver listening');
		loadVersions();
	});
});

function loadVersions() {

	request.get({
		url: 'http://saucelabs.com/rest/v1/info/platforms/webdriver',
		json: true,
	}, function(err, resp, data) {
		if (err) {
			throw new Error(err);
		}
		versionsData = data;
		startTests();
	});
}

function startTests() {

	request.post({
		url: tunnel.baseUrl + '/js-tests',
		json: true,
		body: {
			url: 'http://127.0.0.1:8080/tests/index.html',
			platforms: resolveVersions(browserVersions),
			framework: 'qunit',
			tunnelIdentifier: tunnel.identifier,
		},
	}, function(err, resp, data) {
		if (err) {
			throw new Error(err);
		}
		checkStatus(data['js tests']);
	});
}

function resolveVersions(platforms) {

	return platforms.map(function(platform) {

		if (platform[2] === 'latest') {

			var versions = [];
			versionsData.forEach(function(browser) {
				if (browser.os === platform[0] && browser.api_name === platform[1]) {
					versions.push(browser.short_version);
				}
			});

			versions.sort(function(a, b) {
				var ab = [a, b].map(function(version) {
					if (version.match(/^\d+(?:\.\d+)*$/)) {
						return version.split('.').reduce(function(sum, current, index) {
							return sum + (parseFloat(current) * Math.pow(100, 4 - index))
						}, 0);
					}
					return 0;
				});
				return ab[1] - ab[0];
			});

			if (!versions[0]) {
				throw new Error('No latest version found for ' + platform[0] + ' ' + platform[1]);
			}
			platform[2] = versions[0];

		}

		return platform;

	});

}

function checkStatus(jsTests) {

	request.post({
		url: tunnel.baseUrl + '/js-tests/status',
		json: true,
		body: {
			'js tests': jsTests,
		},
	}, function(err, resp, data) {

		if (err) {
			throw new Error(err);
		}

		process.stdout.write('.');

		if (data.completed || data['js tests'].filter(function(test) {
			return test.status === 'test error';
		}).length) {

			console.log('tests done');

			var failed = [];
			data['js tests'].forEach(function(test) {
				if ((test.result && test.result.failed) || typeof test.result === 'string') {
					failed.push([
						test.platform.join(' '),
						'failed: ' + (test.result.failed || test.result),
						test.url,
					].join('\n'));
				}
				else if (test.status && !test.result) {
					failed.push([
						test.platform.join(' '),
						'failed: ' + test.status,
						test.url,
					].join('\n'));
				}
			});

			if (failed.length) {
				console.log('Sauce Labs tests failed\n');
				console.log(failed.join('\n\n') + '\n');
				tunnel.stop(function(){
					console.log('Sauce tunnel stopped');
					process.exit(1);
				});
			}
			else {
				console.log('Sauce Labs tests finished');
				tunnel.stop(function(){
					console.log('Sauce tunnel stopped');
					process.exit(0);
				});
			}

		}
		else {
			setTimeout(checkStatus, 5000, jsTests);
		}

	});

}
<commit_msg>Fix linting errors in sauce.js<commit_after>/*eslint-env node*/
/*eslint-disable strict, no-process-exit */

var connect = require('connect');
var serveStatic = require('serve-static');
var request = require('request');
var SauceTunnel = require('sauce-tunnel');

var browserVersions = [
	/*eslint-disable no-multi-spaces */
	['Windows 10',  'chrome',             '40'    ],
	['Mac 10.10',   'chrome',             'latest'],
	['Linux',       'chrome',             'beta'  ],
	['Windows 10',  'firefox',            '36'    ],
	['Mac 10.10',   'firefox',            'latest'],
	['Linux',       'firefox',            'beta'  ],
	['Mac 10.9',    'safari',             'latest'],
	['Mac 10.10',   'safari',             'latest'],
	['Mac 10.11',   'safari',             'latest'],
	['Windows 7',   'internet explorer',  '9'     ],
	['Windows 8',   'internet explorer',  '10'    ],
	['Windows 8.1', 'internet explorer',  '11'    ],
	['Windows 10',  'internet explorer',  'latest'],
	['Mac 10.10',   'iphone',             '7.0'   ],
	['Mac 10.10',   'iphone',             'latest'],
	['Linux',       'android',            '4.0'   ],
	['Linux',       'android',            'latest'],
	/*eslint-enable no-multi-spaces */
];
var versionsData;

var tunnel = new SauceTunnel(process.env.SAUCE_USERNAME, process.env.SAUCE_ACCESS_KEY, 'tunnel', true);

tunnel.start(function(status) {

	if (status === false){
		throw new Error('Something went wrong with the tunnel');
	}
	console.log('Sauce tunnel started');

	connect().use(serveStatic(__dirname)).listen(8080, function() {
		console.log('Webserver listening');
		loadVersions();
	});
});

function loadVersions() {

	request.get({
		url: 'http://saucelabs.com/rest/v1/info/platforms/webdriver',
		json: true,
	}, function(err, resp, data) {
		if (err) {
			throw new Error(err);
		}
		versionsData = data;
		startTests();
	});
}

function startTests() {

	request.post({
		url: tunnel.baseUrl + '/js-tests',
		json: true,
		body: {
			url: 'http://127.0.0.1:8080/tests/index.html',
			platforms: resolveVersions(browserVersions),
			framework: 'qunit',
			tunnelIdentifier: tunnel.identifier,
		},
	}, function(err, resp, data) {
		if (err) {
			throw new Error(err);
		}
		checkStatus(data['js tests']);
	});
}

function resolveVersions(platforms) {

	return platforms.map(function(platform) {

		if (platform[2] === 'latest') {

			var versions = [];
			versionsData.forEach(function(browser) {
				if (browser.os === platform[0] && browser.api_name === platform[1]) {
					versions.push(browser.short_version);
				}
			});

			versions.sort(function(a, b) {
				var ab = [a, b].map(function(version) {
					if (version.match(/^\d+(?:\.\d+)*$/)) {
						return version.split('.').reduce(function(sum, current, index) {
							return sum + (parseFloat(current) * Math.pow(100, 4 - index));
						}, 0);
					}
					return 0;
				});
				return ab[1] - ab[0];
			});

			if (!versions[0]) {
				throw new Error('No latest version found for ' + platform[0] + ' ' + platform[1]);
			}
			platform[2] = versions[0];

		}

		return platform;

	});

}

function checkStatus(jsTests) {

	request.post({
		url: tunnel.baseUrl + '/js-tests/status',
		json: true,
		body: {
			'js tests': jsTests,
		},
	}, function(err, resp, data) {

		if (err) {
			throw new Error(err);
		}

		process.stdout.write('.');

		if (data.completed || data['js tests'].filter(function(test) {
			return test.status === 'test error';
		}).length) {

			console.log('tests done');

			var failed = [];
			data['js tests'].forEach(function(test) {
				if ((test.result && test.result.failed) || typeof test.result === 'string') {
					failed.push([
						test.platform.join(' '),
						'failed: ' + (test.result.failed || test.result),
						test.url,
					].join('\n'));
				}
				else if (test.status && !test.result) {
					failed.push([
						test.platform.join(' '),
						'failed: ' + test.status,
						test.url,
					].join('\n'));
				}
			});

			if (failed.length) {
				console.log('Sauce Labs tests failed\n');
				console.log(failed.join('\n\n') + '\n');
				tunnel.stop(function(){
					console.log('Sauce tunnel stopped');
					process.exit(1);
				});
			}
			else {
				console.log('Sauce Labs tests finished');
				tunnel.stop(function(){
					console.log('Sauce tunnel stopped');
					process.exit(0);
				});
			}

		}
		else {
			setTimeout(checkStatus, 5000, jsTests);
		}

	});

}
<|endoftext|>


<commit_before>var align = {
  "oneOf": [
    {"enum": ["all", "each", "none"]},
    {"$ref": "#/refs/signal"}
  ]
};

export default {
  "defs": {
    "layout": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "align": {
              "oneOf": [
                align,
                {
                  "type": "object",
                  "properties": {
                    "row": align,
                    "column": align
                  },
                  "additionalProperties": false
                }
              ]
            },
            "bounds": {
              "oneOf": [
                {"enum": ["full", "flush"]},
                {"$ref": "#/refs/signal"}
              ]
            },
            "columns": {"$ref": "#/refs/numberOrSignal"},
            "padding": {
              "oneOf": [
                {"$ref": "#/refs/numberOrSignal"},
                {
                  "type": "object",
                  "properties": {
                    "row": {"$ref": "#/refs/numberOrSignal"},
                    "column": {"$ref": "#/refs/numberOrSignal"}
                  },
                  "additionalProperties": false
                }
              ]
            },
            "offset": {
              "oneOf": [
                {"$ref": "#/refs/numberOrSignal"},
                {
                  "type": "object",
                  "properties": {
                    "rowHeader": {"$ref": "#/refs/numberOrSignal"},
                    "rowFooter": {"$ref": "#/refs/numberOrSignal"},
                    "rowTitle": {"$ref": "#/refs/numberOrSignal"},
                    "columnHeader": {"$ref": "#/refs/numberOrSignal"},
                    "columnFooter": {"$ref": "#/refs/numberOrSignal"},
                    "columnTitle": {"$ref": "#/refs/numberOrSignal"}
                  },
                  "additionalProperties": false
                }
              ]
            },
            "titleBand": {
              "oneOf": [
                {"$ref": "#/refs/numberOrSignal"},
                {
                  "type": "object",
                  "properties": {
                    "row": {"$ref": "#/refs/numberOrSignal"},
                    "column": {"$ref": "#/refs/numberOrSignal"}
                  },
                  "additionalProperties": false
                }
              ]
            }
          }
        },
        {"$ref": "#/refs/signal"}
      ]
    }
  }
};
<commit_msg>Add header/footer band to schema.<commit_after>var align = {
  "oneOf": [
    {"enum": ["all", "each", "none"]},
    {"$ref": "#/refs/signal"}
  ]
};

var band = {
  "oneOf": [
    {"$ref": "#/refs/numberOrSignal"},
    {"type": "null"},
    {
      "type": "object",
      "properties": {
        "row": {"$ref": "#/refs/numberOrSignal"},
        "column": {"$ref": "#/refs/numberOrSignal"}
      },
      "additionalProperties": false
    }
  ]
};

export default {
  "defs": {
    "layout": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "align": {
              "oneOf": [
                align,
                {
                  "type": "object",
                  "properties": {
                    "row": align,
                    "column": align
                  },
                  "additionalProperties": false
                }
              ]
            },
            "bounds": {
              "oneOf": [
                {"enum": ["full", "flush"]},
                {"$ref": "#/refs/signal"}
              ]
            },
            "columns": {"$ref": "#/refs/numberOrSignal"},
            "padding": {
              "oneOf": [
                {"$ref": "#/refs/numberOrSignal"},
                {
                  "type": "object",
                  "properties": {
                    "row": {"$ref": "#/refs/numberOrSignal"},
                    "column": {"$ref": "#/refs/numberOrSignal"}
                  },
                  "additionalProperties": false
                }
              ]
            },
            "offset": {
              "oneOf": [
                {"$ref": "#/refs/numberOrSignal"},
                {
                  "type": "object",
                  "properties": {
                    "rowHeader": {"$ref": "#/refs/numberOrSignal"},
                    "rowFooter": {"$ref": "#/refs/numberOrSignal"},
                    "rowTitle": {"$ref": "#/refs/numberOrSignal"},
                    "columnHeader": {"$ref": "#/refs/numberOrSignal"},
                    "columnFooter": {"$ref": "#/refs/numberOrSignal"},
                    "columnTitle": {"$ref": "#/refs/numberOrSignal"}
                  },
                  "additionalProperties": false
                }
              ]
            },
            "headerBand": band,
            "footerBand": band,
            "titleBand": band
          }
        },
        {"$ref": "#/refs/signal"}
      ]
    }
  }
};
<|endoftext|>


<commit_before>//require mongoose, a popular MongoDB library for nodejs
//Mongoose connects in the app.js file. Once mongoose is connected, it stays connected across all of the files in this project
//As long as you import this after you have connected, then mongoose will give you the active DB connection which is what we want
var mongoose = require('mongoose');

//variable to hold our Model
//A Model is our data structure to handle data. This can be an object, JSON, XML or anything else.
//A mongoDB model is a Mongo database structure with the API attached
//That is, a model has built-in functions for its data structure like find, findOne, etc.
//Usually you will retrieve data from the database through the Model object
var DogModel;

//A DB Schema to define our data structure
//The schema really just defines a DB data structure.
//In this case it also defines what functions/methods will be attached to objects that come
//back from the database.
//Schemas also add constraints to the fields so that you can enforce that objects have fields of the right type
//This should always be done since it ensures your variables will be the right type and
//it helps prevent injection of invalid data
//Schemas are made in JSON.
//The name of the field will be the variable name for each object
//The json of each field are the constraints around it
//There are many constraints available
//For example,
//type is the data type (String, Number, Date, Boolean, etc).
//required is whether or not the field is required to allow a document to be created
//trim is whether or not the field should strip spaces before and after value
//unique is whether or not the field must be a unique value (meaning no two Cat object can have the same value for that field)
//min is the minimum numeric value
//max is the maximum numeric value
//default is the default value if one is not provided
//match is the format to match done through regex
var DogSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },

	breed: {
        type: String,
        required: true,
        trim: true,
    },

    age: {
        type: Number,
        min: 0,
        required: true
    },

    createdData: {
        type: Date,
        default: Date.now
    }

});

//Schema.methods are the methods attached to each object
//In this case each cat will have its own sayName function that prints the values from the object
//You attach these with schema.method. Each individual object has its own attached version of this
DogSchema.methods.sayName = function() {
    console.log(this.name);
};

//Schema.statics are static methods attached to the Model or objects
//These DO NOT have their own instance. They are all the static function. They do not look at
//individual instance variables since there is no instance of them. Every static function
//only exists once and is called.
//In this case, findByName will be attached to the model and objects.
//They will be able to call this function, but they won't be able to reference any instance variables of that object (or at least accurately)
//These are used when you want a public function you can call to do a task, not a method that uses or returns instance variables
//That is, these are used when you don't need an object, just a function to call.
DogSchema.statics.findByName = function(name, callback) {

    var search = {
        name: name
    };

    return DogModel.findOne(search, callback);
};

//Create the cat model based on the schema. You provide it with a custom discriminator (the name of the object type. Can be anything)
//and the schema to make a model from.
//Look at the model variable definition above for more details.
DogModel = mongoose.model('Dog', DogSchema);

//export our public properties
module.exports.CatModel = DogModel;
module.exports.CatSchema = DogSchema;<commit_msg>yet another<commit_after>//require mongoose, a popular MongoDB library for nodejs
//Mongoose connects in the app.js file. Once mongoose is connected, it stays connected across all of the files in this project
//As long as you import this after you have connected, then mongoose will give you the active DB connection which is what we want
var mongoose = require('mongoose');

//variable to hold our Model
//A Model is our data structure to handle data. This can be an object, JSON, XML or anything else.
//A mongoDB model is a Mongo database structure with the API attached
//That is, a model has built-in functions for its data structure like find, findOne, etc.
//Usually you will retrieve data from the database through the Model object
var DogModel;

//A DB Schema to define our data structure
//The schema really just defines a DB data structure.
//In this case it also defines what functions/methods will be attached to objects that come
//back from the database.
//Schemas also add constraints to the fields so that you can enforce that objects have fields of the right type
//This should always be done since it ensures your variables will be the right type and
//it helps prevent injection of invalid data
//Schemas are made in JSON.
//The name of the field will be the variable name for each object
//The json of each field are the constraints around it
//There are many constraints available
//For example,
//type is the data type (String, Number, Date, Boolean, etc).
//required is whether or not the field is required to allow a document to be created
//trim is whether or not the field should strip spaces before and after value
//unique is whether or not the field must be a unique value (meaning no two Cat object can have the same value for that field)
//min is the minimum numeric value
//max is the maximum numeric value
//default is the default value if one is not provided
//match is the format to match done through regex
var DogSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },

	breed: {
        type: String,
        required: true,
        trim: true,
    },

    age: {
        type: Number,
        min: 0,
        required: true
    },

    createdData: {
        type: Date,
        default: Date.now
    }

});

//Schema.methods are the methods attached to each object
//In this case each cat will have its own sayName function that prints the values from the object
//You attach these with schema.method. Each individual object has its own attached version of this
DogSchema.methods.sayName = function() {
    console.log(this.name);
};

//Schema.statics are static methods attached to the Model or objects
//These DO NOT have their own instance. They are all the static function. They do not look at
//individual instance variables since there is no instance of them. Every static function
//only exists once and is called.
//In this case, findByName will be attached to the model and objects.
//They will be able to call this function, but they won't be able to reference any instance variables of that object (or at least accurately)
//These are used when you want a public function you can call to do a task, not a method that uses or returns instance variables
//That is, these are used when you don't need an object, just a function to call.
DogSchema.statics.findByName = function(name, callback) {

    var search = {
        name: name
    };

    return DogModel.findOne(search, callback);
};

//Create the cat model based on the schema. You provide it with a custom discriminator (the name of the object type. Can be anything)
//and the schema to make a model from.
//Look at the model variable definition above for more details.
DogModel = mongoose.model('Dog', DogSchema);

//export our public properties
module.exports.DogModel = DogModel;
module.exports.DOgSchema = DogSchema;<|endoftext|>


<commit_before>/* global window */
/* global document */
/* global location */
import { routerRedux } from 'dva/router'
import qs from 'qs'
import config from 'config'
import { queryStatus, logout } from 'services/app'
import * as menusService from 'services/menus'
import { queryHashURL } from 'utils'

const { prefix } = config

export default {
  namespace: 'app',
  state: {
    sessionID: window.localStorage.getItem(`${prefix}SessionID`),
    authToken: window.localStorage.getItem(`${prefix}AuthToken`),
    onlineUser: { },
    menu: [
      {
        id: 1,
        icon: 'laptop',
        name: 'Dashboard',
        router: '/dashboard',
      },
    ],
    menuPopoverVisible: false,
    siderFold: window.localStorage.getItem(`${prefix}siderFold`) === 'true',
    darkTheme: window.localStorage.getItem(`${prefix}darkTheme`) === 'true',
    isNavbar: document.body.clientWidth < 769,
    navOpenKeys: JSON.parse(window.localStorage.getItem(`${prefix}navOpenKeys`)) || [],
    locationPathname: '',
    locationQuery: {},
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen((location) => {
        dispatch({
          type: 'updateState',
          payload: { locationPathname: location.pathname },
        })
      })
    },

    setup({ dispatch }) {
      dispatch({ type: 'query' })
    },

  },

  effects: {
    * query({ payload }, { call, put, select }) {
      const { sessionID, authToken, locationPathname } = yield select(_ => _.app)
      const data = yield call(queryStatus, { sessionID, authToken, ...payload })
      if (data.errorCode === 0) {
        const { onlineEntry } = data
        const { menu, errorCode } = yield call(menusService.query, { authToken: data.authToken })

        if (errorCode === 0) {
          yield put({
            type: 'updateState',
            payload: {
              sessionID: data.sessionID,
              authToken: data.authToken,
              onlineUser: onlineEntry,
              menu: JSON.parse(menu),
            },
          })

          const from = queryHashURL('from')
          if (from) {
            yield put(routerRedux.push({ pathname: from }))
          }
        }
      } else if (config.openPages && config.openPages.indexOf(locationPathname) < 0) {
        yield put(routerRedux.push({
          pathname: '/login',
          search: qs.stringify({ from: locationPathname }),
        }))
      }
    },

    * logout({ payload }, { call, put, select }) {
      const { sessionID, authToken } = yield select(_ => _.app)
      const data = yield call(logout, { sessionID, authToken, ...payload })
      if (data.success) {
        yield put({ type: 'clearStatus' })
        yield put({ type: 'query' })
      } else {
        throw (data)
      }
    },

    * changeNavbar(action, { put, select }) {
      const { app } = yield (select(_ => _))
      const isNavbar = document.body.clientWidth < 769
      if (isNavbar !== app.isNavbar) {
        yield put({ type: 'handleNavbar', payload: isNavbar })
      }
    },

  },

  reducers: {
    updateState(state, { payload }) {
      const { sessionID, authToken } = payload

      if (sessionID && authToken) {
        window.localStorage.setItem(`${prefix}SessionID`, sessionID)
        window.localStorage.setItem(`${prefix}AuthToken`, authToken)
      }

      return {
        ...state,
        ...payload,
      }
    },

    clearStatus(state) {
      window.localStorage.removeItem(`${prefix}SessionID`)
      window.localStorage.removeItem(`${prefix}AuthToken`)

      return {
        ...state,
        sessionID: '',
        authToken: '',
        onlineUser: {},
        permissions: { visit: [] },
      }
    },

    switchSider(state) {
      window.localStorage.setItem(`${prefix}siderFold`, !state.siderFold)
      return {
        ...state,
        siderFold: !state.siderFold,
      }
    },

    switchTheme(state) {
      window.localStorage.setItem(`${prefix}darkTheme`, !state.darkTheme)
      return {
        ...state,
        darkTheme: !state.darkTheme,
      }
    },

    switchMenuPopver(state) {
      return {
        ...state,
        menuPopoverVisible: !state.menuPopoverVisible,
      }
    },

    handleNavbar(state, { payload }) {
      return {
        ...state,
        isNavbar: payload,
      }
    },

    handleNavOpenKeys(state, { payload: navOpenKeys }) {
      return {
        ...state,
        ...navOpenKeys,
      }
    },
  },
}
<commit_msg>update app.js<commit_after>/* global window */
/* global document */
/* global location */
import { routerRedux } from 'dva/router'
import qs from 'qs'
import config from 'config'
import { queryStatus, logout } from 'services/app'
import * as menusService from 'services/menus'
import { queryHashURL } from 'utils'

const { prefix } = config

export default {
  namespace: 'app',
  state: {
    sessionID: window.localStorage.getItem(`${prefix}SessionID`),
    authToken: window.localStorage.getItem(`${prefix}AuthToken`),
    onlineUser: { },
    menu: [
      {
        id: 1,
        icon: 'laptop',
        name: 'Dashboard',
        router: '/dashboard',
      },
    ],
    menuPopoverVisible: false,
    siderFold: window.localStorage.getItem(`${prefix}siderFold`) === 'true',
    darkTheme: window.localStorage.getItem(`${prefix}darkTheme`) === 'true',
    isNavbar: document.body.clientWidth < 769,
    navOpenKeys: JSON.parse(window.localStorage.getItem(`${prefix}navOpenKeys`)) || [],
    locationPathname: '',
    locationQuery: {},
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen((location) => {
        dispatch({
          type: 'updateState',
          payload: { locationPathname: location.pathname },
        })
      })
    },

    setup({ dispatch }) {
      dispatch({ type: 'query' })
    },

  },

  effects: {
    * query({ payload }, { call, put, select }) {
      const { sessionID, authToken, locationPathname } = yield select(_ => _.app)
      const data = yield call(queryStatus, { sessionID, authToken, ...payload })
      if (data.errorCode === 0) {
        const { onlineEntry } = data
        const { menu, errorCode } = yield call(menusService.query, { authToken: data.authToken })

        if (errorCode === 0) {
          yield put({
            type: 'updateState',
            payload: {
              sessionID: data.sessionID,
              authToken: data.authToken,
              onlineUser: onlineEntry,
              menu: JSON.parse(menu),
            },
          })

          const from = queryHashURL('from')
          if (from) {
            yield put(routerRedux.push({ pathname: from }))
          } else {
            yield put(routerRedux.push({
              pathname: '/dashboard',
            }))
          }
        }
      } else if (config.openPages && config.openPages.indexOf(locationPathname) < 0) {
        yield put(routerRedux.push({
          pathname: '/login',
          search: qs.stringify({ from: locationPathname }),
        }))
      }
    },

    * logout({ payload }, { call, put, select }) {
      const { sessionID, authToken } = yield select(_ => _.app)
      const data = yield call(logout, { sessionID, authToken, ...payload })
      if (data.success) {
        yield put({ type: 'clearStatus' })
        yield put({ type: 'query' })
      } else {
        throw (data)
      }
    },

    * changeNavbar(action, { put, select }) {
      const { app } = yield (select(_ => _))
      const isNavbar = document.body.clientWidth < 769
      if (isNavbar !== app.isNavbar) {
        yield put({ type: 'handleNavbar', payload: isNavbar })
      }
    },

  },

  reducers: {
    updateState(state, { payload }) {
      const { sessionID, authToken } = payload

      if (sessionID && authToken) {
        window.localStorage.setItem(`${prefix}SessionID`, sessionID)
        window.localStorage.setItem(`${prefix}AuthToken`, authToken)
      }

      return {
        ...state,
        ...payload,
      }
    },

    clearStatus(state) {
      window.localStorage.removeItem(`${prefix}SessionID`)
      window.localStorage.removeItem(`${prefix}AuthToken`)

      return {
        ...state,
        sessionID: '',
        authToken: '',
        onlineUser: {},
        permissions: { visit: [] },
      }
    },

    switchSider(state) {
      window.localStorage.setItem(`${prefix}siderFold`, !state.siderFold)
      return {
        ...state,
        siderFold: !state.siderFold,
      }
    },

    switchTheme(state) {
      window.localStorage.setItem(`${prefix}darkTheme`, !state.darkTheme)
      return {
        ...state,
        darkTheme: !state.darkTheme,
      }
    },

    switchMenuPopver(state) {
      return {
        ...state,
        menuPopoverVisible: !state.menuPopoverVisible,
      }
    },

    handleNavbar(state, { payload }) {
      return {
        ...state,
        isNavbar: payload,
      }
    },

    handleNavOpenKeys(state, { payload: navOpenKeys }) {
      return {
        ...state,
        ...navOpenKeys,
      }
    },
  },
}
<|endoftext|>


<commit_before>module.exports = function(rules) {

  'use strict';

  rules = (rules || []).map(function(rule) {

    var parts = rule.replace(/\s+|\t+/g, ' ').split(' ');

    return {
      regex: new RegExp(parts[0]),
      replace: parts[1],
      last: !!parts[2]
    };

  });

  return function(req, res, next) {

    rules.some(function(rewrite) {

      // Some request are not assets request, which means they don't
      // have an HTTP referer. We only normalize path which are assets
      if(typeof req.headers.referer === 'undefined') {

        console.log(rewrite);
        // Rewrite Url
        req.url = req.url.replace(rewrite.regex, rewrite.replace);
        return rewrite.last;

      // Else normalize path
      } else {

        // Split URLs for later normalization
        var referersSplits = req.headers.referer.split('/'),
            urlSplits = req.url.substr(1).split('/'); // substr(1) is there because the string begins with /
        // Remove hostname
        referersSplits.splice(0, 3);
        // Remove the last part of the referer since it is not
        // supposed to be used in the normalization process
        referersSplits.pop();
        // Normalization process
        urlSplits.forEach(function(value, index) {
          if(value === referersSplits[index]) {
            urlSplits.splice(index, 1);
          } else {
            return false;
          }
        });
        // Join back all splits
        req.url = '/' + urlSplits.join('/');

        // Rewrite Url
        req.url = req.url.replace(rewrite.regex, rewrite.replace);
        return rewrite.last;

      } // End of normalization

    });

    next();

  };
}
<commit_msg>Removed console.log<commit_after>module.exports = function(rules) {

  'use strict';

  rules = (rules || []).map(function(rule) {

    var parts = rule.replace(/\s+|\t+/g, ' ').split(' ');

    return {
      regex: new RegExp(parts[0]),
      replace: parts[1],
      last: !!parts[2]
    };

  });

  return function(req, res, next) {

    rules.some(function(rewrite) {

      // Some request are not assets request, which means they don't
      // have an HTTP referer. We only normalize path which are assets
      if(typeof req.headers.referer === 'undefined') {

        // Rewrite Url
        req.url = req.url.replace(rewrite.regex, rewrite.replace);
        return rewrite.last;

      // Else normalize path
      } else {

        // Split URLs for later normalization
        var referersSplits = req.headers.referer.split('/'),
            urlSplits = req.url.substr(1).split('/'); // substr(1) is there because the string begins with /
        // Remove hostname
        referersSplits.splice(0, 3);
        // Remove the last part of the referer since it is not
        // supposed to be used in the normalization process
        referersSplits.pop();
        // Normalization process
        urlSplits.forEach(function(value, index) {
          if(value === referersSplits[index]) {
            urlSplits.splice(index, 1);
          } else {
            return false;
          }
        });
        // Join back all splits
        req.url = '/' + urlSplits.join('/');

        // Rewrite Url
        req.url = req.url.replace(rewrite.regex, rewrite.replace);
        return rewrite.last;

      } // End of normalization

    });

    next();

  };
}
<|endoftext|>


<commit_before>var fs = require('fs');

function searchSong(message, soundsList){
    var songName = message.slice(1);
    for(var i = 0; i < soundsList.length; i++){
        var soundListName = soundsList[i].split('.');   // Splitting the name and extension
        soundListName = soundListName[0];
        if(soundListName === songName) return i;
    }
    return null;
}

module.exports.playSound = function(bot, channelID, message) {
	var soundsList = fs.readdirSync('./sounds');
	var songNum = searchSong(message, soundsList);
	if(songNum === null) return;
	var voiceChannelID = "";
	var file = 'sounds/'+soundsList[songNum];

    for(var i in bot.servers[bot.serverFromChannel(channelID)].channels){       // Get first voice channel
        if(bot.servers[bot.serverFromChannel(channelID)].channels[i].type === "voice" && bot.servers[bot.serverFromChannel(channelID)].channels[i].position === 0){
            voiceChannelID = bot.servers[bot.serverFromChannel(channelID)].channels[i].id;
            break;
        }
    }
    // play
    bot.joinVoiceChannel(voiceChannelID, function(){
        bot.getAudioContext({channel: voiceChannelID, stereo: true}, function (stream){
        	stream.playAudioFile(file);
            stream.once('fileEnd', function(){
                bot.leaveVoiceChannel(voiceChannelID);
            });
        });
    });
}<commit_msg>Code Revised<commit_after>var fs = require('fs');

function searchSong(message, soundsList){
    var soundName = message.slice(1);
    for(var i = 0; i < soundsList.length; i++){
        var soundListName = soundsList[i].split('.')[0];
        if(soundListName === soundName) return i;
    }
    return null;
}

module.exports.playSound = function(bot, channelID, message) {
	var soundsList = fs.readdirSync('./sounds');
	var songNum = searchSong(message, soundsList);
	if(songNum === null) return;
	var voiceChannelID = "";
	var file = 'sounds/'+soundsList[songNum];

    var serverChannels = bot.servers[bot.serverFromChannel(channelID)].channels;
    for(var i in serverChannels){       // Get first voice channel
        if(serverChannels[i].type === "voice" && serverChannels[i].position === 0){
            voiceChannelID = serverChannels[i].id;
            break;
        }
    }

    // play
    bot.joinVoiceChannel(voiceChannelID, function(){
        bot.getAudioContext({channel: voiceChannelID, stereo: true}, function (stream){
        	stream.playAudioFile(file);
            stream.once('fileEnd', function(){
                bot.leaveVoiceChannel(voiceChannelID);
            });
        });
    });
}<|endoftext|>