<commit_before>'use strict';

const OFF = 'off';
const ERROR = 'error';
const WARN = 'warn';

const COMPLEXITY_MAX = 5;
const TABWIDTH = 2;
const NESTED_CALLBACK_MAX = 4;
const ARGUMENTS_MAX = 4;

module.exports = {
  extends: 'eslint:recommended',
  env: {
    node: true,
  },
  globals: {
    require: false,
    module: false,
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'script',
    arrowFunctions: true,
    binaryLiterals: true,
    blockBindings: true,
    classes: false,
    defaultParams: true,
    destructuring: true,
    forOf: true,
    generators: false,
    modules: false,
    objectLiteralComputedProperties: true,
    objectLiteralDuplicateProperties: true,
    objectLiteralShorthandMethods: true,
    objectLiteralShorthandProperties: true,
    octalLiterals: false,
    regexUFlag: true,
    regexYFlag: true,
    restParams: true,
    spread: true,
    superInFunctions: true,
    templateStrings: true,
    unicodeCodePointEscapes: true,
  },
  rules: {
    'accessor-pairs': [ERROR, { getWithoutSet: false, setWithoutGet: true }],
    'array-bracket-newline': OFF,
    'array-bracket-spacing': [ERROR, 'never'],
    'array-callback-return': ERROR,
    'array-element-newline': OFF,
    'arrow-body-style': [ERROR, 'as-needed'],
    'arrow-parens': [ERROR, 'as-needed'],
    'arrow-spacing': ERROR,
    'block-spacing': [ERROR, 'always'],
    'brace-style': OFF,
    'callback-return': [ERROR, ['callback', 'cb', 'next', 'done']],
    camelcase: OFF,
    'capitalized-comments': OFF,
    'class-methods-use-this': ERROR,
    'comma-dangle': [ERROR, 'always-multiline'],
    'comma-spacing': [ERROR, { before: false, after: true }],
    'comma-style': [ERROR, 'last'],
    complexity: [WARN, COMPLEXITY_MAX],
    'computed-property-spacing': [ERROR, 'never'],
    'consistent-return': ERROR,
    'consistent-this': [ERROR, '_this'],
    'constructor-super': ERROR,
    curly: ERROR,
    'default-case': ERROR,
    'dot-location': [ERROR, 'property'],
    'dot-notation': ERROR,
    'eol-last': ERROR,
    eqeqeq: [ERROR, 'smart'],
    'for-direction': ERROR,
    'func-call-spacing': [ERROR, 'never'],
    'func-names': WARN,
    'func-name-matching': OFF,
    'func-style': [ERROR, 'declaration', { allowArrowFunctions: true }],
    'function-paren-newline': OFF,
    'getter-return': ERROR,
    'global-require': ERROR,
    'guard-for-in': ERROR,
    'handle-callback-err': ERROR,
    'id-blacklist': OFF,
    'id-length': OFF,
    'id-match': OFF,
    indent: OFF,
    'init-declarations': OFF,
    'jsx-quotes': OFF,
    'key-spacing': [ERROR, { beforeColon: false, afterColon: true }],
    'lines-between-class-members': OFF,
    'line-comment-position': OFF,
    'linebreak-style': [ERROR, 'unix'],
    'lines-around-comment': OFF,
    'lines-around-directive': OFF,
    'max-len': [
      WARN,
      100,
      TABWIDTH,
      {
        ignoreComments: true,
        ignorePattern: '^\\s*import\\s.+\\sfrom\\s.+;$',
      },
    ],
    'max-lines': [WARN, { max: 1000 }],
    'max-nested-callbacks': [ERROR, NESTED_CALLBACK_MAX],
    'max-params': [ERROR, ARGUMENTS_MAX],
    'max-statements-per-line': [WARN, { max: 2 }],
    'multiline-comment-style': OFF,
    'multiline-ternary': OFF,
    'new-cap': [ERROR, { newIsCap: true, capIsNew: true }],
    'new-parens': ERROR,
    'newline-after-var': WARN,
    'newline-before-return': OFF,
    'newline-per-chained-call': OFF,
    'no-alert': ERROR,
    'no-array-constructor': ERROR,
    'no-await-in-loop': ERROR,
    'no-buffer-constructor': ERROR,
    'no-caller': ERROR,
    'no-case-declarations': ERROR,
    'no-catch-shadow': ERROR,
    'no-class-assign': ERROR,
    'no-compare-neg-zero': ERROR,
    'no-confusing-arrow': OFF,
    'no-cond-assign': ERROR,
    'no-console': ERROR,
    'no-const-assign': ERROR,
    'no-constant-condition': ERROR,
    'no-continue': OFF,
    'no-control-regex': ERROR,
    'no-debugger': ERROR,
    'no-delete-var': ERROR,
    'no-div-regex': ERROR,
    'no-dupe-args': ERROR,
    'no-dupe-class-members': OFF,
    'no-dupe-keys': ERROR,
    'no-duplicate-case': ERROR,
    'no-duplicate-imports': ERROR,
    'no-else-return': ERROR,
    'no-empty': ERROR,
    'no-empty-character-class': ERROR,
    'no-empty-pattern': ERROR,
    'no-global-assign': ERROR,
    'no-labels': ERROR,
    'no-eq-null': ERROR,
    'no-eval': ERROR,
    'no-ex-assign': ERROR,
    'no-extend-native': ERROR,
    'no-extra-bind': ERROR,
    'no-extra-boolean-cast': ERROR,
    'no-extra-label': OFF,
    'no-extra-parens': OFF,
    'no-extra-semi': ERROR,
    'no-fallthrough': ERROR,
    'no-floating-decimal': ERROR,
    'no-func-assign': ERROR,
    'no-implicit-coercion': OFF,
    'no-implicit-globals': OFF,
    'no-implied-eval': ERROR,
    'no-inline-comments': OFF,
    'no-inner-declarations': ERROR,
    'no-invalid-regexp': ERROR,
    'no-invalid-this': WARN,
    'no-irregular-whitespace': ERROR,
    'no-iterator': ERROR,
    'no-label-var': ERROR,
    'no-lone-blocks': ERROR,
    'no-lonely-if': ERROR,
    'no-loop-func': ERROR,
    'no-magic-numbers': [
      ERROR,
      {
        ignoreArrayIndexes: true,
        ignore: [
          -1,
          0,
          1,
          100,
          101,
          102,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          210,
          226,
          300,
          301,
          302,
          303,
          304,
          305,
          306,
          307,
          308,
          310,
          400,
          401,
          402,
          403,
          404,
          405,
          406,
          407,
          408,
          409,
          410,
          411,
          412,
          413,
          414,
          415,
          416,
          417,
          418,
          421,
          422,
          423,
          424,
          425,
          426,
          427,
          428,
          429,
          431,
          449,
          450,
          451,
          456,
          499,
          500,
          501,
          502,
          503,
          504,
          505,
          506,
          507,
          508,
          509,
          510,
          511,
          520,
        ],
      },
    ],
    'no-mixed-operators': OFF,
    'no-mixed-requires': OFF,
    'no-mixed-spaces-and-tabs': ERROR,
    'no-multi-spaces': ERROR,
    'no-multi-str': ERROR,
    'no-multiple-empty-lines': [ERROR, { max: 2 }],
    'no-native-reassign': ERROR,
    'no-negated-condition': OFF,
    'no-negated-in-lhs': ERROR,
    'no-nested-ternary': OFF,
    'no-new': WARN,
    'no-new-func': ERROR,
    'no-new-object': ERROR,
    'no-new-require': ERROR,
    'no-new-symbol': ERROR,
    'no-obj-calls': ERROR,
    'no-octal': ERROR,
    'no-octal-escape': ERROR,
    'no-param-reassign': OFF,
    'no-path-concat': ERROR,
    'no-process-env': OFF,
    'no-process-exit': OFF,
    'no-proto': ERROR,
    'no-prototype-builtins': WARN,
    'no-redeclare': ERROR,
    'no-regex-spaces': ERROR,
    'no-reserved-keys': OFF,
    'no-restricted-globals': OFF,
    'no-restricted-imports': OFF,
    'no-restricted-modules': OFF,
    'no-restricted-syntax': OFF,
    'no-restricted-properties': [
      ERROR,
      {
        object: 'describe',
        property: 'only',
        message: 'Using describe.only is not allowed',
      },
      {
        object: 'it',
        property: 'only',
        message: 'Using it.only is not allowed',
      },
    ],
    'no-return-assign': ERROR,
    'no-return-await': ERROR,
    'no-script-url': ERROR,
    'no-self-assign': ERROR,
    'no-self-compare': ERROR,
    'no-sequences': ERROR,
    'no-shadow': WARN,
    'no-shadow-restricted-names': ERROR,
    'no-spaced-func': ERROR,
    'no-sparse-arrays': ERROR,
    'no-sync': OFF,
    'no-tabs': ERROR,
    'no-ternary': OFF,
    'no-template-curly-in-string': WARN,
    'no-throw-literal': ERROR,
    'no-this-before-super': ERROR,
    'no-trailing-spaces': ERROR,
    'no-undef': ERROR,
    'no-undef-init': ERROR,
    'no-undefined': ERROR,
    'no-underscore-dangle': OFF,
    'no-unexpected-multiline': ERROR,
    'no-unmodified-loop-condition': ERROR,
    'no-unneeded-ternary': ERROR,
    'no-unreachable': ERROR,
    'no-unsafe-finally': ERROR,
    'no-unsafe-negation': ERROR,
    'no-unused-expressions': ERROR,
    'no-unused-labels': OFF,
    'no-unused-vars': [ERROR, { args: 'none' }],
    'no-use-before-define': [ERROR, 'nofunc'],
    'no-useless-call': ERROR,
    'no-useless-computed-key': ERROR,
    'no-useless-concat': ERROR,
    'no-useless-constructor': ERROR,
    'no-useless-escape': WARN,
    'no-useless-rename': WARN,
    'no-useless-return': ERROR,
    'no-void': ERROR,
    'no-warning-comments': OFF,
    'no-with': ERROR,
    'no-whitespace-before-property': WARN,
    'nonblock-statement-body-position': OFF,
    'object-curly-newline': OFF,
    'object-curly-spacing': [ERROR, 'always'],
    'object-property-newline': [
      ERROR,
      { allowMultiplePropertiesPerLine: true },
    ],
    'one-var': [ERROR, 'never'],
    'one-var-declaration-per-line': OFF,
    'operator-assignment': [ERROR, 'always'],
    'operator-linebreak': OFF,
    'padded-blocks': OFF,
    'padding-line-between-statements': OFF,
    'prefer-arrow-callback': OFF,
    'prefer-destructuring': OFF,
    'prefer-numeric-literals': ERROR,
    'prefer-reflect': OFF,
    'prefer-rest-params': WARN,
    'prefer-spread': OFF,
    'prefer-template': OFF,
    'quote-props': [ERROR, 'as-needed'],
    quotes: [ERROR, 'single', { avoidEscape: true }],
    radix: ERROR,
    'require-await': WARN,
    'require-jsdoc': OFF,
    'require-yield': ERROR,
    'rest-spread-spacing': [ERROR, 'never'],
    semi: [ERROR, 'always'],
    'semi-spacing': [ERROR, { before: false, after: true }],
    'semi-style': ERROR,
    'sort-imports': OFF,
    'sort-keys': OFF,
    'sort-vars': OFF,
    'space-after-keywords': OFF,
    'space-before-blocks': [ERROR, 'always'],
    'space-before-function-paren': OFF,
    'keyword-spacing': [
      'error',
      {
        before: true,
      },
    ],
    'space-in-parens': [ERROR, 'never'],
    'space-infix-ops': ERROR,
    'space-unary-ops': ERROR,
    'spaced-comment': [ERROR, 'always'],
    'switch-colon-spacing': WARN,
    'symbol-description': ERROR,
    'template-curly-spacing': [ERROR, 'never'],
    'template-tag-spacing': OFF,
    'unicode-bom': ERROR,
    'valid-jsdoc': ERROR,
    'valid-typeof': ERROR,
    'vars-on-top': ERROR,
    'wrap-iife': ERROR,
    'wrap-regex': OFF,
    yoda: OFF,
  },
};
<commit_msg>refactor(eslint): replace eslint 4.16 deprecated property<commit_after>'use strict';

const OFF = 'off';
const ERROR = 'error';
const WARN = 'warn';

const COMPLEXITY_MAX = 5;
const TABWIDTH = 2;
const NESTED_CALLBACK_MAX = 4;
const ARGUMENTS_MAX = 4;

module.exports = {
  extends: 'eslint:recommended',
  env: {
    node: true,
  },
  globals: {
    require: false,
    module: false,
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'script',
    arrowFunctions: true,
    binaryLiterals: true,
    blockBindings: true,
    classes: false,
    defaultParams: true,
    destructuring: true,
    forOf: true,
    generators: false,
    modules: false,
    objectLiteralComputedProperties: true,
    objectLiteralDuplicateProperties: true,
    objectLiteralShorthandMethods: true,
    objectLiteralShorthandProperties: true,
    octalLiterals: false,
    regexUFlag: true,
    regexYFlag: true,
    restParams: true,
    spread: true,
    superInFunctions: true,
    templateStrings: true,
    unicodeCodePointEscapes: true,
  },
  rules: {
    'accessor-pairs': [ERROR, { getWithoutSet: false, setWithoutGet: true }],
    'array-bracket-newline': OFF,
    'array-bracket-spacing': [ERROR, 'never'],
    'array-callback-return': ERROR,
    'array-element-newline': OFF,
    'arrow-body-style': [ERROR, 'as-needed'],
    'arrow-parens': [ERROR, 'as-needed'],
    'arrow-spacing': ERROR,
    'block-spacing': [ERROR, 'always'],
    'brace-style': OFF,
    'callback-return': [ERROR, ['callback', 'cb', 'next', 'done']],
    camelcase: OFF,
    'capitalized-comments': OFF,
    'class-methods-use-this': ERROR,
    'comma-dangle': [ERROR, 'always-multiline'],
    'comma-spacing': [ERROR, { before: false, after: true }],
    'comma-style': [ERROR, 'last'],
    complexity: [WARN, COMPLEXITY_MAX],
    'computed-property-spacing': [ERROR, 'never'],
    'consistent-return': ERROR,
    'consistent-this': [ERROR, '_this'],
    'constructor-super': ERROR,
    curly: ERROR,
    'default-case': ERROR,
    'dot-location': [ERROR, 'property'],
    'dot-notation': ERROR,
    'eol-last': ERROR,
    eqeqeq: [ERROR, 'smart'],
    'for-direction': ERROR,
    'func-call-spacing': [ERROR, 'never'],
    'func-names': WARN,
    'func-name-matching': OFF,
    'func-style': [ERROR, 'declaration', { allowArrowFunctions: true }],
    'function-paren-newline': OFF,
    'getter-return': ERROR,
    'global-require': ERROR,
    'guard-for-in': ERROR,
    'handle-callback-err': ERROR,
    'id-blacklist': OFF,
    'id-length': OFF,
    'id-match': OFF,
    indent: OFF,
    'init-declarations': OFF,
    'jsx-quotes': OFF,
    'key-spacing': [ERROR, { beforeColon: false, afterColon: true }],
    'lines-between-class-members': OFF,
    'line-comment-position': OFF,
    'linebreak-style': [ERROR, 'unix'],
    'lines-around-comment': OFF,
    'lines-around-directive': OFF,
    'max-len': [
      WARN,
      100,
      TABWIDTH,
      {
        ignoreComments: true,
        ignorePattern: '^\\s*import\\s.+\\sfrom\\s.+;$',
      },
    ],
    'max-lines': [WARN, { max: 1000 }],
    'max-nested-callbacks': [ERROR, NESTED_CALLBACK_MAX],
    'max-params': [ERROR, ARGUMENTS_MAX],
    'max-statements-per-line': [WARN, { max: 2 }],
    'multiline-comment-style': OFF,
    'multiline-ternary': OFF,
    'new-cap': [ERROR, { newIsCap: true, capIsNew: true }],
    'new-parens': ERROR,
    'newline-after-var': WARN,
    'newline-before-return': OFF,
    'newline-per-chained-call': OFF,
    'no-alert': ERROR,
    'no-array-constructor': ERROR,
    'no-await-in-loop': ERROR,
    'no-buffer-constructor': ERROR,
    'no-caller': ERROR,
    'no-case-declarations': ERROR,
    'no-catch-shadow': ERROR,
    'no-class-assign': ERROR,
    'no-compare-neg-zero': ERROR,
    'no-confusing-arrow': OFF,
    'no-cond-assign': ERROR,
    'no-console': ERROR,
    'no-const-assign': ERROR,
    'no-constant-condition': ERROR,
    'no-continue': OFF,
    'no-control-regex': ERROR,
    'no-debugger': ERROR,
    'no-delete-var': ERROR,
    'no-div-regex': ERROR,
    'no-dupe-args': ERROR,
    'no-dupe-class-members': OFF,
    'no-dupe-keys': ERROR,
    'no-duplicate-case': ERROR,
    'no-duplicate-imports': ERROR,
    'no-else-return': ERROR,
    'no-empty': ERROR,
    'no-empty-character-class': ERROR,
    'no-empty-pattern': ERROR,
    'no-global-assign': ERROR,
    'no-labels': ERROR,
    'no-eq-null': ERROR,
    'no-eval': ERROR,
    'no-ex-assign': ERROR,
    'no-extend-native': ERROR,
    'no-extra-bind': ERROR,
    'no-extra-boolean-cast': ERROR,
    'no-extra-label': OFF,
    'no-extra-parens': OFF,
    'no-extra-semi': ERROR,
    'no-fallthrough': ERROR,
    'no-floating-decimal': ERROR,
    'no-func-assign': ERROR,
    'no-implicit-coercion': OFF,
    'no-implicit-globals': OFF,
    'no-implied-eval': ERROR,
    'no-inline-comments': OFF,
    'no-inner-declarations': ERROR,
    'no-invalid-regexp': ERROR,
    'no-invalid-this': WARN,
    'no-irregular-whitespace': ERROR,
    'no-iterator': ERROR,
    'no-label-var': ERROR,
    'no-lone-blocks': ERROR,
    'no-lonely-if': ERROR,
    'no-loop-func': ERROR,
    'no-magic-numbers': [
      ERROR,
      {
        ignoreArrayIndexes: true,
        ignore: [
          -1,
          0,
          1,
          100,
          101,
          102,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          210,
          226,
          300,
          301,
          302,
          303,
          304,
          305,
          306,
          307,
          308,
          310,
          400,
          401,
          402,
          403,
          404,
          405,
          406,
          407,
          408,
          409,
          410,
          411,
          412,
          413,
          414,
          415,
          416,
          417,
          418,
          421,
          422,
          423,
          424,
          425,
          426,
          427,
          428,
          429,
          431,
          449,
          450,
          451,
          456,
          499,
          500,
          501,
          502,
          503,
          504,
          505,
          506,
          507,
          508,
          509,
          510,
          511,
          520,
        ],
      },
    ],
    'no-mixed-operators': OFF,
    'no-mixed-requires': OFF,
    'no-mixed-spaces-and-tabs': ERROR,
    'no-multi-spaces': ERROR,
    'no-multi-str': ERROR,
    'no-multiple-empty-lines': [ERROR, { max: 2 }],
    'no-native-reassign': ERROR,
    'no-negated-condition': OFF,
    'no-negated-in-lhs': ERROR,
    'no-nested-ternary': OFF,
    'no-new': WARN,
    'no-new-func': ERROR,
    'no-new-object': ERROR,
    'no-new-require': ERROR,
    'no-new-symbol': ERROR,
    'no-obj-calls': ERROR,
    'no-octal': ERROR,
    'no-octal-escape': ERROR,
    'no-param-reassign': OFF,
    'no-path-concat': ERROR,
    'no-process-env': OFF,
    'no-process-exit': OFF,
    'no-proto': ERROR,
    'no-prototype-builtins': WARN,
    'no-redeclare': ERROR,
    'no-regex-spaces': ERROR,
    'no-reserved-keys': OFF,
    'no-restricted-globals': OFF,
    'no-restricted-imports': OFF,
    'no-restricted-modules': OFF,
    'no-restricted-syntax': OFF,
    'no-restricted-properties': [
      ERROR,
      {
        object: 'describe',
        property: 'only',
        message: 'Using describe.only is not allowed',
      },
      {
        object: 'it',
        property: 'only',
        message: 'Using it.only is not allowed',
      },
    ],
    'no-return-assign': ERROR,
    'no-return-await': ERROR,
    'no-script-url': ERROR,
    'no-self-assign': ERROR,
    'no-self-compare': ERROR,
    'no-sequences': ERROR,
    'no-shadow': WARN,
    'no-shadow-restricted-names': ERROR,
    'no-spaced-func': ERROR,
    'no-sparse-arrays': ERROR,
    'no-sync': OFF,
    'no-tabs': ERROR,
    'no-ternary': OFF,
    'no-template-curly-in-string': WARN,
    'no-throw-literal': ERROR,
    'no-this-before-super': ERROR,
    'no-trailing-spaces': ERROR,
    'no-undef': ERROR,
    'no-undef-init': ERROR,
    'no-undefined': ERROR,
    'no-underscore-dangle': OFF,
    'no-unexpected-multiline': ERROR,
    'no-unmodified-loop-condition': ERROR,
    'no-unneeded-ternary': ERROR,
    'no-unreachable': ERROR,
    'no-unsafe-finally': ERROR,
    'no-unsafe-negation': ERROR,
    'no-unused-expressions': ERROR,
    'no-unused-labels': OFF,
    'no-unused-vars': [ERROR, { args: 'none' }],
    'no-use-before-define': [ERROR, 'nofunc'],
    'no-useless-call': ERROR,
    'no-useless-computed-key': ERROR,
    'no-useless-concat': ERROR,
    'no-useless-constructor': ERROR,
    'no-useless-escape': WARN,
    'no-useless-rename': WARN,
    'no-useless-return': ERROR,
    'no-void': ERROR,
    'no-warning-comments': OFF,
    'no-with': ERROR,
    'no-whitespace-before-property': WARN,
    'nonblock-statement-body-position': OFF,
    'object-curly-newline': OFF,
    'object-curly-spacing': [ERROR, 'always'],
    'object-property-newline': [
      ERROR,
      { allowAllPropertiesOnSameLine: true },
    ],
    'one-var': [ERROR, 'never'],
    'one-var-declaration-per-line': OFF,
    'operator-assignment': [ERROR, 'always'],
    'operator-linebreak': OFF,
    'padded-blocks': OFF,
    'padding-line-between-statements': OFF,
    'prefer-arrow-callback': OFF,
    'prefer-destructuring': OFF,
    'prefer-numeric-literals': ERROR,
    'prefer-reflect': OFF,
    'prefer-rest-params': WARN,
    'prefer-spread': OFF,
    'prefer-template': OFF,
    'quote-props': [ERROR, 'as-needed'],
    quotes: [ERROR, 'single', { avoidEscape: true }],
    radix: ERROR,
    'require-await': WARN,
    'require-jsdoc': OFF,
    'require-yield': ERROR,
    'rest-spread-spacing': [ERROR, 'never'],
    semi: [ERROR, 'always'],
    'semi-spacing': [ERROR, { before: false, after: true }],
    'semi-style': ERROR,
    'sort-imports': OFF,
    'sort-keys': OFF,
    'sort-vars': OFF,
    'space-after-keywords': OFF,
    'space-before-blocks': [ERROR, 'always'],
    'space-before-function-paren': OFF,
    'keyword-spacing': [
      'error',
      {
        before: true,
      },
    ],
    'space-in-parens': [ERROR, 'never'],
    'space-infix-ops': ERROR,
    'space-unary-ops': ERROR,
    'spaced-comment': [ERROR, 'always'],
    'switch-colon-spacing': WARN,
    'symbol-description': ERROR,
    'template-curly-spacing': [ERROR, 'never'],
    'template-tag-spacing': OFF,
    'unicode-bom': ERROR,
    'valid-jsdoc': ERROR,
    'valid-typeof': ERROR,
    'vars-on-top': ERROR,
    'wrap-iife': ERROR,
    'wrap-regex': OFF,
    yoda: OFF,
  },
};
<|endoftext|>


<commit_before>var colors     = require('colors'),
    dateformat = require('dateformat');
var slice = Array.prototype.slice;
var LOG_LEVELS = {
      error:    5,
      warn:     4,
      info:     3,
      verbose:  2,
      debug:    1},
    LOG_COLORS = {
      error:    'red',
      warn:     'yellow',
      info:     'green',
      verbose:  'cyan',
      debug:    'grey'};

function Logger () {
}

Logger.prototype = {
  log: function () { // logger.log(level, 'format text', arg1, arg2 ...);
    var args  = slice.call(arguments);
    var level  = args.shift(),
        format = args.shift();
    if (this.level > LOG_LEVELS[level]) return;
    var tag = '[' + level.toUpperCase() + ']'
    var time = this.time ? '[' + dateformat(new Date(), 'HH:MM:ss:l') + ']' : '';
    args.unshift(time.grey + tag[LOG_COLORS[level]] + ' ' + format);
    console.log.apply(console, args);

  },
  debug:   function () { this.log.apply(this, [].concat('debug',   slice.call(arguments))); },
  verbose: function () { this.log.apply(this, [].concat('verbose', slice.call(arguments))); },
  info:    function () { this.log.apply(this, [].concat('info',    slice.call(arguments))); },
  warn:    function () { this.log.apply(this, [].concat('warn',    slice.call(arguments))); },
  error:   function () { this.log.apply(this, [].concat('error',   slice.call(arguments))); },
};

var __level = LOG_LEVELS.info;
Object.defineProperty(Logger.prototype, 'level', {
  enumerable:   true,
  configurable: true,
  get: function ()      { return __level;         },
  set: function (value) {
    if (!LOG_LEVELS[value]) throw new Error("Unsupported log level '"+value+"'")
    __level = LOG_LEVELS[value];
  }
});

var __time = false;
Object.defineProperty(Logger.prototype, 'time', {
  enumerable:   true,
  configurable: true,
  get: function ()      { return __time;         },
  set: function (value) {        __time = value; }
});

module.exports = new Logger();
module.exports.Logger = Logger;
<commit_msg>set color to magenta for debug level.<commit_after>var colors     = require('colors'),
    dateformat = require('dateformat');
var slice = Array.prototype.slice;
var LOG_LEVELS = {
      error:    5,
      warn:     4,
      info:     3,
      verbose:  2,
      debug:    1},
    LOG_COLORS = {
      error:    'red',
      warn:     'yellow',
      info:     'green',
      verbose:  'cyan',
      debug:    'magenta'};

function Logger () {
}

Logger.prototype = {
  log: function () { // logger.log(level, 'format text', arg1, arg2 ...);
    var args  = slice.call(arguments);
    var level  = args.shift(),
        format = args.shift();
    if (this.level > LOG_LEVELS[level]) return;
    var tag = '[' + level.toUpperCase() + ']'
    var time = this.time ? '[' + dateformat(new Date(), 'HH:MM:ss:l') + ']' : '';
    args.unshift(time.grey + tag[LOG_COLORS[level]] + ' ' + format);
    console.log.apply(console, args);

  },
  debug:   function () { this.log.apply(this, [].concat('debug',   slice.call(arguments))); },
  verbose: function () { this.log.apply(this, [].concat('verbose', slice.call(arguments))); },
  info:    function () { this.log.apply(this, [].concat('info',    slice.call(arguments))); },
  warn:    function () { this.log.apply(this, [].concat('warn',    slice.call(arguments))); },
  error:   function () { this.log.apply(this, [].concat('error',   slice.call(arguments))); },
};

var __level = LOG_LEVELS.info;
Object.defineProperty(Logger.prototype, 'level', {
  enumerable:   true,
  configurable: true,
  get: function ()      { return __level;         },
  set: function (value) {
    if (!LOG_LEVELS[value]) throw new Error("Unsupported log level '"+value+"'")
    __level = LOG_LEVELS[value];
  }
});

var __time = false;
Object.defineProperty(Logger.prototype, 'time', {
  enumerable:   true,
  configurable: true,
  get: function ()      { return __time;         },
  set: function (value) {        __time = value; }
});

module.exports = new Logger();
module.exports.Logger = Logger;
<|endoftext|>


<commit_before>/*
    A small plugin to help Foxy help his friends like Echidnabot
*/

let core = undefined;
let exec = require('child_process').execFile;

let CODEHAUS_Server = "215661302692052992";
let echidnasDir = "/home/vitaly/_Bots/echidnabot";

function isGranted(message)
{
    return (core.botConfig.myboss.indexOf(message.author.id) !== -1) || (message.author.id === "133426635998232577");
}

let knuxLog = function(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    let linesNumber = (args === "" ? 25 : Number(args));

    exec('tail', ["-n", linesNumber.toString(), "knuxlog.log"], {cwd: echidnasDir}, function(err, data)
    {
        if(err == null)
        {
            let s = data.toString();
            if(s.length > 1900)
                s = s.substr(s.length - 1900);
            message.reply("tail -n " + linesNumber + " knuxlog.log\n```\n" + s + "\n```\n");
        }
        else
        {
            message.reply("ERROR of tail -n 25 knuxlog.log```\n" + err + "\n\n" + data.toString() + "\n```\n");
        }
    });
}

let knuxFullLog = function(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    exec('bzip2', ["-fk", echidnasDir + "/knuxlog.log"], {cwd: echidnasDir}, function(err, data)
    {
        if(err == null)
            message.channel.sendFile(echidnasDir + "/knuxlog.log.bz2", "knuxlog.log.bz2").catch(core.msgSendError);
        else
            message.reply("ERROR of bzip2 -fk " + echidnasDir + "/knuxlog.log\n```\n" + err + "\n\n" + data.toString() + "\n```\n");
    });

}

let knuxPoke = function(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    exec('git', ["pull", "origin", "master"], {cwd: echidnasDir}, function(err, data)
    {
        if(err == null)
            message.reply("git pull origin master\n```\n" + data.toString() + "\n```\n");
        else
        {
            message.reply("ERROR of git pull origin master```\n" + err + "\n\n" + data.toString() + "\n```\n");
            exec('git', ["merge", "--abort"], {cwd: echidnasDir}, function(err, data){});
        }
    });
}

function registerCommands(foxyCore)
{
    core = foxyCore;
    core.addCMD(["knuxlog",    knuxLog,           "Check out Knux's log tail. Has optional argument - a count of lines to print.", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knuxlogfile",knuxFullLog,       "Get a complete Knux's log file.", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knuxpoke",   knuxPoke,          "Poke Knux if he is asleep", [], true, [CODEHAUS_Server] ]);
}

module.exports =
{
    registerCommands:   registerCommands
};
<commit_msg>More controls of bots<commit_after>/*
    A small plugin to help Foxy help his friends like Echidnabot
*/

let core = undefined;
let exec = require('child_process').execFile;

let CODEHAUS_Server = "215661302692052992";
let echidnasDir = "/home/vitaly/_Bots/echidnabot";
let minnieDir = "/home/vitaly/_Bots/minnie-marygold";

function isGranted(message)
{
    return (core.botConfig.myboss.indexOf(message.author.id) !== -1) || (message.author.id === "133426635998232577");
}

function knuxLog(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    let linesNumber = (args === "" ? 25 : Number(args));

    exec('tail', ["-n", linesNumber.toString(), "knuxlog.log"], {cwd: echidnasDir}, function(err, data)
    {
        if(err == null)
        {
            let s = data.toString();
            if(s.length > 1900)
                s = s.substr(s.length - 1900);
            message.reply("tail -n " + linesNumber + " knuxlog.log\n```\n" + s + "\n```\n");
        }
        else
        {
            message.reply("ERROR of tail -n 25 knuxlog.log```\n" + err + "\n\n" + data.toString() + "\n```\n");
        }
    });
}

function knuxFullLog(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    exec('bzip2', ["-fk", echidnasDir + "/knuxlog.log"], {cwd: echidnasDir}, function(err, data)
    {
        if(err == null)
            message.channel.sendFile(echidnasDir + "/knuxlog.log.bz2", "knuxlog.log.bz2").catch(core.msgSendError);
        else
            message.reply("ERROR of bzip2 -fk " + echidnasDir + "/knuxlog.log\n```\n" + err + "\n\n" + data.toString() + "\n```\n");
    });

}

function pokeBot(bot, message, botPath)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    exec('git', ["pull", "origin", "master"], {cwd: botPath}, function(err, data)
    {
        if(err == null)
            message.reply("git pull origin master\n```\n" + data.toString() + "\n```\n");
        else
        {
            message.reply("ERROR of git pull origin master```\n" + err + "\n\n" + data.toString() + "\n```\n");
            exec('git', ["merge", "--abort"], {cwd: botPath}, function(err, data){});
        }
    });
}

function knuxPoke(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    pokeBot(bot, message, echidnasDir);
}

function minniePoke(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    pokeBot(bot, message, minnieDir);
}

function systemDofBot(bot, message, botPath, botName, action)
{
    if(!isGranted(message))
    {
        message.reply("Sorry, I can't help you, you are not allowed to use this command");
        return;
    }

    exec('sudo', ["systemctl", action, botName], {cwd: botPath}, function(err, data)
    {
        let fullCommand = "systemctl " + action + " " + botName;
        if(err == null)
            message.reply(fullCommand + "\n```\n" + data.toString() + "\n```\n");
        else
            message.reply("ERROR of " + fullCommand + "```\n" + err + "\n\n" + data.toString() + "\n```\n");
    });
}

function minnieStart(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-minnie", "start");
}

function minnieStop(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-minnie", "stop");
}

function minnieRestart(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-minnie", "restart");
}

function minnieStatus(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-minnie", "status");
}

function knuxStart(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-knux", "start");
}

function knuxStop(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-knux", "stop");
}

function knuxRestart(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-knux", "restart");
}

function knuxStatus(/*Client*/ bot, /*Message*/ message, /*string*/ args)
{
    systemDofBot(bot, message, minnieDir, "discord-knux", "status");
}

function registerCommands(foxyCore)
{
    core = foxyCore;
    core.addCMD(["knuxlog",    knuxLog,           "Check out Knux's log tail. Has optional argument - a count of lines to print.", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knuxlogfile",knuxFullLog,       "Get a complete Knux's log file.", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knuxpoke",   knuxPoke,          "Poke Knux if he is asleep", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["minniepoke", minniePoke,        "Poke Minnie Marygold if she is asleep", [], true, [CODEHAUS_Server] ]);

    core.addCMD(["knux-start",   knuxStart,   "Start Knuckles", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knux-stop",    knuxStop,    "Stop Knuckles", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knux-restart", knuxRestart, "Restart Knuckles", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["knux-status",  knuxStatus,  "Show status of Knuckles", [], true, [CODEHAUS_Server] ]);

    core.addCMD(["minnie-start",   minnieStart,   "Start Minnie Marygold", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["minnie-stop",    minnieStop,    "Stop Minnie Marygold", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["minnie-restart", minnieRestart, "Restart Minnie Marygold", [], true, [CODEHAUS_Server] ]);
    core.addCMD(["minnie-status",  minnieStatus,  "Show status of Minnie Marygold", [], true, [CODEHAUS_Server] ]);
}

module.exports =
{
    registerCommands:   registerCommands
};
<|endoftext|>


<commit_before>/*eslint-disable no-empty */
import warning from 'warning'

const KeyPrefix = '@@History/'
const QuotaExceededError = 'QuotaExceededError'
const SecurityError = 'SecurityError'

function createKey(key) {
  return KeyPrefix + key
}

export function saveState(key, state) {
  try {
    window.sessionStorage.setItem(createKey(key), JSON.stringify(state))
  } catch (error) {
    if (error.name === SecurityError) {
      // Blocking cookies in Mobile Safari (at least) will trigger "SecurityError: DOM Exception 18" on any attempt to access window.sessionStorage.
      warning(
        false,
        '[history] Unable to save state; sessionStorage is not available due to security settings'
      )

      return
    }

    if (error.name === QuotaExceededError || window.sessionStorage.length === 0) {
      // Probably in Safari "private mode" where sessionStorage quota is 0. #42
      warning(
        false,
        '[history] Unable to save state; sessionStorage is not available in Safari private mode'
      )

      return
    }

    throw error
  }
}

export function readState(key) {
  let json
  try {
    json = window.sessionStorage.getItem(createKey(key))
  } catch (error) {
    if (error.name === SecurityError) {
      // Blocking cookies in Mobile Safari (at least) will trigger "SecurityError: DOM Exception 18" on any attempt to access window.sessionStorage.
      warning(
        false,
        '[history] Unable to read state; sessionStorage is not available due to security settings'
      )

      return null
    }
  }

  if (json) {
    try {
      return JSON.parse(json)
    } catch (error) {
      // Ignore invalid JSON.
    }
  }

  return null
}
<commit_msg>Fix formatting<commit_after>/*eslint-disable no-empty */
import warning from 'warning'

const KeyPrefix = '@@History/'
const QuotaExceededError = 'QuotaExceededError'
const SecurityError = 'SecurityError'

function createKey(key) {
  return KeyPrefix + key
}

export function saveState(key, state) {
  try {
    window.sessionStorage.setItem(createKey(key), JSON.stringify(state))
  } catch (error) {
    if (error.name === SecurityError) {
      // Blocking cookies in Safari will trigger "SecurityError: DOM Exception 18"
      // on any attempt to access window.sessionStorage.
      warning(
        false,
        '[history] Unable to save state; sessionStorage is not available due to security settings'
      )

      return
    }

    if (error.name === QuotaExceededError && window.sessionStorage.length === 0) {
      // Safari "private mode" throws "QuotaExceededError: DOM Exception 22".
      warning(
        false,
        '[history] Unable to save state; sessionStorage is not available in Safari private mode'
      )

      return
    }

    throw error
  }
}

export function readState(key) {
  let json
  try {
    json = window.sessionStorage.getItem(createKey(key))
  } catch (error) {
    if (error.name === SecurityError) {
      // Blocking cookies in Safari will trigger "SecurityError: DOM Exception 18"
      // on any attempt to access window.sessionStorage.
      warning(
        false,
        '[history] Unable to read state; sessionStorage is not available due to security settings'
      )

      return null
    }
  }

  if (json) {
    try {
      return JSON.parse(json)
    } catch (error) {
      // Ignore invalid JSON.
    }
  }

  return null
}
<|endoftext|>


<commit_before>var fs = require('fs');
var config = require('../config');
var rss = require('../utils/rss');
var client = require('./discord');

// FEED class
module.exports = function(params) {

  var that = this;

  // -------------------- INIT -------------------- //
  this.init = function(params) {

    // try to get channel by id
    this.channel = client.Channels.find(function(g) {
      return (g.id === params.channel);
    });
    if(!this.channel) {
      console.log('ERROR - channel ' + params.channel + ' not found');
    }

    this.title =        params.title;
    this.description =  params.description;
    this.url =          params.url;
    this.tags =         params.tags;

    this.worker = null;
    this.startWorker();
  };

  // -------------------- TO STRING -------------------- //
  this.toString = function() {
    var str = this.title + ' - ' + this.url;
    if(this.tags.length > 0) {
      str += ' [' + this.tags.toString() + ']';
    }
    return str;
  };

  // -------------------- TO JSON -------------------- //
  this.toJson = function() {
    return {
      channel:      this.channel.id,
      title:        this.title,
      description:  this.description,
      url:          this.url,
      tags:         this.tags,
    };
  };

  // -------------------- ADD TAGS -------------------- //
  this.addTags = function(tags) {
    if(tags) {
      for(var i=0; i<tags.length; i++) {
        this.tags.push(tags[i]);
      }
      this.restartWorker();
    }
  };

  // -------------------- REMOVE TAGS -------------------- //
  this.removeTags = function(tags) {
    if(tags) {
      for(var i=0; i<tags.length; i++) {
        var tag = tags[i];
        var tagIndex = this.tags.indexOf(tag);
        if(tagIndex !== -1) {
          this.tags.splice(tagIndex, 1);
        }
      }
      this.restartWorker();
    }
  };

  // -------------------- START WORKER -------------------- //
  this.startWorker = function() {
    this.getDate();
    this.worker = setInterval(this.getArticles, config.timer * 1000);
  };

  // -------------------- STOP WORKER -------------------- //
  this.stopWorker = function() {
    clearInterval(this.worker);
  };

  // -------------------- RESTART WORKER -------------------- //
  this.restartWorker = function() {
    this.stopWorker();
    this.startWorker();
  };

  // -------------------- CHECK TAGS -------------------- //
  this.checkTags = function(article) {
    if(that.tags.length > 0) {
      var matches = 0;
      // check if article matches all tags
      for(var i=0; i<that.tags.length; i++) {
        var tag = that.tags[i];
        var title = article.title.toLowerCase();
        var descr = article.description.toLowerCase();
        var summary = article.summary.toLowerCase();
        if(
          title.indexOf(tag) !== -1 ||
          descr.indexOf(tag) !== -1 ||
          summary.indexOf(tag) !== -1
        ) {
          matches++;
        }
      }
      return (matches === that.tags.length);
    }
    else {
      return true;
    }
  };

  // -------------------- GET ARTICLES -------------------- //
  this.getArticles = function() {
    rss.get(that.url)
    .then(function(data) {

      // parse articles
      for(var i=data.length-1; i>=0; i--) {

        var article = data[i];
        var date = new Date(article.date);
        var link = article.link || article.origlink;

        // if new article
        if(that.minDate && date.getTime()>that.minDate) {
          // if tags match
          if(that.checkTags(article)) {
            var msg = 'I found an article in "' + that.title + '"';
            if(that.tags.length > 0) {
              msg += ' matching the tags [' + that.tags.toString() + ']'
            }
            msg += ':\n' + link;
            that.channel.sendMessage(msg);
          }
        }

        // get date from latest article
        if(i===0) {
          that.minDate = date.getTime();
        }
      }
    })
    .catch(function(e) {
      console.log('ERROR - ' + e);
    });
  };

  // -------------------- GET DATE -------------------- //
  this.getDate = function() {
    rss.get(that.url)
    .then(function(data) {
      if(data[0]) {
        var date = new Date(data[0].date);
        that.minDate = date.getTime();
      }
      else {
        that.minDate = Date.now();
      }
    })
    .catch(function(e) {
      console.log('ERROR - ' + e);
    });
  };

  this.init(params);
};<commit_msg>fix link<commit_after>var fs = require('fs');
var config = require('../config');
var rss = require('../utils/rss');
var client = require('./discord');

// FEED class
module.exports = function(params) {

  var that = this;

  // -------------------- INIT -------------------- //
  this.init = function(params) {

    // try to get channel by id
    this.channel = client.Channels.find(function(g) {
      return (g.id === params.channel);
    });
    if(!this.channel) {
      console.log('ERROR - channel ' + params.channel + ' not found');
    }

    this.title =        params.title;
    this.description =  params.description;
    this.url =          params.url;
    this.tags =         params.tags;

    this.worker = null;
    this.startWorker();
  };

  // -------------------- TO STRING -------------------- //
  this.toString = function() {
    var str = this.title + ' - ' + this.url;
    if(this.tags.length > 0) {
      str += ' [' + this.tags.toString() + ']';
    }
    return str;
  };

  // -------------------- TO JSON -------------------- //
  this.toJson = function() {
    return {
      channel:      this.channel.id,
      title:        this.title,
      description:  this.description,
      url:          this.url,
      tags:         this.tags,
    };
  };

  // -------------------- ADD TAGS -------------------- //
  this.addTags = function(tags) {
    if(tags) {
      for(var i=0; i<tags.length; i++) {
        this.tags.push(tags[i]);
      }
      this.restartWorker();
    }
  };

  // -------------------- REMOVE TAGS -------------------- //
  this.removeTags = function(tags) {
    if(tags) {
      for(var i=0; i<tags.length; i++) {
        var tag = tags[i];
        var tagIndex = this.tags.indexOf(tag);
        if(tagIndex !== -1) {
          this.tags.splice(tagIndex, 1);
        }
      }
      this.restartWorker();
    }
  };

  // -------------------- START WORKER -------------------- //
  this.startWorker = function() {
    this.getDate();
    this.worker = setInterval(this.getArticles, config.timer * 1000);
  };

  // -------------------- STOP WORKER -------------------- //
  this.stopWorker = function() {
    clearInterval(this.worker);
  };

  // -------------------- RESTART WORKER -------------------- //
  this.restartWorker = function() {
    this.stopWorker();
    this.startWorker();
  };

  // -------------------- CHECK TAGS -------------------- //
  this.checkTags = function(article) {
    if(that.tags.length > 0) {
      var matches = 0;
      // check if article matches all tags
      for(var i=0; i<that.tags.length; i++) {
        var tag = that.tags[i];
        var title = article.title.toLowerCase();
        var descr = article.description.toLowerCase();
        var summary = article.summary.toLowerCase();
        if(
          title.indexOf(tag) !== -1 ||
          descr.indexOf(tag) !== -1 ||
          summary.indexOf(tag) !== -1
        ) {
          matches++;
        }
      }
      return (matches === that.tags.length);
    }
    else {
      return true;
    }
  };

  // -------------------- GET ARTICLES -------------------- //
  this.getArticles = function() {
    rss.get(that.url)
    .then(function(data) {

      // parse articles
      for(var i=data.length-1; i>=0; i--) {

        var article = data[i];
        var date = new Date(article.date);
        var link = article.origlink || article.link;

        // if new article
        if(that.minDate && date.getTime()>that.minDate) {
          // if tags match
          if(that.checkTags(article)) {
            var msg = 'I found an article in "' + that.title + '"';
            if(that.tags.length > 0) {
              msg += ' matching the tags [' + that.tags.toString() + ']'
            }
            msg += ':\n' + link;
            that.channel.sendMessage(msg);
          }
        }

        // get date from latest article
        if(i===0) {
          that.minDate = date.getTime();
        }
      }
    })
    .catch(function(e) {
      console.log('ERROR - ' + e);
    });
  };

  // -------------------- GET DATE -------------------- //
  this.getDate = function() {
    rss.get(that.url)
    .then(function(data) {
      if(data[0]) {
        var date = new Date(data[0].date);
        that.minDate = date.getTime();
      }
      else {
        that.minDate = Date.now();
      }
    })
    .catch(function(e) {
      console.log('ERROR - ' + e);
    });
  };

  this.init(params);
};<|endoftext|>


<commit_before>/* eslint-disable */
Element.prototype.matches = Element.prototype.matches || Element.prototype.msMatches;

Element.prototype.closest = function closest(selector, selectedElement = this) {
  if (!selectedElement) return;
  return selectedElement.matches(selector) ? selectedElement : Element.prototype.closest(selector, selectedElement.parentElement);
};
<commit_msg>Added Element extension with .matches and .closest<commit_after>/* global Element */
/* eslint-disable consistent-return, max-len */

Element.prototype.matches = Element.prototype.matches || Element.prototype.msMatchesSelector;

Element.prototype.closest = function closest(selector, selectedElement = this) {
  if (!selectedElement) return;
  return selectedElement.matches(selector) ? selectedElement : Element.prototype.closest(selector, selectedElement.parentElement);
};
<|endoftext|>


<commit_before>/*global config:true, file:true, task:true, module: true */

var files = {
  0: [
    'libs/jquery-1.6.1.js',
    'libs/underscore.js'
  ],
  1: [
    'libs/jquery.scrollTo-1.4.2.js',
    'libs/jquery.hoverintent.js'
  ],
  2: [
    'src/js/core.js'
  ],
  3: [
    'src/js/models/fact.js',
    'src/js/views/ballooney_thingy.js',
    'src/js/views/balloon.js',
    'src/js/views/prepare.js'
  ],
  4: [
    'src/js/replace.js',
    'src/js/annotate.js',
    'src/js/highlight.js',
    'src/js/scrollto.js',
    'src/js/loaded_message.js',
    'src/js/search.js',
    'src/js/create.js',
    'src/js/modal.js',
    'src/js/lib/indicator.js'
  ],
  5: [
    'src/js/xdm.js'
  ],
  6: [
    'src/js/last.js'
  ]
};

var loaderFiles = {
  0: [
    'libs/easyXDM.js'
  ],
  1: [
    'src/js/loader.js'
  ]
};

module.exports = function(grunt){

  function createFactlinkConcatObject(filesObj) {
    return grunt.utils._.flatten(["<banner>", grunt.utils._(filesObj).map(function(fileGroup) {
      return fileGroup.map(function(file) {
        return "<file_strip_banner:" + file + ">";
      });
    })], true);
  }

  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! \n' +
      ' * <%= pkg.title || pkg.name %> - v<%= pkg.version %> - \n' +
      '<%= pkg.homepage ? " * " + pkg.homepage + "\n" : "" %>' +
      ' *\n' +
      ' * Date: <%= grunt.template.today("m/d/yyyy") %>\n' +
      ' *\n' +
      ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>;\n' +
      ' */'
    },
    concat: {
      'dist/factlink.core.js': createFactlinkConcatObject(files),
      'dist/factlink.start_annotating.js': '<file_strip_banner:src/js/chrome/start_annotating.js>',
      'dist/factlink.stop_annotating.js': '<file_strip_banner:src/js/chrome/stop_annotating.js>',
      'dist/factlink.start_highlighting.js': '<file_strip_banner:src/js/chrome/start_highlighting.js>',
      'dist/factlink.stop_highlighting.js': '<file_strip_banner:src/js/chrome/stop_highlighting.js>',
      'dist/easyXDM/easyXDM.js': '<file_strip_banner:libs/easyXDM.js>',
      'dist/factlink.js': createFactlinkConcatObject(loaderFiles)
    },
    copy: {
      'dist/server/css/basic.css': 'dist/css/basic.css',

      'dist/server/images/arrow.png': 'src/images/arrow.png',
      'dist/server/images/arrows-bottom.png': 'src/images/arrows-bottom.png',
      'dist/server/images/arrows-top.png': 'src/images/arrows-top.png',
      'dist/server/images/bookmark.gif': 'src/images/bookmark.gif',
      'dist/server/images/logo-small.png': 'src/images/logo-small.png',

      'dist/images/arrow.png': 'src/images/arrow.png',
      'dist/images/arrows-bottom.png': 'src/images/arrows-bottom.png',
      'dist/images/arrows-top.png': 'src/images/arrows-top.png',
      'dist/images/bookmark.gif': 'src/images/bookmark.gif',
      'dist/images/logo-small.png': 'src/images/logo-small.png'
    },
    less: {
      basic: {
        src: 'src/css/basic.less',
        dest: 'dist/css/basic.css',
        options: {
          yuicompress: true
        }
      }
    },
    min: {
      'dist/server/factlink.core.min.js': ['<banner>', 'dist/factlink.core.js'],
      'dist/server/factlink.start_annotating.min.js': ['<banner>', 'dist/factlink.start_annotating.js'],
      'dist/server/factlink.stop_annotating.min.js': ['<banner>', 'dist/factlink.stop_annotating.js'],
      'dist/server/factlink.start_highlighting.min.js': ['<banner>', 'dist/factlink.start_highlighting.js'],
      'dist/server/factlink.stop_highlighting.min.js': ['<banner>', 'dist/factlink.stop_highlighting.js'],
      'dist/server/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js'], // for the server
      'dist/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js'],        // for local
      'dist/factlink.min.js': ['<banner>', 'dist/factlink.js']
    },
    qunit: {
      files: ['test/*.html']
    },
    lint: {
      files: ['grunt.js', 'src/js/**/*.js', 'test/**/*.js']
    },
    watch: {
      files: ['src/js/**/*', 'test/**/*', 'grunt.js'],
      tasks: 'lint qunit concat less copy'
    },
    jshint: {
      options: {
        // Settings
        "passfail"      : false,  // Stop on first error.
        "maxerr"        : 100,    // Maximum error before stopping.

        // Predefined globals whom JSHint will ignore.
        "browser"       : true,   // Standard browser globals e.g. `window`, `document`.

        "node"          : false,
        "rhino"         : false,
        "couch"         : false,
        "wsh"           : false,   // Windows Scripting Host.

        "jquery"        : true,
        "prototypejs"   : false,
        "mootools"      : false,
        "dojo"          : false,

        "predef"        : [  // Custom globals.
          "Factlink", "FactlinkConfig", "escape"
        ],

        // Development.
        "debug"         : false,  // Allow debugger statements e.g. browser breakpoints.
        "devel"         : true,   // Allow developments statements e.g. `console.log();`.

        // ECMAScript 5.
        "es5"           : true,   // Allow ECMAScript 5 syntax.
        "strict"        : false,  // Require `use strict` pragma  in every file.
        "globalstrict"  : false,  // Allow global "use strict" (also enables 'strict').

        // The Good Parts.
        "asi"           : false,  // Tolerate Automatic Semicolon Insertion (no semicolons).
        "laxbreak"      : true,   // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
        "bitwise"       : true,   // Prohibit bitwise operators (&, |, ^, etc.).
        "boss"          : true,   // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
        "curly"         : true,   // Require {} for every new block or scope.
        "eqeqeq"        : true,   // Require triple equals i.e. `===`.
        "eqnull"        : false,  // Tolerate use of `== null`.
        "evil"          : false,  // Tolerate use of `eval`.
        "expr"          : false,  // Tolerate `ExpressionStatement` as Programs.
        "forin"         : false,  // Tolerate `for in` loops without `hasOwnPrototype`.
        "immed"         : false,  // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
        "latedef"       : true,   // Prohipit variable use before definition.
        "loopfunc"      : true,   // Allow functions to be defined within loops.
        "noarg"         : true,   // Prohibit use of `arguments.caller` and `arguments.callee`.
        "regexp"        : false,  // Prohibit `.` and `[^...]` in regular expressions.
        "regexdash"     : false,  // Tolerate unescaped last dash i.e. `[-...]`.
        "scripturl"     : true,   // Tolerate script-targeted URLs.
        "shadow"        : false,  // Allows re-define variables later in code e.g. `var x=1; x=2;`.
        "supernew"      : false,  // Tolerate `new function () { ... };` and `new Object;`.
        "undef"         : true,   // Require all non-global variables be declared before they are used.

        // Personal styling preferences.
        "newcap"        : true,   // Require capitalization of all constructor functions e.g. `new F()`.
        "noempty"       : true,   // Prohibit use of empty blocks.
        "nonew"         : true,   // Prohibit use of constructors for side-effects.
        "nomen"         : false,  // Prohibit use of initial or trailing underbars in names.
        "onevar"        : false,  // Allow only one `var` statement per function.
        "plusplus"      : false,  // Prohibit use of `++` & `--`.
        "sub"           : false,  // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
        "trailing"      : true,   // Prohibit trailing whitespaces.
        "white"         : false,  // Check against strict whitespace and indentation rules.
        "indent"        : 2       // Specify indentation spacing
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint qunit concat min copy');
  grunt.registerTask('server', 'concat min copy');

  grunt.registerMultiTask('copy', 'copy files', function () {
    grunt.file.copy(this.data,this.target);
  });

  grunt.loadNpmTasks('grunt-less');
};
<commit_msg>Fixed location of factlink.min.js script<commit_after>/*global config:true, file:true, task:true, module: true */

var files = {
  0: [
    'libs/jquery-1.6.1.js',
    'libs/underscore.js'
  ],
  1: [
    'libs/jquery.scrollTo-1.4.2.js',
    'libs/jquery.hoverintent.js'
  ],
  2: [
    'src/js/core.js'
  ],
  3: [
    'src/js/models/fact.js',
    'src/js/views/ballooney_thingy.js',
    'src/js/views/balloon.js',
    'src/js/views/prepare.js'
  ],
  4: [
    'src/js/replace.js',
    'src/js/annotate.js',
    'src/js/highlight.js',
    'src/js/scrollto.js',
    'src/js/loaded_message.js',
    'src/js/search.js',
    'src/js/create.js',
    'src/js/modal.js',
    'src/js/lib/indicator.js'
  ],
  5: [
    'src/js/xdm.js'
  ],
  6: [
    'src/js/last.js'
  ]
};

var loaderFiles = {
  0: [
    'libs/easyXDM.js'
  ],
  1: [
    'src/js/loader.js'
  ]
};

module.exports = function(grunt){

  function createFactlinkConcatObject(filesObj) {
    return grunt.utils._.flatten(["<banner>", grunt.utils._(filesObj).map(function(fileGroup) {
      return fileGroup.map(function(file) {
        return "<file_strip_banner:" + file + ">";
      });
    })], true);
  }

  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! \n' +
      ' * <%= pkg.title || pkg.name %> - v<%= pkg.version %> - \n' +
      '<%= pkg.homepage ? " * " + pkg.homepage + "\n" : "" %>' +
      ' *\n' +
      ' * Date: <%= grunt.template.today("m/d/yyyy") %>\n' +
      ' *\n' +
      ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>;\n' +
      ' */'
    },
    concat: {
      'dist/factlink.core.js': createFactlinkConcatObject(files),
      'dist/factlink.start_annotating.js': '<file_strip_banner:src/js/chrome/start_annotating.js>',
      'dist/factlink.stop_annotating.js': '<file_strip_banner:src/js/chrome/stop_annotating.js>',
      'dist/factlink.start_highlighting.js': '<file_strip_banner:src/js/chrome/start_highlighting.js>',
      'dist/factlink.stop_highlighting.js': '<file_strip_banner:src/js/chrome/stop_highlighting.js>',
      'dist/easyXDM/easyXDM.js': '<file_strip_banner:libs/easyXDM.js>',
      'dist/factlink.js': createFactlinkConcatObject(loaderFiles)
    },
    copy: {
      'dist/server/css/basic.css': 'dist/css/basic.css',

      'dist/server/images/arrow.png': 'src/images/arrow.png',
      'dist/server/images/arrows-bottom.png': 'src/images/arrows-bottom.png',
      'dist/server/images/arrows-top.png': 'src/images/arrows-top.png',
      'dist/server/images/bookmark.gif': 'src/images/bookmark.gif',
      'dist/server/images/logo-small.png': 'src/images/logo-small.png',

      'dist/images/arrow.png': 'src/images/arrow.png',
      'dist/images/arrows-bottom.png': 'src/images/arrows-bottom.png',
      'dist/images/arrows-top.png': 'src/images/arrows-top.png',
      'dist/images/bookmark.gif': 'src/images/bookmark.gif',
      'dist/images/logo-small.png': 'src/images/logo-small.png'
    },
    less: {
      basic: {
        src: 'src/css/basic.less',
        dest: 'dist/css/basic.css',
        options: {
          yuicompress: true
        }
      }
    },
    min: {
      'dist/server/factlink.core.min.js': ['<banner>', 'dist/factlink.core.js'],
      'dist/server/factlink.start_annotating.min.js': ['<banner>', 'dist/factlink.start_annotating.js'],
      'dist/server/factlink.stop_annotating.min.js': ['<banner>', 'dist/factlink.stop_annotating.js'],
      'dist/server/factlink.start_highlighting.min.js': ['<banner>', 'dist/factlink.start_highlighting.js'],
      'dist/server/factlink.stop_highlighting.min.js': ['<banner>', 'dist/factlink.stop_highlighting.js'],
      'dist/server/factlink.min.js': ['<banner>', 'dist/factlink.js']
      'dist/server/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js'], // for the server
      'dist/easyXDM/easyXDM.min.js': ['<banner>', 'dist/easyXDM/easyXDM.js'],        // for local
    },
    qunit: {
      files: ['test/*.html']
    },
    lint: {
      files: ['grunt.js', 'src/js/**/*.js', 'test/**/*.js']
    },
    watch: {
      files: ['src/js/**/*', 'test/**/*', 'grunt.js'],
      tasks: 'lint qunit concat less copy'
    },
    jshint: {
      options: {
        // Settings
        "passfail"      : false,  // Stop on first error.
        "maxerr"        : 100,    // Maximum error before stopping.

        // Predefined globals whom JSHint will ignore.
        "browser"       : true,   // Standard browser globals e.g. `window`, `document`.

        "node"          : false,
        "rhino"         : false,
        "couch"         : false,
        "wsh"           : false,   // Windows Scripting Host.

        "jquery"        : true,
        "prototypejs"   : false,
        "mootools"      : false,
        "dojo"          : false,

        "predef"        : [  // Custom globals.
          "Factlink", "FactlinkConfig", "escape"
        ],

        // Development.
        "debug"         : false,  // Allow debugger statements e.g. browser breakpoints.
        "devel"         : true,   // Allow developments statements e.g. `console.log();`.

        // ECMAScript 5.
        "es5"           : true,   // Allow ECMAScript 5 syntax.
        "strict"        : false,  // Require `use strict` pragma  in every file.
        "globalstrict"  : false,  // Allow global "use strict" (also enables 'strict').

        // The Good Parts.
        "asi"           : false,  // Tolerate Automatic Semicolon Insertion (no semicolons).
        "laxbreak"      : true,   // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
        "bitwise"       : true,   // Prohibit bitwise operators (&, |, ^, etc.).
        "boss"          : true,   // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
        "curly"         : true,   // Require {} for every new block or scope.
        "eqeqeq"        : true,   // Require triple equals i.e. `===`.
        "eqnull"        : false,  // Tolerate use of `== null`.
        "evil"          : false,  // Tolerate use of `eval`.
        "expr"          : false,  // Tolerate `ExpressionStatement` as Programs.
        "forin"         : false,  // Tolerate `for in` loops without `hasOwnPrototype`.
        "immed"         : false,  // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
        "latedef"       : true,   // Prohipit variable use before definition.
        "loopfunc"      : true,   // Allow functions to be defined within loops.
        "noarg"         : true,   // Prohibit use of `arguments.caller` and `arguments.callee`.
        "regexp"        : false,  // Prohibit `.` and `[^...]` in regular expressions.
        "regexdash"     : false,  // Tolerate unescaped last dash i.e. `[-...]`.
        "scripturl"     : true,   // Tolerate script-targeted URLs.
        "shadow"        : false,  // Allows re-define variables later in code e.g. `var x=1; x=2;`.
        "supernew"      : false,  // Tolerate `new function () { ... };` and `new Object;`.
        "undef"         : true,   // Require all non-global variables be declared before they are used.

        // Personal styling preferences.
        "newcap"        : true,   // Require capitalization of all constructor functions e.g. `new F()`.
        "noempty"       : true,   // Prohibit use of empty blocks.
        "nonew"         : true,   // Prohibit use of constructors for side-effects.
        "nomen"         : false,  // Prohibit use of initial or trailing underbars in names.
        "onevar"        : false,  // Allow only one `var` statement per function.
        "plusplus"      : false,  // Prohibit use of `++` & `--`.
        "sub"           : false,  // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
        "trailing"      : true,   // Prohibit trailing whitespaces.
        "white"         : false,  // Check against strict whitespace and indentation rules.
        "indent"        : 2       // Specify indentation spacing
      }
    },
    uglify: {}
  });

  // Default task.
  grunt.registerTask('default', 'lint qunit concat min copy');
  grunt.registerTask('server', 'concat min copy');

  grunt.registerMultiTask('copy', 'copy files', function () {
    grunt.file.copy(this.data,this.target);
  });

  grunt.loadNpmTasks('grunt-less');
};
<|endoftext|>


<commit_before>var app = angular.module('auction', ['ui.bootstrap', 'ngCookies', 'pascalprecht.translate', 'timer', 'angular-growl']);
var db = {};
var bidder_id = "0";
var auction_doc_id = auction_doc_id||"";
var db_url = db_url||"";

app.constant('AuctionConfig', {
    auction_doc_id: auction_doc_id,
    remote_db: db_url,
    restart_retries: 10,
    default_lang: 'uk',
    debug: true
});

app.filter('formatnumber', ['$filter',
    function(filter) {
        return function(val) {
            return (filter('number')(val) || "").replace(/,/g, " ") || "";
        }
    }
]);

app.config(['$logProvider', 'AuctionConfig', 'growlProvider', function($logProvider, AuctionConfig, growlProvider) {
    $logProvider.debugEnabled(AuctionConfig.debug); // default is true
    growlProvider.globalTimeToLive({
        success: 4000,
        error: 10000,
        warning: 10000,
        info: 4000
    });
    growlProvider.globalPosition('top-center');
    growlProvider.onlyUniqueMessages(false);
}]);

// Catch error log msgs
app.config([ "$provide", function( $provide ) {
    // Use the `decorator` solution to substitute or attach behaviors to
    // original service instance; @see angular-mocks for more examples....

    $provide.decorator( '$log', [ "$delegate", function( $delegate )
    {
        // Save the original $log.debug()
        var origDebug = $delegate.error;

        $delegate.error = function () {
            var args = [].slice.call(arguments);
            dataLayer.push({"event": "JS.error", "MESSAGE": args.join(" ")});
            origDebug.apply(null, arguments)
        };

        return $delegate;
    }]);
}]);

// Catch exceptions
app.factory('$exceptionHandler', function() {
  return function(exception, cause) {
    dataLayer.push({"event": "JS.error", "MESSAGE": exception.message});
    throw exception;
  };
});
<commit_msg>Added truncate package<commit_after>var app = angular.module('auction', ['ui.bootstrap', 'ngCookies', 'pascalprecht.translate', 'timer', 'angular-growl', 'angular-ellipses']);
var db = {};
var bidder_id = "0";
var auction_doc_id = auction_doc_id||"";
var db_url = db_url||"";

app.constant('AuctionConfig', {
    auction_doc_id: auction_doc_id,
    remote_db: db_url,
    restart_retries: 10,
    default_lang: 'uk',
    debug: true
});

app.filter('formatnumber', ['$filter',
    function(filter) {
        return function(val) {
            return (filter('number')(val) || "").replace(/,/g, " ") || "";
        }
    }
]);

app.config(['$logProvider', 'AuctionConfig', 'growlProvider', function($logProvider, AuctionConfig, growlProvider) {
    $logProvider.debugEnabled(AuctionConfig.debug); // default is true
    growlProvider.globalTimeToLive({
        success: 4000,
        error: 10000,
        warning: 10000,
        info: 4000
    });
    growlProvider.globalPosition('top-center');
    growlProvider.onlyUniqueMessages(false);
}]);

// Catch error log msgs
app.config([ "$provide", function( $provide ) {
    // Use the `decorator` solution to substitute or attach behaviors to
    // original service instance; @see angular-mocks for more examples....

    $provide.decorator( '$log', [ "$delegate", function( $delegate )
    {
        // Save the original $log.debug()
        var origDebug = $delegate.error;

        $delegate.error = function () {
            var args = [].slice.call(arguments);
            dataLayer.push({"event": "JS.error", "MESSAGE": args.join(" ")});
            origDebug.apply(null, arguments)
        };

        return $delegate;
    }]);
}]);

// Catch exceptions
app.factory('$exceptionHandler', function() {
  return function(exception, cause) {
    dataLayer.push({"event": "JS.error", "MESSAGE": exception.message});
    throw exception;
  };
});
<|endoftext|>


<commit_before><commit_msg>bugfix import shape<commit_after><|endoftext|>


<commit_before>var pendingOrders = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function oid() {
    //Get Token Balance
    try {
        $("#tokenBal").html(allTokens.balanceTokens.totalEarned.toFixed(2) + " tokens");
    } catch (err) {
        console.log(err)
        $("#tokenBal").html('
<svg id="userWallet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 334.877 334.877" style="enable-background:new 0 0 334.877 334.877; width: 24px; float: left; margin-top: 16px;" xml:space="preserve"> <path d="M333.196,155.999h-16.067V82.09c0-17.719-14.415-32.134-32.134-32.134h-21.761L240.965,9.917 C237.571,3.798,231.112,0,224.107,0c-3.265,0-6.504,0.842-9.364,2.429l-85.464,47.526H33.815 c-17.719,0-32.134,14.415-32.134,32.134v220.653c0,17.719,14.415,32.134,32.134,32.134h251.18 c17.719,0,32.134-14.415,32.134-32.134v-64.802h16.067V155.999z M284.995,62.809c9.897,0,17.982,7.519,19.068,17.14h-24.152 l-9.525-17.14H284.995z M220.996,13.663c3.014-1.69,7.07-0.508,8.734,2.494l35.476,63.786H101.798L220.996,13.663z M304.275,302.742c0,10.63-8.651,19.281-19.281,19.281H33.815c-10.63,0-19.281-8.651-19.281-19.281V82.09 c0-10.63,8.651-19.281,19.281-19.281h72.353L75.345,79.95H37.832c-3.554,0-6.427,2.879-6.427,6.427s2.873,6.427,6.427,6.427h14.396 h234.83h17.217v63.201h-46.999c-21.826,0-39.589,17.764-39.589,39.589v2.764c0,21.826,17.764,39.589,39.589,39.589h46.999V302.742z M320.342,225.087h-3.213h-59.853c-14.743,0-26.736-11.992-26.736-26.736v-2.764c0-14.743,11.992-26.736,26.736-26.736h59.853 h3.213V225.087z M276.961,197.497c0,7.841-6.35,14.19-14.19,14.19c-7.841,0-14.19-6.35-14.19-14.19s6.35-14.19,14.19-14.19 C270.612,183.306,276.961,189.662,276.961,197.497z" style="fill: white;"></path> </svg>
locked

');
    }

    if (window.location.hash != undefined) {

        //check if hash is oid
        var type = window.location.hash.substr(1);
        // split the hash
        var fields = type.split('=');
        var htpe = fields[0];
        var hval = fields[1];
        if (htpe == "oid") {
            M.toast({
                html: 'opening order...

',
                displayLength: 5000,
            });
            //get the shop and the oder details
            var shop = getBitsWinOpt('s')
            // oid
            $(".otitle").html("");
            $(".otitle").append("Your Order");
            $(".of").html("");
            //var uid = JSON.parseInt(hval)
            var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name"));
            od.onsuccess = function(event) {
                try {
                    var odData = JSON.parse(event.target.result);
                    for (var ii = 0; ii < odData.length; ++ii) {
                        var xx = odData[ii].items
                        var xid = odData[ii].id
                        //makeOrder(products)
                        // match oid to url id
                        var urloid = getBitsOpt("oid")
                        if (urloid == xid) {
                            makeOrder(JSON.parse(xx), odData[ii].location)
                        } else {
                            //console.log("no match")
                        }
                    }
                } catch (err) {}
            };
            od.onerror = function() {};
            //makeOrder(hval)
        } else {
            //console.log("we dont know this hash")
        }
    } else {}
}

function getUserOders(f) {

    doFetch({
        action: 'getAllOrders',
        uid: localStorage.getItem("bits-user-name")
    }).then(function(e) {
        if (e.status == "ok") {
            userOrders = e.data;
            for (ordersPending in userOrders) {

                if (userOrders[ordersPending].state != 'cancelled'){
                    var typeIcn='cancel';
                }else if(userOrders[ordersPending].state != 'wishlist') {
                     var typeIcn='loyalty';
                }else if(userOrders[ordersPending].state != 'pending') {
                    pendingOrders = true;
                    var typeIcn='schedule';
                }else if(userOrders[ordersPending].state != 'delivering') {
                     var typeIcn='motorcycle';
                    pendingOrders = true;
                }else if(userOrders[ordersPending].state != 'complete') {
                    var typeIcn='done_all';
                }

                //list orders for this service
                //

                if(parseInt(getBitsWinOpt('s'))==userOrders[ordersPending].toservice){
       $(".allUserOrders").html('
'+
      ''+typeIcn+''+
      'Title'+
      '
First Line
Second Line
'+
      'grade'+
    '
');
                    }

            }

            Notification.requestPermission().then(function(result) {

  if (result === 'denied' || result === 'default') {
    $(".allUserOrdersNote").html('notifications are disabled!, turn on to easily manage your orders.');
   // return;
  }else{
    $(".allUserOrdersNote").html('complete pending orders to make new orders');
   // return;
  }
  // Do something with the granted permission.
});
            xx = e.data;
            //var earnedPoints = 0;

            for (var ii in allTokens) {
                allTokens[ii].totalEarned = 0;
            }
            for (var ii in xx) {
                var items = xx[ii].points;
                try {
                    var typeofCoin = JSON.parse(items).coin;
                } catch (err) {
                    //console.log(err);
                    continue;
                }
                try {
                    var purchasePoints = JSON.parse(items).purchase;
                    if (purchasePoints == undefined) {
                        var purchasePoints = 0;
                    }
                } catch (err) {
                    //console.log('this order does not have any purchase rewards', err);
                    var purchasePoints = 0;
                }
                try {
                    var deliveryPoints = JSON.parse(items).delivery;
                    if (deliveryPoints == undefined) {
                        var deliveryPoints = 0;
                    }
                } catch (err) {
                    //console.log('this order does not have any delivery rewards', err);
                    var deliveryPoints = 0;
                }
                try {
                    allTokens[typeofCoin].totalEarned = allTokens[typeofCoin].totalEarned + purchasePoints + deliveryPoints;

                } catch (err) {
                    //console.log('this coin had not been included in the rewards since its currently inactive', typeofCoin);
                    continue;
                }

                //console.log(typeofCoin, purchasePoints, deliveryPoints);

            };

            var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name"));
            setdb.onsuccess = function() {
                oid();
            }

        } else {
            swal("Cancelled", "an error occcured", "error");
        }
    })

}
// 		var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name"));
//
function updateEarnedTokens(f) {

    $('.coinlist').html('');

    var at = allTokens['allContracts'];

    var i = 0;
    var tCe = 0;
    tBal = 0;
    for (var i in at) {

        try {
            // if (!(location.origin + '/').includes(allTokens[at[i]].webpage)) {
            //     continue;
            // }
            var rate = allTokens[at[i]].rate;
            var coinName = allTokens[at[i]].name;
            //if i have 1000 kobos
            //var koboBalance = 1000;
            //		//console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES');
            var koboRate = Math.floor(rate * baseX);
            var qq = rate * baseX;
            var xx = qq.toFixed(2);
            var coinId = at[i];
            var tA = allTokens[coinId].totalEarned + (allTokens[coinId].balance / Math.pow(10, allTokens[coinId].decimals));
            if (tA > 0) {
                //only display the coin if the user has a balance
                $('.coinlist').append('

' + coinName + '')
                $('.coin-' + coinId + '-bal').html('').append(tA.toFixed(5));
                $('.tokenBal').html(tA.toFixed(5));

            }
            $('.coin-' + coinId + '-xrate').html('').append('1 ' + coinName + ' = ' + xx + ' ' + baseCd);
            tBal = tBal + (tA * allTokens[coinId].rate * baseX);
        } catch (e) {
            console.log(e)
        }
        i++;
    }
    if (sessionStorage.getItem('walletKey')) {

        $('.balance-coins').html('').append(numberify(tBal, 2) + ' ' + baseCd);

    } else {

        $('.balance-coins').html("locked");
    }

}
<commit_msg>Update bits-oder-functions.js<commit_after>var pendingOrders = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function oid() {
    //Get Token Balance
    try {
        $("#tokenBal").html(allTokens.balanceTokens.totalEarned.toFixed(2) + " tokens");
    } catch (err) {
        console.log(err)
        $("#tokenBal").html('
<svg id="userWallet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 334.877 334.877" style="enable-background:new 0 0 334.877 334.877; width: 24px; float: left; margin-top: 16px;" xml:space="preserve"> <path d="M333.196,155.999h-16.067V82.09c0-17.719-14.415-32.134-32.134-32.134h-21.761L240.965,9.917 C237.571,3.798,231.112,0,224.107,0c-3.265,0-6.504,0.842-9.364,2.429l-85.464,47.526H33.815 c-17.719,0-32.134,14.415-32.134,32.134v220.653c0,17.719,14.415,32.134,32.134,32.134h251.18 c17.719,0,32.134-14.415,32.134-32.134v-64.802h16.067V155.999z M284.995,62.809c9.897,0,17.982,7.519,19.068,17.14h-24.152 l-9.525-17.14H284.995z M220.996,13.663c3.014-1.69,7.07-0.508,8.734,2.494l35.476,63.786H101.798L220.996,13.663z M304.275,302.742c0,10.63-8.651,19.281-19.281,19.281H33.815c-10.63,0-19.281-8.651-19.281-19.281V82.09 c0-10.63,8.651-19.281,19.281-19.281h72.353L75.345,79.95H37.832c-3.554,0-6.427,2.879-6.427,6.427s2.873,6.427,6.427,6.427h14.396 h234.83h17.217v63.201h-46.999c-21.826,0-39.589,17.764-39.589,39.589v2.764c0,21.826,17.764,39.589,39.589,39.589h46.999V302.742z M320.342,225.087h-3.213h-59.853c-14.743,0-26.736-11.992-26.736-26.736v-2.764c0-14.743,11.992-26.736,26.736-26.736h59.853 h3.213V225.087z M276.961,197.497c0,7.841-6.35,14.19-14.19,14.19c-7.841,0-14.19-6.35-14.19-14.19s6.35-14.19,14.19-14.19 C270.612,183.306,276.961,189.662,276.961,197.497z" style="fill: white;"></path> </svg>
locked

');
    }

    if (window.location.hash != undefined) {

        //check if hash is oid
        var type = window.location.hash.substr(1);
        // split the hash
        var fields = type.split('=');
        var htpe = fields[0];
        var hval = fields[1];
        if (htpe == "oid") {
            M.toast({
                html: 'opening order...

',
                displayLength: 5000,
            });
            //get the shop and the oder details
            var shop = getBitsWinOpt('s')
            // oid
            $(".otitle").html("");
            $(".otitle").append("Your Order");
            $(".of").html("");
            //var uid = JSON.parseInt(hval)
            var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name"));
            od.onsuccess = function(event) {
                try {
                    var odData = JSON.parse(event.target.result);
                    for (var ii = 0; ii < odData.length; ++ii) {
                        var xx = odData[ii].items
                        var xid = odData[ii].id
                        //makeOrder(products)
                        // match oid to url id
                        var urloid = getBitsOpt("oid")
                        if (urloid == xid) {
                            makeOrder(JSON.parse(xx), odData[ii].location)
                        } else {
                            //console.log("no match")
                        }
                    }
                } catch (err) {}
            };
            od.onerror = function() {};
            //makeOrder(hval)
        } else {
            //console.log("we dont know this hash")
        }
    } else {}
}

function getUserOders(f) {

    doFetch({
        action: 'getAllOrders',
        uid: localStorage.getItem("bits-user-name")
    }).then(function(e) {
        if (e.status == "ok") {
            userOrders = e.data;
            for (ordersPending in userOrders) {

                if (userOrders[ordersPending].state != 'cancelled'){
                    var typeIcn='cancel';
                }else if(userOrders[ordersPending].state != 'wishlist') {
                     var typeIcn='loyalty';
                }else if(userOrders[ordersPending].state != 'pending') {
                    pendingOrders = true;
                    var typeIcn='schedule';
                }else if(userOrders[ordersPending].state != 'delivering') {
                     var typeIcn='motorcycle';
                    pendingOrders = true;
                }else if(userOrders[ordersPending].state != 'complete') {
                    var typeIcn='done_all';
                }

                //list orders for this service
                //

                if(parseInt(getBitsWinOpt('s'))==userOrders[ordersPending].toservice){
       $(".allUserOrders").html('
'+
      ''+typeIcn+''+
      ''+moment(userOrders[ordersPending].date).fromNow()+''+
      '
'+userOrders[ordersPending].items+'
'+userOrders[ordersPending].state+'
'+
      'grade'+
    '
');
                    }

            }

            Notification.requestPermission().then(function(result) {

  if (result === 'denied' || result === 'default') {
    $(".allUserOrdersNote").html('notifications are disabled!, turn on to easily manage your orders.');
   // return;
  }else{
    $(".allUserOrdersNote").html('complete pending orders to make new orders');
   // return;
  }
  // Do something with the granted permission.
});
            xx = e.data;
            //var earnedPoints = 0;

            for (var ii in allTokens) {
                allTokens[ii].totalEarned = 0;
            }
            for (var ii in xx) {
                var items = xx[ii].points;
                try {
                    var typeofCoin = JSON.parse(items).coin;
                } catch (err) {
                    //console.log(err);
                    continue;
                }
                try {
                    var purchasePoints = JSON.parse(items).purchase;
                    if (purchasePoints == undefined) {
                        var purchasePoints = 0;
                    }
                } catch (err) {
                    //console.log('this order does not have any purchase rewards', err);
                    var purchasePoints = 0;
                }
                try {
                    var deliveryPoints = JSON.parse(items).delivery;
                    if (deliveryPoints == undefined) {
                        var deliveryPoints = 0;
                    }
                } catch (err) {
                    //console.log('this order does not have any delivery rewards', err);
                    var deliveryPoints = 0;
                }
                try {
                    allTokens[typeofCoin].totalEarned = allTokens[typeofCoin].totalEarned + purchasePoints + deliveryPoints;

                } catch (err) {
                    //console.log('this coin had not been included in the rewards since its currently inactive', typeofCoin);
                    continue;
                }

                //console.log(typeofCoin, purchasePoints, deliveryPoints);

            };

            var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name"));
            setdb.onsuccess = function() {
                oid();
            }

        } else {
            swal("Cancelled", "an error occcured", "error");
        }
    })

}
// 		var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name"));
//
function updateEarnedTokens(f) {

    $('.coinlist').html('');

    var at = allTokens['allContracts'];

    var i = 0;
    var tCe = 0;
    tBal = 0;
    for (var i in at) {

        try {
            // if (!(location.origin + '/').includes(allTokens[at[i]].webpage)) {
            //     continue;
            // }
            var rate = allTokens[at[i]].rate;
            var coinName = allTokens[at[i]].name;
            //if i have 1000 kobos
            //var koboBalance = 1000;
            //		//console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES');
            var koboRate = Math.floor(rate * baseX);
            var qq = rate * baseX;
            var xx = qq.toFixed(2);
            var coinId = at[i];
            var tA = allTokens[coinId].totalEarned + (allTokens[coinId].balance / Math.pow(10, allTokens[coinId].decimals));
            if (tA > 0) {
                //only display the coin if the user has a balance
                $('.coinlist').append('

' + coinName + '')
                $('.coin-' + coinId + '-bal').html('').append(tA.toFixed(5));
                $('.tokenBal').html(tA.toFixed(5));

            }
            $('.coin-' + coinId + '-xrate').html('').append('1 ' + coinName + ' = ' + xx + ' ' + baseCd);
            tBal = tBal + (tA * allTokens[coinId].rate * baseX);
        } catch (e) {
            console.log(e)
        }
        i++;
    }
    if (sessionStorage.getItem('walletKey')) {

        $('.balance-coins').html('').append(numberify(tBal, 2) + ' ' + baseCd);

    } else {

        $('.balance-coins').html("locked");
    }

}
<|endoftext|>


<commit_before>// Generic rendering canvas.
function canvas(div_attach) {

  // *******************************************
  // Private variables:
  // *******************************************

  this.annotations = Array(); // includes name, deleted, verified info
  this.div_attach = div_attach; // name of DIV element to attach to

  // *******************************************
  // Public methods:
  // *******************************************

  // Returns the last annotation in the array (null if empty).
  this.Peek = function () {
    var i = this.annotations.length-1;
    if(i < 0) return null;
    return this.annotations[i];
  };

  // Attach the annotation to the canvas.
  this.AttachAnnotation = function (anno,rendering_style) {
    this.annotations.push(anno);
    anno.SetDivAttach(this.div_attach);
  };

  // Detach annotation from the canvas.
  // 1. If zero arguments are passed in, then the last annotation is
  // detached and returned.
  // 2. If the annotation ID is passed in, then the corresponding
  // annotation is located, detached, and returned.
  this.DetachAnnotation = function() {
    var i;
    if(arguments.length==0) {
      // Get index of last annotation:
      i = (this.annotations.length-1);
    }
    else {
      // Get index of annotation matching input annotation ID:
      var anno_id = arguments[0];
      var is_matched = false;
      for(i=0; i<this.annotations.length; i++) {
	if(this.annotations[i].GetAnnoID()==anno_id) {
	  is_matched = true;
	  break;
	}
      }
      if(!is_matched) i = -1;
    }

    // If invalid index, then did not find valid annotation, so return null:
    if(i<0) return null;

    // Remove annotation structure from list:
    var anno = this.annotations.splice(i,1)[0];

    // Remove rendering of polygon from the canvas:
    anno.DeletePolygon();

    return anno;
  };

  // Render all attached annotations:
  this.RenderAnnotations = function () {
    // Clear the canvas:
    this.ClearAnnotations();

    for(var pp=0; pp < this.annotations.length; pp++) {
      // Render the annotation:
      var anno_id = this.annotations[pp].GetAnnoID();
      this.annotations[pp].DrawPolygon(main_image.GetImRatio());

      // Set polygon actions:
      this.annotations[pp].SetAttribute('onmousedown','StartEditEvent(' + anno_id + ',evt); return false;');
      this.annotations[pp].SetAttribute('onmousemove','main_handler.CanvasMouseMove(evt,'+ anno_id +'); return false;');
      this.annotations[pp].SetAttribute('oncontextmenu','return false');
      this.annotations[pp].SetCSS('cursor','pointer');
    }
  };

  // Loop through all of the annotations and clear them from the canvas.
  this.ClearAnnotations = function () {
    for(var i=0;i<this.annotations.length;i++) {
      this.annotations[i].DeletePolygon();
    }
  };

}
<commit_msg>cleaned canvas class<commit_after>// Generic rendering canvas.
function canvas(div_attach) {

  // *******************************************
  // Private variables:
  // *******************************************

  this.annotations = Array(); // includes name, deleted, verified info
  this.div_attach = div_attach; // name of DIV element to attach to

  // *******************************************
  // Public methods:
  // *******************************************

  // Attach the annotation to the canvas.
  this.AttachAnnotation = function (anno,rendering_style) {
    this.annotations.push(anno);
    anno.SetDivAttach(this.div_attach);
  };

  // Detach annotation from the canvas.
  // 1. If zero arguments are passed in, then the last annotation is
  // detached and returned.
  // 2. If the annotation ID is passed in, then the corresponding
  // annotation is located, detached, and returned.
  this.DetachAnnotation = function() {
    var i;
    if(arguments.length==0) {
      // Get index of last annotation:
      i = (this.annotations.length-1);
    }
    else {
      // Get index of annotation matching input annotation ID:
      var anno_id = arguments[0];
      var is_matched = false;
      for(i=0; i<this.annotations.length; i++) {
	if(this.annotations[i].GetAnnoID()==anno_id) {
	  is_matched = true;
	  break;
	}
      }
      if(!is_matched) i = -1;
    }

    // If invalid index, then did not find valid annotation, so return null:
    if(i<0) return null;

    // Remove annotation structure from list:
    var anno = this.annotations.splice(i,1)[0];

    // Remove rendering of polygon from the canvas:
    anno.DeletePolygon();

    return anno;
  };

  // Render all attached annotations:
  this.RenderAnnotations = function () {
    // Clear the canvas:
    this.ClearAnnotations();

    for(var pp=0; pp < this.annotations.length; pp++) {
      // Render the annotation:
      var anno_id = this.annotations[pp].GetAnnoID();
      this.annotations[pp].DrawPolygon(main_image.GetImRatio());

      // Set polygon actions:
      this.annotations[pp].SetAttribute('onmousedown','StartEditEvent(' + anno_id + ',evt); return false;');
      this.annotations[pp].SetAttribute('onmousemove','main_handler.CanvasMouseMove(evt,'+ anno_id +'); return false;');
      this.annotations[pp].SetAttribute('oncontextmenu','return false');
      this.annotations[pp].SetCSS('cursor','pointer');
    }
  };

  // Loop through all of the annotations and clear them from the canvas.
  this.ClearAnnotations = function () {
    for(var i=0;i<this.annotations.length;i++) {
      this.annotations[i].DeletePolygon();
    }
  };

}
<|endoftext|>


<commit_before>var events = require('events')
  , util = require('util');

function Mapper(options) {
  options = options || {};

  events.EventEmitter.call(this);
  this._index = options.index || false;
}

util.inherits(Mapper, events.EventEmitter);

Mapper.prototype.map = function(server) {
  var pages = []
    , sitemaps = [];

  server.on('request', function(page) {
    pages.push(page);

    if (page.sitemap) {
      sitemaps.push(page);
    }
  });

  this.request('/sitemap.xml', function(page) {
    page.locals = page.locals || Object.create(null);
    page.locals.pages = pages;
  });
  if (this._index) {
    this.request('/sitemap-index.xml', function(page) {
      page.locals = page.locals || Object.create(null);
      page.locals.sitemaps = sitemaps;
    });
  }
  this.emit('finish');
};

module.exports = Mapper;
<commit_msg>Wait for server to finish before generating sitemap.<commit_after>var events = require('events')
  , util = require('util');

function Mapper(options) {
  options = options || {};

  events.EventEmitter.call(this);
  this._index = options.index || false;
}

util.inherits(Mapper, events.EventEmitter);

Mapper.prototype.map = function(server) {
  var self = this
    , pages = []
    , sitemaps = [];

  server.on('request', function(page) {
    pages.push(page);
    if (page.sitemap) {
      sitemaps.push(page);
    }
  });

  this.wait = true;

  server.once('finish', function() {
    self.request('/sitemap.xml', function(page) {
      page.locals = page.locals || Object.create(null);
      page.locals.pages = pages;
    });
    if (self._index) {
      self.request('/sitemap-index.xml', function(page) {
        page.locals = page.locals || Object.create(null);
        page.locals.sitemaps = sitemaps;
      });
    }

    self.emit('finish');
  });
};

module.exports = Mapper;
<|endoftext|>


<commit_before>import React, { Component, PureComponent } from 'react';
import cx from 'classnames';

import { getElementLeft, getElementTop } from './getPosition';

export default class Loading extends (PureComponent || Component) {
  state = {
    show: this.props.show,
  };

  show = info => {
    // Do not add this optimization, setState is an async operation
    // Assume this.state.show is false,
    // show({show: true}); show({show: false})
    // will not set show to false if we add these lines.
    //
    // if (info.show === this.state.show) {
    //   return;
    // }

    if (info.show) {
      let target = this.props.target;
      if (target) {
        this.style = {
          left: getElementLeft(target),
          top: getElementTop(target),
          width: target.offsetWidth,
          height: target.offsetHeight,
        };
      }
    }

    this.setState({
      show: info.show,
    });
  };

  setPosition = () => {
    if (!this.wrapper) {
      return;
    }

    this.wrapper.style.zIndex = this.props.zIndex;

    if (this.style) {
      this.wrapper.style.top = `${this.style.top}px`;
      this.wrapper.style.left = `${this.style.left}px`;
      this.wrapper.style.width = `${this.style.width}px`;
      this.wrapper.style.height = `${this.style.height}px`;
    } else {
      this.wrapper.style.position = 'fixed';
    }
  };

  setWrapperRef = el => {
    this.wrapper = el;
  };

  componentDidMount() {
    this.setPosition();
  }

  componentDidUpdate() {
    this.setPosition();
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      show: nextProps.show,
    });
  }

  render() {
    let { prefix, className, containerClass, children } = this.props;

    if (!this.props.float) {
      return (
        <div
          className={cx(
            `${prefix}-loading-container`,
            `${prefix}-loading-container-static`,
            containerClass,
            {
              [`${prefix}-loading-container--empty`]:
                React.Children.count(children) === 0,
            }
          )}
          style={{
            height:
              children || !this.state.show ? 'initial' : this.props.height,
          }}
        >
          {children}
          {this.state.show && (
            <div className={`${prefix}-page-loading ${className}`}>
              <div className={`${prefix}-page-mask`} />

          )}

      );
    }

    return (
      this.state.show && (
        <div
          className={`${prefix}-page-loading ${className}`}
          ref={this.setWrapperRef}
        >
          <div className={`${prefix}-page-mask`} />

      )
    );
  }
}
<commit_msg>更新Loading组件高度设置逻辑<commit_after>import React, { Component, PureComponent } from 'react';
import cx from 'classnames';

import { getElementLeft, getElementTop } from './getPosition';

export default class Loading extends (PureComponent || Component) {
  state = {
    show: this.props.show,
  };

  show = info => {
    // Do not add this optimization, setState is an async operation
    // Assume this.state.show is false,
    // show({show: true}); show({show: false})
    // will not set show to false if we add these lines.
    //
    // if (info.show === this.state.show) {
    //   return;
    // }

    if (info.show) {
      let target = this.props.target;
      if (target) {
        this.style = {
          left: getElementLeft(target),
          top: getElementTop(target),
          width: target.offsetWidth,
          height: target.offsetHeight,
        };
      }
    }

    this.setState({
      show: info.show,
    });
  };

  setPosition = () => {
    if (!this.wrapper) {
      return;
    }

    this.wrapper.style.zIndex = this.props.zIndex;

    if (this.style) {
      this.wrapper.style.top = `${this.style.top}px`;
      this.wrapper.style.left = `${this.style.left}px`;
      this.wrapper.style.width = `${this.style.width}px`;
      this.wrapper.style.height = `${this.style.height}px`;
    } else {
      this.wrapper.style.position = 'fixed';
    }
  };

  setWrapperRef = el => {
    this.wrapper = el;
  };

  componentDidMount() {
    this.setPosition();
  }

  componentDidUpdate() {
    this.setPosition();
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      show: nextProps.show,
    });
  }

  render() {
    let { prefix, className, containerClass, children } = this.props;

    if (!this.props.float) {
      return (
        <div
          className={cx(
            `${prefix}-loading-container`,
            `${prefix}-loading-container-static`,
            containerClass,
            {
              [`${prefix}-loading-container--empty`]:
                React.Children.count(children) === 0,
            }
          )}
          style={{
            height: !this.state.show ? 'initial' : this.props.height,
          }}
        >
          {children}
          {this.state.show && (
            <div className={`${prefix}-page-loading ${className}`}>
              <div className={`${prefix}-page-mask`} />

          )}

      );
    }

    return (
      this.state.show && (
        <div
          className={`${prefix}-page-loading ${className}`}
          ref={this.setWrapperRef}
        >
          <div className={`${prefix}-page-mask`} />

      )
    );
  }
}
<|endoftext|>