<commit_before>module.exports = {
  parser: '@typescript-eslint/parser',
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  ignorePatterns: ['**/*.scss'],
  plugins: [
    'react',
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  rules: {
    '@typescript-eslint/array-type': [1, {default: 'array-simple'}],
    '@typescript-eslint/ban-types': 1,
    '@typescript-eslint/comma-dangle': [1, 'always-multiline'],
    '@typescript-eslint/comma-spacing': [1, {'before': false, 'after': true}],
    '@typescript-eslint/consistent-type-definitions': [1, 'interface'],
    '@typescript-eslint/consistent-type-imports': [1, {prefer: 'type-imports'}],
    '@typescript-eslint/func-call-spacing': [1, 'never'],
    '@typescript-eslint/keyword-spacing': [1, {before: true, after: true}],
    '@typescript-eslint/member-delimiter-style': [1, {
      multiline: {delimiter: 'semi'},
      singleline: {delimiter: 'semi'},
    }],
    '@typescript-eslint/method-signature-style': [1, 'property'],
    '@typescript-eslint/naming-convention': [1,
      {selector: 'variableLike', format: ['camelCase', 'PascalCase', 'UPPER_CASE']},
      {selector: 'memberLike', format: ['camelCase', 'PascalCase']},
      {selector: 'typeLike', format: ['PascalCase']},
      {selector: 'property', format: ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE']},
      {selector: 'method', format: ['camelCase']},
    ],
    '@typescript-eslint/no-confusing-non-null-assertion': 1,
    '@typescript-eslint/no-dupe-class-members': 1,
    '@typescript-eslint/no-duplicate-imports': [1, {'includeExports': true}],
    '@typescript-eslint/no-dynamic-delete': 1,
    '@typescript-eslint/no-empty-function': 1,
    '@typescript-eslint/no-empty-interface': 1,
    'no-empty-pattern': 1,
    '@typescript-eslint/no-explicit-any': 1,
    '@typescript-eslint/no-extra-parens': 1,
    '@typescript-eslint/no-extra-semi': 1,
    '@typescript-eslint/no-inferrable-types': 1,
    '@typescript-eslint/no-invalid-void-type': 1,
    '@typescript-eslint/no-loop-func': 1,
    '@typescript-eslint/no-parameter-properties': 1,
    '@typescript-eslint/no-shadow': 1,
    '@typescript-eslint/no-this-alias': 1,
    '@typescript-eslint/no-unused-expressions': 1,
    '@typescript-eslint/no-unused-vars': 1,
    '@typescript-eslint/no-use-before-define': 1,
    '@typescript-eslint/no-useless-constructor': 1,
    '@typescript-eslint/no-var-requires': 1,
    '@typescript-eslint/object-curly-spacing': 1,
    '@typescript-eslint/prefer-enum-initializers': 1,
    '@typescript-eslint/prefer-optional-chain': 1,
    '@typescript-eslint/quotes': ['warn', 'single', {'avoidEscape': true}],
    '@typescript-eslint/semi': 1,
    '@typescript-eslint/sort-type-union-intersection-members': 1,
    '@typescript-eslint/space-before-function-paren': [1, {
      anonymous: 'always',
      named: 'never',
      asyncArrow: 'never',
    }],
    '@typescript-eslint/type-annotation-spacing': [1, {
      before: false,
      after: true,
      overrides: {
        arrow: {
          before: true,
          after: true,
        },
      },
    }],
    '@typescript-eslint/unified-signatures': 1,
    'arrow-body-style': [1, 'as-needed', {'requireReturnForObjectLiteral': true}],
    'arrow-parens': [1, 'always'],
    'arrow-spacing': 1,
    'block-spacing': [1, 'never'],
    'brace-style': [1, '1tbs', {'allowSingleLine': true}],
    'comma-dangle': 'off',
    'comma-spacing': 'off',
    'curly': 1,
    'eol-last': [1, 'always'],
    'eqeqeq': 1,
    'func-call-spacing': 'off',
    'jsx-quotes': ['warn', 'prefer-single'],
    'key-spacing': [1, {'beforeColon': false, 'afterColon': true, 'mode': 'strict'}],
    'max-nested-callbacks': [1, 6],
    'no-case-declarations': 1,
    'no-confusing-arrow': 1,
    'no-console': 1,
    'no-control-regex': 0,
    'no-debugger': 1,
    'no-duplicate-imports': 'off',
    'no-extend-native': 1,
    'no-extra-bind': 1,
    'no-extra-boolean-cast': 1,
    'no-extra-semi': 1,
    'no-fallthrough': 1,
    'no-inner-declarations': 1,
    'no-irregular-whitespace': 1,
    'no-lonely-if': 1,
    'no-mixed-spaces-and-tabs': 1,
    'no-multi-spaces': 1,
    'no-multiple-empty-lines': [1, {'max': 2, 'maxEOF': 1}],
    'no-nonoctal-decimal-escape': 'off',
    'no-prototype-builtins': 1,
    'no-trailing-spaces': 1,
    'no-undef-init': 1,
    'no-undef': 1,
    'no-unexpected-multiline': 1,
    'no-unsafe-optional-chaining': 'off',
    'no-unused-expressions': 'off',
    'no-useless-backreference': 'off',
    'no-useless-escape': 1,
    'no-useless-rename': 1,
    'no-var': 1,
    'no-whitespace-before-property': 1,
    'one-var': ['warn', 'never'],
    'prefer-const': 1,
    'prefer-spread': 1,
    'quotes': 'off',
    'react/jsx-boolean-value': 1,
    'react/jsx-no-undef': 2,
    'react/jsx-sort-prop-types': 0,
    'react/jsx-sort-props': 0,
    'react/jsx-uses-react': 2,
    'react/jsx-uses-vars': 2,
    'react/no-did-mount-set-state': 0,
    'react/no-did-update-set-state': 2,
    'react/no-multi-comp': 0,
    'react/no-unknown-property': 0,
    'react/prop-types': 0,
    'react/react-in-jsx-scope': 2,
    'react/self-closing-comp': 2,
    'react/wrap-multilines': 0,
    'semi-spacing': [1, {'before': false, 'after': true}],
    'semi-style': [1, 'last'],
    'semi': 'off',
    'space-before-function-paren': 'off',
    'space-in-parens': [1, 'never'],
    'space-infix-ops': 1,
    'strict': 1,
  },
  globals: {
    inject: false,
    module: false,
    describe: false,
    it: false,
    before: false,
    beforeEach: false,
    after: false,
    afterEach: false,
    expect: false,
    window: false,
    document: false,
    Parse: false,
    chai: true,
    t: 'readonly',
    $: 'readonly',
    ga: 'readonly',
  },
};
<commit_msg>drop no extra parens rule<commit_after>module.exports = {
  parser: '@typescript-eslint/parser',
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  ignorePatterns: ['**/*.scss'],
  plugins: [
    'react',
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  rules: {
    '@typescript-eslint/array-type': [1, {default: 'array-simple'}],
    '@typescript-eslint/ban-types': 1,
    '@typescript-eslint/comma-dangle': [1, 'always-multiline'],
    '@typescript-eslint/comma-spacing': [1, {'before': false, 'after': true}],
    '@typescript-eslint/consistent-type-definitions': [1, 'interface'],
    '@typescript-eslint/consistent-type-imports': [1, {prefer: 'type-imports'}],
    '@typescript-eslint/func-call-spacing': [1, 'never'],
    '@typescript-eslint/keyword-spacing': [1, {before: true, after: true}],
    '@typescript-eslint/member-delimiter-style': [1, {
      multiline: {delimiter: 'semi'},
      singleline: {delimiter: 'semi'},
    }],
    '@typescript-eslint/method-signature-style': [1, 'property'],
    '@typescript-eslint/naming-convention': [1,
      {selector: 'variableLike', format: ['camelCase', 'PascalCase', 'UPPER_CASE']},
      {selector: 'memberLike', format: ['camelCase', 'PascalCase']},
      {selector: 'typeLike', format: ['PascalCase']},
      {selector: 'property', format: ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE']},
      {selector: 'method', format: ['camelCase']},
    ],
    '@typescript-eslint/no-confusing-non-null-assertion': 1,
    '@typescript-eslint/no-dupe-class-members': 1,
    '@typescript-eslint/no-duplicate-imports': [1, {'includeExports': true}],
    '@typescript-eslint/no-dynamic-delete': 1,
    '@typescript-eslint/no-empty-function': 1,
    '@typescript-eslint/no-empty-interface': 1,
    'no-empty-pattern': 1,
    '@typescript-eslint/no-explicit-any': 1,
    '@typescript-eslint/no-extra-parens': 'off',
    '@typescript-eslint/no-extra-semi': 1,
    '@typescript-eslint/no-inferrable-types': 1,
    '@typescript-eslint/no-invalid-void-type': 1,
    '@typescript-eslint/no-loop-func': 1,
    '@typescript-eslint/no-parameter-properties': 1,
    '@typescript-eslint/no-shadow': 1,
    '@typescript-eslint/no-this-alias': 1,
    '@typescript-eslint/no-unused-expressions': 1,
    '@typescript-eslint/no-unused-vars': 1,
    '@typescript-eslint/no-use-before-define': 1,
    '@typescript-eslint/no-useless-constructor': 1,
    '@typescript-eslint/no-var-requires': 1,
    '@typescript-eslint/object-curly-spacing': 1,
    '@typescript-eslint/prefer-enum-initializers': 1,
    '@typescript-eslint/prefer-optional-chain': 1,
    '@typescript-eslint/quotes': ['warn', 'single', {'avoidEscape': true}],
    '@typescript-eslint/semi': 1,
    '@typescript-eslint/sort-type-union-intersection-members': 1,
    '@typescript-eslint/space-before-function-paren': [1, {
      anonymous: 'always',
      named: 'never',
      asyncArrow: 'never',
    }],
    '@typescript-eslint/type-annotation-spacing': [1, {
      before: false,
      after: true,
      overrides: {
        arrow: {
          before: true,
          after: true,
        },
      },
    }],
    '@typescript-eslint/unified-signatures': 1,
    'arrow-body-style': [1, 'as-needed', {'requireReturnForObjectLiteral': true}],
    'arrow-parens': [1, 'always'],
    'arrow-spacing': 1,
    'block-spacing': [1, 'never'],
    'brace-style': [1, '1tbs', {'allowSingleLine': true}],
    'comma-dangle': 'off',
    'comma-spacing': 'off',
    'curly': 1,
    'eol-last': [1, 'always'],
    'eqeqeq': 1,
    'func-call-spacing': 'off',
    'jsx-quotes': ['warn', 'prefer-single'],
    'key-spacing': [1, {'beforeColon': false, 'afterColon': true, 'mode': 'strict'}],
    'max-nested-callbacks': [1, 6],
    'no-case-declarations': 1,
    'no-confusing-arrow': 1,
    'no-console': 1,
    'no-control-regex': 0,
    'no-debugger': 1,
    'no-duplicate-imports': 'off',
    'no-extend-native': 1,
    'no-extra-bind': 1,
    'no-extra-boolean-cast': 1,
    'no-extra-semi': 1,
    'no-fallthrough': 1,
    'no-inner-declarations': 1,
    'no-irregular-whitespace': 1,
    'no-lonely-if': 1,
    'no-mixed-spaces-and-tabs': 1,
    'no-multi-spaces': 1,
    'no-multiple-empty-lines': [1, {'max': 2, 'maxEOF': 1}],
    'no-nonoctal-decimal-escape': 'off',
    'no-prototype-builtins': 1,
    'no-trailing-spaces': 1,
    'no-undef-init': 1,
    'no-undef': 1,
    'no-unexpected-multiline': 1,
    'no-unsafe-optional-chaining': 'off',
    'no-unused-expressions': 'off',
    'no-useless-backreference': 'off',
    'no-useless-escape': 1,
    'no-useless-rename': 1,
    'no-var': 1,
    'no-whitespace-before-property': 1,
    'one-var': ['warn', 'never'],
    'prefer-const': 1,
    'prefer-spread': 1,
    'quotes': 'off',
    'react/jsx-boolean-value': 1,
    'react/jsx-no-undef': 2,
    'react/jsx-sort-prop-types': 0,
    'react/jsx-sort-props': 0,
    'react/jsx-uses-react': 2,
    'react/jsx-uses-vars': 2,
    'react/no-did-mount-set-state': 0,
    'react/no-did-update-set-state': 2,
    'react/no-multi-comp': 0,
    'react/no-unknown-property': 0,
    'react/prop-types': 0,
    'react/react-in-jsx-scope': 2,
    'react/self-closing-comp': 2,
    'react/wrap-multilines': 0,
    'semi-spacing': [1, {'before': false, 'after': true}],
    'semi-style': [1, 'last'],
    'semi': 'off',
    'space-before-function-paren': 'off',
    'space-in-parens': [1, 'never'],
    'space-infix-ops': 1,
    'strict': 1,
  },
  globals: {
    inject: false,
    module: false,
    describe: false,
    it: false,
    before: false,
    beforeEach: false,
    after: false,
    afterEach: false,
    expect: false,
    window: false,
    document: false,
    Parse: false,
    chai: true,
    t: 'readonly',
    $: 'readonly',
    ga: 'readonly',
  },
};
<|endoftext|>


<commit_before>'use strict';

/**
* ESLint rules specific to stdlib.
*
* @namespace rules
*/
var rules = {};

/**
* Require an empty line before single-line comments.
*
* @name empty-line-before-comment
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* function square( x ) {
*     var out;
*     // Square the number:
*     out = x*x;
*     return out;
* }
*
* @example
* // Good...
* function square( x ) {
*     var out;
*
*     // Square the number:
*     out = x*x;
*     return out;
* }
*/
rules[ 'stdlib/empty-line-before-comment' ] = 'error';

/**
* Require that only allowed JSDoc tags are used.
*
* @name jsdoc-tag-names
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
*
* /**
* * Squares a number.
* *
* * @arg {number} x - input number
* * @return {number} x squared
* *
* * @examples
* * var y = square( 2.0 );
* * // returns 4.0
* *\/
* function square( x ) {
*     return x*x;
* }
*
* @example
* // Good...
*
* /**
* * Squares a number.
* *
* * @param {number} x - input number
* * @returns {number} x squared
* *
* * @example
* * var y = square( 2.0 );
* * // returns 4.0
* *\/
* function square( x ) {
*     return x*x;
* }
*/
rules[ 'stdlib/jsdoc-tag-names' ] = 'error';

/**
* Require that JSDoc descriptions start with an uppercase letter and end with a period.
*
* @name jsdoc-leading-description-sentence
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
*
* /**
* * returns a pseudo-random number on [0,1]
* *
* * @returns {number} uniform random number
* *
* * @example
* * var y = rand();
* * // e.g., returns 0.5363925252089496
* *\/
* function rand() {
*     return Math.random();
* }
*
* @example
* // Good...
*
* /**
* * Returns a pseudo-random number on [0,1].
* *
* * @returns {number} uniform random number
* *
* * @example
* * var y = rand();
* * // e.g., returns 0.5363925252089496
* *\/
* function rand() {
*     return Math.random();
* }
*/
rules[ 'stdlib/jsdoc-leading-description-sentence' ] = 'error';

/**
* Enforce that require() calls have only string literals as parameters.
*
* @name no-dynamic-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var pkg = '@stdlib/math/base/special/betainc';
* var betainc = require( pkg );
*
* @example
* // Good...
* var betainc = require( '@stdlib/math/base/special/betainc' );
*/
rules[ 'stdlib/no-dynamic-require' ] = 'error';

/**
* Enforce that require() expressions are not immediately invoked.
*
* @name no-immediate-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var debug = require( 'debug' )( 'stdlib' );
*
* @example
* // Good...
* var logger = require( 'debug' );
* var debug = logger( 'stdlib' );
*/
rules[ 'stdlib/no-immediate-require' ] = 'off'; // TODO: Enable once require( 'object-keys').shim() has been replaced

/**
* Disallow require() calls of another package's internals.
*
* @name no-internal-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var betainc = require( '@stdlib/math/base/special/betainc/lib/index.js' );
*
* @example
* // Good...
* var betainc = require( '@stdlib/math/base/special/betainc' );
*/
rules[ 'stdlib/no-internal-require' ] = 'error';

/**
* Enforce that one does not use nested property access for `require()` expressions.
*
* @name no-nested-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var special = require( '@stdlib' ).math.base.special;
*
* @example
* // Good...
* var special = require( '@stdlib/math/base' ).special;
*
* @example
* // Good...
* var special = require( '@stdlib/math/base/special' );
*/
rules[ 'stdlib/no-nested-require' ] = 'error';

/**
* Never allow a variable to be declared multiple times within the same scope or for built-in globals to be redeclared.
*
* @name no-redeclare
* @memberof rules
* @type {Array}
* @default [ 'error', { 'builtinGlobals': false, 'globalsWhitelist': [] } ]
* @see [no-redeclare]{@link http://eslint.org/docs/rules/no-redeclare}
*
* @example
* // Bad...
* var a = 'beep';
* // ...
* var a = 'boop';
*
* @example
* // Good...
* var a = 'beep';
* // ...
* a = 'boop';
*/
rules[ 'stdlib/no-redeclare' ] = [ 'error', {
	'builtinGlobals': true,
	'globalsWhitelist': [
		'Array',
		'ArrayBuffer',
		'Boolean',
		'Buffer',
		'DataView',
		'Date',
		'Error',
		'EvalError',
		'Float32Array',
		'Float64Array',
		'Int8Array',
		'Int16Array',
		'Int32Array',
		'Map',
		'Number',
		'Object',
		'Promise',
		'RangeError',
		'ReferenceError',
		'RegExp',
		'Set',
		'SharedArrayBuffer',
		'String',
		'Symbol',
		'SyntaxError',
		'TypeError',
		'Uint8Array',
		'Uint8ClampedArray',
		'Uint16Array',
		'Uint32Array',
		'URIError'
	]
}];

/**
* Enforce that require() calls of files end with a whitelisted file extension.
*
* @name require-file-extensions
* @memberof rules
* @type {Array}
* @default [ 'error', { 'extensionsWhitelist': [ '.js', '.json', '.node' ] } ]
*
* @example
* // Bad...
*
* // Invalid file extension:
* var readme = require( '@stdlib/array/int32/README.md' );
*
* // Missing file extension:
* var debug = require( 'debug/src/browser' );
*
* @example
* // Good...
*
* var Int32Array = require( '@stdlib/array/int32' );
*
* var debug = require( 'debug/src/browser.js' );
*/
rules[ 'stdlib/require-file-extensions' ] = [ 'off', { // TODO: Enable once all @stdlib/tools packages are moved to @stdlib/_tools
	'extensionsWhitelist': [
		'.js',
		'.json',
		'.node'
	]
}];

/**
* Enforce that specified globals are explicitly required.
*
* @name require-globals
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var arr = new Float32Array();
*
* @example
* // Good...
* var Float32Array = require( '@stdlib/array/float32' );
*
* var arr = new Float32Array();
*/
rules[ 'stdlib/require-globals' ] = [ 'error', {
	'globals': [
		'ArrayBuffer',
		'Buffer',
		'DataView',
		'Float32Array',
		'Float64Array',
		'Int8Array',
		'Int16Array',
		'Int32Array',
		'SharedArrayBuffer',
		'Uint8Array',
		'Uint8ClampedArray',
		'Uint16Array',
		'Uint32Array'
	]
}];

/**
* Enforce that typed array constructors are explicitly required.
*
* @name section-headers
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad... (require two trailing slashes)
*
* // EXPORTS
*
* module.exports = {};
*
* @example
* // Bad... (require a known header type)
*
* // EXPRTS //
*
* module.exports = {};
*
* @example
* // Bad... (require all uppercase letters)
*
* // EXPorts //
*
* module.exports = {};
*
* @example
* // Good...
*
* // EXPORTS //
*
* module.exports = {};
*/
rules[ 'stdlib/section-headers' ] = 'error';

// EXPORTS //

module.exports = rules;
<commit_msg>Activate rule<commit_after>'use strict';

/**
* ESLint rules specific to stdlib.
*
* @namespace rules
*/
var rules = {};

/**
* Require an empty line before single-line comments.
*
* @name empty-line-before-comment
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* function square( x ) {
*     var out;
*     // Square the number:
*     out = x*x;
*     return out;
* }
*
* @example
* // Good...
* function square( x ) {
*     var out;
*
*     // Square the number:
*     out = x*x;
*     return out;
* }
*/
rules[ 'stdlib/empty-line-before-comment' ] = 'error';

/**
* Require that only allowed JSDoc tags are used.
*
* @name jsdoc-tag-names
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
*
* /**
* * Squares a number.
* *
* * @arg {number} x - input number
* * @return {number} x squared
* *
* * @examples
* * var y = square( 2.0 );
* * // returns 4.0
* *\/
* function square( x ) {
*     return x*x;
* }
*
* @example
* // Good...
*
* /**
* * Squares a number.
* *
* * @param {number} x - input number
* * @returns {number} x squared
* *
* * @example
* * var y = square( 2.0 );
* * // returns 4.0
* *\/
* function square( x ) {
*     return x*x;
* }
*/
rules[ 'stdlib/jsdoc-tag-names' ] = 'error';

/**
* Require that JSDoc descriptions start with an uppercase letter and end with a period.
*
* @name jsdoc-leading-description-sentence
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
*
* /**
* * returns a pseudo-random number on [0,1]
* *
* * @returns {number} uniform random number
* *
* * @example
* * var y = rand();
* * // e.g., returns 0.5363925252089496
* *\/
* function rand() {
*     return Math.random();
* }
*
* @example
* // Good...
*
* /**
* * Returns a pseudo-random number on [0,1].
* *
* * @returns {number} uniform random number
* *
* * @example
* * var y = rand();
* * // e.g., returns 0.5363925252089496
* *\/
* function rand() {
*     return Math.random();
* }
*/
rules[ 'stdlib/jsdoc-leading-description-sentence' ] = 'error';

/**
* Enforce that error constructors are invoked with the `new` keyword.
*
* @name new-cap-error
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var err = Error( 'error message' );
*
* @example
* // Good...
* var err = new Error( 'error message' );
*/
rules[ 'stdlib/new-cap-error' ] = 'error';

/**
* Enforce that require() calls have only string literals as parameters.
*
* @name no-dynamic-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var pkg = '@stdlib/math/base/special/betainc';
* var betainc = require( pkg );
*
* @example
* // Good...
* var betainc = require( '@stdlib/math/base/special/betainc' );
*/
rules[ 'stdlib/no-dynamic-require' ] = 'error';

/**
* Enforce that require() expressions are not immediately invoked.
*
* @name no-immediate-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var debug = require( 'debug' )( 'stdlib' );
*
* @example
* // Good...
* var logger = require( 'debug' );
* var debug = logger( 'stdlib' );
*/
rules[ 'stdlib/no-immediate-require' ] = 'off'; // TODO: Enable once require( 'object-keys').shim() has been replaced

/**
* Disallow require() calls of another package's internals.
*
* @name no-internal-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var betainc = require( '@stdlib/math/base/special/betainc/lib/index.js' );
*
* @example
* // Good...
* var betainc = require( '@stdlib/math/base/special/betainc' );
*/
rules[ 'stdlib/no-internal-require' ] = 'error';

/**
* Enforce that one does not use nested property access for `require()` expressions.
*
* @name no-nested-require
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var special = require( '@stdlib' ).math.base.special;
*
* @example
* // Good...
* var special = require( '@stdlib/math/base' ).special;
*
* @example
* // Good...
* var special = require( '@stdlib/math/base/special' );
*/
rules[ 'stdlib/no-nested-require' ] = 'error';

/**
* Never allow a variable to be declared multiple times within the same scope or for built-in globals to be redeclared.
*
* @name no-redeclare
* @memberof rules
* @type {Array}
* @default [ 'error', { 'builtinGlobals': false, 'globalsWhitelist': [] } ]
* @see [no-redeclare]{@link http://eslint.org/docs/rules/no-redeclare}
*
* @example
* // Bad...
* var a = 'beep';
* // ...
* var a = 'boop';
*
* @example
* // Good...
* var a = 'beep';
* // ...
* a = 'boop';
*/
rules[ 'stdlib/no-redeclare' ] = [ 'error', {
	'builtinGlobals': true,
	'globalsWhitelist': [
		'Array',
		'ArrayBuffer',
		'Boolean',
		'Buffer',
		'DataView',
		'Date',
		'Error',
		'EvalError',
		'Float32Array',
		'Float64Array',
		'Int8Array',
		'Int16Array',
		'Int32Array',
		'Map',
		'Number',
		'Object',
		'Promise',
		'RangeError',
		'ReferenceError',
		'RegExp',
		'Set',
		'SharedArrayBuffer',
		'String',
		'Symbol',
		'SyntaxError',
		'TypeError',
		'Uint8Array',
		'Uint8ClampedArray',
		'Uint16Array',
		'Uint32Array',
		'URIError'
	]
}];

/**
* Enforce that require() calls of files end with a whitelisted file extension.
*
* @name require-file-extensions
* @memberof rules
* @type {Array}
* @default [ 'error', { 'extensionsWhitelist': [ '.js', '.json', '.node' ] } ]
*
* @example
* // Bad...
*
* // Invalid file extension:
* var readme = require( '@stdlib/array/int32/README.md' );
*
* // Missing file extension:
* var debug = require( 'debug/src/browser' );
*
* @example
* // Good...
*
* var Int32Array = require( '@stdlib/array/int32' );
*
* var debug = require( 'debug/src/browser.js' );
*/
rules[ 'stdlib/require-file-extensions' ] = [ 'off', { // TODO: Enable once all @stdlib/tools packages are moved to @stdlib/_tools
	'extensionsWhitelist': [
		'.js',
		'.json',
		'.node'
	]
}];

/**
* Enforce that specified globals are explicitly required.
*
* @name require-globals
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad...
* var arr = new Float32Array();
*
* @example
* // Good...
* var Float32Array = require( '@stdlib/array/float32' );
*
* var arr = new Float32Array();
*/
rules[ 'stdlib/require-globals' ] = [ 'error', {
	'globals': [
		'ArrayBuffer',
		'Buffer',
		'DataView',
		'Float32Array',
		'Float64Array',
		'Int8Array',
		'Int16Array',
		'Int32Array',
		'SharedArrayBuffer',
		'Uint8Array',
		'Uint8ClampedArray',
		'Uint16Array',
		'Uint32Array'
	]
}];

/**
* Enforce that typed array constructors are explicitly required.
*
* @name section-headers
* @memberof rules
* @type {string}
* @default 'error'
*
* @example
* // Bad... (require two trailing slashes)
*
* // EXPORTS
*
* module.exports = {};
*
* @example
* // Bad... (require a known header type)
*
* // EXPRTS //
*
* module.exports = {};
*
* @example
* // Bad... (require all uppercase letters)
*
* // EXPorts //
*
* module.exports = {};
*
* @example
* // Good...
*
* // EXPORTS //
*
* module.exports = {};
*/
rules[ 'stdlib/section-headers' ] = 'error';

// EXPORTS //

module.exports = rules;
<|endoftext|>


<commit_before>var Document, Element, Euler, Scene, Vector, dom, fs, vm, _;

fs = require('fs');

_ = require("underscore");

vm = require('vm');

dom = require("../lib/dom-lite");

Element = require("../lib/node");

Document = require("../lib/document");

Vector = require("../lib/vector");

Euler = require("../lib/euler");

Scene = dom.HTMLElement;

// fixme - these are added to all instances of htmlelement, not just the Scene

_.extend(Scene.prototype, {
  stop: function() {
    this.clearTimeouts();
    return this.childNodes = [];
  },
  clearTimeouts: function() {
    return null;
  }
});

Scene.prototype.start = function(reflector){
  var document = this.ownerDocument;

  var timeouts = [];
  var intervals = [];

  this.clearTimeouts = function() {
    var interval, timeout, _j, _k, _len1, _len2;
    for (_j = 0, _len1 = timeouts.length; _j < _len1; _j++) {
      timeout = timeouts[_j];
      clearTimeout(timeout);
    }
    for (_k = 0, _len2 = intervals.length; _k < _len2; _k++) {
      interval = intervals[_k];
      clearInterval(interval);
    }
    timeouts = [];
    return intervals = [];
  };

  // Fixme - this all requires lots of work and thought (do we run in a sandboxed content?) -
  // we should also wrap setTimeout and setInterval calls so that broken code doesn't bring
  // down the server.

  var self = this;

  document.getElementsByTagName("script").map(function(scriptElement){
    var script = null,
      code = null;

    if(scriptElement.innerXML.match(/<!\[CDATA\[/)){
      code = scriptElement.innerXML.replace(/^[\n\r\s]+<!\[CDATA\[/, '').replace(/\]\]>[\n\r\s]+$/,'');
    }else{
      code = scriptElement.textContent;
    }

    try {
      script = vm.createScript(code, document.filename);
    } catch (e) {
      console.log("[server] " + document.filename + ":\n  " + (e.toString()));
      return;
    }

    try {

      // Run a script. Wrap setInterval and setTimeout so that errors in callbacks don't
      // kill the server.

      script.runInNewContext({
        document: document,
        Vector: Vector,
        Euler: Euler,

        channel : {
          log : function(message){
            reflector.chatChannel.sendMessage(self, message)
          }
        },

        setInterval: function(func, timeout) {
          var handle;
          handle = setInterval(function() {
            try {
              return func();
            } catch (_error) {
              e = _error;
              console.log("[server] " + document.filename + ":\n  " + (e.toString()));
              return clearInterval(handle);
            }
          }, timeout);
          intervals.push(handle);
          return handle;
        },

        setTimeout: function(func, timeout) {
          var handle;
          handle = setTimeout(function() {
            try {
              return func();
            } catch (_error) {
              e = _error;
              return console.log("[server] " + document.filename + ":\n  " + (e.toString()));
            }
          }, timeout);
          timeouts.push(handle);
          return handle;
        },
        console: console
      });
    } catch (_error) {
      e = _error;
      console.log("[server] " + document.filename);
      console.log("  " + e.stack.split("\n").slice(0, 2).join("\n  "));
    }
  });

  try{
    document.dispatchEvent("ready");
  }catch(e){
    console.log("[server] " + document.filename);
    console.log("  " + e.stack.split("\n").slice(0, 2).join("\n  "));
  }
}

Scene.load = function(filename, callback) {
  var document, e, intervals, node, parsedScene, script, scriptElement, timeouts, _i, _j, _len, _len1, _ref, _ref1;

  document = Document.createDocument();

  parsedScene = new Element("null");
  parsedScene.ownerDocument = document;

  if (filename.match(/</)) {
    parsedScene.innerXML = filename;
  } else {
    parsedScene.innerXML = fs.readFileSync(filename).toString();
  }

  _ref = parsedScene.childNodes;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    node = _ref[_i];
    if (node.nodeName === 'scene') {
      document.scene = node;
    }
  }

  if (!document.scene) {
    console.log("[server] Couldn't find a <scene /> element in " + filename);
    return;
  }

  document.filename = filename;

  callback(document.scene);
};

module.exports = Scene;
<commit_msg>Add ticksPerSecond.<commit_after>var Document, Element, Euler, Scene, Vector, dom, fs, vm, _;

fs = require('fs');

_ = require("underscore");

vm = require('vm');

dom = require("../lib/dom-lite");

Element = require("../lib/node");

Document = require("../lib/document");

Vector = require("../lib/vector");

Euler = require("../lib/euler");

Scene = dom.HTMLElement;

// fixme - these are added to all instances of htmlelement, not just the Scene

_.extend(Scene.prototype, {
  stop: function() {
    this.clearTimeouts();
    return this.childNodes = [];
  },
  clearTimeouts: function() {
    return null;
  }
});

Scene.prototype.ticksPerSecond = 5;

Scene.prototype.start = function(reflector){
  var document = this.ownerDocument;

  var timeouts = [];
  var intervals = [];

  this.clearTimeouts = function() {
    var interval, timeout, _j, _k, _len1, _len2;
    for (_j = 0, _len1 = timeouts.length; _j < _len1; _j++) {
      timeout = timeouts[_j];
      clearTimeout(timeout);
    }
    for (_k = 0, _len2 = intervals.length; _k < _len2; _k++) {
      interval = intervals[_k];
      clearInterval(interval);
    }
    timeouts = [];
    return intervals = [];
  };

  // Fixme - this all requires lots of work and thought (do we run in a sandboxed content?) -
  // we should also wrap setTimeout and setInterval calls so that broken code doesn't bring
  // down the server.

  var self = this;

  document.getElementsByTagName("script").map(function(scriptElement){
    var script = null,
      code = null;

    if(scriptElement.innerXML.match(/<!\[CDATA\[/)){
      code = scriptElement.innerXML.replace(/^[\n\r\s]+<!\[CDATA\[/, '').replace(/\]\]>[\n\r\s]+$/,'');
    }else{
      code = scriptElement.textContent;
    }

    try {
      script = vm.createScript(code, document.filename);
    } catch (e) {
      console.log("[server] " + document.filename + ":\n  " + (e.toString()));
      return;
    }

    try {

      // Run a script. Wrap setInterval and setTimeout so that errors in callbacks don't
      // kill the server.

      script.runInNewContext({
        document: document,
        Vector: Vector,
        Euler: Euler,

        channel : {
          log : function(message){
            reflector.chatChannel.sendMessage(self, message)
          }
        },

        setInterval: function(func, timeout) {
          var handle;
          handle = setInterval(function() {
            try {
              return func();
            } catch (_error) {
              e = _error;
              console.log("[server] " + document.filename + ":\n  " + (e.toString()));
              return clearInterval(handle);
            }
          }, timeout);
          intervals.push(handle);
          return handle;
        },

        setTimeout: function(func, timeout) {
          var handle;
          handle = setTimeout(function() {
            try {
              return func();
            } catch (_error) {
              e = _error;
              return console.log("[server] " + document.filename + ":\n  " + (e.toString()));
            }
          }, timeout);
          timeouts.push(handle);
          return handle;
        },
        console: console
      });
    } catch (_error) {
      e = _error;
      console.log("[server] " + document.filename);
      console.log("  " + e.stack.split("\n").slice(0, 2).join("\n  "));
    }
  });

  try{
    document.dispatchEvent("ready");
  }catch(e){
    console.log("[server] " + document.filename);
    console.log("  " + e.stack.split("\n").slice(0, 2).join("\n  "));
  }
}

Scene.load = function(filename, callback) {
  var document, e, intervals, node, parsedScene, script, scriptElement, timeouts, _i, _j, _len, _len1, _ref, _ref1;

  document = Document.createDocument();

  parsedScene = new Element("null");
  parsedScene.ownerDocument = document;

  if (filename.match(/</)) {
    parsedScene.innerXML = filename;
  } else {
    parsedScene.innerXML = fs.readFileSync(filename).toString();
  }

  _ref = parsedScene.childNodes;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    node = _ref[_i];
    if (node.nodeName === 'scene') {
      document.scene = node;
    }
  }

  if (!document.scene) {
    console.log("[server] Couldn't find a <scene /> element in " + filename);
    return;
  }

  document.filename = filename;

  callback(document.scene);
};

module.exports = Scene;
<|endoftext|>


<commit_before>(function(){
  'use strict';
  /**
   * Toggle the view/edit form visibility.
   * @param form - The jQuery form selector.
   * @param edit - True to set form to edit mode;
   * false to set form to view mode.
   */
  function toggleFormVisibility(form, edit) {
    if (edit) {
      form.find("[data-part='view']").hide();
      form.find("[data-part='edit']").show();
      form.find("[data-part='edit'] input:not([type='file']):not([type='submit']):first").focus();
    } else {
      form.find("[data-part='view']").show();
      form.find("[data-part='edit'] input").blur();
      form.find("[data-part='edit']").hide();

      // Clear all errors on the parent form
      form.clearFormErrors();

      // Clear any neccesary fields
      form.find("input[data-role='clear']").val("");

      // Copy field data
      var val = form.find("input[data-role='src']").val();
      form.find("input[data-role='edit']").val(val);
    }
  }

  var forms = $("form[data-for]");

  // Add "edit form" listeners
  forms
  .find("[data-action='edit']").click(function() {
    var form = $(this).closest("form");

    // First, hide all form edits
    _.each(forms, function(form) {
      toggleFormVisibility($(form), false);
    });

    // Then, edit the current form
    toggleFormVisibility(form, true);
  });

  // Add "cancel form" listeners
  forms
  .find("[data-action='cancel']").click(function() {
    var form = $(this).closest("form");

    // Hide the edit portion of the form
    toggleFormVisibility(form, false);
  });

  // Add form submit listeners
  forms
  .on("ajax:success", function(ev, data, status) {
    // Simply reload the page
    location.reload();
  })
  .on("ajax:error", function(ev, data, status) {
    // Render form errors
    $(this).renderFormErrors("user", data.responseJSON);
  });

  var repeatTutorialModal = $("#repeat-tutorial-modal");
  var repeatTutorialModalBody = repeatTutorialModal.find(".modal-body");
  initRepeatTutorialModal();
  notificationsSettings();
  initNotificationSettingsForm();

  $("#reset-tutorial-btn")
    .on("ajax:before", function () {
      repeatTutorialModal.modal('show');
    })

    .on("ajax:success", function (e, data) {
      initRepeatTutorialModalBody(data);
    });

  function initRepeatTutorialModal() {
  // Remove modal content when modal window is closed.
    repeatTutorialModal.on("hidden.bs.modal", function () {
      repeatTutorialModalBody.html("");
    });
  }

  // Initialize ajax listeners and elements style on modal body. This
  // function must be called when modal body is changed.
  function initRepeatTutorialModalBody(data) {
    repeatTutorialModalBody.html(data.html);
    repeatTutorialModalBody.find(".selectpicker").selectpicker();
  }

  // Setup notification checkbox buttons
  function notificationsSettings() {
    var notification_settings = [ "recent_notification",
                                  "assignments_notification" ]

    for (var i = 0; i < notification_settings.length; i++ ) {
      var setting = $('[name="' + notification_settings[i] + '"]');
      var dependant = $('[name="' + notification_settings[i] + '_email"]');
      setting
        .checkboxpicker({
          onActiveCls: 'btn-primary'
        }).change(function() {
          if ( $(this).prop('checked') ) {
            enableDependant($('[name="' + $(this).attr('name') + '_email"]'));
          } else {
            disableDependant($('[name="' + $(this).attr('name') + '_email"]'));
          }
        });

      if ( setting.attr('value') === 'true' ) {
        setting.prop('checked', true);
      } else {
        setting.prop('checked', false);
        disableDependant(dependant);
      }

      setEmailSwitch(dependant);
    }

    function setEmailSwitch(setting) {
      setting
        .checkboxpicker({
          onActiveCls: 'btn-primary'
        });
      if ( setting.attr('value') === 'true' ) {
        setting.prop('checked', true);
        enableDependant(setting);
      } else {
        setting.prop('checked', false);
      }
    }

    function disableDependant(dependant) {
      dependant.checkboxpicker().prop('disabled', true);
      dependant.checkboxpicker().prop('checked', false);
    }

    function enableDependant(dependant) {
      dependant.checkboxpicker().prop('disabled', false);
    }

    // Initialize system messages
    var system_message_notification = $('[name="system_message_notification"]');
    system_message_notification
      .checkboxpicker({
        onActiveCls: 'btn-primary'
      });
    system_message_notification.prop('checked', true);
    system_message_notification.prop('disabled', true);

    // Initialize system messages email
    var system_message_notification_mail = $('[name="system_message_notification_email"]');
    system_message_notification_mail
      .checkboxpicker({
        onActiveCls: 'btn-primary'
      });
    system_message_notification_mail.prop(
      'checked',
      system_message_notification_mail.attr('value') === 'true'
    );
  }

  // triggers submit action when the user clicks
  function initNotificationSettingsForm() {
    $('#notifications-settings-panel')
      .find('.btn-group')
      .on('click', function() {
        $(this).submit();
      });
  }
})();
<commit_msg>Fixes different color of buttons in notifications settings [SCI-590]<commit_after>(function(){
  'use strict';
  /**
   * Toggle the view/edit form visibility.
   * @param form - The jQuery form selector.
   * @param edit - True to set form to edit mode;
   * false to set form to view mode.
   */
  function toggleFormVisibility(form, edit) {
    if (edit) {
      form.find("[data-part='view']").hide();
      form.find("[data-part='edit']").show();
      form.find("[data-part='edit'] input:not([type='file']):not([type='submit']):first").focus();
    } else {
      form.find("[data-part='view']").show();
      form.find("[data-part='edit'] input").blur();
      form.find("[data-part='edit']").hide();

      // Clear all errors on the parent form
      form.clearFormErrors();

      // Clear any neccesary fields
      form.find("input[data-role='clear']").val("");

      // Copy field data
      var val = form.find("input[data-role='src']").val();
      form.find("input[data-role='edit']").val(val);
    }
  }

  var forms = $("form[data-for]");

  // Add "edit form" listeners
  forms
  .find("[data-action='edit']").click(function() {
    var form = $(this).closest("form");

    // First, hide all form edits
    _.each(forms, function(form) {
      toggleFormVisibility($(form), false);
    });

    // Then, edit the current form
    toggleFormVisibility(form, true);
  });

  // Add "cancel form" listeners
  forms
  .find("[data-action='cancel']").click(function() {
    var form = $(this).closest("form");

    // Hide the edit portion of the form
    toggleFormVisibility(form, false);
  });

  // Add form submit listeners
  forms
  .on("ajax:success", function(ev, data, status) {
    // Simply reload the page
    location.reload();
  })
  .on("ajax:error", function(ev, data, status) {
    // Render form errors
    $(this).renderFormErrors("user", data.responseJSON);
  });

  var repeatTutorialModal = $("#repeat-tutorial-modal");
  var repeatTutorialModalBody = repeatTutorialModal.find(".modal-body");
  initRepeatTutorialModal();
  notificationsSettings();
  initNotificationSettingsForm();

  $("#reset-tutorial-btn")
    .on("ajax:before", function () {
      repeatTutorialModal.modal('show');
    })

    .on("ajax:success", function (e, data) {
      initRepeatTutorialModalBody(data);
    });

  function initRepeatTutorialModal() {
  // Remove modal content when modal window is closed.
    repeatTutorialModal.on("hidden.bs.modal", function () {
      repeatTutorialModalBody.html("");
    });
  }

  // Initialize ajax listeners and elements style on modal body. This
  // function must be called when modal body is changed.
  function initRepeatTutorialModalBody(data) {
    repeatTutorialModalBody.html(data.html);
    repeatTutorialModalBody.find(".selectpicker").selectpicker();
  }

  // Setup notification checkbox buttons
  function notificationsSettings() {
    var notification_settings = [ "recent_notification",
                                  "assignments_notification" ]

    for (var i = 0; i < notification_settings.length; i++ ) {
      var setting = $('[name="' + notification_settings[i] + '"]');
      var dependant = $('[name="' + notification_settings[i] + '_email"]');
      dependant.checkboxpicker({ onActiveCls: 'btn-primary' });
      setting
        .checkboxpicker({
          onActiveCls: 'btn-primary'
        }).change(function() {
          if ( $(this).prop('checked') ) {
            enableDependant($('[name="' + $(this).attr('name') + '_email"]'));
          } else {
            disableDependant($('[name="' + $(this).attr('name') + '_email"]'));
          }
        });

      if ( setting.attr('value') === 'true' ) {
        setting.prop('checked', true);
      } else {
        setting.prop('checked', false);
        disableDependant(dependant);
      }

      setEmailSwitch(dependant);
    }

    function setEmailSwitch(setting) {
      setting
        .checkboxpicker({
          onActiveCls: 'btn-primary'
        });
      if ( setting.attr('value') === 'true' ) {
        setting.prop('checked', true);
        enableDependant(setting);
      } else {
        setting.prop('checked', false);
      }
    }

    function disableDependant(dependant) {
      dependant.checkboxpicker().prop('disabled', true);
      dependant.checkboxpicker().prop('checked', false);
    }

    function enableDependant(dependant) {
      dependant.checkboxpicker().prop('disabled', false);
    }

    // Initialize system messages
    var system_message_notification = $('[name="system_message_notification"]');
    system_message_notification
      .checkboxpicker({
        onActiveCls: 'btn-primary'
      });
    system_message_notification.prop('checked', true);
    system_message_notification.prop('disabled', true);

    // Initialize system messages email
    var system_message_notification_mail = $('[name="system_message_notification_email"]');
    system_message_notification_mail
      .checkboxpicker({
        onActiveCls: 'btn-primary'
      });
    system_message_notification_mail.prop(
      'checked',
      system_message_notification_mail.attr('value') === 'true'
    );
  }

  // triggers submit action when the user clicks
  function initNotificationSettingsForm() {
    $('#notifications-settings-panel')
      .find('.btn-group')
      .on('click', function() {
        $(this).submit();
      });
  }
})();
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');

App.WizardStep3View = Em.View.extend({

  templateName: require('templates/wizard/step3'),
  category: '',

  didInsertElement: function () {
    this.get('controller').navigateStep();
  },

  message:'',
  linkText: '',
  status: '',

  registeredHostsMessage: '',

  setRegisteredHosts: function(){
    this.set('registeredHostsMessage',Em.I18n.t('installer.step3.warning.registeredHosts').format(this.get('controller.registeredHosts').length));
  }.observes('controller.registeredHosts'),

  monitorStatuses: function() {
    var failedHosts = 0;
    var hosts = this.get('controller.bootHosts');
    hosts.forEach(function(host) {
      if (host.get('bootStatus') == 'FAILED') {
        failedHosts++;
      }
    });
    if (hosts.length==0) {
      this.set('status', 'alert-warn');
      this.set('linkText', '');
      this.set('message', Em.I18n.t('installer.step3.warnings.missingHosts'));
    } else if (this.get('controller.isHostHaveWarnings')) {
      this.set('status', 'alert-warn');
      this.set('linkText', Em.I18n.t('installer.step3.warnings.linkText'));
      this.set('message', Em.I18n.t('installer.step3.warnings.fails').format(hosts.length, failedHosts));
    } else {
      this.set('status', 'alert-success');
      this.set('linkText', Em.I18n.t('installer.step3.noWarnings.linkText'));
      if (failedHosts == 0) {
        // all are ok
        this.set('message', Em.I18n.t('installer.step3.warnings.noWarnings').format(hosts.length));
      } else if (failedHosts == hosts.length) {
        // all failed
        this.set('status', 'alert-warn');
        this.set('linkText', '');
        this.set('message', Em.I18n.t('installer.step3.warnings.allFailed').format(failedHosts));
      } else {
        // some failed
        this.set('message', Em.I18n.t('installer.step3.warnings.someWarnings').format((hosts.length-failedHosts), failedHosts));
      }
    }
  }.observes('controller.isHostHaveWarnings', 'controller.bootHosts.@each.bootStatus')
});

//todo: move it inside WizardStep3View
App.WizardHostView = Em.View.extend({

  tagName: 'tr',
  classNameBindings: ['hostInfo.bootStatus'],
  hostInfo: null,

  remove: function () {
    this.get('controller').removeHost(this.get('hostInfo'));
  },

  retry: function() {
    this.get('controller').retryHost(this.get('hostInfo'));
  },

  isRemovable: function () {
    return true;
  }.property(),

  isRetryable: function() {
    // return ['FAILED'].contains(this.get('hostInfo.bootStatus'));
    return false;
  }.property('hostInfo.bootStatus')

});

<commit_msg>AMBARI-3066 Host checks should be skipped on failed to register host. (atkach)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');

App.WizardStep3View = Em.View.extend({

  templateName: require('templates/wizard/step3'),
  category: '',

  didInsertElement: function () {
    this.get('controller').navigateStep();
  },

  message:'',
  linkText: '',
  status: '',

  registeredHostsMessage: '',

  setRegisteredHosts: function(){
    this.set('registeredHostsMessage',Em.I18n.t('installer.step3.warning.registeredHosts').format(this.get('controller.registeredHosts').length));
  }.observes('controller.registeredHosts'),

  monitorStatuses: function() {
    var failedHosts = 0;
    var hosts = this.get('controller.bootHosts');
    hosts.forEach(function(host) {
      if (host.get('bootStatus') == 'FAILED') {
        failedHosts++;
      }
    });
    if (hosts.length==0) {
      this.set('status', 'alert-warn');
      this.set('linkText', '');
      this.set('message', Em.I18n.t('installer.step3.warnings.missingHosts'));
    } else if (this.get('controller.isHostHaveWarnings')) {
      this.set('status', 'alert-warn');
      this.set('linkText', Em.I18n.t('installer.step3.warnings.linkText'));
      this.set('message', Em.I18n.t('installer.step3.warnings.fails').format(hosts.length - failedHosts));
    } else {
      this.set('status', 'alert-success');
      this.set('linkText', Em.I18n.t('installer.step3.noWarnings.linkText'));
      if (failedHosts == 0) {
        // all are ok
        this.set('message', Em.I18n.t('installer.step3.warnings.noWarnings').format(hosts.length));
      } else if (failedHosts == hosts.length) {
        // all failed
        this.set('status', 'alert-warn');
        this.set('linkText', '');
        this.set('message', Em.I18n.t('installer.step3.warnings.allFailed').format(failedHosts));
      } else {
        // some failed
        this.set('message', Em.I18n.t('installer.step3.warnings.someWarnings').format((hosts.length-failedHosts), failedHosts));
      }
    }
  }.observes('controller.isHostHaveWarnings', 'controller.bootHosts.@each.bootStatus')
});

//todo: move it inside WizardStep3View
App.WizardHostView = Em.View.extend({

  tagName: 'tr',
  classNameBindings: ['hostInfo.bootStatus'],
  hostInfo: null,

  remove: function () {
    this.get('controller').removeHost(this.get('hostInfo'));
  },

  retry: function() {
    this.get('controller').retryHost(this.get('hostInfo'));
  },

  isRemovable: function () {
    return true;
  }.property(),

  isRetryable: function() {
    // return ['FAILED'].contains(this.get('hostInfo.bootStatus'));
    return false;
  }.property('hostInfo.bootStatus')

});

<|endoftext|>


<commit_before>module.exports = {
    env: {
        browser: true,
        es6: true,
        node: true,
    },
    parserOptions: {
        ecmaVersion: 8,
        sourceType: 'module',
    },
    parser: 'babel-eslint',
    plugins: [
        'react',
        'jsx-a11y',
    ],
    rules: {
        //////////////////////////////////////////
        // Starting from the top of ESLint rules//
        //////////////////////////////////////////
        // 'for-direction': 2,
        'no-await-in-loop': 1,
        'no-compare-neg-zero': 2,
        'no-cond-assign': 1,
        'no-console': 1,
        'no-control-regex': 2,
        'no-debugger': 0,
        'no-dupe-args': 2,
        'no-dupe-keys': 2,
        'no-duplicate-case': 2,
        'no-empty': [1, { allowEmptyCatch: true }],
        'no-empty-character-class': 1,
        'no-ex-assign': 1,
        'no-extra-boolean-cast': 2,
        'no-invalid-regexp': 2,
        'no-irregular-whitespace': [2, {
            skipStrings: true,
            skipComments: true,
            // skipRegExps: true,
            skipTemplates: true,
        }],
        'no-obj-calls': 2,
        'no-prototype-builtins': 0,
        'no-regex-spaces': 1,
        'no-sparse-arrays': 1,
        'no-template-curly-in-string': 1,
        'no-unexpected-multiline': 1,
        'no-unreachable': 1,
        'no-unsafe-finally': 1,
        'no-unsafe-negation': 1,
        'use-isnan': 2,
        'valid-jsdoc': 1,
        'valid-typeof': 2,

        'accessor-pairs': 1,
        'array-callback-return': 2,
        'block-scoped-var': 1,
        'class-methods-use-this': 1,
        complexity: 0,
        'consistent-return': 0,
        curly: 1,
        'default-case': 0,
        'dot-location': 0,
        'dot-notation': 1,
        'eqeqeq': 1,
        'guard-for-in': 1,
        'no-alert': 1,
        'no-caller': 1,
        'no-case-declarations': 1,
        'no-div-regex': 0,
        'no-else-return': 1,
        'no-empty-function': [1, { allow: ['arrowFunctions', ] }],
        'no-empty-pattern': 2,
        'no-eq-null': 0, // eqeqeq takes care of this
        'no-eval': 1,
        'no-extend-native': 1,
        'no-extra-bind': 1,
        'no-extra-label': 1,
        'no-fallthrough': 1,
        'no-floating-decimal': 1,
        'no-global-assign': 1,
        'no-implicit-coercion': 0,
        'no-implicit-globals': 1,
        'no-implied-eval': 2,
        'no-invalid-this': 1,
        'no-iterator': 1,
        'no-labels': 1,
        'no-lone-blocks': 1,
        'no-loop-func': 0,
        'no-magic-numbers': 0,
        'no-multi-spaces': [1, {
            // ignoreEOLComments: true,
        }],
        'no-multi-str': 1,
        'no-new': 1,
        'no-new-func': 1,
        'no-new-wrappers': 1,
        'no-octal': 1,
        'no-param-reassign': 0,
        'no-proto': 1,
        'no-redeclare': 1,
        // 'no-restricted-properties': don't need,
        'no-return-assign': 0,
        'no-return-await': 1,
        'no-script-url': 1,

        //////////////////////////////
        // Rules changed in process //
        //////////////////////////////
        'react/jsx-filename-extension': [1, { 'extensions': ['.js', '.jsx'] }],
        'react/no-unescaped-entities': [0],
        'react/no-array-index-key': [0],
        'react/prop-types': [0],
        'prefer-template': [0],
        'comma-dangle': [0],
        'import/newline-after-import': [0],
        'no-mixed-operators': [0],
        indent: ['error', 4],
        'react/jsx-indent': [2, 4],
        'max-len': [0],
        'quote-props': 0,
        'one-var': 0,
        'object-curly-spacing': 0,
        quotes: [1, 'single'],
        'sort-keys': 0,
        'object-curly-newline': 0,
        'padded-blocks': 0,
        'capitalized-comments': 0,
        'sort-imports': 0,
        'require-jsdoc': 0,
        'space-before-function-paren': 0,
        'react/jsx-sort-props': 0,
        'react/jsx-max-props-per-line': 0,
        'react/jsx-no-literals': 0,
        'react/require-optimization': 0,
        'react/jsx-handler-names': 0,
        'func-style': 0,
        'no-undefined': 0,
        'newline-after-var': 0,
        'semi': 1,
        'no-unused-vars': 1,
        'keyword-spacing': 1,
        'prefer-destructuring': 0,
        camelcase: 0,
        'arrow-parens': 0,
        'react/jsx-no-bind': 1,
        'arrow-body-style': 1,
        'no-extra-parens': 0,
        'newline-per-chained-call': 0,
        'react/forbid-component-props': 0,
        'id-length': 0,
        'multiline-ternary': 0,
        'no-ternary': 0,
        'object-property-newline': 0,
        'newline-before-return': 0,
        'no-inline-comments': 0,
        'max-statements': 0,
        'no-case-declarations': 0,
    },
    // Applied in everse order - react/all will override eslint:all
    extends: [
        'plugin:react/all',
        'eslint:all',
        'plugin:jsx-a11y/recommended',
    ],
};
<commit_msg>Complete eslint main rules<commit_after>module.exports = {
    env: {
        browser: true,
        es6: true,
        node: true,
    },
    parserOptions: {
        ecmaVersion: 8,
        sourceType: 'module',
    },
    parser: 'babel-eslint',
    plugins: [
        'react',
        'jsx-a11y',
    ],
    rules: {
        //////////////////////////////////////////
        // Starting from the top of ESLint rules//
        //////////////////////////////////////////
        'no-await-in-loop': 1,
        'no-compare-neg-zero': 2,
        'no-cond-assign': 1,
        'no-console': 1,
        'no-control-regex': 2,
        'no-debugger': 0,
        'no-dupe-args': 2,
        'no-dupe-keys': 2,
        'no-duplicate-case': 2,
        'no-empty': [1, { allowEmptyCatch: true }],
        'no-empty-character-class': 1,
        'no-ex-assign': 1,
        'no-extra-boolean-cast': 2,
        'no-invalid-regexp': 2,
        'no-irregular-whitespace': [2, {
            skipStrings: true,
            skipComments: true,
            // skipRegExps: true,
            skipTemplates: true,
        }],
        'no-obj-calls': 2,
        'no-prototype-builtins': 0,
        'no-regex-spaces': 1,
        'no-sparse-arrays': 1,
        'no-template-curly-in-string': 1,
        'no-unexpected-multiline': 1,
        'no-unreachable': 1,
        'no-unsafe-finally': 1,
        'no-unsafe-negation': 1,
        'use-isnan': 2,
        'valid-jsdoc': 1,
        'valid-typeof': 2,

        'accessor-pairs': 1,
        'array-callback-return': 2,
        'block-scoped-var': 1,
        'class-methods-use-this': 1,
        complexity: 0,
        'consistent-return': 0,
        curly: 1,
        'default-case': 0,
        'dot-location': 0,
        'dot-notation': 1,
        'eqeqeq': 1,
        'guard-for-in': 1,
        'no-alert': 1,
        'no-caller': 1,
        'no-case-declarations': 1,
        'no-div-regex': 0,
        'no-else-return': 1,
        'no-empty-function': [1, { allow: ['arrowFunctions', ] }],
        'no-empty-pattern': 2,
        'no-eq-null': 0, // eqeqeq takes care of this
        'no-eval': 1,
        'no-extend-native': 1,
        'no-extra-bind': 1,
        'no-extra-label': 1,
        'no-fallthrough': 1,
        'no-floating-decimal': 1,
        'no-global-assign': 1,
        'no-implicit-coercion': 0,
        'no-implicit-globals': 1,
        'no-implied-eval': 2,
        'no-invalid-this': 1,
        'no-iterator': 1,
        'no-labels': 1,
        'no-lone-blocks': 1,
        'no-loop-func': 0,
        'no-magic-numbers': 0,
        'no-multi-spaces': [1, {
            // ignoreEOLComments: true,
        }],
        'no-multi-str': 1,
        'no-new': 1,
        'no-new-func': 1,
        'no-new-wrappers': 1,
        'no-octal': 1,
        'no-param-reassign': 0,
        'no-proto': 1,
        'no-redeclare': 1,
        // 'no-restricted-properties': don't need,
        'no-return-assign': 0,
        'no-return-await': 1,
        'no-script-url': 1,
        'no-self-assign': 2,
        'no-self-compare': 2,
        'no-sequences': 1,
        'no-throw-literal': 1,
        'no-unmodified-loop-condition': 1,
        'no-unused-labels': 1,
        'no-unused-expressions': [1, {
            allowTernary: true,
            allowShortCircuit: true,
        }],
        'no-useless-call': 1,
        'no-useless-concat': 1,
        'no-useless-escape': 1,
        'no-useless-return': 1,
        'no-void': 1,
        'no-warning-comments': 0,
        'no-with': 1,
        'prefer-promise-reject-errors': 1,
        radix: 0,
        'require-await': 1,
        'vars-on-top': 0,
        'wrap-iife': [1, 'inside'],
        yoda: 1,
        strict: 0,
        'init-declarations': 0,
        'no-catch-shadow': 1,
        'no-delete-var': 1,
        'no-label-var': 1,
        'no-restricted-globals': 0,
        'no-shadow': 1,
        'no-shadow-restricted-names': 2,
        'no-undef': 1,
        'no-undef-init': 1,
        'no-undefined': 0,
        'no-unused-vars': 1,
        'no-use-before-define': 2,

        //////////
        // Node //
        //////////
        'callback-return': 0,
        'global-require': 0,
        'handle-callback-err': 1,
        'no-mixed-requires': 1,
        'no-new-require': 1,
        'no-path-concat': 1,
        'no-process-env': 0,
        'no-process-exit': 0,
        'no-restricted-modules': 0,
        'no-sync': 1,

        ////////////
        // Styling//
        ////////////
        'array-bracket-newline': 0,
        'array-bracket-spacing': 0,
        'array-element-newline': 0,
        'block-spacing': 1,
        'brace-style': 1,
        'camelcase': 0,
        'capitalized-comments': 0,
        'comma-dangle': 0,
        'comma-spacing': 1,
        'comma-style': 1,
        'consistent-this': 0,
        'eol-last': 1,
        'func-call-spacing': 1,
        'func-name-matching': 1,
        'func-names': 0,
        'func-style': [1, 'declaration'],
        'id-blacklist': 0,
        'id-length': 0,
        'id-match': 0,
        'indent': [1, 4],
        'jsx-quotes': [1, 'prefer-double'],
        'key-spacing': 1,
        'keyword-spacing': 1,
        'line-comment-positon': 0,
        'linebreak-style': 0,
        'lines-around-comment': 0,
        'max-depth': 0,
        'max-len': 0,
        'max-lines': 0,
        'max-nested-callbacks': 0,
        'max-params': [1, 2],
        'max-statements': 0,
        'max-statements-per-line': 0,
        'multiline-ternary': 0,
        'new-cap': 1,
        'new-parens': 1,
        'newline-per-chained-call': 0,
        'no-array-constructor': 1,
        'no-bitwise': 0,
        'no-continue': 0,
        'no-inline-comments': 0,
        'no-lonely-if': 1,
        'no-mixed-operators': 0,
        'no-mixed-spaces-and-tabs': 0, //other rules take care of this
        'no-multi-assign': 1,
        'no-multiple-empty-lines': 0,
        'no-nested-ternary': 0,
        'no-new-object': 1,
        'no-plusplus': 0,
        'no-restricted-syntax': 0,
        'no-tabs': 0, // other rules take care of this
        'no-ternary': 0,
        'no-trailing-spaces': 1,
        'no-underscore-dangle': 0,
        'no-unneeded-ternary': 1,
        'no-whitespace-before-property': 1,
        'nonblock-statement-body-position': 0, // other rules take care of this
        'object-curly-newline': 0,
        'object-curly-spacing': [1, 'always'],
        'object-property-newline': 0,
        'one-var': 1,
        'one-var-declaration-per-line': 1,
        'operator-assignment': 1,
        'operator-linebreak': 0,
        'padded-blocks': 0,
        'padding-line-between-statements': 0,
        'quote-props': 0,
        quotes: [1, 'single'],
        'require-jsdoc': 0,
        semi: 1,
        'semi-spacing': 1,
        'sort-keys': 0,
        'sort-vars': 0,
        'space-before-blocks': 1,
        'space-before-function-paren': [1, 'never'],
        'space-in-parens': 0,
        'space-infix-ops': 1,
        'space-unary-ops': 1,
        'spaced-comment': 0,
        'template-tag-spacing': 1,
        'unicode-bom': 0,
        'wrap-regex': 0,

        ////////
        // ES6//
        ////////
        'arrow-body-style': [1, 'as-needed'],
        'arrow-parens': [1, 'as-needed'],
        'arrow-spacing': 1,
        'constructor-super': 2,
        'generator-star-spacing': [1, { 'before': false, 'after': true }],
        'no-class-assign': 2,
        'no-confusing-arrow': 0,
        'no-const-assign': 2,
        'no-dupe-class-members': 2,
        'no-duplicate-imports': 1,
        'no-new-symbol': 2,
        'no-restricted-imports': 0,
        'no-this-before-super': 2,
        'no-useless-computed-key': 1,
        'no-useless-constructor': 1,
        'no-useless-rename': 1,
        'no-var': 1,
        'prefer-arrow-callback': 0,
        'prefer-const': 1,
        'prefer-destructuring': 0,
        'prefer-numeric-literals': 1,
        'prefer-rest-params': 1,
        'prefer-spread': 1,
        'prefer-template': 0,
        'require-yield': 1,
        'rest-spread-spacing': 1,
        'sort-imports': 0,
        'symbol-description': 1,
        'template-curly-spacing': 1,
        'yield-star-spacing': 1,

        //////////////////////////////
        // Rules changed in process //
        //////////////////////////////
        'react/jsx-filename-extension': [1, { 'extensions': ['.js', '.jsx'] }],
        'react/no-unescaped-entities': [0],
        'react/no-array-index-key': [0],
        'react/prop-types': [0],
        'import/newline-after-import': [0],
        'react/jsx-indent': [2, 4],
        'react/jsx-sort-props': 0,
        'react/jsx-max-props-per-line': 0,
        'react/jsx-no-literals': 0,
        'react/require-optimization': 0,
        'react/jsx-handler-names': 0,
        'react/jsx-no-bind': 1,
        'react/forbid-component-props': 0,
    },
    // Applied in everse order - react/all will override eslint:all
    extends: [
        'plugin:react/all',
        'eslint:all',
        'plugin:jsx-a11y/recommended',
    ],
};
<|endoftext|>


<commit_before>(function (App) {
  'use strict';

  var Collection = Backbone.Collection.extend({
    url: 'flag_colors.json'
  });

  App.View.FlagColorsView = Backbone.View.extend({
    className: 'c-flag-colors',
    template: HandlebarsTemplates['admin/flag-colors'],

    defaults: {
      color: '#000000',
      maxColors: 5
    },

    events: {
      'click .js-add-color': '_addColor',
      'click .js-remove-color': '_removeColor',
      'change input': '_updateColor'
    },

    initialize: function (settings) {
      this.options = Object.assign({}, this.defaults, settings);
      this.collection = new Collection((window.gon && gon.global.colorArray && gon.global.colorArray) || []);
      this.render();
    },

    /**
     * Add a new element to the collection with the default color
     */
    _addColor: function () {
      if (this._canAddColor()) {
        this.collection.push({ color: this.options.color });
        this.render();
      }
    },

    /**
     * Remove the color designated by the DOM node
     * @param {object} e - DOM node designating the color to remove
     */
    _removeColor: function (e) {
      var index = $(e.target).data('id');
      var model = this.collection.at(+index);
      this.collection.remove(model);
      this.render();
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var input = e.currentTarget;
      var color = input.value;
      var position = input.dataset.id;
      var model = this.collection.at(position);

      model.set({ color: color });

      // We can't just render here because otherwise, when the user is choosing a
      // color in the color picker, Chrome will send the event while the user is
      // still picking one. On FF, the event is sent only when the user closes the
      // picker.
      input.nextElementSibling.style.backgroundColor = color;

      // We then manually update the hidden field
      this.hiddenColorsInput.value = this._serializeColors();
    },

    /**
     * Serialize the colors for the hidden input
     * @returns {string}
     */
    _serializeColors: function () {
      return this.collection.toJSON().reduce(function (eachRes, color) {
        return eachRes + ' ' + color.color;
      }, '');
    },

    /**
     * Return whether the user can add a new color
     * @returns {boolean} true if can add a color
     */
    _canAddColor: function () {
      return (this.collection.length < this.options.maxColors);
    },

    render: function () {
      this.$el.html(this.template({
        colors: this.collection.toJSON()
          .map(function (color, i) {
            color.index = i + 1; // Index used by the label
            return color;
          }, this),
        addButtonVisible: this._canAddColor(),
        inputId: window.gon && gon.global && gon.global.colorControllerId,
        inputName: window.gon && gon.global && gon.global.colorControllerName,
        colorsValue: this._serializeColors()
      }));
      this.setElement(this.el);

      this.hiddenColorsInput = this.el.querySelector('.js-colors-input');
    }
  });
})(this.App);
<commit_msg>returns if element doesnt exists<commit_after>(function (App) {
  'use strict';

  var Collection = Backbone.Collection.extend({
    url: 'flag_colors.json'
  });

  App.View.FlagColorsView = Backbone.View.extend({
    className: 'c-flag-colors',
    template: HandlebarsTemplates['admin/flag-colors'],

    defaults: {
      color: '#000000',
      maxColors: 5
    },

    events: {
      'click .js-add-color': '_addColor',
      'click .js-remove-color': '_removeColor',
      'change input': '_updateColor'
    },

    initialize: function (settings) {
      this.options = Object.assign({}, this.defaults, settings);
      this.collection = new Collection((window.gon && gon.global.colorArray && gon.global.colorArray) || []);
      this.render();
    },

    /**
     * Add a new element to the collection with the default color
     */
    _addColor: function () {
      if (this._canAddColor()) {
        this.collection.push({ color: this.options.color });
        this.render();
      }
    },

    /**
     * Remove the color designated by the DOM node
     * @param {object} e - DOM node designating the color to remove
     */
    _removeColor: function (e) {
      var index = $(e.target).data('id');
      var model = this.collection.at(+index);
      this.collection.remove(model);
      this.render();
    },

    /**
     * Update the color corresponding to the modified input
     * @param {Event} e - DOM input node
     */
    _updateColor: function (e) {
      var input = e.currentTarget;
      var color = input.value;
      var position = input.dataset.id;
      var model = this.collection.at(position);

      model.set({ color: color });

      // We can't just render here because otherwise, when the user is choosing a
      // color in the color picker, Chrome will send the event while the user is
      // still picking one. On FF, the event is sent only when the user closes the
      // picker.
      input.nextElementSibling.style.backgroundColor = color;

      // We then manually update the hidden field
      this.hiddenColorsInput.value = this._serializeColors();
    },

    /**
     * Serialize the colors for the hidden input
     * @returns {string}
     */
    _serializeColors: function () {
      return this.collection.toJSON().reduce(function (eachRes, color) {
        return eachRes + ' ' + color.color;
      }, '');
    },

    /**
     * Return whether the user can add a new color
     * @returns {boolean} true if can add a color
     */
    _canAddColor: function () {
      return (this.collection.length < this.options.maxColors);
    },

    render: function () {
      if (!this.el) return;

      this.$el.html(this.template({
        colors: this.collection.toJSON()
          .map(function (color, i) {
            color.index = i + 1; // Index used by the label
            return color;
          }, this),
        addButtonVisible: this._canAddColor(),
        inputId: window.gon && gon.global && gon.global.colorControllerId,
        inputName: window.gon && gon.global && gon.global.colorControllerName,
        colorsValue: this._serializeColors()
      }));
      this.setElement(this.el);

      this.hiddenColorsInput = this.el.querySelector('.js-colors-input');
    }
  });
})(this.App);
<|endoftext|>


<commit_before>var express = require('express');
var request = require('superagent');
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var npm = require("npm");
var bodyParser = require('body-parser');

var npmi = require('npmi');
var tarball = require('tarball-extract')
var exec = require('child_process').exec,
  child;
var app = express();

app.use(bodyParser.json())

var resume = require('resume-schema').resumeJson;
var themeDir = 'themes';

function runTheme(options, req, res) {
  var themeDirectory = options.themeDirectory;
  console.log('Generating HTML');
  console.log('hey', themeDirectory)
  var theme = require( path.join(__dirname,'/',themeDirectory) );
  if (theme.render) {
    res.send(theme.render(options.resume));
  } else {
    res.send('Theme error!');
  }
};

var getTheme = function(req, res) {
  if (req.body && req.body.resume) {
    console.log('Use posted resume');
    resume = req.body.resume;
  }

  var theme = 'jsonresume-theme-' + req.params.theme;
  var version = '0';
  var versionCheck = theme.split('@');
  if (versionCheck.length > 1) {
    theme = versionCheck[0];
    version = versionCheck[1];
  }

  var directoryFolder = path.join(themeDir, theme, version);

  console.log(theme, version);
  fs.exists(directoryFolder, function(exists) {
    console.log(directoryFolder, exists);
    if (exists && version !== '0') {
      console.log('Theme cached');
      runTheme({
        themeDirectory: directoryFolder,
        resume: resume
      }, req, res);
      return;
    } else {
      console.log('Checking NPM');
      request.get('https://registry.npmjs.org/' + theme, function(response) {

        var lib = response.body;
        if (version === '0') {
          version = lib['dist-tags'].latest;
        }

        var directoryFolder = path.join(themeDir, theme, version);
        fs.exists(directoryFolder, function(exists) {
          if (exists) {
            runTheme({
              themeDirectory: directoryFolder,
              resume: resume
            }, req, res);
            return;
          } else {
            console.log(directoryFolder);
            var tarballURL = lib.versions[version].dist.tarball;
            console.log(tarballURL);
            var themeVersion = theme + '@' + version;

            mkdirp(directoryFolder, function(err) {
              var tempExtractPath = __dirname + '/tmp/' + themeVersion;
              console.log('Downloading NPM module');
              tarball.extractTarballDownload(tarballURL, __dirname + '/tmp/' + themeVersion + '.tar.gz', tempExtractPath, {}, function(err, result) {
                fs.readdir(tempExtractPath, function(err, files) {
                  var containingFolder = files[0];
                  fs.rename(path.join(tempExtractPath, containingFolder), directoryFolder, function() {
                    console.log('Installing dependencies');
                    child = exec('cd ' + directoryFolder + ' && npm install',
                      function(error, stdout, stderr) {

                        runTheme({
                          themeDirectory: directoryFolder,
                          resume: resume
                        }, req, res);
                        if (error !== null) {
                          console.log('exec error: ' + error);
                        }
                      });
                  });
                })
              })
            });
          }
        });

      });
      // Do something
    }

  });

  var resume = JSON.parse(fs.readFileSync('resume.json', 'utf8')); // Be careful, synchronous operation can block the event loop.

};

app.post('/theme/:theme', getTheme);

app.get('/theme/:theme', getTheme);

console.log('Theme Manager server started');
app.listen(3000);
<commit_msg>Prevent resume override<commit_after>var express = require('express');
var request = require('superagent');
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var npm = require("npm");
var bodyParser = require('body-parser');

var npmi = require('npmi');
var tarball = require('tarball-extract')
var exec = require('child_process').exec,
  child;
var app = express();

app.use(bodyParser.json())

var resume = require('resume-schema').resumeJson;
var themeDir = 'themes';

function runTheme(options, req, res) {
  var themeDirectory = options.themeDirectory;
  console.log('Generating HTML');
  console.log('hey', themeDirectory)
  var theme = require( path.join(__dirname,'/',themeDirectory) );
  if (theme.render) {
    res.send(theme.render(options.resume));
  } else {
    res.send('Theme error!');
  }
};

var getTheme = function(req, res) {
  var resumeObject = resume;

  if (req.body && req.body.resume) {
    console.log('Use posted resume');
    resumeObject = req.body.resume;
  }

  var theme = 'jsonresume-theme-' + req.params.theme;
  var version = '0';
  var versionCheck = theme.split('@');
  if (versionCheck.length > 1) {
    theme = versionCheck[0];
    version = versionCheck[1];
  }

  var directoryFolder = path.join(themeDir, theme, version);

  console.log(theme, version);
  fs.exists(directoryFolder, function(exists) {
    console.log(directoryFolder, exists);
    if (exists && version !== '0') {
      console.log('Theme cached');
      runTheme({
        themeDirectory: directoryFolder,
        resume: resumeObject
      }, req, res);
      return;
    } else {
      console.log('Checking NPM');
      request.get('https://registry.npmjs.org/' + theme, function(response) {

        var lib = response.body;
        if (version === '0') {
          version = lib['dist-tags'].latest;
        }

        var directoryFolder = path.join(themeDir, theme, version);
        fs.exists(directoryFolder, function(exists) {
          if (exists) {
            runTheme({
              themeDirectory: directoryFolder,
              resume: resumeObject
            }, req, res);
            return;
          } else {
            console.log(directoryFolder);
            var tarballURL = lib.versions[version].dist.tarball;
            console.log(tarballURL);
            var themeVersion = theme + '@' + version;

            mkdirp(directoryFolder, function(err) {
              var tempExtractPath = __dirname + '/tmp/' + themeVersion;
              console.log('Downloading NPM module');
              tarball.extractTarballDownload(tarballURL, __dirname + '/tmp/' + themeVersion + '.tar.gz', tempExtractPath, {}, function(err, result) {
                fs.readdir(tempExtractPath, function(err, files) {
                  var containingFolder = files[0];
                  fs.rename(path.join(tempExtractPath, containingFolder), directoryFolder, function() {
                    console.log('Installing dependencies');
                    child = exec('cd ' + directoryFolder + ' && npm install',
                      function(error, stdout, stderr) {
                        runTheme({
                          themeDirectory: directoryFolder,
                          resume: resumeObject
                        }, req, res);
                        if (error !== null) {
                          console.log('exec error: ' + error);
                        }
                      });
                  });
                })
              })
            });
          }
        });
      });
    }
  });

};

app.post('/theme/:theme', getTheme);

app.get('/theme/:theme', getTheme);

console.log('Theme Manager server started');
app.listen(3000);
<|endoftext|>


<commit_before>/* jshint ignore:start */
/*
 * Tests the presence of affix-bottom on different resolutions and
 * data-force-affix-width values;
 *
 * Resolutions: 320x480, 600x800, 768x1024, 720x1280 and 1080x1920.
 * data-foce-affix-width: 568, 768 and 868.
 *
 * affix-bottom should be present if
 * data-force-affix-width > browser.manage().window().width
 */
describe("affix-bottom-directive tests", function () {

  var html;
  var dataForceAffixWidth;

  function setDataForceAffixWidth(width) {
    dataForceAffixWidth = width;
    return '
' +
            '
' +
            '

';
  }

  function testResolutions() {
    for (var i = 0; i < 5; i++) {
      var browserWidth;
      var browserHeight;
      switch (i) {
        case 0:
          browserWidth = 320;
          browserHeight = 480;
          break;
        case 1:
          browserWidth = 600;
          browserHeight = 800;
          break;
        case 2:
          browserWidth = 768;
          browserHeight = 1024;
          break;
        case 3:
          browserWidth = 720;
          browserHeight = 1280;
          break;
        case 4:
          browserWidth = 1080;
          browserHeight = 1920;
          break;
        default:
          return;
      }
      browser.manage().window().setSize(browserWidth, browserHeight);
      browser.get('/#/unit-test-e2e?html=' + encodeURIComponent(html));
    }
  }

  it("affix-bottom is present (568)", function () {
    html = setDataForceAffixWidth(568);
    testResolutions();
  });

  it("affix-bottom is present (768)", function () {
    html = setDataForceAffixWidth(768);
    testResolutions();
  });

  it("affix-bottom is present (868)", function () {
    html = setDataForceAffixWidth(868);
    testResolutions();
  });

  afterEach(function () {
    if (dataForceAffixWidth > browser.manage().window().width) {
      expect(element(by.css('.affix-bottom')).isPresent()).toBe(true);
    } else {
      expect(element(by.css('.affix-bottom')).isPresent()).toBe(false);
    }
  });

});

/* jshint ignore:end */<commit_msg>fix affix-bottom directive test<commit_after>/* jshint ignore:start */
/*
 * Tests the presence of affix-bottom on different resolutions and
 * data-force-affix-width values;
 *
 * Resolutions: 320x480, 600x800, 768x1024, 720x1280 and 1080x1920.
 * data-foce-affix-width: 568, 768 and 868.
 *
 * affix-bottom should be present if
 * data-force-affix-width > browser.manage().window().width
 */
describe("affix-bottom-directive tests", function () {

  var html;
  var dataForceAffixWidth;

  function setDataForceAffixWidth(width) {
    dataForceAffixWidth = width;
    return '
' +
            '
' +
            '

';
  }

  function testResolutions() {
    for (var i = 0; i < 5; i++) {
      var browserWidth;
      var browserHeight;
      switch (i) {
        case 0:
          browserWidth = 320;
          browserHeight = 480;
          break;
        case 1:
          browserWidth = 600;
          browserHeight = 800;
          break;
        case 2:
          browserWidth = 768;
          browserHeight = 1024;
          break;
        case 3:
          browserWidth = 720;
          browserHeight = 1280;
          break;
        case 4:
          browserWidth = 1080;
          browserHeight = 1920;
          break;
        default:
          return;
      }

      browser.manage().window().setSize(browserWidth, browserHeight);
      browser.get('/#/unit-test-e2e?html=' + encodeURIComponent(html));

      if (dataForceAffixWidth > browserWidth) {
        expect(element(by.css('.affix-bottom')).isPresent()).toBe(true);
      } else {
        expect(element(by.css('.affix-bottom')).isPresent()).toBe(false);
      }
    }
  }

  it("affix-bottom is present (568)", function () {
    html = setDataForceAffixWidth(568);
    testResolutions();
  });

  it("affix-bottom is present (768)", function () {
    html = setDataForceAffixWidth(768);
    testResolutions();
  });

  it("affix-bottom is present (868)", function () {
    html = setDataForceAffixWidth(868);
    testResolutions();
  });

});

/* jshint ignore:end */<|endoftext|>


<commit_before>module.exports = {
  env: {
    es6: true,
    amd: true,
    browser: true,
    "jest/globals": true
  },
  extends: [
    "airbnb",
    "prettier",
    "prettier/react",
    "plugin:jest/recommended",
    "plugin:jsx-a11y/recommended"
  ],
  parserOptions: {
    ecmaVersion: 7,
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
      jsx: true
    },
    sourceType: "module"
  },
  parser: "babel-eslint",

  globals: {
    ENV: true,
    INST: true,
  },
  plugins: [
    "promise",
    "import",
    "notice",
    "jest",
    "prettier"
  ],
  // 0 - off, 1 - warning, 2 - error
  rules: {
    "camelcase": [0], // because we have a ton of `const $user_name = $('#user_name')`
    "class-methods-use-this": [0],
    "comma-dangle": [2, "only-multiline"],
    "func-names": [0],
    'guard-for-in': 'off',
    "max-len": [1, {"code": 140}],
    "no-continue": [0],
    "react/destructuring-assignment": [0],
    "react/no-typos": [0],
    "no-cond-assign": ["warn", "except-parens"],
    "no-else-return": [0],
    "no-nested-ternary": "off",
    "no-plusplus": [0],
    'no-prototype-builtins': 'off',
    "no-restricted-syntax": [
      "warn",
      // note: in the default airbnb styleguide this is enabled but we do this
      // all the time and we don't have to worry about somone garbage to
      // Object.prototype (or if someone did, a ton of other code would break too)
      // so we're turning it off
      // {
      //   "selector": "ForInStatement",
      //   "message": "for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array."
      // },
      {
        "selector": "ForOfStatement",
        "message": "iterators/generators require regenerator-runtime ... unless you know for sure you're dealing with an array, in which case they are fine. so `for (const el of Array.from($('someSelector')))` and `for (const key of ['foo', 'bar'])` are both ok but `for (const el of $('someSelector'))` is not."
      },
      {
        "selector": "LabeledStatement",
        "message": "Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand."
      },
      {
        "selector": "WithStatement",
        "message": "`with` is disallowed in strict mode because it makes code impossible to predict and optimize."
      }
    ],
    "no-return-assign": "off",
    "no-underscore-dangle": [0],
    "no-unused-vars": [2, { "argsIgnorePattern": "^_"}],
    "no-use-before-define": "off",
    "one-var": ["error", { initialized: "never" }], // allow `let foo, bar` but not `let foo=1, bar=2`
    "object-curly-spacing": [0],
    "prefer-destructuring": "off",
    "padded-blocks": [0], // so we can have space between the define([... and the callback
    "semi": [0],
    "import/named": [2],
    "import/no-extraneous-dependencies": ["error", {"devDependencies": true}],
    "import/no-commonjs": "off",
    "jest/prefer-to-be-null": "error",
    "jest/prefer-to-be-undefined": "error",
    "react/jsx-filename-extension": [2, { "extensions": [".js"] }],
    "import/extensions": [1, { "js": "never", "jsx": "never", "json": "always" }],
    'notice/notice': ['error', {
      templateFile: 'config/copyright-template.js',
      // purposely lenient so we don't automatically put our copyright notice on
      // top of something already copyrighted by someone else.
      mustMatch: 'Copyright '
    }],
    "promise/avoid-new": [0],
  },
  overrides: [
    {
      files: ['app/**/*', 'spec/**/*', 'public/**/*'],
      rules: {
        // Turn off the "absolute-first" rule. Until we get rid of the `compiled/` and `jsx/`
        // stuff and use real realitive paths it will tell you to do the wrong thing
        "import/first": ["error", {"absolute-first": false}],

        "import/no-amd": "error",
        "import/no-commonjs": "error",
        "import/no-extraneous-dependencies": "off", // allows 'i18n!webzip_exports' and 'compiled/foo/bar'
        "import/no-nodejs-modules": "error",
        'import/order': 'off', // because it thinks 'jsx/whatever' and 'compiled/baz' should go in their groups. we don't want to encourage people to do that just so they move them back together once  those everything is in same dir
        "import/no-unresolved": "off",
        "import/no-webpack-loader-syntax": "off"
      },
    },
    {
      // If you are starting a new project or section of greenfield code,
      // or if there is a folder of code that your team controls that you want
      // to start ensuring conforms to prettier, add it to this array to opt-in
      // now to conform to prettier.
      files: [
        'app/jsx/permissions/**/*.js',
        'app/jsx/account_course_user_search/**/*.js',
        'app/jsx/discussions/**/*.js',
        'app/jsx/announcements/**/*.js'
      ],
      rules: {
        'prettier/prettier': 'error'
      }
    }
  ]
}

<commit_msg>[eslint] turn of no-param-reassign<commit_after>module.exports = {
  env: {
    es6: true,
    amd: true,
    browser: true,
    "jest/globals": true
  },
  extends: [
    "airbnb",
    "prettier",
    "prettier/react",
    "plugin:jest/recommended",
    "plugin:jsx-a11y/recommended"
  ],
  parserOptions: {
    ecmaVersion: 7,
    ecmaFeatures: {
      experimentalObjectRestSpread: true,
      jsx: true
    },
    sourceType: "module"
  },
  parser: "babel-eslint",

  globals: {
    ENV: true,
    INST: true,
  },
  plugins: [
    "promise",
    "import",
    "notice",
    "jest",
    "prettier"
  ],
  // 0 - off, 1 - warning, 2 - error
  rules: {
    "camelcase": [0], // because we have a ton of `const $user_name = $('#user_name')`
    "class-methods-use-this": [0],
    "comma-dangle": [2, "only-multiline"],
    "func-names": [0],
    'guard-for-in': 'off',
    "max-len": [1, {"code": 140}],
    "no-continue": [0],
    "react/destructuring-assignment": [0],
    "react/no-typos": [0],
    "no-cond-assign": ["warn", "except-parens"],
    "no-else-return": [0],
    "no-nested-ternary": "off",
    'no-param-reassign': 'off',
    "no-plusplus": [0],
    'no-prototype-builtins': 'off',
    "no-restricted-syntax": [
      "warn",
      // note: in the default airbnb styleguide this is enabled but we do this
      // all the time and we don't have to worry about somone garbage to
      // Object.prototype (or if someone did, a ton of other code would break too)
      // so we're turning it off
      // {
      //   "selector": "ForInStatement",
      //   "message": "for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array."
      // },
      {
        "selector": "ForOfStatement",
        "message": "iterators/generators require regenerator-runtime ... unless you know for sure you're dealing with an array, in which case they are fine. so `for (const el of Array.from($('someSelector')))` and `for (const key of ['foo', 'bar'])` are both ok but `for (const el of $('someSelector'))` is not."
      },
      {
        "selector": "LabeledStatement",
        "message": "Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand."
      },
      {
        "selector": "WithStatement",
        "message": "`with` is disallowed in strict mode because it makes code impossible to predict and optimize."
      }
    ],
    "no-return-assign": "off",
    "no-underscore-dangle": [0],
    "no-unused-vars": [2, { "argsIgnorePattern": "^_"}],
    "no-use-before-define": "off",
    "one-var": ["error", { initialized: "never" }], // allow `let foo, bar` but not `let foo=1, bar=2`
    "object-curly-spacing": [0],
    "prefer-destructuring": "off",
    "padded-blocks": [0], // so we can have space between the define([... and the callback
    "semi": [0],
    "import/named": [2],
    "import/no-extraneous-dependencies": ["error", {"devDependencies": true}],
    "import/no-commonjs": "off",
    "jest/prefer-to-be-null": "error",
    "jest/prefer-to-be-undefined": "error",
    "react/jsx-filename-extension": [2, { "extensions": [".js"] }],
    "import/extensions": [1, { "js": "never", "jsx": "never", "json": "always" }],
    'notice/notice': ['error', {
      templateFile: 'config/copyright-template.js',
      // purposely lenient so we don't automatically put our copyright notice on
      // top of something already copyrighted by someone else.
      mustMatch: 'Copyright '
    }],
    "promise/avoid-new": [0],
  },
  overrides: [
    {
      files: ['app/**/*', 'spec/**/*', 'public/**/*'],
      rules: {
        // Turn off the "absolute-first" rule. Until we get rid of the `compiled/` and `jsx/`
        // stuff and use real realitive paths it will tell you to do the wrong thing
        "import/first": ["error", {"absolute-first": false}],

        "import/no-amd": "error",
        "import/no-commonjs": "error",
        "import/no-extraneous-dependencies": "off", // allows 'i18n!webzip_exports' and 'compiled/foo/bar'
        "import/no-nodejs-modules": "error",
        'import/order': 'off', // because it thinks 'jsx/whatever' and 'compiled/baz' should go in their groups. we don't want to encourage people to do that just so they move them back together once  those everything is in same dir
        "import/no-unresolved": "off",
        "import/no-webpack-loader-syntax": "off"
      },
    },
    {
      // If you are starting a new project or section of greenfield code,
      // or if there is a folder of code that your team controls that you want
      // to start ensuring conforms to prettier, add it to this array to opt-in
      // now to conform to prettier.
      files: [
        'app/jsx/permissions/**/*.js',
        'app/jsx/account_course_user_search/**/*.js',
        'app/jsx/discussions/**/*.js',
        'app/jsx/announcements/**/*.js'
      ],
      rules: {
        'prettier/prettier': 'error'
      }
    }
  ]
}

<|endoftext|>