<commit_before>
module.exports = {
  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },

  "plugins": [
    "require-path-exists"
  ],

  "ecmaFeatures": {
    "arrowFunctions": true,
    "binaryLiterals": true,
    "blockBindings": true,
    "classes": true,
    "defaultParams": true,
    "destructuring": true,
    "forOf": true,
    "generators": true,
    "modules": true,
    "objectLiteralComputedProperties": true,
    "objectLiteralDuplicateProperties": true,
    "objectLiteralShorthandMethods": true,
    "objectLiteralShorthandProperties": true,
    "octalLiterals": true,
    "regexUFlag": true,
    "regexYFlag": true,
    "spread": true,
    "superInFunctions": true,
    "templateStrings": true,
    "unicodeCodePointEscapes": true,
    "globalReturn": true,
    "jsx": true
  },

  "rules": {

    //
    //Possible Errors
    //
    // The following rules point out areas where you might have made mistakes.
    //
    "comma-dangle": [1, "always-multiline"], // disallow or enforce trailing commas
    "no-cond-assign": 2, // disallow assignment in conditional expressions
    "no-console": 1, // disallow use of console (off by default in the node environment)
    "no-constant-condition": 2, // disallow use of constant expressions in conditions
    "no-control-regex": 2, // disallow control characters in regular expressions
    "no-debugger": 2, // disallow use of debugger
    "no-dupe-args": 2, // disallow duplicate arguments in functions
    "no-dupe-keys": 2, // disallow duplicate keys when creating object literals
    "no-duplicate-case": 2, // disallow a duplicate case label.
    "no-empty": 2, // disallow empty statements
    "no-empty-character-class": 2, // disallow the use of empty character classes in regular expressions
    "no-ex-assign": 2, // disallow assigning to the exception in a catch block
    "no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context
    "no-extra-parens": 0, // disallow unnecessary parentheses (off by default)
    "no-extra-semi": 2, // disallow unnecessary semicolons
    "no-func-assign": 2, // disallow overwriting functions written as function declarations
    "no-inner-declarations": 2, // disallow function or variable declarations in nested blocks
    "no-invalid-regexp": 2, // disallow invalid regular expression strings in the RegExp constructor
    "no-irregular-whitespace": 2, // disallow irregular whitespace outside of strings and comments
    "no-negated-in-lhs": 2, // disallow negation of the left operand of an in expression
    "no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-regex-spaces": 2, // disallow multiple spaces in a regular expression literal
    "no-sparse-arrays": 2, // disallow sparse arrays
    "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement
    "use-isnan": 2, // disallow comparisons with the value NaN
    "quote-props": [2, "as-needed"],
    "valid-jsdoc": 2, // Ensure JSDoc comments are valid (off by default)
    "valid-typeof": 2, // Ensure that the results of typeof are compared against a valid string

    //
    // Best Practices
    //
    // These are rules designed to prevent you from making mistakes.
    // They either prescribe a better way of doing something or help you avoid footguns.
    //
    "block-scoped-var": 0, // treat var statements as if they were block scoped (off by default). 0: deep destructuring is not compatible https://github.com/eslint/eslint/issues/1863
    "complexity": 0, // specify the maximum cyclomatic complexity allowed in a program (off by default)
    "consistent-return": 2, // require return statements to either always or never specify values
    "curly": 2, // specify curly brace conventions for all control statements
    "default-case": 2, // require default case in switch statements (off by default)
    "dot-notation": 2, // encourages use of dot notation whenever possible
    "eqeqeq": 2, // require the use of === and !==
    "guard-for-in": 2, // make sure for-in loops have an if statement (off by default)
    "no-alert": 2, // disallow the use of alert, confirm, and prompt
    "no-caller": 2, // disallow use of arguments.caller or arguments.callee
    "no-div-regex": 2, // disallow division operators explicitly at beginning of regular expression (off by default)
    "no-else-return": 2, // disallow else after a return in an if (off by default)
    "no-empty-label": 2, // disallow use of labels for anything other then loops and switches
    "no-eq-null": 2, // disallow comparisons to null without a type-checking operator (off by default)
    "no-eval": 2, // disallow use of eval()
    "no-extend-native": 2, // disallow adding to native types
    "no-extra-bind": 2, // disallow unnecessary function binding
    "no-fallthrough": 2, // disallow fallthrough of case statements
    "no-floating-decimal": 2, // disallow the use of leading or trailing decimal points in numeric literals (off by default)
    "no-implied-eval": 2, // disallow use of eval()-like methods
    "no-iterator": 2, // disallow usage of __iterator__ property
    "no-labels": 2, // disallow use of labeled statements
    "no-lone-blocks": 2, // disallow unnecessary nested blocks
    "no-loop-func": 2, // disallow creation of functions within loops
    "no-multi-spaces": 2, // disallow use of multiple spaces
    "no-multi-str": 2, // disallow use of multiline strings
    "no-native-reassign": 2, // disallow reassignments of native objects
    "no-new": 2, // disallow use of new operator when not part of the assignment or comparison
    "no-new-func": 2, // disallow use of new operator for Function object
    "no-new-wrappers": 2, // disallows creating new instances of String,Number, and Boolean
    "no-octal": 2, // disallow use of octal literals
    "no-octal-escape": 2, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-param-reassign": 2, // disallow reassignment of function parameters (off by default)
    "no-process-env": 2, // disallow use of process.env (off by default)
    "no-proto": 2, // disallow usage of __proto__ property
    "no-redeclare": 2, // disallow declaring the same variable more then once
    "no-return-assign": 2, // disallow use of assignment in return statement
    "no-script-url": 2, // disallow use of javascript: urls.
    "no-self-compare": 2, // disallow comparisons where both sides are exactly the same (off by default)
    "no-sequences": 2, // disallow use of comma operator
    "no-throw-literal": 2, // restrict what can be thrown as an exception (off by default)
    "no-unused-expressions": 2, // disallow usage of expressions in statement position
    "no-void": 2, // disallow use of void operator (off by default)
    "no-warning-comments": [0, {"terms": ["todo", "fixme"], "location": "start"}], // disallow usage of configurable warning terms in comments": 2, // e.g. TODO or FIXME (off by default)
    "no-with": 2, // disallow use of the with statement
    "radix": 2, // require use of the second argument for parseInt() (off by default)
    "vars-on-top": 2, // requires to declare all vars on top of their containing scope (off by default)
    "wrap-iife": 2, // require immediate function invocation to be wrapped in parentheses (off by default)
    "yoda": 2, // require or disallow Yoda conditions

    //
    // Strict Mode
    //
    // These rules relate to using strict mode.
    //
    "strict": [0, "global"],    // controls location of Use Strict Directives. 0: required by `babel-eslint`

    //
    // Variables
    //
    // These rules have to do with variable declarations.
    //
    "no-catch-shadow": 2, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
    "no-delete-var": 2, // disallow deletion of variables
    "no-label-var": 2, // disallow labels that share a name with a variable
    "no-shadow": 2, // disallow declaration of variables already declared in the outer scope
    "no-shadow-restricted-names": 2, // disallow shadowing of names such as arguments
    "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-undef-init": 2, // disallow use of undefined when initializing variables
    "no-undefined": 2, // disallow use of undefined variable (off by default)
    "no-unused-vars": 2, // disallow declaration of variables that are not used in the code
    "no-use-before-define": 2, // disallow use of variables before they are defined

    //
    //Stylistic Issues
    //
    // These rules are purely matters of style and are quite subjective.
    //
    "indent": [1, 2], // this option sets a specific tab width for your code (off by default)
    "brace-style": 1, // enforce one true brace style (off by default)
    "camelcase": 1, // require camel case names
    "comma-spacing": [1, {"before": false, "after": true}], // enforce spacing before and after comma
    "comma-style": [1, "last"], // enforce one true comma style (off by default)
    "consistent-this": [1, "self"], // enforces consistent naming when capturing the current execution context (off by default)
    "eol-last": 1, // enforce newline at the end of file, with no multiple empty lines
    "func-names": 0, // require function expressions to have a name (off by default)
    "func-style": 0, // enforces use of function declarations or expressions (off by default)
    "key-spacing": [1, {"beforeColon": false, "afterColon": true}], // enforces spacing between keys and values in object literal properties
    "max-nested-callbacks": [1, 3], // specify the maximum depth callbacks can be nested (off by default)
    "new-cap": [1, {newIsCap: true, capIsNew: false}], // require a capital letter for constructors
    "new-parens": 1, // disallow the omission of parentheses when invoking a constructor with no arguments
    "newline-after-var": 0, // allow/disallow an empty newline after var statement (off by default)
    "no-array-constructor": 1, // disallow use of the Array constructor
    "no-inline-comments": 1, // disallow comments inline after code (off by default)
    "no-lonely-if": 1, // disallow if as the only statement in an else block (off by default)
    "no-mixed-spaces-and-tabs": 1, // disallow mixed spaces and tabs for indentation
    "no-multiple-empty-lines": [1, {"max": 2}], // disallow multiple empty lines (off by default)
    "no-nested-ternary": 1, // disallow nested ternary expressions (off by default)
    "no-new-object": 1, // disallow use of the Object constructor
    "no-spaced-func": 1, // disallow space between function identifier and application
    "no-ternary": 0, // disallow the use of ternary operators (off by default)
    "no-trailing-spaces": 1, // disallow trailing whitespace at the end of lines
    "no-underscore-dangle": 1, // disallow dangling underscores in identifiers
    "no-extra-parens": 2, // disallow wrapping of non-IIFE statements in parens
    "one-var": [1, "never"], // allow just one var statement per function (off by default)
    "operator-assignment": [2, "always"], // require assignment operator shorthand where possible or prohibit it entirely (off by default)
    "padded-blocks": [1, "never"], // enforce padding within blocks (off by default)
    "quote-props": [1, "as-needed"], // require quotes around object literal property names (off by default)
    "quotes": [1, "single"], // specify whether double or single quotes should be used
    "semi": [1, "always"], // require or disallow use of semicolons instead of ASI
    "semi-spacing": [1, {"before": false, "after": true}], // enforce spacing before and after semicolons
    "sort-vars": 0, // sort variables within the same declaration block (off by default)
    "space-after-keywords": [1, "always"], // require a space after certain keywords (off by default)
    "space-before-blocks": [1, "always"], // require or disallow space before blocks (off by default)
    "space-before-function-paren": 2, // require or disallow space before function opening parenthesis (off by default)
    "object-curly-spacing": [2, "always"],		// require or disallow spaces inside objects (off by default)
    "computed-property-spacing": [2, "never"],
    "array-bracket-spacing": 1,       // require or disallow spaces inside arrays (off by default)

    "space-in-parens": [1, "never"], // require or disallow spaces inside parentheses (off by default)
    "space-infix-ops": [2, {"int32Hint": false}],   // require spaces around operators
    "space-return-throw-case": 2, // require a space after return, throw, and case
    "space-unary-ops": [1, {"words": true, "nonwords": false}], // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default)
    "spaced-comment": [2, "always"],  // require or disallow a space immediately following the // in a line comment (off by default)
    "wrap-regex": 0, // require regex literals to be wrapped in parentheses (off by default)

    //
    // ECMAScript 6
    //
    // These rules are only relevant to ES6 environments and are off by default.
    //
    "no-var": 2, // require let or const instead of var (off by default)
    "generator-star-spacing": [2, "before"], // enforce the spacing around the * in generator functions (off by default)

    //
    // Legacy
    //
    // The following rules are included for compatibility with JSHint and JSLint.
    // While the names of the rules may not match up with the JSHint/JSLint counterpart,
    // the functionality is the same.
    //
    "max-depth": [2, 3], // specify the maximum depth that blocks can be nested (off by default)
    "max-len": [2, 100, 2], // specify the maximum length of a line in your program (off by default)
    "max-params": [2, 5], // limits the number of parameters that can be used in the function declaration. (off by default)
    "max-statements": 0, // specify the maximum number of statement allowed in a function (off by default)
    "no-bitwise": 0, // disallow use of bitwise operators (off by default)
    "no-plusplus": [2, {     // disallow use of unary operators, ++ and -- (off by default)
      "allowForLoopAfterthoughts": true
    }]
  }
};
<commit_msg>do not allow space before parens<commit_after>
module.exports = {
  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },

  "plugins": [
    "require-path-exists"
  ],

  "ecmaFeatures": {
    "arrowFunctions": true,
    "binaryLiterals": true,
    "blockBindings": true,
    "classes": true,
    "defaultParams": true,
    "destructuring": true,
    "forOf": true,
    "generators": true,
    "modules": true,
    "objectLiteralComputedProperties": true,
    "objectLiteralDuplicateProperties": true,
    "objectLiteralShorthandMethods": true,
    "objectLiteralShorthandProperties": true,
    "octalLiterals": true,
    "regexUFlag": true,
    "regexYFlag": true,
    "spread": true,
    "superInFunctions": true,
    "templateStrings": true,
    "unicodeCodePointEscapes": true,
    "globalReturn": true,
    "jsx": true
  },

  "rules": {

    //
    //Possible Errors
    //
    // The following rules point out areas where you might have made mistakes.
    //
    "comma-dangle": [1, "always-multiline"], // disallow or enforce trailing commas
    "no-cond-assign": 2, // disallow assignment in conditional expressions
    "no-console": 1, // disallow use of console (off by default in the node environment)
    "no-constant-condition": 2, // disallow use of constant expressions in conditions
    "no-control-regex": 2, // disallow control characters in regular expressions
    "no-debugger": 2, // disallow use of debugger
    "no-dupe-args": 2, // disallow duplicate arguments in functions
    "no-dupe-keys": 2, // disallow duplicate keys when creating object literals
    "no-duplicate-case": 2, // disallow a duplicate case label.
    "no-empty": 2, // disallow empty statements
    "no-empty-character-class": 2, // disallow the use of empty character classes in regular expressions
    "no-ex-assign": 2, // disallow assigning to the exception in a catch block
    "no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context
    "no-extra-parens": 0, // disallow unnecessary parentheses (off by default)
    "no-extra-semi": 2, // disallow unnecessary semicolons
    "no-func-assign": 2, // disallow overwriting functions written as function declarations
    "no-inner-declarations": 2, // disallow function or variable declarations in nested blocks
    "no-invalid-regexp": 2, // disallow invalid regular expression strings in the RegExp constructor
    "no-irregular-whitespace": 2, // disallow irregular whitespace outside of strings and comments
    "no-negated-in-lhs": 2, // disallow negation of the left operand of an in expression
    "no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-regex-spaces": 2, // disallow multiple spaces in a regular expression literal
    "no-sparse-arrays": 2, // disallow sparse arrays
    "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement
    "use-isnan": 2, // disallow comparisons with the value NaN
    "quote-props": [2, "as-needed"],
    "valid-jsdoc": 2, // Ensure JSDoc comments are valid (off by default)
    "valid-typeof": 2, // Ensure that the results of typeof are compared against a valid string

    //
    // Best Practices
    //
    // These are rules designed to prevent you from making mistakes.
    // They either prescribe a better way of doing something or help you avoid footguns.
    //
    "block-scoped-var": 0, // treat var statements as if they were block scoped (off by default). 0: deep destructuring is not compatible https://github.com/eslint/eslint/issues/1863
    "complexity": 0, // specify the maximum cyclomatic complexity allowed in a program (off by default)
    "consistent-return": 2, // require return statements to either always or never specify values
    "curly": 2, // specify curly brace conventions for all control statements
    "default-case": 2, // require default case in switch statements (off by default)
    "dot-notation": 2, // encourages use of dot notation whenever possible
    "eqeqeq": 2, // require the use of === and !==
    "guard-for-in": 2, // make sure for-in loops have an if statement (off by default)
    "no-alert": 2, // disallow the use of alert, confirm, and prompt
    "no-caller": 2, // disallow use of arguments.caller or arguments.callee
    "no-div-regex": 2, // disallow division operators explicitly at beginning of regular expression (off by default)
    "no-else-return": 2, // disallow else after a return in an if (off by default)
    "no-empty-label": 2, // disallow use of labels for anything other then loops and switches
    "no-eq-null": 2, // disallow comparisons to null without a type-checking operator (off by default)
    "no-eval": 2, // disallow use of eval()
    "no-extend-native": 2, // disallow adding to native types
    "no-extra-bind": 2, // disallow unnecessary function binding
    "no-fallthrough": 2, // disallow fallthrough of case statements
    "no-floating-decimal": 2, // disallow the use of leading or trailing decimal points in numeric literals (off by default)
    "no-implied-eval": 2, // disallow use of eval()-like methods
    "no-iterator": 2, // disallow usage of __iterator__ property
    "no-labels": 2, // disallow use of labeled statements
    "no-lone-blocks": 2, // disallow unnecessary nested blocks
    "no-loop-func": 2, // disallow creation of functions within loops
    "no-multi-spaces": 2, // disallow use of multiple spaces
    "no-multi-str": 2, // disallow use of multiline strings
    "no-native-reassign": 2, // disallow reassignments of native objects
    "no-new": 2, // disallow use of new operator when not part of the assignment or comparison
    "no-new-func": 2, // disallow use of new operator for Function object
    "no-new-wrappers": 2, // disallows creating new instances of String,Number, and Boolean
    "no-octal": 2, // disallow use of octal literals
    "no-octal-escape": 2, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-param-reassign": 2, // disallow reassignment of function parameters (off by default)
    "no-process-env": 2, // disallow use of process.env (off by default)
    "no-proto": 2, // disallow usage of __proto__ property
    "no-redeclare": 2, // disallow declaring the same variable more then once
    "no-return-assign": 2, // disallow use of assignment in return statement
    "no-script-url": 2, // disallow use of javascript: urls.
    "no-self-compare": 2, // disallow comparisons where both sides are exactly the same (off by default)
    "no-sequences": 2, // disallow use of comma operator
    "no-throw-literal": 2, // restrict what can be thrown as an exception (off by default)
    "no-unused-expressions": 2, // disallow usage of expressions in statement position
    "no-void": 2, // disallow use of void operator (off by default)
    "no-warning-comments": [0, {"terms": ["todo", "fixme"], "location": "start"}], // disallow usage of configurable warning terms in comments": 2, // e.g. TODO or FIXME (off by default)
    "no-with": 2, // disallow use of the with statement
    "radix": 2, // require use of the second argument for parseInt() (off by default)
    "vars-on-top": 2, // requires to declare all vars on top of their containing scope (off by default)
    "wrap-iife": 2, // require immediate function invocation to be wrapped in parentheses (off by default)
    "yoda": 2, // require or disallow Yoda conditions

    //
    // Strict Mode
    //
    // These rules relate to using strict mode.
    //
    "strict": [0, "global"],    // controls location of Use Strict Directives. 0: required by `babel-eslint`

    //
    // Variables
    //
    // These rules have to do with variable declarations.
    //
    "no-catch-shadow": 2, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment)
    "no-delete-var": 2, // disallow deletion of variables
    "no-label-var": 2, // disallow labels that share a name with a variable
    "no-shadow": 2, // disallow declaration of variables already declared in the outer scope
    "no-shadow-restricted-names": 2, // disallow shadowing of names such as arguments
    "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-undef-init": 2, // disallow use of undefined when initializing variables
    "no-undefined": 2, // disallow use of undefined variable (off by default)
    "no-unused-vars": 2, // disallow declaration of variables that are not used in the code
    "no-use-before-define": 2, // disallow use of variables before they are defined

    //
    //Stylistic Issues
    //
    // These rules are purely matters of style and are quite subjective.
    //
    "indent": [1, 2], // this option sets a specific tab width for your code (off by default)
    "brace-style": 1, // enforce one true brace style (off by default)
    "camelcase": 1, // require camel case names
    "comma-spacing": [1, {"before": false, "after": true}], // enforce spacing before and after comma
    "comma-style": [1, "last"], // enforce one true comma style (off by default)
    "consistent-this": [1, "self"], // enforces consistent naming when capturing the current execution context (off by default)
    "eol-last": 1, // enforce newline at the end of file, with no multiple empty lines
    "func-names": 0, // require function expressions to have a name (off by default)
    "func-style": 0, // enforces use of function declarations or expressions (off by default)
    "key-spacing": [1, {"beforeColon": false, "afterColon": true}], // enforces spacing between keys and values in object literal properties
    "max-nested-callbacks": [1, 3], // specify the maximum depth callbacks can be nested (off by default)
    "new-cap": [1, {newIsCap: true, capIsNew: false}], // require a capital letter for constructors
    "new-parens": 1, // disallow the omission of parentheses when invoking a constructor with no arguments
    "newline-after-var": 0, // allow/disallow an empty newline after var statement (off by default)
    "no-array-constructor": 1, // disallow use of the Array constructor
    "no-inline-comments": 1, // disallow comments inline after code (off by default)
    "no-lonely-if": 1, // disallow if as the only statement in an else block (off by default)
    "no-mixed-spaces-and-tabs": 1, // disallow mixed spaces and tabs for indentation
    "no-multiple-empty-lines": [1, {"max": 2}], // disallow multiple empty lines (off by default)
    "no-nested-ternary": 1, // disallow nested ternary expressions (off by default)
    "no-new-object": 1, // disallow use of the Object constructor
    "no-spaced-func": 1, // disallow space between function identifier and application
    "no-ternary": 0, // disallow the use of ternary operators (off by default)
    "no-trailing-spaces": 1, // disallow trailing whitespace at the end of lines
    "no-underscore-dangle": 1, // disallow dangling underscores in identifiers
    "no-extra-parens": 2, // disallow wrapping of non-IIFE statements in parens
    "one-var": [1, "never"], // allow just one var statement per function (off by default)
    "operator-assignment": [2, "always"], // require assignment operator shorthand where possible or prohibit it entirely (off by default)
    "padded-blocks": [1, "never"], // enforce padding within blocks (off by default)
    "quote-props": [1, "as-needed"], // require quotes around object literal property names (off by default)
    "quotes": [1, "single"], // specify whether double or single quotes should be used
    "semi": [1, "always"], // require or disallow use of semicolons instead of ASI
    "semi-spacing": [1, {"before": false, "after": true}], // enforce spacing before and after semicolons
    "sort-vars": 0, // sort variables within the same declaration block (off by default)
    "space-after-keywords": [1, "always"], // require a space after certain keywords (off by default)
    "space-before-blocks": [1, "always"], // require or disallow space before blocks (off by default)
    "space-before-function-paren": [2, "never"], // require or disallow space before function opening parenthesis (off by default)
    "object-curly-spacing": [2, "always"],		// require or disallow spaces inside objects (off by default)
    "computed-property-spacing": [2, "never"],
    "array-bracket-spacing": 1,       // require or disallow spaces inside arrays (off by default)

    "space-in-parens": [1, "never"], // require or disallow spaces inside parentheses (off by default)
    "space-infix-ops": [2, {"int32Hint": false}],   // require spaces around operators
    "space-return-throw-case": 2, // require a space after return, throw, and case
    "space-unary-ops": [1, {"words": true, "nonwords": false}], // Require or disallow spaces before/after unary operators (words on by default, nonwords off by default)
    "spaced-comment": [2, "always"],  // require or disallow a space immediately following the // in a line comment (off by default)
    "wrap-regex": 0, // require regex literals to be wrapped in parentheses (off by default)

    //
    // ECMAScript 6
    //
    // These rules are only relevant to ES6 environments and are off by default.
    //
    "no-var": 2, // require let or const instead of var (off by default)
    "generator-star-spacing": [2, "before"], // enforce the spacing around the * in generator functions (off by default)

    //
    // Legacy
    //
    // The following rules are included for compatibility with JSHint and JSLint.
    // While the names of the rules may not match up with the JSHint/JSLint counterpart,
    // the functionality is the same.
    //
    "max-depth": [2, 3], // specify the maximum depth that blocks can be nested (off by default)
    "max-len": [2, 100, 2], // specify the maximum length of a line in your program (off by default)
    "max-params": [2, 5], // limits the number of parameters that can be used in the function declaration. (off by default)
    "max-statements": 0, // specify the maximum number of statement allowed in a function (off by default)
    "no-bitwise": 0, // disallow use of bitwise operators (off by default)
    "no-plusplus": [2, {     // disallow use of unary operators, ++ and -- (off by default)
      "allowForLoopAfterthoughts": true
    }]
  }
};
<|endoftext|>


<commit_before>'use strict';
/**
 * INIT VARIABLES
 */
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var socketIO = require('socket.io')(http);
var firebase = require('firebase');
var _ = require('lodash');
require('dotenv').config();

/**
 * FIREBASE CONFIG
 */
var config = {
  apiKey: process.env.APIKEY,
  authDomain: process.env.AUTHDOMAIN,
  databaseURL: process.env.DATABASEURL,
  storageBucket: process.env.STORAGEBUCKET,
  messagingSenderId: process.env.MESSAGINGSENDERID
};

/**
 * FIREBASE INIT
 */
firebase.initializeApp(config);
var messagesDbRef = firebase.database().ref('chat/messages/');

/**
 * ANONYMOUS USER
 */
firebase.auth().signInAnonymously().catch(function(error) {
  console.log(error);
});

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    console.log('user login');
  } else {
    console.log('user not found');
  }
});

/**
 * EXPRESS SETUP
 */
app.set('port', (process.env.PORT || 3000));
app.use('/npm', express.static('node_modules'));
app.use(express.static('app'));

app.get('/', function(req, res) {
  res.sendfile('./app/index.html');
});

/**
 * SOCKET LISTEN EVENT
 */
io.on('connection', function(socket) {

  console.log('user connected:', socket.id);

  socketIO.emit('clean-chat');
  loadMessageFromDb(2);

  socket.broadcast.emit('user-connected', socket.id);

  socket.on('send-message', function(msg) {
    saveMessageToDb(socket.id, msg);
    socketIO.emit('read-message', { msg: msg, userId: socket.id, time: new Date().getTime() });
  });
});

/**
 * CREATE SERVER
 */
http.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

function loadMessageFromDb(limit) {
  messagesDbRef.orderByChild('time').limitToLast(limit).once('value', function(snapshot) {
    var data = snapshot.val();
    _.forEach(data, function(data) {
      socketIO.emit('read-message', { msg: data.message, userId: data.userId, time: data.time });
    });
  });
}

function saveMessageToDb(userId, message) {
  firebase.database().ref('/chat/messages/').push({
    userId: userId,
    message: message,
    time: new Date().getTime()
  });
}

<commit_msg>fix bug "io not defined"<commit_after>'use strict';
/**
 * INIT VARIABLES
 */
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var socketIO = require('socket.io')(http);
var firebase = require('firebase');
var _ = require('lodash');
require('dotenv').config();

/**
 * FIREBASE CONFIG
 */
var config = {
  apiKey: process.env.APIKEY,
  authDomain: process.env.AUTHDOMAIN,
  databaseURL: process.env.DATABASEURL,
  storageBucket: process.env.STORAGEBUCKET,
  messagingSenderId: process.env.MESSAGINGSENDERID
};

/**
 * FIREBASE INIT
 */
firebase.initializeApp(config);
var messagesDbRef = firebase.database().ref('chat/messages/');

/**
 * ANONYMOUS USER
 */
firebase.auth().signInAnonymously().catch(function(error) {
  console.log(error);
});

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    console.log('user login');
  } else {
    console.log('user not found');
  }
});

/**
 * EXPRESS SETUP
 */
app.set('port', (process.env.PORT || 3000));
app.use('/npm', express.static('node_modules'));
app.use(express.static('app'));

app.get('/', function(req, res) {
  res.sendfile('./app/index.html');
});

/**
 * SOCKET LISTEN EVENT
 */
socketIO.on('connection', function(socket) {

  console.log('user connected:', socket.id);

  socketIO.emit('clean-chat');
  loadMessageFromDb(2);

  socket.broadcast.emit('user-connected', socket.id);

  socket.on('send-message', function(msg) {
    saveMessageToDb(socket.id, msg);
    socketIO.emit('read-message', { msg: msg, userId: socket.id, time: new Date().getTime() });
  });
});

/**
 * CREATE SERVER
 */
http.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

function loadMessageFromDb(limit) {
  messagesDbRef.orderByChild('time').limitToLast(limit).once('value', function(snapshot) {
    var data = snapshot.val();
    _.forEach(data, function(data) {
      socketIO.emit('read-message', { msg: data.message, userId: data.userId, time: data.time });
    });
  });
}

function saveMessageToDb(userId, message) {
  firebase.database().ref('/chat/messages/').push({
    userId: userId,
    message: message,
    time: new Date().getTime()
  });
}

<|endoftext|>


<commit_before>"use strict";

var _ = require("lodash"),
    Sequelize = require("sequelize"),
    when = require("when");

module.exports = function G(sequelizeModelOrInstance, options) {
    options = _.merge({
        attributes: {},
        number: 1
    }, options);

    function valueBasedOnAttribute(attribute) {
        var typeString;

        if (attribute.type) {
            typeString = attribute.type.toString();
        } else {
            typeString = attribute;
        }

        if (typeString === "ENUM") {
            return _.sample(attribute.values);
        } else if (_.contains(["INTEGER", "SMALLINT UNSIGNED"], typeString)) {
            return _.parseInt(_.uniqueId(), 10);
            // starts with VARCHAR( or CHAR(, or is TEXT
        } else if (typeString.indexOf("VARCHAR(") === 0 || typeString.indexOf("CHAR") === 0 || typeString === "TEXT") {
            if (attribute.validate && attribute.validate.isUrl) {
                return "http://example.com/" + _.uniqueId();
            } else {
                return _.uniqueId();
            }
        }

        return null;
    }

    function setDefaultAttributesValue(rawAttributes, customValues, associationIdentifiers) {
        var attributes = _.clone(customValues) || {};

        _(rawAttributes)
        // Removes from rawAttributes any attributes from customValues. We want user-passed values to take precedence
        .omit(_.keys(customValues))
        // Loop the remaining rawAttributes to set values according to its Sequelize data type
        .forEach(function (value, key) {
            if (!_.has(value, "autoIncrement") && value.autoIncrement !== true) {
                if (_.has(value, "references") || _.contains(associationIdentifiers, key)) {
                    attributes[key] = null;
                } else {
                    var valueToPopulate = valueBasedOnAttribute(value);
                    if (!_.isNull(valueToPopulate)) {
                        attributes[key] = valueToPopulate;
                    }
                }
            }
        }).value();

        return attributes;
    }

    function instancesIfNeeded(sequelizeModelOrInstance) {
        // It is a model, create the instance
        if (sequelizeModelOrInstance.tableName) {
            var associationIdentifiers = _.pluck(sequelizeModelOrInstance.associations, "identifier"),
                bulkCreateArgument = [];

            for (var i = 0; i < options.number; i++) {
                var attributes = setDefaultAttributesValue(sequelizeModelOrInstance.rawAttributes, options.attributes, associationIdentifiers);

                _.forEach(options.attributes, function (value, key) {
                    if (_.isArray(value)) { // If value is an array, we consume the first element
                        attributes[key] = value[i];
                    } else if (_.isFunction(value)) { // If value is a function, execute it
                        attributes[key] = value();
                    }
                });

                bulkCreateArgument.push(attributes);
            }

            // Sadly .bulkCreate does not return the newly created instances. We need to .findAll, but since calling G() multiple times
            // could potentially run .findAll and return previously created records, we need to .slice with just the last options.number
            // elements
            return sequelizeModelOrInstance.bulkCreate(bulkCreateArgument).then(function () {
                return sequelizeModelOrInstance.findAll();
            }).then(function (instances) {
                return instances.slice(-options.number);
            });
        } else {
            // It is already an instance, not a model, so wrap it as a promise
            return when([sequelizeModelOrInstance]);
        }
    }

    function getSetterMethod(association, instance) {
        if (association.accessors && association.accessors.set) {
            return instance[association.accessors.set];
        } else {
            // setterName code copied straight from Sequelize
            // https://github.com/sequelize/sequelize/blob/0299ce638fc13ad79a50cd0714f274143babaf29/lib/associations/belongs-to.js#L71
            var setterName = Sequelize.Utils._.camelize("set_" + (association.options.as || Sequelize.Utils.singularize(association.target.tableName, association.options.language)));

            if (instance[setterName]) {
                return instance[setterName];
            } else if (instance[setterName + "s"]) {
                return instance[setterName + "s"];
            }
        }
    }

    return instancesIfNeeded(sequelizeModelOrInstance).then(function (instances) {
        var instance;

        if (options.number > 1) {
            var originalNumber = options.number;

            options.number = options.number - instances.length;

            return when.map(instances, function (instance) {
                var optionsCopy = _.clone(options);

                if (originalNumber > 0) {
                    // This part should be refactored with bulkCreateArgument.push's from instancesIfNeeded()
                    var attributes = {};

                    _.forEach(options.attributes, function (value, key) {
                        if (_.isArray(value)) { // If value is an array, we consume the first element
                            attributes[key] = value.shift();
                        } else if (_.isFunction(value)) { // If value is a function, execute it
                            attributes[key] = value();
                        } else {
                            attributes[key] = value;
                        }
                    });

                    optionsCopy.attributes = attributes;
                }

                return new G(instance, optionsCopy);
            });
        } else {
            instance = instances[0];
        }

        // Since G is recursive, options.rootInstance keeps track of what should be ultimately returned
        if (!options.rootInstance) {
            options.rootInstance = instance;
        }

        instance.generator = {};

        var associations = _.where(instance.daoFactory.associations, {
            associationType: "BelongsTo"
        });

        if (_.isEmpty(associations)) {
            return instance;
        } else {
            return when.map(associations, function (association) {
                var target = association.target,
                    targetAttributes = options[target.name] && options[target.name].attributes || {},
                    targetInstancePromise;

                var associationIdentifiers = _.pluck(target.associations, "identifier");

                targetAttributes = setDefaultAttributesValue(target.rawAttributes, targetAttributes, associationIdentifiers);

                if (options[target.name] && options[target.name] === "shared") {
                    targetInstancePromise = target.findAll().then(function (targetInstances) {
                        if (targetInstances.length === 0) {
                            return target.create(targetAttributes);
                        } else {
                            return _.first(targetInstances);
                        }
                    });
                } else if (options[target.name] === null) {
                    return;
                } else {
                    // If the target identifier was passed as an atribute of instance, try to get the
                    // existing record from the database. In other words, the foreign key value is set.
                    // Otherwise, create the instance.
                    targetInstancePromise = target.findOrCreate({
                        id: options.attributes[association.identifier] || null
                    }, targetAttributes);
                }

                return targetInstancePromise.then(function (targetInstance) {
                    var setterMethod = getSetterMethod(association, instance);

                    if (association.associationType === "HasMany") {
                        targetInstance = [targetInstance];
                    }

                    instance.generator[target.name] = targetInstance;

                    return setterMethod.call(instance, targetInstance).then(function () {
                        return targetInstance;
                    });
                });
            }).then(function (targetInstances) {
                return when.map(targetInstances, function (targetInstance) {
                    if (targetInstance && !_.isEmpty(targetInstance.daoFactory.associations)) {
                        return new G(targetInstance, options);
                    } else {
                        return targetInstance;
                    }
                });
            }).then(function () {
                return options.rootInstance;
            });
        }
    });
};
<commit_msg>Removed untaken branch<commit_after>"use strict";

var _ = require("lodash"),
    Sequelize = require("sequelize"),
    when = require("when");

module.exports = function G(sequelizeModelOrInstance, options) {
    options = _.merge({
        attributes: {},
        number: 1
    }, options);

    function valueBasedOnAttribute(attribute) {
        var typeString;

        if (attribute.type) {
            typeString = attribute.type.toString();
        } else {
            typeString = attribute;
        }

        if (typeString === "ENUM") {
            return _.sample(attribute.values);
        } else if (_.contains(["INTEGER", "SMALLINT UNSIGNED"], typeString)) {
            return _.parseInt(_.uniqueId(), 10);
            // starts with VARCHAR( or CHAR(, or is TEXT
        } else if (typeString.indexOf("VARCHAR(") === 0 || typeString.indexOf("CHAR") === 0 || typeString === "TEXT") {
            if (attribute.validate && attribute.validate.isUrl) {
                return "http://example.com/" + _.uniqueId();
            } else {
                return _.uniqueId();
            }
        }

        return null;
    }

    function setDefaultAttributesValue(rawAttributes, customValues, associationIdentifiers) {
        var attributes = _.clone(customValues);

        _(rawAttributes)
        // Removes from rawAttributes any attributes from customValues. We want user-passed values to take precedence
        .omit(_.keys(customValues))
        // Loop the remaining rawAttributes to set values according to its Sequelize data type
        .forEach(function (value, key) {
            if (!_.has(value, "autoIncrement") && value.autoIncrement !== true) {
                if (_.has(value, "references") || _.contains(associationIdentifiers, key)) {
                    attributes[key] = null;
                } else {
                    var valueToPopulate = valueBasedOnAttribute(value);
                    if (!_.isNull(valueToPopulate)) {
                        attributes[key] = valueToPopulate;
                    }
                }
            }
        }).value();

        return attributes;
    }

    function instancesIfNeeded(sequelizeModelOrInstance) {
        // It is a model, create the instance
        if (sequelizeModelOrInstance.tableName) {
            var associationIdentifiers = _.pluck(sequelizeModelOrInstance.associations, "identifier"),
                bulkCreateArgument = [];

            for (var i = 0; i < options.number; i++) {
                var attributes = setDefaultAttributesValue(sequelizeModelOrInstance.rawAttributes, options.attributes, associationIdentifiers);

                _.forEach(options.attributes, function (value, key) {
                    if (_.isArray(value)) { // If value is an array, we consume the first element
                        attributes[key] = value[i];
                    } else if (_.isFunction(value)) { // If value is a function, execute it
                        attributes[key] = value();
                    }
                });

                bulkCreateArgument.push(attributes);
            }

            // Sadly .bulkCreate does not return the newly created instances. We need to .findAll, but since calling G() multiple times
            // could potentially run .findAll and return previously created records, we need to .slice with just the last options.number
            // elements
            return sequelizeModelOrInstance.bulkCreate(bulkCreateArgument).then(function () {
                return sequelizeModelOrInstance.findAll();
            }).then(function (instances) {
                return instances.slice(-options.number);
            });
        } else {
            // It is already an instance, not a model, so wrap it as a promise
            return when([sequelizeModelOrInstance]);
        }
    }

    function getSetterMethod(association, instance) {
        if (association.accessors && association.accessors.set) {
            return instance[association.accessors.set];
        } else {
            // setterName code copied straight from Sequelize
            // https://github.com/sequelize/sequelize/blob/0299ce638fc13ad79a50cd0714f274143babaf29/lib/associations/belongs-to.js#L71
            var setterName = Sequelize.Utils._.camelize("set_" + (association.options.as || Sequelize.Utils.singularize(association.target.tableName, association.options.language)));

            if (instance[setterName]) {
                return instance[setterName];
            } else if (instance[setterName + "s"]) {
                return instance[setterName + "s"];
            }
        }
    }

    return instancesIfNeeded(sequelizeModelOrInstance).then(function (instances) {
        var instance;

        if (options.number > 1) {
            var originalNumber = options.number;

            options.number = options.number - instances.length;

            return when.map(instances, function (instance) {
                var optionsCopy = _.clone(options);

                if (originalNumber > 0) {
                    // This part should be refactored with bulkCreateArgument.push's from instancesIfNeeded()
                    var attributes = {};

                    _.forEach(options.attributes, function (value, key) {
                        if (_.isArray(value)) { // If value is an array, we consume the first element
                            attributes[key] = value.shift();
                        } else if (_.isFunction(value)) { // If value is a function, execute it
                            attributes[key] = value();
                        } else {
                            attributes[key] = value;
                        }
                    });

                    optionsCopy.attributes = attributes;
                }

                return new G(instance, optionsCopy);
            });
        } else {
            instance = instances[0];
        }

        // Since G is recursive, options.rootInstance keeps track of what should be ultimately returned
        if (!options.rootInstance) {
            options.rootInstance = instance;
        }

        instance.generator = {};

        var associations = _.where(instance.daoFactory.associations, {
            associationType: "BelongsTo"
        });

        if (_.isEmpty(associations)) {
            return instance;
        } else {
            return when.map(associations, function (association) {
                var target = association.target,
                    targetAttributes = options[target.name] && options[target.name].attributes || {},
                    targetInstancePromise;

                var associationIdentifiers = _.pluck(target.associations, "identifier");

                targetAttributes = setDefaultAttributesValue(target.rawAttributes, targetAttributes, associationIdentifiers);

                if (options[target.name] && options[target.name] === "shared") {
                    targetInstancePromise = target.findAll().then(function (targetInstances) {
                        if (targetInstances.length === 0) {
                            return target.create(targetAttributes);
                        } else {
                            return _.first(targetInstances);
                        }
                    });
                } else if (options[target.name] === null) {
                    return;
                } else {
                    // If the target identifier was passed as an atribute of instance, try to get the
                    // existing record from the database. In other words, the foreign key value is set.
                    // Otherwise, create the instance.
                    targetInstancePromise = target.findOrCreate({
                        id: options.attributes[association.identifier] || null
                    }, targetAttributes);
                }

                return targetInstancePromise.then(function (targetInstance) {
                    var setterMethod = getSetterMethod(association, instance);

                    if (association.associationType === "HasMany") {
                        targetInstance = [targetInstance];
                    }

                    instance.generator[target.name] = targetInstance;

                    return setterMethod.call(instance, targetInstance).then(function () {
                        return targetInstance;
                    });
                });
            }).then(function (targetInstances) {
                return when.map(targetInstances, function (targetInstance) {
                    if (targetInstance && !_.isEmpty(targetInstance.daoFactory.associations)) {
                        return new G(targetInstance, options);
                    } else {
                        return targetInstance;
                    }
                });
            }).then(function () {
                return options.rootInstance;
            });
        }
    });
};
<|endoftext|>


<commit_before>var godot = require( "godot" );
var nconf = require( "nconf" );
var OpsGenieReactor = require( "godot-opsgenie" );
nconf.defaults({
    graphite: {
        url: "",
        prefix: "xxxx.godot",
    },
    port: 1337,
    host: "localhost"
}).argv();

var server = godot.createServer({
    type: "udp",
    multiplex: false,
       reactors: [
         godot.reactor()
           .graphite({
             url: nconf.get( "graphite:url" ),
             prefix: nconf.get( "graphite:prefix" )
            }),
           .console(),
        godot.reactor()
            .where( "service", "elasticsearch/health/healtcheck" )
            .change( "state" )
            .opsgenie({
                customerKey: nconf.get( "opsgenie.customerKey" )
            })
            .console()

       ]
});

function onError( err ){
  console.error( "Error occured %s - %s", err.message, err.stack );
}
server
    .on( "error", onError )
    .listen( nconf.get( "port" ), nconf.get( "host" ), function( err ){
        if( !err ){
          console.info( "Godot server is listening on port %s", server.port  );
        }
      });
<commit_msg>removed colon<commit_after>var godot = require( "godot" );
var nconf = require( "nconf" );
var OpsGenieReactor = require( "godot-opsgenie" );
nconf.defaults({
    graphite: {
        url: "",
        prefix: "xxxx.godot",
    },
    port: 1337,
    host: "localhost"
}).argv();

var server = godot.createServer({
    type: "udp",
    multiplex: false,
       reactors: [
         godot.reactor()
           .graphite({
             url: nconf.get( "graphite:url" ),
             prefix: nconf.get( "graphite:prefix" )
            })
           .console(),
        godot.reactor()
            .where( "service", "elasticsearch/health/healtcheck" )
            .change( "state" )
            .opsgenie({
                customerKey: nconf.get( "opsgenie.customerKey" )
            })
            .console()

       ]
});

function onError( err ){
  console.error( "Error occured %s - %s", err.message, err.stack );
}
server
    .on( "error", onError )
    .listen( nconf.get( "port" ), nconf.get( "host" ), function( err ){
        if( !err ){
          console.info( "Godot server is listening on port %s", server.port  );
        }
      });
<|endoftext|>


<commit_before>/* ========================================================================
 * StorageAPI: index.js v0.0.1
 * Author: Mike Grabowski (@grabbou)
 * Created at: 14/08/2014
 * ========================================================================
 * Description: Abstract StorageAPI client provider. Ensures all of the
 * providers integrated within that package implement all of the required
 * methods. Every package needs to inherit from that abstract one to work.
 * ========================================================================
 */

/* jshint unused: false */

'use strict';

/**
 * Initializes StorageClient, connection and saves config
 * Creates container/folder to use if necessary
 * @param config {Object} containing provider-specific data
 * @param connection {Object} containing reference to connection method
 * @constructor
 */
var StorageClient = function StorageClient(config, connection) {

	if (this.constructor === StorageClient) {
		throw new Error('StorageClient: Cannot initialize abstract class');
	}

	this.__config = config;
	this.__connection = connection;

	this.__ensureContainer(function onEnsured(err) {
		if (err) {
			throw new Error('StorageClient: There was a problem with initialization. Details: ' + err.message);
		}
	});
};

/**
 * Uploads given file
 * @param fileSrc {String} path to the file
 * @param filename {String} name of the file
 * @param callback {Function} to invoke after completing
 * @abstract
 * @access public
 */
StorageClient.prototype.upload = function (fileSrc, filename, callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Removes given file
 * @param filename {String} filename to delete
 * @param callback {Function} to invoke after completing
 * @abstract
 * @access public
 */
StorageClient.prototype.remove = function (filename, callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Downloads given file
 * @param filename {String} to download
 * @param fileSrc {String} path to save the file
 * @param callback {Function} to invoke after downloading
 * @abstract
 * @access public
 */
StorageClient.prototype.download = function (filename, fileSrc, callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Ensures that container/folder we want to use is defined and created
 * @param callback {Function} to be invoked after completion
 * @public
 * @abstract
 * @access protected
 */
StorageClient.prototype.__ensureContainer = function (callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Checks whether config passed is valid
 * @param schema
 * @param config
 * @access protected
 */
StorageClient.prototype.__ensureValid = function (schema, config) {
	schema.forEach(function (key) {
		if (!config.hasOwnProperty(key)) {
			throw new Error('StorageClient: Missing argument for ' + key + '. Check the docs for further assistance');
		}
	});
};

module.exports = StorageClient;

<commit_msg>Fixed StorageClient to pass tests<commit_after>/* ========================================================================
 * StorageAPI: index.js v0.0.1
 * Author: Mike Grabowski (@grabbou)
 * Created at: 14/08/2014
 * ========================================================================
 * Description: Abstract StorageAPI client provider. Ensures all of the
 * providers integrated within that package implement all of the required
 * methods. Every package needs to inherit from that abstract one to work.
 * ========================================================================
 */

/* jshint unused: false */

'use strict';

/**
 * Initializes StorageClient, connection and saves config
 * Creates container/folder to use if necessary
 * @param config {Object} containing provider-specific data
 * @param connection {Object} containing reference to connection method
 * @constructor
 */
var StorageClient = function StorageClient(config, connection) {

	if (this.constructor === StorageClient) {
		throw new Error('StorageClient: Cannot initialize abstract class');
	}

	this.__config = config;
	this.__connection = connection;

	this.__ensureContainer(function onEnsured(err) {
		if (err) {
			throw new Error('StorageClient: There was a problem with initialization. Details: ' + err.message);
		}
	});
};

/**
 * Uploads given file
 * @param fileSrc {String} path to the file
 * @param filename {String} name of the file
 * @param callback {Function} to invoke after completing
 * @abstract
 * @access public
 */
StorageClient.prototype.upload = function (fileSrc, filename, callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Removes given file
 * @param filename {String} filename to delete
 * @param callback {Function} to invoke after completing
 * @abstract
 * @access public
 */
StorageClient.prototype.remove = function (filename, callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Downloads given file
 * @param filename {String} to download
 * @param fileSrc {String} path to save the file
 * @param callback {Function} to invoke after downloading
 * @abstract
 * @access public
 */
StorageClient.prototype.download = function (filename, fileSrc, callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Ensures that container/folder we want to use is defined and created
 * @param callback {Function} to be invoked after completion
 * @public
 * @abstract
 * @access protected
 */
StorageClient.prototype.__ensureContainer = function (callback) {
	throw new Error('Cannot invoke abstract method');
};

/**
 * Checks whether config passed is valid
 * @param schema
 * @param config
 * @access protected
 */
StorageClient.prototype.__ensureValid = function (schema, config) {
	if (typeof schema === 'string') schema = [schema];
	schema.forEach(function (key) {
		if (!config.hasOwnProperty(key)) {
			throw new Error('StorageClient: Missing argument for ' + key + '. Check the docs for further assistance');
		}
	});
};

module.exports = StorageClient;

<|endoftext|>


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

var createTraceurPreprocessor = function(args, config, logger, helper) {
  config = config || {};

  var log = logger.create('preprocessor.traceur');
  var defaultOptions = {
    sourceMap: false,
    modules: 'requirejs'
  };
  var options = helper.merge(defaultOptions, args.options || {}, config.options || {});

  var transformPath = args.transformPath || config.transformPath || function(filepath) {
    return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js');
  };

  return function(content, file, done) {
    log.debug('Processing "%s".', file.originalPath);
    file.path = transformPath(file.originalPath);
    options.filename = file.originalPath;

    var result = traceur.compile(content, options);
    var transpiledContent = result.js;

    result.errors.forEach(function(err) {
      log.error(err);
    });

    if (result.sourceMap) {
      transpiledContent += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,';
      transpiledContent += new Buffer(result.sourceMap).toString('base64') + '\n';
    }

    return done(transpiledContent);
  };
};

createTraceurPreprocessor.$inject = ['args', 'config.traceurPreprocessor', 'logger', 'helper'];

var initTraceurFramework = function(files) {
  // TODO(vojta): Traceur module should provide this path
  files.unshift({pattern: __dirname + '/node_modules/traceur/bin/traceur-runtime.js', included: true, served: true, watched: false});
};

initTraceurFramework.$inject = ['config.files'];

// PUBLISH DI MODULE
module.exports = {
  'preprocessor:traceur': ['factory', createTraceurPreprocessor],
  'framework:traceur': ['factory', initTraceurFramework]
};
<commit_msg>Source maps - show original filename.<commit_after>var traceur = require('traceur');

var createTraceurPreprocessor = function(args, config, logger, helper) {
  config = config || {};

  var log = logger.create('preprocessor.traceur');
  var defaultOptions = {
    sourceMap: false,
    modules: 'requirejs'
  };
  var options = helper.merge(defaultOptions, args.options || {}, config.options || {});

  var transformPath = args.transformPath || config.transformPath || function(filepath) {
    return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js');
  };

  return function(content, file, done) {
    log.debug('Processing "%s".', file.originalPath);
    file.path = transformPath(file.originalPath);
    options.filename = file.originalPath;

    var result = traceur.compile(content, options);
    var transpiledContent = result.js;

    result.errors.forEach(function(err) {
      log.error(err);
    });

    // TODO(vojta): Tracer should return JS object, rather than a string.
    if (result.sourceMap) {
      var map = JSON.parse(result.sourceMap);
      map.file = file.path;
      transpiledContent += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,';
      transpiledContent += new Buffer(JSON.stringify(map)).toString('base64') + '\n';

      file.sourceMap = map
    }

    return done(transpiledContent);
  };
};

createTraceurPreprocessor.$inject = ['args', 'config.traceurPreprocessor', 'logger', 'helper'];

var initTraceurFramework = function(files) {
  // TODO(vojta): Traceur module should provide this path
  files.unshift({pattern: __dirname + '/node_modules/traceur/bin/traceur-runtime.js', included: true, served: true, watched: false});
};

initTraceurFramework.$inject = ['config.files'];

// PUBLISH DI MODULE
module.exports = {
  'preprocessor:traceur': ['factory', createTraceurPreprocessor],
  'framework:traceur': ['factory', initTraceurFramework]
};
<|endoftext|>


<commit_before>var  craigslist = require('node-craigslist');
var print = function(err, listing) {
  if (err)
    return err;
  console.log(JSON.stringify(listing, null, 2))
}
var QueryCraigslist = module.exports = function(options, callback) {
  client = craigslist({
     city : options.city ? options.city : ''
  })

  if (options.citiesOnly)
    options.allCities = true
  var url = options.url
  if (url) {
    var idx = url.indexOf('://') + 3;
    var idx1 = url.indexOf('/', idx);
    options.hostname = url.substring(idx, idx1)
    options.path = url.substring(idx1)
  }
  client.search(options, '', function (err, listings) {
  	if (!listings) {
      callback(null, {})
      return;
    }
    if (!callback)
      callback = print
    if (options.citiesOnly) {
      callback(err, listings)
      return;
    }

    var all = options.allCities

    if (all) {
    // play with listings here...
      listings.forEach(function (listing) {
        var options1 = { city: listing.city, cityName: listing.cityName }
        Object.keys(options).forEach(function(key) {
          if (key != 'allCities')
            options1[key] = options[key]
        })
        client.search(options1, '', function (err, l1) {
          if (l1)
            callback(err, l1)
        })
      })
    }
    else {
      if (!options.fullListing) {
        callback(err, listings)
        return
      }
      if (options.url)
        return callback(err, listings)

      // For the listing with full description we need to run request per listings url and extract description from it
      listings.forEach(function(listing) {
        var idx = listing.url.indexOf('://') + 3;
        var idx1 = listing.url.indexOf('/', idx);
        options.hostname = listing.url.substring(idx, idx1)
        options.path = listing.url.substring(idx1)
        client.search(options, '', function (err, description) {
          listing.description = description
          callback(err, listing)
        })
      })
    }
  })
}<commit_msg>minor change<commit_after>var  craigslist = require('node-craigslist');
var print = function(err, listing) {
  if (err)
    return err;
  console.log(JSON.stringify(listing, null, 2))
}
var QueryCraigslist = module.exports = function(options, callback) {
  client = craigslist({
     city : options.city ? options.city : ''
  })

  if (options.citiesOnly)
    options.allCities = true
  var url = options.url
  if (url) {
    var idx = url.indexOf('://') + 3;
    var idx1 = url.indexOf('/', idx);
    options.hostname = url.substring(idx, idx1)
    options.path = url.substring(idx1)
    options.fullListing = true
  }
  client.search(options, '', function (err, listings) {
  	if (!listings) {
      callback(null, {})
      return;
    }
    if (!callback)
      callback = print
    if (options.citiesOnly) {
      callback(err, listings)
      return;
    }

    var all = options.allCities

    if (all) {
    // play with listings here...
      listings.forEach(function (listing) {
        var options1 = { city: listing.city, cityName: listing.cityName }
        Object.keys(options).forEach(function(key) {
          if (key != 'allCities')
            options1[key] = options[key]
        })
        client.search(options1, '', function (err, l1) {
          if (l1)
            callback(err, l1)
        })
      })
    }
    else {
      if (!options.fullListing) {
        callback(err, listings)
        return
      }
      if (options.url)
        return callback(err, listings)

      // For the listing with full description we need to run request per listings url and extract description from it
      listings.forEach(function(listing) {
        var idx = listing.url.indexOf('://') + 3;
        var idx1 = listing.url.indexOf('/', idx);
        options.hostname = listing.url.substring(idx, idx1)
        options.path = listing.url.substring(idx1)
        client.search(options, '', function (err, description) {
          listing.description = description
          callback(err, listing)
        })
      })
    }
  })
}<|endoftext|>


<commit_before>const { Transform } = require('stream')
const DataFlatter = require('./dataFlatter')

/**
 * Flattens the object stream
 */
class StreamFlatter extends Transform {
  /**
   * @constructor
   *
   * @param {Object} jsonSchema JSON schema
   * @param {string} collectionName Collection name
   * @param {string} [pathSeparator=undefined] Path separator
   * @param {string} [generatedFieldPrefix=undefined] Generated field prefix
   * @param {string} [placeholder=undefined] Placeholder
   */
  constructor (jsonSchema, collectionName, pathSeparator = undefined, generatedFieldPrefix = undefined, placeholder = undefined) {
    super({
      objectMode: true
    })

    this._dataFlatter = new DataFlatter(jsonSchema, collectionName, pathSeparator, generatedFieldPrefix, placeholder)
  }

  /**
   * https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
   * @override
   */
  _transform (chunk, encoding, callback) {
    try {
      const flattened = this._dataFlatter.flatten(chunk)
      callback(null, flattened)
    } catch (error) {
      console.error('Failed to flatten data', error)
      callback(error, null)
    }
  }
}

module.exports = StreamFlatter
<commit_msg>StreamFlatter supports metadata as well<commit_after>const { Transform } = require('stream')
const DataFlatter = require('./dataFlatter')

/**
 * Flattens the object stream
 */
class StreamFlatter extends Transform {
  /**
   * @constructor
   *
   * @param {Object} jsonSchema JSON schema
   * @param {string} collectionName Collection name
   * @param {boolean} [includeMetadata=false] True if metadata should be included into data
   * @param {string} [pathSeparator=undefined] Path separator
   * @param {string} [generatedFieldPrefix=undefined] Generated field prefix
   * @param {string} [placeholder=undefined] Placeholder
   */
  constructor (jsonSchema, collectionName, includeMetadata = false, pathSeparator = undefined, generatedFieldPrefix = undefined, placeholder = undefined) {
    super({
      objectMode: true
    })

    this._includeMetadata = includeMetadata
    this._dataFlatter = new DataFlatter(jsonSchema, collectionName, pathSeparator, generatedFieldPrefix, placeholder)
  }

  /**
   * https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
   * @override
   */
  _transform (chunk, encoding, callback) {
    try {
      const flattened = this._dataFlatter.flatten(chunk, this._includeMetadata)
      callback(null, flattened)
    } catch (error) {
      console.error('Failed to flatten data', error)
      callback(error, null)
    }
  }
}

module.exports = StreamFlatter
<|endoftext|>


<commit_before>var events = require("events");
var fs = require('fs');
var http = require('http');
var https = require('https');
var util = require('util');

var Promise = require('promise');
var Speaker = require('speaker');
var lame = require('lame');
var mpg123Util = require('node-mpg123-util');

/**
 * @param {string} uri
 * @constructor
 */
StupidPlayer = function(uri) {
	this._decoder = null;
	this._speaker = null;
	this._request = null;

	this._src = uri;

	this._onDecoderFormatted = this._onDecoderFormatted.bind(this);
	this._onDecoderClosed = this._onDecoderClosed.bind(this);
	this._onError = this._onError.bind(this);

	this.play(uri);
};
util.inherits(StupidPlayer, events.EventEmitter);

/**
 * @param {string} uri
 * @return {Promise.<Format>}
 */
StupidPlayer.prototype.play = function(uri) {
	if (this._isStream()) {
		return this.playStream(uri);
	} else {
		return this.playFile(uri);
	}
};

/**
 * @param {string} url
 * @return {Promise.<Format>}
 */
StupidPlayer.prototype.playStream = function(url) {
	return new Promise(function(resolve, reject) {
		var request = url.indexOf('https') === 0 ? https : http;

		this._request = request.get(url, function(res, req) {
			this._makeDecoder(res)
				.then(function(format) {
					resolve(format);
				});
		}.bind(this));

		this._request.once('error', this._onError);
	}.bind(this));
};

/**
 * @param {string} path
 * @return {Promise.<Format>}
 */
StupidPlayer.prototype.playFile = function(path) {
	return new Promise(function(resolve, reject) {
		var readStream = fs.createReadStream(path);

		readStream.once('error', this._onError);

		return this
			._makeDecoder(readStream)
			.then(function(format) {
				resolve(format);
			});
	}.bind(this));
};

/**
 *
 */
StupidPlayer.prototype.stop = function() {
	if (this._state !== this.state.STOP) {
		this._state = this.state.STOP;
		this._emit(this.EVENT_STOP);
		this.deinit();
	}
};

/**
 * @param {number} value 0..1
 * @return {Promise.<number>}
 */
StupidPlayer.prototype.setVolume = function(value) {
	return new Promise(function(resolve, reject) {
		var resolver = function() {
			resolve(value);
			this._emit(this.EVENT_VOLUME_CHANGE, value);
		}.bind(this);

		if (this._decoder) {
			mpg123Util.setVolume(this._decoder.mh, value);
			setTimeout(resolver, this.VOLUME_CHANGE_TIMEOUT);
		} else {
			reject(null);
		}
	}.bind(this));
};

/**
 * @return {?number} 0..1
 */
StupidPlayer.prototype.getVolume = function() {
	if (this._decoder) {
		return mpg123Util.getVolume(this._decoder.mh);
	} else {
		return null;
	}
};

/**
 *
 */
StupidPlayer.prototype.deinit = function() {
	this._closeConnection();
	if (this._speaker) {
		this._decoder.removeListener('error', this._onError);

		this._decoder.unpipe();
		this._speaker.end();

		this._speaker = null;
		this._decoder = null;
	}
};

/**
 *
 * @protected
 */
StupidPlayer.prototype._closeConnection = function() {
	if (this._request) {
		this._request.removeListener('error', this._onError);
		this._request.destroy();
		this._request = null;
	}
};

/**
 *
 * @return {boolean}
 * @protected
 */
StupidPlayer.prototype._isStream = function() {
	var src = this._src;
	return src.indexOf('http') === 0 || src.indexOf('https') === 0;
};

/**
 *
 * @param res
 * @return {Promise.<Format>}
 * @protected
 */
StupidPlayer.prototype._makeDecoder = function(res) {
	return new Promise(function(resolve, reject) {
		if (!this._isStream() || this._checkConnect(res, function() {})) {// todo need simple method
			this._decoder = new lame.Decoder();
			res.pipe(this._decoder);

			this._decoder.once('format', function(format) {
				this._onDecoderFormatted(format);
				resolve(format);
			}.bind(this));

			this._decoder.on('error', this._onError);

		} else {
			this._state = this.state.STOP;
			this._emit(this.EVENT_STOP);
		}
	}.bind(this));
};

/**
 *
 * @param format
 * @protected
 */
StupidPlayer.prototype._play = function(format) {
	if (this._state !== this.state.STOP) {
		this._speaker = new Speaker(format);

		this._emit(this.EVENT_START, this._isStream());
		this._state = this.state.PLAY;

		this._pipedDecoder = this._decoder.pipe(this._speaker);
		this._pipedDecoder.once('close', this._onDecoderClosed);
	}
};

/**
 *
 * @param res
 * @param callback
 * @return {boolean}
 * @protected
 */
StupidPlayer.prototype._checkConnect = function(res, callback) {
	var isOk = res.statusCode === 200;
	var isAudio = (res.headers['content-type'].indexOf('audio/mpeg') !== -1);
	if (!isOk) {
		callback(new Error('resource invalid'));
		return false;
	}
	if (!isAudio) {
		callback(new Error('resource type is unsupported'));
		return false;
	}
	return true;
};

/**
 * @param {string} event
 * @param {*?} opt_data
 * @protected
 */
StupidPlayer.prototype._emit = function(event, opt_data) {
//	console.log('stupid-player emit', event);
	this.emit(event, opt_data);
};

/**
 *
 * @param format
 * @protected
 */
StupidPlayer.prototype._onDecoderFormatted = function(format) {
	this._play(format);
};

/**
 *
 * @protected
 */
StupidPlayer.prototype._onDecoderClosed = function() {
	this.stop();
};

/**
 *
 * @param {string} error
 * @protected
 */
StupidPlayer.prototype._onError = function(error) {
	if (this._request) {
		this._request = null;
	} else {
		return;
	}
	this._emit(this.EVENT_ERROR, error);
};

/**
 *
 */
StupidPlayer.prototype._decoder;

/**
 *
 */
StupidPlayer.prototype._speaker;

/**
 *
 */
StupidPlayer.prototype._pipedDecoder;

/**
 * @type {string}
 */
StupidPlayer.prototype._src;

/**
 * @type {ClientRequest}
 */
StupidPlayer.prototype._request;

/**
 * @const {number}
 */
StupidPlayer.prototype.VOLUME_CHANGE_TIMEOUT = 300;

/**
 * @const {string}
 */
StupidPlayer.prototype.EVENT_START = 'start';

/**
 * @const {string}
 */
StupidPlayer.prototype.EVENT_STOP = 'stop';

/**
 * Fired with: {number} volume
 * @const {string}
 */
StupidPlayer.prototype.EVENT_VOLUME_CHANGE = 'volume-change';

/**
 * Fired with: string
 * @const {string}
 */
StupidPlayer.prototype.EVENT_ERROR = 'error';

/**
 * @enum {string}
 */
StupidPlayer.prototype.state = {
	PLAY: 'play',
	STOP: 'stop',
	PAUSE: 'pause'
};

module.exports = StupidPlayer;
<commit_msg>Refactoring: remove call play from constructor<commit_after>var events = require("events");
var fs = require('fs');
var http = require('http');
var https = require('https');
var util = require('util');

var Promise = require('promise');
var Speaker = require('speaker');
var lame = require('lame');
var mpg123Util = require('node-mpg123-util');

/**
 * @param {string} uri
 * @constructor
 */
StupidPlayer = function(uri) {
	this._decoder = null;
	this._speaker = null;
	this._request = null;

	this._src = uri;

	this._onDecoderFormatted = this._onDecoderFormatted.bind(this);
	this._onDecoderClosed = this._onDecoderClosed.bind(this);
	this._onError = this._onError.bind(this);
};
util.inherits(StupidPlayer, events.EventEmitter);

/**
 * @return {Promise.<Format>}
 */
StupidPlayer.prototype.play = function() {
	var uri = this._src;
	if (this._isStream()) {
		return this.playStream(uri);
	} else {
		return this.playFile(uri);
	}
};

/**
 * @param {string} url
 * @return {Promise.<Format>}
 */
StupidPlayer.prototype.playStream = function(url) {
	return new Promise(function(resolve, reject) {
		var request = url.indexOf('https') === 0 ? https : http;

		this._request = request.get(url, function(res, req) {
			this._makeDecoder(res)
				.then(function(format) {
					resolve(format);
				});
		}.bind(this));

		this._request.once('error', this._onError);
	}.bind(this));
};

/**
 * @param {string} path
 * @return {Promise.<Format>}
 */
StupidPlayer.prototype.playFile = function(path) {
	return new Promise(function(resolve, reject) {
		var readStream = fs.createReadStream(path);

		readStream.once('error', this._onError);

		return this
			._makeDecoder(readStream)
			.then(function(format) {
				resolve(format);
			});
	}.bind(this));
};

/**
 *
 */
StupidPlayer.prototype.stop = function() {
	if (this._state !== this.state.STOP) {
		this._state = this.state.STOP;
		this._emit(this.EVENT_STOP);
		this.deinit();
	}
};

/**
 * @param {number} value 0..1
 * @return {Promise.<number>}
 */
StupidPlayer.prototype.setVolume = function(value) {
	return new Promise(function(resolve, reject) {
		var resolver = function() {
			resolve(value);
			this._emit(this.EVENT_VOLUME_CHANGE, value);
		}.bind(this);

		if (this._decoder) {
			mpg123Util.setVolume(this._decoder.mh, value);
			setTimeout(resolver, this.VOLUME_CHANGE_TIMEOUT);
		} else {
			reject(null);
		}
	}.bind(this));
};

/**
 * @return {?number} 0..1
 */
StupidPlayer.prototype.getVolume = function() {
	if (this._decoder) {
		return mpg123Util.getVolume(this._decoder.mh);
	} else {
		return null;
	}
};

/**
 *
 */
StupidPlayer.prototype.deinit = function() {
	this._closeConnection();
	if (this._speaker) {
		this._decoder.removeListener('error', this._onError);

		this._decoder.unpipe();
		this._speaker.end();

		this._speaker = null;
		this._decoder = null;
	}
};

/**
 *
 * @protected
 */
StupidPlayer.prototype._closeConnection = function() {
	if (this._request) {
		this._request.removeListener('error', this._onError);
		this._request.destroy();
		this._request = null;
	}
};

/**
 *
 * @return {boolean}
 * @protected
 */
StupidPlayer.prototype._isStream = function() {
	var src = this._src;
	return src.indexOf('http') === 0 || src.indexOf('https') === 0;
};

/**
 *
 * @param res
 * @return {Promise.<Format>}
 * @protected
 */
StupidPlayer.prototype._makeDecoder = function(res) {
	return new Promise(function(resolve, reject) {
		if (!this._isStream() || this._checkConnect(res, function() {})) {// todo need simple method
			this._decoder = new lame.Decoder();
			res.pipe(this._decoder);

			this._decoder.once('format', function(format) {
				this._onDecoderFormatted(format);
				resolve(format);
			}.bind(this));

			this._decoder.on('error', this._onError);

		} else {
			this._state = this.state.STOP;
			this._emit(this.EVENT_STOP);
		}
	}.bind(this));
};

/**
 *
 * @param format
 * @protected
 */
StupidPlayer.prototype._play = function(format) {
	if (this._state !== this.state.STOP) {
		this._speaker = new Speaker(format);

		this._emit(this.EVENT_START, this._isStream());
		this._state = this.state.PLAY;

		this._pipedDecoder = this._decoder.pipe(this._speaker);
		this._pipedDecoder.once('close', this._onDecoderClosed);
	}
};

/**
 *
 * @param res
 * @param callback
 * @return {boolean}
 * @protected
 */
StupidPlayer.prototype._checkConnect = function(res, callback) {
	var isOk = res.statusCode === 200;
	var isAudio = (res.headers['content-type'].indexOf('audio/mpeg') !== -1);
	if (!isOk) {
		callback(new Error('resource invalid'));
		return false;
	}
	if (!isAudio) {
		callback(new Error('resource type is unsupported'));
		return false;
	}
	return true;
};

/**
 * @param {string} event
 * @param {*?} opt_data
 * @protected
 */
StupidPlayer.prototype._emit = function(event, opt_data) {
//	console.log('stupid-player emit', event);
	this.emit(event, opt_data);
};

/**
 *
 * @param format
 * @protected
 */
StupidPlayer.prototype._onDecoderFormatted = function(format) {
	this._play(format);
};

/**
 *
 * @protected
 */
StupidPlayer.prototype._onDecoderClosed = function() {
	this.stop();
};

/**
 *
 * @param {string} error
 * @protected
 */
StupidPlayer.prototype._onError = function(error) {
	if (this._request) {
		this._request = null;
	} else {
		return;
	}
	this._emit(this.EVENT_ERROR, error);
};

/**
 *
 */
StupidPlayer.prototype._decoder;

/**
 *
 */
StupidPlayer.prototype._speaker;

/**
 *
 */
StupidPlayer.prototype._pipedDecoder;

/**
 * @type {string}
 */
StupidPlayer.prototype._src;

/**
 * @type {ClientRequest}
 */
StupidPlayer.prototype._request;

/**
 * @const {number}
 */
StupidPlayer.prototype.VOLUME_CHANGE_TIMEOUT = 300;

/**
 * @const {string}
 */
StupidPlayer.prototype.EVENT_START = 'start';

/**
 * @const {string}
 */
StupidPlayer.prototype.EVENT_STOP = 'stop';

/**
 * Fired with: {number} volume
 * @const {string}
 */
StupidPlayer.prototype.EVENT_VOLUME_CHANGE = 'volume-change';

/**
 * Fired with: string
 * @const {string}
 */
StupidPlayer.prototype.EVENT_ERROR = 'error';

/**
 * @enum {string}
 */
StupidPlayer.prototype.state = {
	PLAY: 'play',
	STOP: 'stop',
	PAUSE: 'pause'
};

module.exports = StupidPlayer;
<|endoftext|>


<commit_before>var http = require("http"),
	https = require("https"),
	url = require("url");

module.exports = function(options, cb){
	if(typeof options === "string"){
		options = { uri: url.parse(options) };
	}
	return new Request(options, cb);
};

//Add methods for the most common cases
["GET", "POST", "HEAD", "DELETE", "UPDATE"].forEach(function(method){
	module.exports[method.toLowerCase()] = function(uri, cb){
		uri = url.parse(uri);
		uri.method = method;
		return new Request({ uri: uri }, cb);
	};
});

var protocols = {
	"http:": http,
	"https:": https
};
module.exports.addProtocol = function(name, module){
	protocols[name] = module;
};

var re_protocol = /^https?:/; //TODO: what about other protocols?

var Request = function(options, cb){
	this._options = options;
	this._cb = cb;

	this._ended = false;
	this._redirected = 0;
	this._resp = null;
	this.response = null;
	this._body = "";

	this.writable = options.uri.method === "POST" || options.uri.method === "PUT";

	this._addListeners();

	var scope = this;
	process.nextTick(function(){
		if(!scope._createRequest(options)) return;
		if(!scope.writable) scope._request.end();
		else{
			if(options.body) scope._request.write(options.body);
			scope._prepareClose();
		}
	});
};

var Stream = require("stream").Stream;
require("util").inherits(Request, Stream);

Request.prototype.readable = true;

//save the pipe function for later
var pipe = Stream.prototype.pipe;

Request.prototype.pipe = function(dest, opts){
	if(this._body){
		throw Error("Data was already emitted!");
	}
	else if(this._ended){
		throw Error("Request is closed!");
	}

	return pipe.call(this, dest, opts);
};

Request.prototype._prepareClose = function(){
	this._close = true;
	var scope = this;
	process.nextTick(function(){
		if(scope._close){
			scope._request.end();
			scope.writable = false;
		}
	});
};

Request.prototype._addListeners = function(){
	var scope = this;

	this.on("error", function(err){
		scope._cb(err);
	});

	this.on("end", function(){
		scope._ended = true;
		if(scope._cb) scope._cb(null, scope.response, scope._body);
	});

	this.on("data", function(chunk){
		if(!scope._written) scope._written = true;
		scope._body += chunk;
	});

	this.on("redirect", function(location){
		var options = scope._options,
			method = options.uri.method;

		if(scope._redirected++ < (options.maxRedirects || 10)){
			if(!re_protocol.test(location)){
		 		location = url.resolve(options.uri, location);
		 	}

		 	options.uri = url.parse(location);
		 	options.uri.method = method;

		 	scope._createRequest(options);
		 	scope._request.end();
		 } else {
		 	scope.emit("error", Error("Too many redirects"));
		 }
	});

	this.once("pipe", function(src){
		if(!scope.writable){
		 	scope.emit("error", Error("Can't write to socket!"));
		 	return;
		 }

		 scope._close = false;
		 var cb = function(){
		 	scope._prepareClose();
		 };
		 src.on("end", cb);
		 src.on("close", cb);

		 scope.on("pipe", function(){
		 	throw Error("There is already a pipe");
		 });
	});
};

Request.prototype._createRequest = function(options){
	if(typeof options.uri !== "object"){
		this.emit("error", Error("No URI specified!"));
		return;
	}

	//fix for node < 0.5
	if(!options.uri.path) options.uri.path = options.uri.pathname;

	var req = protocols[options.uri.protocol];
	if(!req) return this.emit("error", Error("Unknown protocol: " + options.uri.protocol));

	var scope = this;

	this._request = req.request(options.uri, function(resp){
		var statusCode = resp.statusCode;

		if( (!("followRedirect" in options) || options.followRedirect) && (statusCode % 300 < 99) && !scope.writable && resp.headers.location){
				clearTimeout(scope._reqTimeout);
				scope.abort(); //close the socket
				scope.emit("redirect", resp.headers.location);
				return;
		}

		if(options.only2xx && statusCode % 200 >= 100){
			scope.emit("error", Error("Received status code " + statusCode + " (\"" + http.STATUS_CODES[statusCode] + "\")"));
			scope.abort();
		};

		//add some info to the scope
		scope.response = {
			location: url.format(options.uri),
			statusCode: statusCode,
			headers: resp.headers
		};

		scope._resp = resp;

		if(options.encoding){
			resp.setEncoding(options.encoding);
		}

		resp.on("end", function(){
			if(!scope._ended) scope.emit("end");
		}).on("close", function(){
			scope.emit("close");
		}).on("error", function(err){
			scope.emit("error", err);
		}).on("data", function(chunk){
			scope.emit("data", chunk);
		});

		scope.emit("response", resp);
	});

	if(!("timeout" in options) || options.timeout){
		this._reqTimeout = setTimeout(function(){
			if(!scope._ended){
				scope._request.abort();

				scope.emit("timeout");
				scope.emit("error", Error("ETIMEDOUT"));
			}
		}, options.timeout || 1e4);
	}

	return true;
};

Request.prototype.setEncoding = function(encoding){
	//if we are connected, send the encoding to the response
	if(this._resp) this._resp.setEncoding(encoding);
	//else, safe it for later
	else this._options.encoding = encoding;
};
Request.prototype.then = function(cb){
	//for promise-like behavior
	this._cb = cb;
};
Request.prototype.abort = function(){
	this._request.abort();
};
Request.prototype.write = function(chunk){
	if(!this.writable) throw Error("Either request method doesn't support .write or request was sent!");
	return this._request.write(chunk);
};

module.exports.Request = Request;<commit_msg>Removed last reference to Request#_written<commit_after>var http = require("http"),
	https = require("https"),
	url = require("url");

module.exports = function(options, cb){
	if(typeof options === "string"){
		options = { uri: url.parse(options) };
	}
	return new Request(options, cb);
};

//Add methods for the most common cases
["GET", "POST", "HEAD", "DELETE", "UPDATE"].forEach(function(method){
	module.exports[method.toLowerCase()] = function(uri, cb){
		uri = url.parse(uri);
		uri.method = method;
		return new Request({ uri: uri }, cb);
	};
});

var protocols = {
	"http:": http,
	"https:": https
};
module.exports.addProtocol = function(name, module){
	protocols[name] = module;
};

var re_protocol = /^https?:/; //TODO: what about other protocols?

var Request = function(options, cb){
	this._options = options;
	this._cb = cb;

	this._ended = false;
	this._redirected = 0;
	this._resp = null;
	this.response = null;
	this._body = "";

	this.writable = options.uri.method === "POST" || options.uri.method === "PUT";

	this._addListeners();

	var scope = this;
	process.nextTick(function(){
		if(!scope._createRequest(options)) return;
		if(!scope.writable) scope._request.end();
		else{
			if(options.body) scope._request.write(options.body);
			scope._prepareClose();
		}
	});
};

var Stream = require("stream").Stream;
require("util").inherits(Request, Stream);

Request.prototype.readable = true;

//save the pipe function for later
var pipe = Stream.prototype.pipe;

Request.prototype.pipe = function(dest, opts){
	if(this._body){
		throw Error("Data was already emitted!");
	}
	else if(this._ended){
		throw Error("Request is closed!");
	}

	return pipe.call(this, dest, opts);
};

Request.prototype._prepareClose = function(){
	this._close = true;
	var scope = this;
	process.nextTick(function(){
		if(scope._close){
			scope._request.end();
			scope.writable = false;
		}
	});
};

Request.prototype._addListeners = function(){
	var scope = this;

	this.on("error", function(err){
		scope._cb(err);
	});

	this.on("end", function(){
		scope._ended = true;
		if(scope._cb) scope._cb(null, scope.response, scope._body);
	});

	this.on("data", function(chunk){
		scope._body += chunk;
	});

	this.on("redirect", function(location){
		var options = scope._options,
			method = options.uri.method;

		if(scope._redirected++ < (options.maxRedirects || 10)){
			if(!re_protocol.test(location)){
		 		location = url.resolve(options.uri, location);
		 	}

		 	options.uri = url.parse(location);
		 	options.uri.method = method;

		 	scope._createRequest(options);
		 	scope._request.end();
		 } else {
		 	scope.emit("error", Error("Too many redirects"));
		 }
	});

	this.once("pipe", function(src){
		if(!scope.writable){
		 	scope.emit("error", Error("Can't write to socket!"));
		 	return;
		 }

		 scope._close = false;
		 var cb = function(){
		 	scope._prepareClose();
		 };
		 src.on("end", cb);
		 src.on("close", cb);

		 scope.on("pipe", function(){
		 	throw Error("There is already a pipe");
		 });
	});
};

Request.prototype._createRequest = function(options){
	if(typeof options.uri !== "object"){
		this.emit("error", Error("No URI specified!"));
		return;
	}

	//fix for node < 0.5
	if(!options.uri.path) options.uri.path = options.uri.pathname;

	var req = protocols[options.uri.protocol];
	if(!req) return this.emit("error", Error("Unknown protocol: " + options.uri.protocol));

	var scope = this;

	this._request = req.request(options.uri, function(resp){
		var statusCode = resp.statusCode;

		if( (!("followRedirect" in options) || options.followRedirect) && (statusCode % 300 < 99) && !scope.writable && resp.headers.location){
				clearTimeout(scope._reqTimeout);
				scope.abort(); //close the socket
				scope.emit("redirect", resp.headers.location);
				return;
		}

		if(options.only2xx && statusCode % 200 >= 100){
			scope.emit("error", Error("Received status code " + statusCode + " (\"" + http.STATUS_CODES[statusCode] + "\")"));
			scope.abort();
		};

		//add some info to the scope
		scope.response = {
			location: url.format(options.uri),
			statusCode: statusCode,
			headers: resp.headers
		};

		scope._resp = resp;

		if(options.encoding){
			resp.setEncoding(options.encoding);
		}

		resp.on("end", function(){
			if(!scope._ended) scope.emit("end");
		}).on("close", function(){
			scope.emit("close");
		}).on("error", function(err){
			scope.emit("error", err);
		}).on("data", function(chunk){
			scope.emit("data", chunk);
		});

		scope.emit("response", resp);
	});

	if(!("timeout" in options) || options.timeout){
		this._reqTimeout = setTimeout(function(){
			if(!scope._ended){
				scope._request.abort();

				scope.emit("timeout");
				scope.emit("error", Error("ETIMEDOUT"));
			}
		}, options.timeout || 1e4);
	}

	return true;
};

Request.prototype.setEncoding = function(encoding){
	//if we are connected, send the encoding to the response
	if(this._resp) this._resp.setEncoding(encoding);
	//else, safe it for later
	else this._options.encoding = encoding;
};
Request.prototype.then = function(cb){
	//for promise-like behavior
	this._cb = cb;
};
Request.prototype.abort = function(){
	this._request.abort();
};
Request.prototype.write = function(chunk){
	if(!this.writable) throw Error("Either request method doesn't support .write or request was sent!");
	return this._request.write(chunk);
};

module.exports.Request = Request;<|endoftext|>


<commit_before>/*
 * Christmas lights controller - Tim Poulsen
 * License MIT
 *
 *
 */

var rpio = require('rpio'),
	fs = require("fs"),
	path = require("path");

const OFF = rpio.HIGH;
const ON = rpio.LOW;

var pins = [3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24];
var turnOffShowAt;

turnOffAllRelays();

if (process.argv[2]) {
	var showToRun = process.argv[2];
	if (showToRun === 'off') {
		turnOffAllRelays();
	} else if (showToRun === 'on') {
		turnOnAllRelays();
	} else {
		runShow(process.argv[2]);
	}
} else {
	var fields = require("fields");
	var shows = fs.readdirSync('shows');
	fields.set([
		fields.select({
			promptLabel: 'Which show would you like to run?',
			options: shows,
			numbered: true
		})
	]).prompt(function (err, value) {
		if (err) {
			console.error('There was an error!\n' + err);
		} else {
			runShow(value[0]);
		}
	});

}

if (process.argv[3] && !isNaN(process.argv[3])) {
	// turn off the show after x hours
	var now = new Date();
	var futureMS = Math.round(parseFloat(process.argv[3]) * 60 * 60 * 1000);
	turnOffShowAt = now.getTime() + futureMS;
}

function runShow(showName) {
	var filePath = path.join('shows', showName);
	if (!fs.existsSync(filePath)) {
		console.error('No show file by the name ' + showName);
		process.exit(1);
	}
	var showFile = fs.readFileSync(filePath, 'utf8'),
		show = JSON.parse(showFile),
		i = 0;

	var looper = setInterval(function () {
		if (i < show.show.length) {
			drawRow(show.show[i]);
			i++;
		} else {
			if (!show.loop) {
				// show isn't set up to run continously
				clearInterval(looper);
				looper = undefined;
			} else {
				i = 0;
			}
		}
		if (turnOffShowAt) {
			if ((new Date()).getTime() > turnOffShowAt) {
				clearInterval(looper);
				looper = undefined;
				turnOffAllRelays();
				// the app sometimes exits before the relays are turned off
				// so use the rpio module's sleep function to keep it alive
				rpio.sleep(10);
				console.log("Good night");
			}
		}
	}, show.interval);
}

function drawRow(arr) {
	for (var i=0, j=arr.length; i<j; i++) {
		rpio.write(pins[i], arr[i] ? ON : OFF);
	}
}

function turnOffAllRelays() {
	for (var i=0, j=pins.length; i<j; i++) {
		rpio.write(pins[i], rpio.OUTPUT, OFF);
	}
}

function turnOnAllRelays() {
	for (var i=0, j=pins.length; i<j; i++) {
		rpio.write(pins[i], rpio.OUTPUT, ON);
	}
}<commit_msg>fix typos<commit_after>/*
 * Christmas lights controller - Tim Poulsen
 * License MIT
 *
 *
 */

var rpio = require('rpio'),
	fs = require("fs"),
	path = require("path");

const OFF = rpio.HIGH;
const ON = rpio.LOW;

var pins = [3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24];
var turnOffShowAt;

turnOffAllRelays();

if (process.argv[2]) {
	var showToRun = process.argv[2];
	if (showToRun === 'off') {
		turnOffAllRelays();
	} else if (showToRun === 'on') {
		turnOnAllRelays();
	} else {
		runShow(process.argv[2]);
	}
} else {
	var fields = require("fields");
	var shows = fs.readdirSync('shows');
	fields.set([
		fields.select({
			promptLabel: 'Which show would you like to run?',
			options: shows,
			numbered: true
		})
	]).prompt(function (err, value) {
		if (err) {
			console.error('There was an error!\n' + err);
		} else {
			runShow(value[0]);
		}
	});

}

if (process.argv[3] && !isNaN(process.argv[3])) {
	// turn off the show after x hours
	var now = new Date();
	var futureMS = Math.round(parseFloat(process.argv[3]) * 60 * 60 * 1000);
	turnOffShowAt = now.getTime() + futureMS;
}

function runShow(showName) {
	var filePath = path.join('shows', showName);
	if (!fs.existsSync(filePath)) {
		console.error('No show file by the name ' + showName);
		process.exit(1);
	}
	var showFile = fs.readFileSync(filePath, 'utf8'),
		show = JSON.parse(showFile),
		i = 0;

	var looper = setInterval(function () {
		if (i < show.show.length) {
			drawRow(show.show[i]);
			i++;
		} else {
			if (!show.loop) {
				// show isn't set up to run continously
				clearInterval(looper);
				looper = undefined;
			} else {
				i = 0;
			}
		}
		if (turnOffShowAt) {
			if ((new Date()).getTime() > turnOffShowAt) {
				clearInterval(looper);
				looper = undefined;
				turnOffAllRelays();
				// the app sometimes exits before the relays are turned off
				// so use the rpio module's sleep function to keep it alive
				rpio.sleep(10);
				console.log("Good night");
			}
		}
	}, show.interval);
}

function drawRow(arr) {
	for (var i=0, j=arr.length; i<j; i++) {
		rpio.write(pins[i], (arr[i] ? ON : OFF));
	}
}

function turnOffAllRelays() {
	for (var i=0, j=pins.length; i<j; i++) {
		rpio.write(pins[i], OFF);
	}
}

function turnOnAllRelays() {
	for (var i=0, j=pins.length; i<j; i++) {
		rpio.write(pins[i], ON);
	}
}<|endoftext|>