<commit_before>var servPort = process.env.DS_PORT || 8080; // default TCP port 8080

// for each URL route, import environment variable or set default for
// maximum added response latency (milliseconds) and error 503 probability (percentage)
//
// parameters for / [main]
var latencyMax_main = process.env.DS_LAT_MAIN || 1000;
var errorProb_main  = process.env.DS_ERR_MAIN || 10;
// parameters for /alt
var latencyMax_alt  = process.env.DS_LAT_ALT  || 2000;
var errorProb_alt   = process.env.DS_ERR_ALT  || 20;

// for error 503 case, import environment variable or set default for
// extra maximum added response latency (milliseconds)
var latencyMax_err  = process.env.DS_LAT_ERR  || 3000;

// example custom header
var metaVersion = process.env.DS_META_VER || "1.20(3)";

var sleep = require('sleep'); //npm install sleep
var express = require('express'); //npm install express
var app = express();

app.get('/', function (request, response) {
        console.log("Route / (main)")
        var basicSnooze = Math.round(Math.random()*latencyMax_main);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_main) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("503 Service Unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Main</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Surprise!
Something completely different
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

app.get('/alt', function (request, response) {
        console.log("Route /alt")
        var basicSnooze = Math.round(Math.random()*latencyMax_alt);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_alt) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("503 Service Unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Alt</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Cheers!
Everyone loves instant gratification
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

var server = app.listen(servPort, function () {
                        var host = server.address().address;
                        var port = server.address().port;
                        console.log('Demo server listening at http://%s:%s', host, port);
                        });
<commit_msg>Tweaked error message<commit_after>var servPort = process.env.DS_PORT || 8080; // default TCP port 8080

// for each URL route, import environment variable or set default for
// maximum added response latency (milliseconds) and error 503 probability (percentage)
//
// parameters for / [main]
var latencyMax_main = process.env.DS_LAT_MAIN || 1000;
var errorProb_main  = process.env.DS_ERR_MAIN || 10;
// parameters for /alt
var latencyMax_alt  = process.env.DS_LAT_ALT  || 2000;
var errorProb_alt   = process.env.DS_ERR_ALT  || 20;

// for error 503 case, import environment variable or set default for
// extra maximum added response latency (milliseconds)
var latencyMax_err  = process.env.DS_LAT_ERR  || 3000;

// example custom header
var metaVersion = process.env.DS_META_VER || "1.20(3)";

var sleep = require('sleep'); //npm install sleep
var express = require('express'); //npm install express
var app = express();

app.get('/', function (request, response) {
        console.log("Route / (main)")
        var basicSnooze = Math.round(Math.random()*latencyMax_main);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_main) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("HTTP Error 503 Service Unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Main</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Surprise!
Something completely different
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

app.get('/alt', function (request, response) {
        console.log("Route /alt")
        var basicSnooze = Math.round(Math.random()*latencyMax_alt);
        console.log("Adding basic response latency of  "+basicSnooze+" milliseconds");
        sleep.usleep(basicSnooze*1000);
        // respond with simulated overload
        if(Math.random()*100 <= errorProb_alt) {
        var errorSnooze = Math.round(Math.random()*latencyMax_err);
        sleep.usleep(errorSnooze*1000);
        console.log("Adding error response latency of  "+errorSnooze+" milliseconds");
        console.log("Responding with 503 error");
        var totalSnooze = basicSnooze+errorSnooze;
        response.writeHead(503, {"Content-Type": "text/plain"});
        response.write("HTTP Error 503 Service Unavailable\n\nAdded response latency "+totalSnooze+" milliseconds\n");
        response.end();
        // respond normally
        } else {
        console.log("Responding with normal page");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<!DOCTYPE html>");
        response.write("<title>Demo Server Alt</title>");
        response.write("<meta version=\""+metaVersion+"\">");
        response.write("");
        response.write("");
        response.write("Cheers!
Everyone loves instant gratification
");
        if (basicSnooze>0) {response.write("but you had to wait an extra "+basicSnooze+" milliseconds

"); }
        response.write("");
        response.write("

Comments to Larry Lang");
        response.write("");
        response.end();
        }});

var server = app.listen(servPort, function () {
                        var host = server.address().address;
                        var port = server.address().port;
                        console.log('Demo server listening at http://%s:%s', host, port);
                        });
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("julia", function(config, parserConf) {
  function wordRegexp(words, end) {
    if (typeof end === "undefined") { end = "\\b"; }
    return new RegExp("^((" + words.join(")|(") + "))" + end);
  }

  var octChar = "\\\\[0-7]{1,3}";
  var hexChar = "\\\\x[A-Fa-f0-9]{1,2}";
  var sChar = "\\\\[abefnrtv0%?'\"\\\\]";
  var uChar = "([^\\u0027\\u005C\\uD800-\\uDFFF]|[\\uD800-\\uDFFF][\\uDC00-\\uDFFF])";

  var operators = parserConf.operators || wordRegexp([
        "[<>]:", "[<>=]=", "<<=?", ">>>?=?", "=>", "->", "\\/\\/",
        "[\\\\%*+\\-<>!=\\/^|&\\u00F7\\u22BB]=?", "\\?", "\\$", "~", ":",
        "\\u00D7", "\\u2208", "\\u2209", "\\u220B", "\\u220C", "\\u2218",
        "\\u221A", "\\u221B", "\\u2229", "\\u222A", "\\u2260", "\\u2264",
        "\\u2265", "\\u2286", "\\u2288", "\\u228A", "\\u22C5",
        "\\b(in|isa)\\b(?!\.?\\()"], "");
  var delimiters = parserConf.delimiters || /^[;,()[\]{}]/;
  var identifiers = parserConf.identifiers ||
        /^[_A-Za-z\u00A1-\u2217\u2219-\uFFFF][\w\u00A1-\u2217\u2219-\uFFFF]*!*/;

  var chars = wordRegexp([octChar, hexChar, sChar, uChar], "'");

  var openersList = ["begin", "function", "type", "struct", "immutable", "let",
        "macro", "for", "while", "quote", "if", "else", "elseif", "try",
        "finally", "catch", "do"];

  var closersList = ["end", "else", "elseif", "catch", "finally"];

  var keywordsList = ["if", "else", "elseif", "while", "for", "begin", "let",
        "end", "do", "try", "catch", "finally", "return", "break", "continue",
        "global", "local", "const", "export", "import", "importall", "using",
        "function", "where", "macro", "module", "baremodule", "struct", "type",
        "mutable", "immutable", "quote", "typealias", "abstract", "primitive",
        "bitstype"];

  var builtinsList = ["true", "false", "nothing", "NaN", "Inf"];

  CodeMirror.registerHelper("hintWords", "julia", keywordsList.concat(builtinsList));

  var openers = wordRegexp(openersList);
  var closers = wordRegexp(closersList);
  var keywords = wordRegexp(keywordsList);
  var builtins = wordRegexp(builtinsList);

  var macro = /^@[_A-Za-z][\w]*/;
  var symbol = /^:[_A-Za-z\u00A1-\uFFFF][\w\u00A1-\uFFFF]*!*/;
  var stringPrefixes = /^(`|([_A-Za-z\u00A1-\uFFFF]*"("")?))/;

  function inArray(state) {
    return (state.nestedArrays > 0);
  }

  function inGenerator(state) {
    return (state.nestedGenerators > 0);
  }

  function currentScope(state, n) {
    if (typeof(n) === "undefined") { n = 0; }
    if (state.scopes.length <= n) {
      return null;
    }
    return state.scopes[state.scopes.length - (n + 1)];
  }

  // tokenizers
  function tokenBase(stream, state) {
    // Handle multiline comments
    if (stream.match(/^#=/, false)) {
      state.tokenize = tokenComment;
      return state.tokenize(stream, state);
    }

    // Handle scope changes
    var leavingExpr = state.leavingExpr;
    if (stream.sol()) {
      leavingExpr = false;
    }
    state.leavingExpr = false;

    if (leavingExpr) {
      if (stream.match(/^'+/)) {
        return "operator";
      }
    }

    if (stream.match(/\.{4,}/)) {
      return "error";
    } else if (stream.match(/\.{1,3}/)) {
      return "operator";
    }

    if (stream.eatSpace()) {
      return null;
    }

    var ch = stream.peek();

    // Handle single line comments
    if (ch === '#') {
      stream.skipToEnd();
      return "comment";
    }

    if (ch === '[') {
      state.scopes.push('[');
      state.nestedArrays++;
    }

    if (ch === '(') {
      state.scopes.push('(');
      state.nestedGenerators++;
    }

    if (inArray(state) && ch === ']') {
      while (state.scopes.length && currentScope(state) !== "[") { state.scopes.pop(); }
      state.scopes.pop();
      state.nestedArrays--;
      state.leavingExpr = true;
    }

    if (inGenerator(state) && ch === ')') {
      while (state.scopes.length && currentScope(state) !== "(") { state.scopes.pop(); }
      state.scopes.pop();
      state.nestedGenerators--;
      state.leavingExpr = true;
    }

    if (inArray(state)) {
      if (state.lastToken == "end" && stream.match(/^:/)) {
        return "operator";
      }
      if (stream.match(/^end/)) {
        return "number";
      }
    }

    var match;
    if (match = stream.match(openers, false)) {
      state.scopes.push(match[0]);
    }

    if (stream.match(closers, false)) {
      state.scopes.pop();
    }

    // Handle type annotations
    if (stream.match(/^::(?![:\$])/)) {
      state.tokenize = tokenAnnotation;
      return state.tokenize(stream, state);
    }

    // Handle symbols
    if (!leavingExpr && stream.match(symbol) ||
        stream.match(/:([<>]:|<<=?|>>>?=?|->|\/\/|\.{2,3}|[\.\\%*+\-<>!\/^|&]=?|[~\?\$])/)) {
      return "builtin";
    }

    // Handle parametric types
    //if (stream.match(/^{[^}]*}(?=\()/)) {
    //  return "builtin";
    //}

    // Handle operators and Delimiters
    if (stream.match(operators)) {
      return "operator";
    }

    // Handle Number Literals
    if (stream.match(/^\.?\d/, false)) {
      var imMatcher = RegExp(/^im\b/);
      var numberLiteral = false;
      if (stream.match(/^0x\.[0-9a-f_]+p[\+\-]?[_\d]+/i)) { numberLiteral = true; }
      // Integers
      if (stream.match(/^0x[0-9a-f_]+/i)) { numberLiteral = true; } // Hex
      if (stream.match(/^0b[01_]+/i)) { numberLiteral = true; } // Binary
      if (stream.match(/^0o[0-7_]+/i)) { numberLiteral = true; } // Octal
      // Floats
      if (stream.match(/^(?:(?:\d[_\d]*)?\.(?!\.)(?:\d[_\d]*)?|\d[_\d]*\.(?!\.)(?:\d[_\d]*))?([Eef][\+\-]?[_\d]+)?/i)) { numberLiteral = true; }
      if (stream.match(/^\d[_\d]*(e[\+\-]?\d+)?/i)) { numberLiteral = true; } // Decimal
      if (numberLiteral) {
          // Integer literals may be "long"
          stream.match(imMatcher);
          state.leavingExpr = true;
          return "number";
      }
    }

    // Handle Chars
    if (stream.match(/^'/)) {
      state.tokenize = tokenChar;
      return state.tokenize(stream, state);
    }

    // Handle Strings
    if (stream.match(stringPrefixes)) {
      state.tokenize = tokenStringFactory(stream.current());
      return state.tokenize(stream, state);
    }

    if (stream.match(macro)) {
      return "meta";
    }

    if (stream.match(delimiters)) {
      return null;
    }

    if (stream.match(keywords)) {
      return "keyword";
    }

    if (stream.match(builtins)) {
      return "builtin";
    }

    var isDefinition = state.isDefinition || state.lastToken == "function" ||
                       state.lastToken == "macro" || state.lastToken == "type" ||
                       state.lastToken == "struct" || state.lastToken == "immutable";

    if (stream.match(identifiers)) {
      if (isDefinition) {
        if (stream.peek() === '.') {
          state.isDefinition = true;
          return "variable";
        }
        state.isDefinition = false;
        return "def";
      }
      if (stream.match(/^({[^}]*})*\(/, false)) {
        state.tokenize = tokenCallOrDef;
        return state.tokenize(stream, state);
      }
      state.leavingExpr = true;
      return "variable";
    }

    // Handle non-detected items
    stream.next();
    return "error";
  }

  function tokenCallOrDef(stream, state) {
    var match = stream.match(/^(\(\s*)/);
    if (match) {
      if (state.firstParenPos < 0)
        state.firstParenPos = state.scopes.length;
      state.scopes.push('(');
      state.charsAdvanced += match[1].length;
    }
    if (currentScope(state) == '(' && stream.match(/^\)/)) {
      state.scopes.pop();
      state.charsAdvanced += 1;
      if (state.scopes.length <= state.firstParenPos) {
        var isDefinition = stream.match(/^(\s*where\s+[^\s=]+)*\s*?=(?!=)/, false);
        stream.backUp(state.charsAdvanced);
        state.firstParenPos = -1;
        state.charsAdvanced = 0;
        state.tokenize = tokenBase;
        if (isDefinition)
          return "def";
        return "builtin";
      }
    }
    // Unfortunately javascript does not support multiline strings, so we have
    // to undo anything done upto here if a function call or definition splits
    // over two or more lines.
    if (stream.match(/^$/g, false)) {
      stream.backUp(state.charsAdvanced);
      while (state.scopes.length > state.firstParenPos)
        state.scopes.pop();
      state.firstParenPos = -1;
      state.charsAdvanced = 0;
      state.tokenize = tokenBase;
      return "builtin";
    }
    state.charsAdvanced += stream.match(/^([^()]*)/)[1].length;
    return state.tokenize(stream, state);
  }

  function tokenAnnotation(stream, state) {
    stream.match(/.*?(?=,|;|{|}|\(|\)|=|$|\s)/);
    if (stream.match(/^{/)) {
      state.nestedParameters++;
    } else if (stream.match(/^}/) && state.nestedParameters > 0) {
      state.nestedParameters--;
    }
    if (state.nestedParameters > 0) {
      stream.match(/.*?(?={|})/) || stream.next();
    } else if (state.nestedParameters == 0) {
      state.tokenize = tokenBase;
    }
    return "builtin";
  }

  function tokenComment(stream, state) {
    if (stream.match(/^#=/)) {
      state.nestedComments++;
    }
    if (!stream.match(/.*?(?=(#=|=#))/)) {
      stream.skipToEnd();
    }
    if (stream.match(/^=#/)) {
      state.nestedComments--;
      if (state.nestedComments == 0)
        state.tokenize = tokenBase;
    }
    return "comment";
  }

  function tokenChar(stream, state) {
    var isChar = false, match;
    if (stream.match(chars)) {
      isChar = true;
    } else if (match = stream.match(/\\u([a-f0-9]{1,4})(?=')/i)) {
      var value = parseInt(match[1], 16);
      if (value <= 55295 || value >= 57344) { // (U+0,U+D7FF), (U+E000,U+FFFF)
        isChar = true;
        stream.next();
      }
    } else if (match = stream.match(/\\U([A-Fa-f0-9]{5,8})(?=')/)) {
      var value = parseInt(match[1], 16);
      if (value <= 1114111) { // U+10FFFF
        isChar = true;
        stream.next();
      }
    }
    if (isChar) {
      state.leavingExpr = true;
      state.tokenize = tokenBase;
      return "string";
    }
    if (!stream.match(/^[^']+(?=')/)) { stream.skipToEnd(); }
    if (stream.match(/^'/)) { state.tokenize = tokenBase; }
    return "error";
  }

  function tokenStringFactory(delimiter) {
    if (delimiter.substr(-3) === '"""') {
      delimiter = '"""';
    } else if (delimiter.substr(-1) === '"') {
      delimiter = '"';
    }
    function tokenString(stream, state) {
      if (stream.eat('\\')) {
        stream.next();
      } else if (stream.match(delimiter)) {
        state.tokenize = tokenBase;
        state.leavingExpr = true;
        return "string";
      } else {
        stream.eat(/[`"]/);
      }
      stream.eatWhile(/[^\\`"]/);
      return "string";
    }
    return tokenString;
  }

  var external = {
    startState: function() {
      return {
        tokenize: tokenBase,
        scopes: [],
        lastToken: null,
        leavingExpr: false,
        isDefinition: false,
        nestedArrays: 0,
        nestedComments: 0,
        nestedGenerators: 0,
        nestedParameters: 0,
        charsAdvanced: 0,
        firstParenPos: -1
      };
    },

    token: function(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      if (current && style) {
        state.lastToken = current;
      }

      return style;
    },

    indent: function(state, textAfter) {
      var delta = 0;
      if ( textAfter === ']' || textAfter === ')' || textAfter === "end" ||
           textAfter === "else" || textAfter === "catch" || textAfter === "elseif" ||
           textAfter === "finally" ) {
        delta = -1;
      }
      return (state.scopes.length + delta) * config.indentUnit;
    },

    electricInput: /\b(end|else|catch|finally)\b/,
    blockCommentStart: "#=",
    blockCommentEnd: "=#",
    lineComment: "#",
    closeBrackets: "()[]{}\"\"",
    fold: "indent"
  };
  return external;
});

CodeMirror.defineMIME("text/x-julia", "julia");

});
<commit_msg>[julia mode] Tweak indent method<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("julia", function(config, parserConf) {
  function wordRegexp(words, end) {
    if (typeof end === "undefined") { end = "\\b"; }
    return new RegExp("^((" + words.join(")|(") + "))" + end);
  }

  var octChar = "\\\\[0-7]{1,3}";
  var hexChar = "\\\\x[A-Fa-f0-9]{1,2}";
  var sChar = "\\\\[abefnrtv0%?'\"\\\\]";
  var uChar = "([^\\u0027\\u005C\\uD800-\\uDFFF]|[\\uD800-\\uDFFF][\\uDC00-\\uDFFF])";

  var operators = parserConf.operators || wordRegexp([
        "[<>]:", "[<>=]=", "<<=?", ">>>?=?", "=>", "->", "\\/\\/",
        "[\\\\%*+\\-<>!=\\/^|&\\u00F7\\u22BB]=?", "\\?", "\\$", "~", ":",
        "\\u00D7", "\\u2208", "\\u2209", "\\u220B", "\\u220C", "\\u2218",
        "\\u221A", "\\u221B", "\\u2229", "\\u222A", "\\u2260", "\\u2264",
        "\\u2265", "\\u2286", "\\u2288", "\\u228A", "\\u22C5",
        "\\b(in|isa)\\b(?!\.?\\()"], "");
  var delimiters = parserConf.delimiters || /^[;,()[\]{}]/;
  var identifiers = parserConf.identifiers ||
        /^[_A-Za-z\u00A1-\u2217\u2219-\uFFFF][\w\u00A1-\u2217\u2219-\uFFFF]*!*/;

  var chars = wordRegexp([octChar, hexChar, sChar, uChar], "'");

  var openersList = ["begin", "function", "type", "struct", "immutable", "let",
        "macro", "for", "while", "quote", "if", "else", "elseif", "try",
        "finally", "catch", "do"];

  var closersList = ["end", "else", "elseif", "catch", "finally"];

  var keywordsList = ["if", "else", "elseif", "while", "for", "begin", "let",
        "end", "do", "try", "catch", "finally", "return", "break", "continue",
        "global", "local", "const", "export", "import", "importall", "using",
        "function", "where", "macro", "module", "baremodule", "struct", "type",
        "mutable", "immutable", "quote", "typealias", "abstract", "primitive",
        "bitstype"];

  var builtinsList = ["true", "false", "nothing", "NaN", "Inf"];

  CodeMirror.registerHelper("hintWords", "julia", keywordsList.concat(builtinsList));

  var openers = wordRegexp(openersList);
  var closers = wordRegexp(closersList);
  var keywords = wordRegexp(keywordsList);
  var builtins = wordRegexp(builtinsList);

  var macro = /^@[_A-Za-z][\w]*/;
  var symbol = /^:[_A-Za-z\u00A1-\uFFFF][\w\u00A1-\uFFFF]*!*/;
  var stringPrefixes = /^(`|([_A-Za-z\u00A1-\uFFFF]*"("")?))/;

  function inArray(state) {
    return (state.nestedArrays > 0);
  }

  function inGenerator(state) {
    return (state.nestedGenerators > 0);
  }

  function currentScope(state, n) {
    if (typeof(n) === "undefined") { n = 0; }
    if (state.scopes.length <= n) {
      return null;
    }
    return state.scopes[state.scopes.length - (n + 1)];
  }

  // tokenizers
  function tokenBase(stream, state) {
    // Handle multiline comments
    if (stream.match(/^#=/, false)) {
      state.tokenize = tokenComment;
      return state.tokenize(stream, state);
    }

    // Handle scope changes
    var leavingExpr = state.leavingExpr;
    if (stream.sol()) {
      leavingExpr = false;
    }
    state.leavingExpr = false;

    if (leavingExpr) {
      if (stream.match(/^'+/)) {
        return "operator";
      }
    }

    if (stream.match(/\.{4,}/)) {
      return "error";
    } else if (stream.match(/\.{1,3}/)) {
      return "operator";
    }

    if (stream.eatSpace()) {
      return null;
    }

    var ch = stream.peek();

    // Handle single line comments
    if (ch === '#') {
      stream.skipToEnd();
      return "comment";
    }

    if (ch === '[') {
      state.scopes.push('[');
      state.nestedArrays++;
    }

    if (ch === '(') {
      state.scopes.push('(');
      state.nestedGenerators++;
    }

    if (inArray(state) && ch === ']') {
      while (state.scopes.length && currentScope(state) !== "[") { state.scopes.pop(); }
      state.scopes.pop();
      state.nestedArrays--;
      state.leavingExpr = true;
    }

    if (inGenerator(state) && ch === ')') {
      while (state.scopes.length && currentScope(state) !== "(") { state.scopes.pop(); }
      state.scopes.pop();
      state.nestedGenerators--;
      state.leavingExpr = true;
    }

    if (inArray(state)) {
      if (state.lastToken == "end" && stream.match(/^:/)) {
        return "operator";
      }
      if (stream.match(/^end/)) {
        return "number";
      }
    }

    var match;
    if (match = stream.match(openers, false)) {
      state.scopes.push(match[0]);
    }

    if (stream.match(closers, false)) {
      state.scopes.pop();
    }

    // Handle type annotations
    if (stream.match(/^::(?![:\$])/)) {
      state.tokenize = tokenAnnotation;
      return state.tokenize(stream, state);
    }

    // Handle symbols
    if (!leavingExpr && stream.match(symbol) ||
        stream.match(/:([<>]:|<<=?|>>>?=?|->|\/\/|\.{2,3}|[\.\\%*+\-<>!\/^|&]=?|[~\?\$])/)) {
      return "builtin";
    }

    // Handle parametric types
    //if (stream.match(/^{[^}]*}(?=\()/)) {
    //  return "builtin";
    //}

    // Handle operators and Delimiters
    if (stream.match(operators)) {
      return "operator";
    }

    // Handle Number Literals
    if (stream.match(/^\.?\d/, false)) {
      var imMatcher = RegExp(/^im\b/);
      var numberLiteral = false;
      if (stream.match(/^0x\.[0-9a-f_]+p[\+\-]?[_\d]+/i)) { numberLiteral = true; }
      // Integers
      if (stream.match(/^0x[0-9a-f_]+/i)) { numberLiteral = true; } // Hex
      if (stream.match(/^0b[01_]+/i)) { numberLiteral = true; } // Binary
      if (stream.match(/^0o[0-7_]+/i)) { numberLiteral = true; } // Octal
      // Floats
      if (stream.match(/^(?:(?:\d[_\d]*)?\.(?!\.)(?:\d[_\d]*)?|\d[_\d]*\.(?!\.)(?:\d[_\d]*))?([Eef][\+\-]?[_\d]+)?/i)) { numberLiteral = true; }
      if (stream.match(/^\d[_\d]*(e[\+\-]?\d+)?/i)) { numberLiteral = true; } // Decimal
      if (numberLiteral) {
          // Integer literals may be "long"
          stream.match(imMatcher);
          state.leavingExpr = true;
          return "number";
      }
    }

    // Handle Chars
    if (stream.match(/^'/)) {
      state.tokenize = tokenChar;
      return state.tokenize(stream, state);
    }

    // Handle Strings
    if (stream.match(stringPrefixes)) {
      state.tokenize = tokenStringFactory(stream.current());
      return state.tokenize(stream, state);
    }

    if (stream.match(macro)) {
      return "meta";
    }

    if (stream.match(delimiters)) {
      return null;
    }

    if (stream.match(keywords)) {
      return "keyword";
    }

    if (stream.match(builtins)) {
      return "builtin";
    }

    var isDefinition = state.isDefinition || state.lastToken == "function" ||
                       state.lastToken == "macro" || state.lastToken == "type" ||
                       state.lastToken == "struct" || state.lastToken == "immutable";

    if (stream.match(identifiers)) {
      if (isDefinition) {
        if (stream.peek() === '.') {
          state.isDefinition = true;
          return "variable";
        }
        state.isDefinition = false;
        return "def";
      }
      if (stream.match(/^({[^}]*})*\(/, false)) {
        state.tokenize = tokenCallOrDef;
        return state.tokenize(stream, state);
      }
      state.leavingExpr = true;
      return "variable";
    }

    // Handle non-detected items
    stream.next();
    return "error";
  }

  function tokenCallOrDef(stream, state) {
    var match = stream.match(/^(\(\s*)/);
    if (match) {
      if (state.firstParenPos < 0)
        state.firstParenPos = state.scopes.length;
      state.scopes.push('(');
      state.charsAdvanced += match[1].length;
    }
    if (currentScope(state) == '(' && stream.match(/^\)/)) {
      state.scopes.pop();
      state.charsAdvanced += 1;
      if (state.scopes.length <= state.firstParenPos) {
        var isDefinition = stream.match(/^(\s*where\s+[^\s=]+)*\s*?=(?!=)/, false);
        stream.backUp(state.charsAdvanced);
        state.firstParenPos = -1;
        state.charsAdvanced = 0;
        state.tokenize = tokenBase;
        if (isDefinition)
          return "def";
        return "builtin";
      }
    }
    // Unfortunately javascript does not support multiline strings, so we have
    // to undo anything done upto here if a function call or definition splits
    // over two or more lines.
    if (stream.match(/^$/g, false)) {
      stream.backUp(state.charsAdvanced);
      while (state.scopes.length > state.firstParenPos)
        state.scopes.pop();
      state.firstParenPos = -1;
      state.charsAdvanced = 0;
      state.tokenize = tokenBase;
      return "builtin";
    }
    state.charsAdvanced += stream.match(/^([^()]*)/)[1].length;
    return state.tokenize(stream, state);
  }

  function tokenAnnotation(stream, state) {
    stream.match(/.*?(?=,|;|{|}|\(|\)|=|$|\s)/);
    if (stream.match(/^{/)) {
      state.nestedParameters++;
    } else if (stream.match(/^}/) && state.nestedParameters > 0) {
      state.nestedParameters--;
    }
    if (state.nestedParameters > 0) {
      stream.match(/.*?(?={|})/) || stream.next();
    } else if (state.nestedParameters == 0) {
      state.tokenize = tokenBase;
    }
    return "builtin";
  }

  function tokenComment(stream, state) {
    if (stream.match(/^#=/)) {
      state.nestedComments++;
    }
    if (!stream.match(/.*?(?=(#=|=#))/)) {
      stream.skipToEnd();
    }
    if (stream.match(/^=#/)) {
      state.nestedComments--;
      if (state.nestedComments == 0)
        state.tokenize = tokenBase;
    }
    return "comment";
  }

  function tokenChar(stream, state) {
    var isChar = false, match;
    if (stream.match(chars)) {
      isChar = true;
    } else if (match = stream.match(/\\u([a-f0-9]{1,4})(?=')/i)) {
      var value = parseInt(match[1], 16);
      if (value <= 55295 || value >= 57344) { // (U+0,U+D7FF), (U+E000,U+FFFF)
        isChar = true;
        stream.next();
      }
    } else if (match = stream.match(/\\U([A-Fa-f0-9]{5,8})(?=')/)) {
      var value = parseInt(match[1], 16);
      if (value <= 1114111) { // U+10FFFF
        isChar = true;
        stream.next();
      }
    }
    if (isChar) {
      state.leavingExpr = true;
      state.tokenize = tokenBase;
      return "string";
    }
    if (!stream.match(/^[^']+(?=')/)) { stream.skipToEnd(); }
    if (stream.match(/^'/)) { state.tokenize = tokenBase; }
    return "error";
  }

  function tokenStringFactory(delimiter) {
    if (delimiter.substr(-3) === '"""') {
      delimiter = '"""';
    } else if (delimiter.substr(-1) === '"') {
      delimiter = '"';
    }
    function tokenString(stream, state) {
      if (stream.eat('\\')) {
        stream.next();
      } else if (stream.match(delimiter)) {
        state.tokenize = tokenBase;
        state.leavingExpr = true;
        return "string";
      } else {
        stream.eat(/[`"]/);
      }
      stream.eatWhile(/[^\\`"]/);
      return "string";
    }
    return tokenString;
  }

  var external = {
    startState: function() {
      return {
        tokenize: tokenBase,
        scopes: [],
        lastToken: null,
        leavingExpr: false,
        isDefinition: false,
        nestedArrays: 0,
        nestedComments: 0,
        nestedGenerators: 0,
        nestedParameters: 0,
        charsAdvanced: 0,
        firstParenPos: -1
      };
    },

    token: function(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      if (current && style) {
        state.lastToken = current;
      }

      return style;
    },

    indent: function(state, textAfter) {
      var delta = 0;
      if ( textAfter === ']' || textAfter === ')' || /^end/.test(textAfter) ||
           /^else/.test(textAfter) || /^catch/.test(textAfter) || /^elseif/.test(textAfter) ||
           /^finally/.test(textAfter) ) {
        delta = -1;
      }
      return (state.scopes.length + delta) * config.indentUnit;
    },

    electricInput: /\b(end|else|catch|finally)\b/,
    blockCommentStart: "#=",
    blockCommentEnd: "=#",
    lineComment: "#",
    closeBrackets: "()[]{}\"\"",
    fold: "indent"
  };
  return external;
});

CodeMirror.defineMIME("text/x-julia", "julia");

});
<|endoftext|>


<commit_before>import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'

/**
  @internal
*/
class Coordinate {

  /**
   @param {Array} path the address of a property, such as ['text_1', 'content']
   @param {int} offset the position in the property
  */
  constructor(path, offset) {
    // HACK: to allow this class be inherited but without calling this ctor
    if (arguments[0] === 'SKIP') return
    if (arguments.length === 1) {
      let data = arguments[0]
      this.path = data.path
      this.offset = data.offset
    } else {
      this.path = path
      this.offset = offset
    }
    if (!isArray(this.path)) {
      throw new Error('Invalid arguments: path should be an array.')
    }
    if (!isNumber(this.offset) || this.offset < 0) {
      throw new Error('Invalid arguments: offset must be a positive number.')
    }
  }

  equals(other) {
    return (other === this ||
      (isArrayEqual(other.path, this.path) && other.offset === this.offset) )
  }

  withCharPos(offset) {
    return new Coordinate(this.path, offset)
  }

  getNodeId() {
    return this.path[0]
  }

  getPath() {
    return this.path
  }

  getOffset() {
    return this.offset
  }

  toJSON() {
    return {
      path: this.path,
      offset: this.offset
    }
  }

  toString() {
    return "(" + this.path.join('.') + ", " + this.offset + ")"
  }

  isPropertyCoordinate() {
    return this.path.length > 1
  }

  isNodeCoordinate() {
    return this.path.length === 1
  }

  hasSamePath(other) {
    return isArrayEqual(this.path, other.path)
  }
}

Coordinate.prototype._isCoordinate = true

export default Coordinate
<commit_msg>Make sure to copy path in Coordinate.toJSON()<commit_after>import isArray from '../util/isArray'
import isNumber from '../util/isNumber'
import isArrayEqual from '../util/isArrayEqual'

/**
  @internal
*/
class Coordinate {

  /**
   @param {Array} path the address of a property, such as ['text_1', 'content']
   @param {int} offset the position in the property
  */
  constructor(path, offset) {
    // HACK: to allow this class be inherited but without calling this ctor
    if (arguments[0] === 'SKIP') return
    if (arguments.length === 1) {
      let data = arguments[0]
      this.path = data.path
      this.offset = data.offset
    } else {
      this.path = path
      this.offset = offset
    }
    if (!isArray(this.path)) {
      throw new Error('Invalid arguments: path should be an array.')
    }
    if (!isNumber(this.offset) || this.offset < 0) {
      throw new Error('Invalid arguments: offset must be a positive number.')
    }
  }

  equals(other) {
    return (other === this ||
      (isArrayEqual(other.path, this.path) && other.offset === this.offset) )
  }

  withCharPos(offset) {
    return new Coordinate(this.path, offset)
  }

  getNodeId() {
    return this.path[0]
  }

  getPath() {
    return this.path
  }

  getOffset() {
    return this.offset
  }

  toJSON() {
    return {
      path: this.path.slice(),
      offset: this.offset
    }
  }

  toString() {
    return "(" + this.path.join('.') + ", " + this.offset + ")"
  }

  isPropertyCoordinate() {
    return this.path.length > 1
  }

  isNodeCoordinate() {
    return this.path.length === 1
  }

  hasSamePath(other) {
    return isArrayEqual(this.path, other.path)
  }
}

Coordinate.prototype._isCoordinate = true

export default Coordinate
<|endoftext|>


<commit_before>const queries = require('../db/queries');
const utils = require('../utils');

const attributes = ['id', 'performanceId', 'userNameNumber', 'spotId'];

class Challenge {

  static getAttributes() {
    return attributes;
  }

  static getIdName() {
    return 'id';
  }

  static getTableName() {
    return 'challenges';
  }

  create(userId, spotId, performanceId) {
    const sql = 'SELECT make_challenge($1, $2, $3)';

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();
      let returnCode;

      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [userId, performanceId, spotId]);

      query.on('row', ({ make_challenge }) => {
        returnCode = parseInt(make_challenge, 10);
      });
      query.on('end', () => {
        client.end();
        resolve(returnCode);
      });
      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  findAllChallengeablePeopleForUser(user, performanceId) {
    // eslint-disable-next-line
    const sql = queries.challengeablePeople;

    return new Promise((resolve, reject) => {
      if (!performanceId) {
        resolve(null);
      }

      const client = utils.db.createClient();
      const users = [];

      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [user.instrument, user.part, user.spotId, user.nameNumber, performanceId]);

      query.on('row', (dbUser) => users.push(this.parseChallengeAblePerson(dbUser)));
      query.on('end', () => {
        client.end();
        resolve(users);
      });
      query.on('error', (err) => reject(err));
    });
  }

  findAllForPerformanceCSV(performanceId) {
    const sql = queries.challengesForCSV;

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();
      const challenges = [];

      client.connect();
      client.on('error', err => reject(err));

      const query = client.query(sql, [performanceId]);

      query.on('row', challenge => challenges.push(challenge));
      query.on('end', () => {
        client.end();
        resolve(challenges);
      });
      query.on('error', err => {
        client.end();
        reject(err);
      });
    });
  }

  findForUser(nameNumber) {
    const sql = 'SELECT * FROM challenges AS C, performances AS P WHERE userNameNumber = $1 AND C.performanceId = P.id ORDER BY C.id LIMIT 1';

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();

      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [nameNumber]);

      query.on('row', (result) => {
        client.end();
        resolve(this.parseChallenge(result));
      });
      query.on('end', () => {
        client.end();
        resolve(null);
      });
      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  parseChallenge(challenge) {
    return {
      spotId: challenge.spotid,
      performanceName: challenge.name
    };
  }

  parseChallengeAblePerson(challenge) {
    return {
      challengedCount: challenge.challengedcount,
      challengeFull: challenge.open ? challenge.challengedcount === 2 : challenge.challengedcount === 1,
      name: challenge.name,
      spotOpen: challenge.open,
      spotId: challenge.spotid
    };
  }
}

module.exports = Challenge;
<commit_msg>Models: add raw challenge selector based on performance id<commit_after>const queries = require('../db/queries');
const utils = require('../utils');

const attributes = ['id', 'performanceId', 'userNameNumber', 'spotId'];

class Challenge {

  static getAttributes() {
    return attributes;
  }

  static getIdName() {
    return 'id';
  }

  static getTableName() {
    return 'challenges';
  }

  create(userId, spotId, performanceId) {
    const sql = 'SELECT make_challenge($1, $2, $3)';

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();
      let returnCode;

      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [userId, performanceId, spotId]);

      query.on('row', ({ make_challenge }) => {
        returnCode = parseInt(make_challenge, 10);
      });
      query.on('end', () => {
        client.end();
        resolve(returnCode);
      });
      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  findAllChallengeablePeopleForUser(user, performanceId) {
    // eslint-disable-next-line
    const sql = queries.challengeablePeople;

    return new Promise((resolve, reject) => {
      if (!performanceId) {
        resolve(null);
      }

      const client = utils.db.createClient();
      const users = [];

      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [user.instrument, user.part, user.spotId, user.nameNumber, performanceId]);

      query.on('row', (dbUser) => users.push(this.parseChallengeAblePerson(dbUser)));
      query.on('end', () => {
        client.end();
        resolve(users);
      });
      query.on('error', (err) => reject(err));
    });
  }

  findAllForPerformanceCSV(performanceId) {
    const sql = queries.challengesForCSV;

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();
      const challenges = [];

      client.connect();
      client.on('error', err => reject(err));

      const query = client.query(sql, [performanceId]);

      query.on('row', challenge => challenges.push(challenge));
      query.on('end', () => {
        client.end();
        resolve(challenges);
      });
      query.on('error', err => {
        client.end();
        reject(err);
      });
    });
  }

  findAllRawForPerformance(performanceId) {
    const sql = 'SELECT * FROM challenges WHERE performanceId = $1';

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();
      const challenges = [];

      client.connect();
      client.on('error', err => reject(err));

      const query = client.query(sql, [performanceId]);

      query.on('row', challenge => challenges.push(challenge));
      query.on('end', () => {
        client.end();
        resolve(challenges);
      });
      query.on('error', err => {
        client.end();
        reject(err);
      });
    });
  }

  findForUser(nameNumber) {
    const sql = 'SELECT * FROM challenges AS C, performances AS P WHERE userNameNumber = $1 AND C.performanceId = P.id ORDER BY C.id LIMIT 1';

    return new Promise((resolve, reject) => {
      const client = utils.db.createClient();

      client.connect();
      client.on('error', (err) => reject(err));

      const query = client.query(sql, [nameNumber]);

      query.on('row', (result) => {
        client.end();
        resolve(this.parseChallenge(result));
      });
      query.on('end', () => {
        client.end();
        resolve(null);
      });
      query.on('error', (err) => {
        client.end();
        reject(err);
      });
    });
  }

  parseChallenge(challenge) {
    return {
      spotId: challenge.spotid,
      performanceName: challenge.name
    };
  }

  parseChallengeAblePerson(challenge) {
    return {
      challengedCount: challenge.challengedcount,
      challengeFull: challenge.open ? challenge.challengedcount === 2 : challenge.challengedcount === 1,
      name: challenge.name,
      spotOpen: challenge.open,
      spotId: challenge.spotid
    };
  }
}

module.exports = Challenge;
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var request = require('request');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

function proxy (req, res) {
  var x = request({
    url: "http://localhost:5001" + req.path,
    qs: req.query,
    headers: req.headers,
    rejectUnauthorized:false,
  });
  req.pipe(x);
  x.pipe(res);
  x.on("error", function(err) {
    console.log("error", err);
    res.status(500).send("proxy error");
  });
}

// proxy everything else
app.get(/^\/api\//, proxy);
app.put(/^\/api\//, proxy);
app.post(/^\/api\//, proxy);

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(5000, 'localhost', function(err) {
  if (err) {
    console.log("error", err);
    return;
  }

  console.log('Listening at http://localhost:5000');
});
<commit_msg>admin dash on port 5002<commit_after>var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var request = require('request');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

function proxy (req, res) {
  var x = request({
    url: "http://localhost:5000" + req.path,
    qs: req.query,
    headers: req.headers,
    rejectUnauthorized:false,
  });
  req.pipe(x);
  x.pipe(res);
  x.on("error", function(err) {
    console.log("error", err);
    res.status(500).send("proxy error");
  });
}

// proxy everything else
app.get(/^\/api\//, proxy);
app.put(/^\/api\//, proxy);
app.post(/^\/api\//, proxy);

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(5002, 'localhost', function(err) {
  if (err) {
    console.log("error", err);
    return;
  }

  console.log('Listening at http://localhost:5002');
});
<|endoftext|>


<commit_before>// require mongoose
var mongoose = require('mongoose')
	, Schema = mongoose.Schema;

// new Schema
var UserSchema = Schema({
	username: {
		type: String,
		required: true,
		unique: true // make sure the username is not repeated again
	},
	password: {
		type: String,
		required: true
	},
	coins: {
    pennies: { type: Number, default: 0 },
		nickels: { type: Number, default: 0 },
    dimes:  { type: Number, default: 0 },
		quarters: { type: Number, default: 0 }
  }
});

// use the above schema to make the User model
var User = mongoose.model('User', UserSchema);

// export the model so the server can use it
module.exports = User;
<commit_msg>email property<commit_after>// require mongoose
var mongoose = require('mongoose')
	, Schema = mongoose.Schema;

// new Schema
var UserSchema = Schema({
	email: {
		type: String,
		required: true,
		unique: true
	},
	username: {
		type: String,
		required: true,
		unique: true
	},
	password: {
		type: String,
		required: true
	},
	coins: {
    pennies: { type: Number, default: 0 },
		nickels: { type: Number, default: 0 },
    dimes:  { type: Number, default: 0 },
		quarters: { type: Number, default: 0 }
  }
});

// use the above schema to make the User model
var User = mongoose.model('User', UserSchema);

// export the model so the server can use it
module.exports = User;
<|endoftext|>


<commit_before>/* jshint camelcase:false */
var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

gulp.task('help', plug.taskListing);

/**
 * @desc Annotate only
 *  Mostly for show.
 *  See the output of each file?
 *      Uncomment rename, comment concat and uglify
 *  See min'd and concat'd output?
 *      Comment rename, uncomment concat and uglify,
 *      add to index.html, then run it with `gulp serve-dev`.
 */
gulp.task('ngAnnotateTest', function () {
    log('Annotating AngularJS dependencies');
    var source = [].concat(pkg.paths.js);
    return gulp
        // .src(source)
        .src('./client/app/avengers/avengers.js')
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.rename(function (path) {
            path.extname = '.annotated.js';
        }))
        // .pipe(plug.concat('all.min.js'))
        // .pipe(plug.uglify({mangle: true}))
        // .pipe(gulp.dest('./client/app'));
        .pipe(gulp.dest('./client/app/avengers'));
});

/**
 * @desc Lint the code
 */
gulp.task('jshint', function () {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    log('Bundling, minifying, and copying the app\'s  JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function () {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    log('Compressing, bundling, compying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function () {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function () {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 */
gulp.task('stage',
    ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts', 'test'], function () {
        log('Building index.html to stage');

        return gulp
            .src('./client/index.html')
            .pipe(inject([pkg.paths.stage + 'content/vendor.min.css'], 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'content/all.min.css']))
            .pipe(inject(pkg.paths.stage + 'vendor/vendor.min.js', 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'all.min.js']))
            .pipe(gulp.dest(pkg.paths.stage))
            .pipe(plug.notify({
                onLast: true,
                message: 'Deployed code to stage!'
            }));

        function inject(glob, name) {
            var ignorePath = pkg.paths.stage.substring(1);
            var options = {ignorePath: ignorePath};
            if (name) {
                options.name = name;
            }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Remove all files from the build folder
 */
gulp.task('clean', function () {
    log('Cleaning: ' + plug.util.colors.blue(pkg.paths.stage));
    return gulp
        .src(pkg.paths.build, {read: false})
        .pipe(plug.clean({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function () {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event) {
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test', function () {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];

    return gulp
        .src('./useKarmaConfAndNotThis')
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
            action: 'run' // run or watch
        }))
        .on('error', function (err) {
            // failed tests cause gulp to exit
            log(err);
            throw err;
        });
});

/**
 * serve the dev environment
 */
// var serveDevTasks = ['jshint', 'test'];
gulp.task('serve-dev', function () {
    serve('dev');
    startLivereload('development');
});

/**
 * serve the staging environment
 */
var serveStageTasks = ['jshint', 'test', 'stage'];
gulp.task('serve-stage', serveStageTasks, function () {
    serve('stage', serveStageTasks);
    startLivereload('stage');
});

function startLivereload(env) {
    var path = (env === 'stage' ? [pkg.paths.stage, 'client/**'] : ['client/**']);
    var options = {auto: true};
    plug.livereload.listen(options);
    gulp
        .watch(path)
        .on('change', function (file) {
            plug.livereload.changed(file.path);
        });

    log('Serving from ' + env);
}

function serve(env, tasks) {
    plug.nodemon({
        script: 'server/server.js',
        delayTime: 1,
        ext: 'html js',
        env: { 'NODE_ENV': env },
        watch: ['server/', 'client/'],
//        ignore: ['build/'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', tasks)
        .on('restart', function () {
            log('restarted!');
        });
}<commit_msg>modular: needed an array with a length or nodemon died<commit_after>/* jshint camelcase:false */
var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

gulp.task('help', plug.taskListing);

/**
 * @desc Annotate only
 *  Mostly for show.
 *  See the output of each file?
 *      Uncomment rename, comment concat and uglify
 *  See min'd and concat'd output?
 *      Comment rename, uncomment concat and uglify,
 *      add to index.html, then run it with `gulp serve-dev`.
 */
gulp.task('ngAnnotateTest', function () {
    log('Annotating AngularJS dependencies');
    var source = [].concat(pkg.paths.js);
    return gulp
        // .src(source)
        .src('./client/app/avengers/avengers.js')
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.rename(function (path) {
            path.extname = '.annotated.js';
        }))
        // .pipe(plug.concat('all.min.js'))
        // .pipe(plug.uglify({mangle: true}))
        // .pipe(gulp.dest('./client/app'));
        .pipe(gulp.dest('./client/app/avengers'));
});

/**
 * @desc Lint the code
 */
gulp.task('jshint', function () {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    log('Bundling, minifying, and copying the app\'s  JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({add: true, single_quotes: true}))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function () {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    log('Compressing, bundling, compying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function () {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function () {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 */
gulp.task('stage',
    ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts', 'test'], function () {
        log('Building index.html to stage');

        return gulp
            .src('./client/index.html')
            .pipe(inject([pkg.paths.stage + 'content/vendor.min.css'], 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'content/all.min.css']))
            .pipe(inject(pkg.paths.stage + 'vendor/vendor.min.js', 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'all.min.js']))
            .pipe(gulp.dest(pkg.paths.stage))
            .pipe(plug.notify({
                onLast: true,
                message: 'Deployed code to stage!'
            }));

        function inject(glob, name) {
            var ignorePath = pkg.paths.stage.substring(1);
            var options = {ignorePath: ignorePath};
            if (name) {
                options.name = name;
            }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Remove all files from the build folder
 */
gulp.task('clean', function () {
    log('Cleaning: ' + plug.util.colors.blue(pkg.paths.stage));
    return gulp
        .src(pkg.paths.build, {read: false})
        .pipe(plug.clean({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function () {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event) {
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test', function () {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/*[Ss]pec.js'];

    return gulp
        .src('./useKarmaConfAndNotThis')
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
            action: 'run' // run or watch
        }))
        .on('error', function (err) {
            // failed tests cause gulp to exit
            log(err);
            throw err;
        });
});

/**
 * serve the dev environment
 */
var serveDevTasks = ['jshint']; //, 'test'];
gulp.task('serve-dev', function () {
    serve('dev', serveDevTasks);
    startLivereload('development');
});

/**
 * serve the staging environment
 */
var serveStageTasks = ['jshint', 'test', 'stage'];
gulp.task('serve-stage', serveStageTasks, function () {
    serve('stage', serveStageTasks);
    startLivereload('stage');
});

function startLivereload(env) {
    var path = (env === 'stage' ? [pkg.paths.stage, 'client/**'] : ['client/**']);
    var options = {auto: true};
    plug.livereload.listen(options);
    gulp
        .watch(path)
        .on('change', function (file) {
            plug.livereload.changed(file.path);
        });

    log('Serving from ' + env);
}

function serve(env, tasks) {
    plug.nodemon({
        script: 'server/server.js',
        delayTime: 1,
        ext: 'html js',
        env: { 'NODE_ENV': env },
        watch: ['server/', 'client/'],
//        ignore: ['build/'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', tasks)
        .on('restart', function () {
            log('restarted!');
        });
}<|endoftext|>


<commit_before>var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

/**
 * @desc  Add a task to render the output
 */
gulp.task('help', plug.taskListing);

/**
 * @desc Lint the code
 */
gulp.task('jshint', function () {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        //.pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Add injection code for @ngInject annotations
 */
gulp.task('ngAnnotate', function () {
    log('Annotating AngularJS dependencies');

    return gulp
        .src(pkg.paths.js)
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, so we must be explicit there
            add: true,
            single_quotes: true
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    log('Bundling, minifying, and copying the app\'s  JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');

    return gulp
        .src(source)
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({
            add: true,
            single_quotes: true
        }))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function () {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
       .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    log('Compressing, bundling, compying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function () {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function () {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 */
gulp.task('stage',
    ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts', 'test'], function () {
        log('Building index.html to stage');

        return gulp
            .src('./client/index.html')
            .pipe(inject([pkg.paths.stage + 'content/vendor.min.css'], 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'content/all.min.css']))
            .pipe(inject(pkg.paths.stage + 'vendor/vendor.min.js', 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'all.min.js']))
            .pipe(gulp.dest(pkg.paths.stage))
            .pipe(plug.notify({
                onLast: true,
                message: 'Deployed code to stage!'
            }));

        function inject(glob, name) {
            var ignorePath = pkg.paths.stage.substring(1);
            var options = {ignorePath: ignorePath};
            if (name) {
                options.name = name;
            }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Remove all files from the build folder
 */
gulp.task('clean', function () {
    log('Cleaning: ' + plug.util.colors.blue(pkg.paths.stage));
    return gulp
        .src(pkg.paths.build, {read: false})
        .pipe(plug.clean({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function () {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event){
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test', function () {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/**.[Ss]pec.js'];

    return gulp
        .src(testFiles)
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
            action: 'run' // or watch
        }))
        .on('error', function (err) {
            // failed tests cause gulp to exit
            throw err;
        });
});

/**
 * serve the dev environment
 */
var serveDevTasks = ['jshint', 'test'];
gulp.task('serve-dev', serveDevTasks, function () {
    serve('dev', serveDevTasks);
    startLivereload('development');
});

/**
 * serve the staging environment
 */
var serveStageTasks = ['jshint', 'test', 'stage'];
gulp.task('serve-stage', serveStageTasks, function () {
    serve('stage', serveStageTasks);
    startLivereload('stage');
});

function startLivereload(env) {
    var path = (env === 'stage' ? pkg.paths.stage : 'client/') + '**';
    var options = {auto: true};
    plug.livereload.listen(options);
    gulp
        .watch(path)
        .on('change', function (file) {
            plug.livereload.changed(file.path);
        });

    log('Serving from ' + env);
}

function serve(env, tasks) {
    plug.nodemon({
        script: 'server/server.js',
        delayTime: 1,
        ext: 'html js',
        env: { 'NODE_ENV': env },
        watch: ['server/'],
//        ignore: ['build/'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', tasks)
        .on('restart', function () {
            log('restarted!');
        });
}<commit_msg>modular: gulp - refined serve task to watch both pre built and post built code<commit_after>var gulp = require('gulp');
var pkg = require('./package.json');
var common = require('./gulp/common.js');
var plug = require('gulp-load-plugins')();
var env = plug.util.env;
var log = plug.util.log;

/**
 * @desc  Add a task to render the output
 */
gulp.task('help', plug.taskListing);

/**
 * @desc Lint the code
 */
gulp.task('jshint', function () {
    log('Linting the JavaScript');

    var sources = [].concat(pkg.paths.js, pkg.paths.nodejs);
    return gulp
        .src(sources)
        .pipe(plug.jshint('./.jshintrc'))
        //.pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/**
 * @desc Create $templateCache from the html templates
 */
gulp.task('templatecache', function () {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Add injection code for @ngInject annotations
 */
gulp.task('ngAnnotate', function () {
    log('Annotating AngularJS dependencies');

    return gulp
        .src(pkg.paths.js)
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, so we must be explicit there
            add: true,
            single_quotes: true
        }))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Minify and bundle the app's JavaScript
 */
gulp.task('js', ['jshint', 'templatecache'], function () {
    log('Bundling, minifying, and copying the app\'s  JavaScript');

    var source = [].concat(pkg.paths.js, pkg.paths.stage + 'templates.js');
    return gulp
        .src(source)
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js'))
        .pipe(plug.ngAnnotate({
            add: true,
            single_quotes: true
        }))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.stage));
});

/**
 * @desc Copy the Vendor JavaScript
 */
gulp.task('vendorjs', function () {
    log('Bundling, minifying, and copying the Vendor JavaScript');
    return gulp.src(pkg.paths.vendorjs)
        .pipe(plug.concat('vendor.min.js'))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify())
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'vendor'));
});

/**
 * @desc Minify and bundle the CSS
 */
gulp.task('css', function () {
    log('Bundling, minifying, and copying the app\'s CSS');
    return gulp.src(pkg.paths.css)
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
       .pipe(plug.autoprefixer('last 2 version', '> 5%'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Minify and bundle the Vendor CSS
 */
gulp.task('vendorcss', function () {
    log('Compressing, bundling, compying vendor CSS');
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.stage + 'content'));
});

/**
 * @desc Copy fonts
 */
gulp.task('fonts', function () {
    var dest = pkg.paths.stage + 'fonts';
    log('Copying fonts');
    return gulp
        .src(pkg.paths.fonts)
        .pipe(gulp.dest(dest));
});

/**
 * @desc Compress images
 */
gulp.task('images', function () {
    var dest = pkg.paths.stage + 'content/images';
    log('Compressing, caching, and copying images');
    return gulp
        .src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(dest));
});

/**
 * @desc Inject all the files into the new index.html
 */
gulp.task('stage',
    ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts', 'test'], function () {
        log('Building index.html to stage');

        return gulp
            .src('./client/index.html')
            .pipe(inject([pkg.paths.stage + 'content/vendor.min.css'], 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'content/all.min.css']))
            .pipe(inject(pkg.paths.stage + 'vendor/vendor.min.js', 'inject-vendor'))
            .pipe(inject([pkg.paths.stage + 'all.min.js']))
            .pipe(gulp.dest(pkg.paths.stage))
            .pipe(plug.notify({
                onLast: true,
                message: 'Deployed code to stage!'
            }));

        function inject(glob, name) {
            var ignorePath = pkg.paths.stage.substring(1);
            var options = {ignorePath: ignorePath};
            if (name) {
                options.name = name;
            }
            return plug.inject(gulp.src(glob), options);
        }
    });

/**
 * @desc Remove all files from the build folder
 */
gulp.task('clean', function () {
    log('Cleaning: ' + plug.util.colors.blue(pkg.paths.stage));
    return gulp
        .src(pkg.paths.build, {read: false})
        .pipe(plug.clean({force: true}));
});

/**
 * @desc Watch files and build
 */
gulp.task('watch', function () {
    log('Watching all files');

    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var images = ['gulpfile.js'].concat(pkg.paths.images);
    var js = ['gulpfile.js'].concat(pkg.paths.js);

    gulp
        .watch(js, ['js', 'vendorjs'])
        .on('change', logWatch);

    gulp
        .watch(css, ['css', 'vendorcss'])
        .on('change', logWatch);

    gulp
        .watch(images, ['images'])
        .on('change', logWatch);

    function logWatch(event){
        log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    }
});

/**
 * @desc Run all tests
 */
gulp.task('test', function () {
    log('Running tests');
    var testFiles = [pkg.paths.test + 'spec.mocha/**.[Ss]pec.js'];

    return gulp
        .src(testFiles)
        .pipe(plug.karma({
            configFile: pkg.paths.test + '/karma.conf.js',
            action: 'run' // or watch
        }))
        .on('error', function (err) {
            // failed tests cause gulp to exit
            throw err;
        });
});

/**
 * serve the dev environment
 */
var serveDevTasks = ['jshint', 'test'];
gulp.task('serve-dev', serveDevTasks, function () {
    serve('dev', serveDevTasks);
    startLivereload('development');
});

/**
 * serve the staging environment
 */
var serveStageTasks = ['jshint', 'test', 'stage'];
gulp.task('serve-stage', serveStageTasks, function () {
    serve('stage', serveStageTasks);
    startLivereload('stage');
});

function startLivereload(env) {
    var path = (env === 'stage' ? [pkg.paths.stage, 'client/**'] : ['client/**']) ;
    var options = {auto: true};
    plug.livereload.listen(options);
    gulp
        .watch(path)
        .on('change', function (file) {
            plug.livereload.changed(file.path);
        });

    log('Serving from ' + env);
}

function serve(env, tasks) {
    plug.nodemon({
        script: 'server/server.js',
        delayTime: 1,
        ext: 'html js',
        env: { 'NODE_ENV': env },
        watch: ['server/', 'client/'],
//        ignore: ['build/'],
        nodeArgs: ['--debug=9999']
    })
        .on('change', tasks)
        .on('restart', function () {
            log('restarted!');
        });
}<|endoftext|>


<commit_before>//Constants for the different creeps' Bodies that auto spawn
//Tier 1
var hBody = [WORK, CARRY, CARRY, MOVE, MOVE];
var uBody = [WORK, CARRY, CARRY, CARRY, MOVE];
var bBody = [WORK, CARRY, WORK, MOVE];
var rBody = [WORK, WORK, CARRY, MOVE];
var miniHaul = [CARRY,CARRY,CARRY,MOVE,MOVE,MOVE];

//Tier 2
var h2Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE];
var u2Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b2Body = [WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r2Body = [WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE];

//Tier 3
var h3Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY,CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE];
var u3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r3Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];

//Tier4
var haulerBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY, CARRY, MOVE, MOVE, MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE];
var feederBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,WORK];
var minerBody = [WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE];
var u4Body = [WORK, WORK, WORK, WORK, WORK, WORK, CARRY, MOVE];
var soldierBody = [TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, MOVE, MOVE, MOVE, MOVE, RANGED_ATTACK, RANGED_ATTACK];
//800 energy so that two can spawn at rc5 without refil
var geoMinerBody = [WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE];
var merchantBody = [MOVE,CARRY];

//TODO Higher tier(s) for lvl 6,7,8

//Tier 5
var u5Body = [WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, CARRY, MOVE];
var b5Body = [WORK, WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE];
var soldierBody = [TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, MOVE, MOVE, MOVE, MOVE, RANGED_ATTACK, RANGED_ATTACK];

//Tier 6
var hauler6Body = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE];
var feeder6Body = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,WORK,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE];

//NonTiered
var settlerBody = [CLAIM,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE];

var costMap = {
  MOVE:50,
  WORK:100,
  CARRY:50,
  ATTACK:80,
  RANGED_ATTACK:150,
  HEAL:250,
  CLAIM:600,
  TOUGH:10
};

//Object that holds a getter for these body types
var bodyObj = {

  calcCost:function(bodyObj){
    var total = 0;
    for(var part in bodyObj){
      switch(part){
        case MOVE, CARRY:
          total = total + 50;
          break;
        case WORK:
          total = total + 100;
          break;
        case ATTACK:
          total = total + 80;
          break;
        case RANGED_ATTACK:
          total = total + 150;
          break;
        case HEAL:
          total = total + 250;
          break;
        case CLAIM:
          total = total + 600;
          break;
        case TOUGH:
          total = total + 10;
          break;
      }
    }
    return total;
  },
  //getter that useses a lot of switch statement to return the appropriate body array for the given role and tier
  getBody:function(role,tier){
      if(role==='harvester'){
        switch(tier){
          default:
            return hBody;
          case 2:
            return h2Body;
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            return h3Body;
        }
      }else if(role === 'upgrader'){
        switch(tier){
          default:
            return uBody;
          case 2:
            return u2Body;
          case 3:
            return u3Body;
          case 4:
            return u4Body;
          case 5:
          case 6:
          case 7:
            return u5Body;
        }
      }else if(role === 'builder' || role === 'architect'){
        switch(tier){
          default:
            return bBody;
          case 2:
            return b2Body;
          case 3:
          case 4:
            return b3Body;
          case 5:
          case 6:
          case 7:
            return b5Body;
        }
      }else if(role === 'repair'){
        switch(tier){
          default:
            return rBody;
          case 2:
            return r2Body;
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            return r3Body;
        }
      }else if(role === 'hauler'){
        switch(tier){
          default:
            return miniHaul;
          case 4:
          case 5:
            return haulerBody;
          case 6:
          case 7:
            return hauler6Body;
        }
      }else if(role === 'miner'){
        return minerBody;
      }else if(role === 'feeder'){
        switch(tier){
          default:
            return miniHaul;
          case 4:
          case 5:
            return feederBody;
          case 6:
          case 7:
            return feeder6Body;
        }
      }else if(role === 'soldier'){
        return soliderBody;
      }else if(role === 'geo'){
        return geoMinerBody;
      }else if(role === 'merchant'){
        return merchantBody;
      }else if(role === 'settler'){
        return settlerBody;
      }
  }

};

module.exports = bodyObj;
<commit_msg>added new tier 7 haulers<commit_after>//Constants for the different creeps' Bodies that auto spawn
//Tier 1
var hBody = [WORK, CARRY, CARRY, MOVE, MOVE];
var uBody = [WORK, CARRY, CARRY, CARRY, MOVE];
var bBody = [WORK, CARRY, WORK, MOVE];
var rBody = [WORK, WORK, CARRY, MOVE];
var miniHaul = [CARRY,CARRY,CARRY,MOVE,MOVE,MOVE];

//Tier 2
var h2Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE];
var u2Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b2Body = [WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r2Body = [WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE];

//Tier 3
var h3Body = [WORK, WORK, CARRY, CARRY, CARRY, CARRY,CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE];
var u3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, CARRY, MOVE, MOVE];
var b3Body = [WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, MOVE, MOVE, MOVE];
var r3Body = [WORK, WORK, WORK, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE, MOVE];

//Tier4
var haulerBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY, CARRY, MOVE, MOVE, MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE];
var feederBody = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,WORK];
var minerBody = [WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE];
var u4Body = [WORK, WORK, WORK, WORK, WORK, WORK, CARRY, MOVE];
var soldierBody = [TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, MOVE, MOVE, MOVE, MOVE, RANGED_ATTACK, RANGED_ATTACK];
//800 energy so that two can spawn at rc5 without refil
var geoMinerBody = [WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,WORK,CARRY,CARRY,CARRY,MOVE];
var merchantBody = [MOVE,CARRY];

//TODO Higher tier(s) for lvl 6,7,8

//Tier 5
var u5Body = [WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, WORK, CARRY, MOVE];
var b5Body = [WORK, WORK, WORK, WORK, WORK, WORK, CARRY, CARRY, CARRY, CARRY, CARRY, CARRY, MOVE, MOVE, MOVE, MOVE, MOVE];
var soldierBody = [TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, TOUGH, MOVE, MOVE, MOVE, MOVE, RANGED_ATTACK, RANGED_ATTACK];

//Tier 6
var hauler6Body = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE];
var feeder6Body = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,WORK,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE];

//Tier 7
var hauler7Body = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE];
var feeder7Body = [TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,TOUGH,WORK,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE,CARRY,MOVE];

//NonTiered
var settlerBody = [CLAIM,WORK,WORK,WORK,CARRY,CARRY,CARRY,CARRY,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE,MOVE];

var costMap = {
  MOVE:50,
  WORK:100,
  CARRY:50,
  ATTACK:80,
  RANGED_ATTACK:150,
  HEAL:250,
  CLAIM:600,
  TOUGH:10
};

//Object that holds a getter for these body types
var bodyObj = {

  calcCost:function(bodyObj){
    var total = 0;
    for(var part in bodyObj){
      switch(part){
        case MOVE, CARRY:
          total = total + 50;
          break;
        case WORK:
          total = total + 100;
          break;
        case ATTACK:
          total = total + 80;
          break;
        case RANGED_ATTACK:
          total = total + 150;
          break;
        case HEAL:
          total = total + 250;
          break;
        case CLAIM:
          total = total + 600;
          break;
        case TOUGH:
          total = total + 10;
          break;
      }
    }
    return total;
  },
  //getter that useses a lot of switch statement to return the appropriate body array for the given role and tier
  getBody:function(role,tier){
      if(role==='harvester'){
        switch(tier){
          default:
            return hBody;
          case 2:
            return h2Body;
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            return h3Body;
        }
      }else if(role === 'upgrader'){
        switch(tier){
          default:
            return uBody;
          case 2:
            return u2Body;
          case 3:
            return u3Body;
          case 4:
            return u4Body;
          case 5:
          case 6:
          case 7:
            return u5Body;
        }
      }else if(role === 'builder' || role === 'architect'){
        switch(tier){
          default:
            return bBody;
          case 2:
            return b2Body;
          case 3:
          case 4:
            return b3Body;
          case 5:
          case 6:
          case 7:
            return b5Body;
        }
      }else if(role === 'repair'){
        switch(tier){
          default:
            return rBody;
          case 2:
            return r2Body;
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            return r3Body;
        }
      }else if(role === 'hauler'){
        switch(tier){
          default:
            return miniHaul;
          case 4:
          case 5:
            return haulerBody;
          case 6:
            return hauler6Body;
          case 7:
            return hauler7Body;
        }
      }else if(role === 'miner'){
        return minerBody;
      }else if(role === 'feeder'){
        switch(tier){
          default:
            return miniHaul;
          case 4:
          case 5:
            return feederBody;
          case 6:
            return feeder6Body;
          case 7:
            return feeder7Body;
        }
      }else if(role === 'soldier'){
        return soliderBody;
      }else if(role === 'geo'){
        return geoMinerBody;
      }else if(role === 'merchant'){
        return merchantBody;
      }else if(role === 'settler'){
        return settlerBody;
      }
  }

};

module.exports = bodyObj;
<|endoftext|>


<commit_before>var config = require('../config');
var request = require('request');
var fs = require('fs');

var requestOptions = {
	json: true,
	headers: {
		'if-modified-since': (new Date()).toUTCString()
	}
};

var chanInterface = {};

chanInterface.downloadJSONForBoard = function(board, callback) {
	var randomPageNumber = Math.floor(Math.random() * 10) + 1;
	if (board == "f") {
		randomPageNumber = 1;
	}
  var requestUrl = config.CHAN_BASE_URL + board + "/" + randomPageNumber + ".json";
  request(requestUrl, requestOptions, function (err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null, body);
    } else {
      return callback(new Error("Unable to download JSON. Code " + res.statusCode));
    }
  }).on('error', function(err) {
		return callback(err);
	});
};

chanInterface.downloadMedia = function(name, board, localPath, callback) {
  var requestUrl = config.CHAN_IMAGE_BASE_URL + board + "/" + name;
  var targetPath = localPath + "/" + name;
	ensureExists(localPath, 0744, function(err){
		if(err) {
			return callback(err);
		} else {
			request.head(requestUrl, function(err, res, body){
		    if(err) {
		      return callback(err);
		    } else {
		      var r = request(requestUrl).pipe(fs.createWriteStream(targetPath)).on('close', function(){
						callback(null, targetPath);
					}).on('error', function(err) {
						return callback(err);
					});
		    }
		  });
		}
	});
};

function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 0777;
    }
    fs.mkdir(path, mask, function(err) {
        if (err) {
					if (err.code == 'EEXIST') {
						cb(null);
					} else {
						cb(err);
					}
        } else {
					cb(null);
				}
    });
}

module.exports = chanInterface;
<commit_msg>Debug log.<commit_after>var config = require('../config');
var request = require('request');
var fs = require('fs');

var requestOptions = {
	json: true,
	headers: {
		'if-modified-since': (new Date()).toUTCString()
	}
};

var chanInterface = {};

chanInterface.downloadJSONForBoard = function(board, callback) {
	var randomPageNumber = Math.floor(Math.random() * 10) + 1;
	console.log(board);
	if (board == "f") {
		randomPageNumber = 1;
	}
  var requestUrl = config.CHAN_BASE_URL + board + "/" + randomPageNumber + ".json";
  request(requestUrl, requestOptions, function (err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null, body);
    } else {
      return callback(new Error("Unable to download JSON. Code " + res.statusCode));
    }
  }).on('error', function(err) {
		return callback(err);
	});
};

chanInterface.downloadMedia = function(name, board, localPath, callback) {
  var requestUrl = config.CHAN_IMAGE_BASE_URL + board + "/" + name;
  var targetPath = localPath + "/" + name;
	ensureExists(localPath, 0744, function(err){
		if(err) {
			return callback(err);
		} else {
			request.head(requestUrl, function(err, res, body){
		    if(err) {
		      return callback(err);
		    } else {
		      var r = request(requestUrl).pipe(fs.createWriteStream(targetPath)).on('close', function(){
						callback(null, targetPath);
					}).on('error', function(err) {
						return callback(err);
					});
		    }
		  });
		}
	});
};

function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 0777;
    }
    fs.mkdir(path, mask, function(err) {
        if (err) {
					if (err.code == 'EEXIST') {
						cb(null);
					} else {
						cb(err);
					}
        } else {
					cb(null);
				}
    });
}

module.exports = chanInterface;
<|endoftext|>